Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix potential nullref due to missing lambda | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An overlay container that eagerly holds keyboard focus.
/// </summary>
public abstract class FocusedOverlayContainer : OverlayContainer
{
protected InputManager InputManager;
public override bool RequestingFocus => State == Visibility.Visible;
protected override bool OnFocus(InputState state) => true;
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape))
Hide();
base.OnFocusLost(state);
}
[BackgroundDependencyLoader]
private void load(UserInputManager inputManager)
{
InputManager = inputManager;
}
protected override void PopIn()
{
Schedule(InputManager.TriggerFocusContention);
}
protected override void PopOut()
{
if (HasFocus)
InputManager.ChangeFocus(null);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System.Linq;
using osu.Framework.Input;
using OpenTK.Input;
using osu.Framework.Allocation;
namespace osu.Framework.Graphics.Containers
{
/// <summary>
/// An overlay container that eagerly holds keyboard focus.
/// </summary>
public abstract class FocusedOverlayContainer : OverlayContainer
{
protected InputManager InputManager;
public override bool RequestingFocus => State == Visibility.Visible;
protected override bool OnFocus(InputState state) => true;
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape))
Hide();
base.OnFocusLost(state);
}
[BackgroundDependencyLoader]
private void load(UserInputManager inputManager)
{
InputManager = inputManager;
}
protected override void PopIn()
{
Schedule(() => InputManager.TriggerFocusContention());
}
protected override void PopOut()
{
if (HasFocus)
InputManager.ChangeFocus(null);
}
}
}
|
Fix sampler update when connected | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
if (this.pin.IsChanged)
{
if (this.state != null) { this.state.Dispose(); this.state = null; }
}
if (this.state == null || this.state.Disposed)
{
this.state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[0]);
}
shaderinstance.SetByName(this.Name, this.state);
}
else
{
if (this.state != null)
{
this.state.Dispose();
this.state = null;
shaderinstance.SetByName(this.Name, this.state);
}
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using VVVV.DX11.Internals.Effects.Pins;
using VVVV.PluginInterfaces.V2;
using SlimDX.Direct3D11;
using VVVV.PluginInterfaces.V1;
using VVVV.Hosting.Pins;
using VVVV.DX11.Lib.Effects.Pins;
using FeralTic.DX11;
namespace VVVV.DX11.Internals.Effects.Pins
{
public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription>
{
private SamplerState state;
protected override void ProcessAttribute(InputAttribute attr, EffectVariable var)
{
attr.IsSingle = true;
attr.CheckIfChanged = true;
}
protected override bool RecreatePin(EffectVariable var)
{
return false;
}
public override void SetVariable(DX11ShaderInstance shaderinstance, int slice)
{
if (this.pin.PluginIO.IsConnected)
{
using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice]))
{
shaderinstance.SetByName(this.Name, state);
}
}
else
{
shaderinstance.Effect.GetVariableByName(this.Name).AsConstantBuffer().UndoSetConstantBuffer();
}
}
}
} |
Print supported routes in console app. | using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PortableWordPressApi;
using PortableWordPressApi.Resources;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
var indexResponse = await httpClient.GetAsync(api.ApiRootUri);
var index = JsonConvert.DeserializeObject<ApiIndex>(await indexResponse.Content.ReadAsStringAsync());
Console.WriteLine("Supported routes: TODO");
}
}
}
| using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using PortableWordPressApi;
using PortableWordPressApi.Resources;
namespace ApiConsole
{
class Program
{
static void Main(string[] args)
{
Task.WaitAll(AsyncMain());
Console.WriteLine("Press any key to close.");
Console.Read();
}
private static async Task AsyncMain()
{
Console.WriteLine("Enter site URL:");
var url = Console.ReadLine();
Console.WriteLine("Searching for API at {0}", url);
var httpClient = new HttpClient();
var discovery = new WordPressApiDiscovery(new Uri(url, UriKind.Absolute), httpClient);
var api = await discovery.DiscoverApiForSite();
Console.WriteLine("Site's API endpoint: {0}", api.ApiRootUri);
var indexResponse = await httpClient.GetAsync(api.ApiRootUri);
var index = JsonConvert.DeserializeObject<ApiIndex>(await indexResponse.Content.ReadAsStringAsync());
Console.WriteLine("Supported routes:");
foreach (var route in index.Routes)
{
Console.WriteLine("\t" + route.Key);
}
}
}
}
|
Remove default value in Storagemgr | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Game.Tournament.Configuration
{
public class TournamentStorageManager : IniConfigManager<StorageConfig>
{
protected override string Filename => "tournament.ini";
public TournamentStorageManager(Storage storage)
: base(storage)
{
}
protected override void InitialiseDefaults()
{
base.InitialiseDefaults();
Set(StorageConfig.CurrentTournament, string.Empty);
}
}
public enum StorageConfig
{
CurrentTournament,
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Configuration;
using osu.Framework.Platform;
namespace osu.Game.Tournament.Configuration
{
public class TournamentStorageManager : IniConfigManager<StorageConfig>
{
protected override string Filename => "tournament.ini";
public TournamentStorageManager(Storage storage)
: base(storage)
{
}
}
public enum StorageConfig
{
CurrentTournament,
}
}
|
Add canonicalization support for array methods | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Internal.TypeSystem
{
// Implements canonicalization for arrays
partial class ArrayType
{
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
TypeDesc paramTypeConverted = CanonUtilites.ConvertToCanon(ParameterType, kind);
if (paramTypeConverted != ParameterType)
{
// Note: don't use the Rank property here, as that hides the difference
// between a single dimensional MD array and an SZArray.
return Context.GetArrayType(paramTypeConverted, _rank);
}
return this;
}
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Internal.TypeSystem
{
// Implements canonicalization for arrays
partial class ArrayType
{
protected override TypeDesc ConvertToCanonFormImpl(CanonicalFormKind kind)
{
TypeDesc paramTypeConverted = CanonUtilites.ConvertToCanon(ParameterType, kind);
if (paramTypeConverted != ParameterType)
{
// Note: don't use the Rank property here, as that hides the difference
// between a single dimensional MD array and an SZArray.
return Context.GetArrayType(paramTypeConverted, _rank);
}
return this;
}
}
// Implements canonicalization for array methods
partial class ArrayMethod
{
public override bool IsCanonicalMethod(CanonicalFormKind policy)
{
return _owningType.IsCanonicalSubtype(policy);
}
public override MethodDesc GetCanonMethodTarget(CanonicalFormKind kind)
{
TypeDesc canonicalizedTypeOfTargetMethod = _owningType.ConvertToCanonForm(kind);
if (canonicalizedTypeOfTargetMethod == _owningType)
return this;
return ((ArrayType)canonicalizedTypeOfTargetMethod).GetArrayMethod(_kind);
}
}
} |
Fix exception when configuration is read | using System.Configuration;
namespace NStatsD
{
public class StatsDConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = "true", IsRequired = false)]
public bool Enabled
{
get { return (bool) this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("server")]
public ServerElement Server
{
get { return (ServerElement) this["server"]; }
set { this["server"] = value; }
}
[ConfigurationProperty("prefix", DefaultValue = "", IsRequired = false)]
public string Prefix
{
get { return (string)this["prefix"]; }
set { this["prefix"] = value; }
}
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("host", DefaultValue = "localhost", IsRequired = true)]
public string Host
{
get { return (string) this["host"]; }
set { this["host"] = value; }
}
[ConfigurationProperty("port", DefaultValue = "8125", IsRequired = false)]
public int Port
{
get { return (int) this["port"]; }
set { this["port"] = value; }
}
}
}
| using System.Configuration;
namespace NStatsD
{
public class StatsDConfigurationSection : ConfigurationSection
{
[ConfigurationProperty("enabled", DefaultValue = "true", IsRequired = false)]
public bool Enabled
{
get { return (bool) this["enabled"]; }
set { this["enabled"] = value; }
}
[ConfigurationProperty("server")]
public ServerElement Server
{
get { return (ServerElement) this["server"]; }
set { this["server"] = value; }
}
[ConfigurationProperty("prefix", DefaultValue = "", IsRequired = false)]
public string Prefix
{
get { return (string)this["prefix"]; }
set { this["prefix"] = value; }
}
public override bool IsReadOnly()
{
return false;
}
}
public class ServerElement : ConfigurationElement
{
[ConfigurationProperty("host", DefaultValue = "localhost", IsRequired = true)]
public string Host
{
get { return (string) this["host"]; }
set { this["host"] = value; }
}
[ConfigurationProperty("port", DefaultValue = "8125", IsRequired = false)]
public int Port
{
get { return (int) this["port"]; }
set { this["port"] = value; }
}
}
}
|
Fix crash on loading hasted player. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magecrawl.GameEngine.Actors;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Affects
{
internal class Haste : AffectBase
{
private double m_modifier;
public Haste() : base(0)
{
}
public Haste(int strength)
: base(new DiceRoll(1, 4, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn)
{
m_modifier = 1 + (.2 * strength);
}
public override void Apply(Character appliedTo)
{
appliedTo.CTIncreaseModifier *= m_modifier;
}
public override void Remove(Character removedFrom)
{
removedFrom.CTIncreaseModifier /= m_modifier;
}
public override string Name
{
get
{
return "Haste";
}
}
#region SaveLoad
public override void ReadXml(System.Xml.XmlReader reader)
{
base.ReadXml(reader);
m_modifier = reader.ReadContentAsDouble();
}
public override void WriteXml(System.Xml.XmlWriter writer)
{
base.WriteXml(writer);
writer.WriteElementString("Modifier", m_modifier.ToString());
}
#endregion
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Magecrawl.GameEngine.Actors;
using Magecrawl.Utilities;
namespace Magecrawl.GameEngine.Affects
{
internal class Haste : AffectBase
{
private double m_modifier;
public Haste() : base(0)
{
}
public Haste(int strength)
: base(new DiceRoll(1, 4, strength).Roll() * CoreTimingEngine.CTNeededForNewTurn)
{
m_modifier = 1 + (.2 * strength);
}
public override void Apply(Character appliedTo)
{
appliedTo.CTIncreaseModifier *= m_modifier;
}
public override void Remove(Character removedFrom)
{
removedFrom.CTIncreaseModifier /= m_modifier;
}
public override string Name
{
get
{
return "Haste";
}
}
#region SaveLoad
public override void ReadXml(System.Xml.XmlReader reader)
{
base.ReadXml(reader);
m_modifier = reader.ReadElementContentAsDouble();
}
public override void WriteXml(System.Xml.XmlWriter writer)
{
base.WriteXml(writer);
writer.WriteElementString("Modifier", m_modifier.ToString());
}
#endregion
}
}
|
Add check for Standard Id in CloneEntity, and add a CopyEntityProperties method to allow calling it separately | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Sage.Platform;
using Sage.Platform.Orm.Attributes;
using Sage.Platform.Orm.Interfaces;
namespace OpenSlx.Lib.Utility
{
/// <summary>
/// Miscellaneous utilities dealing with SLX entities.
/// </summary>
public static class SlxEntityUtility
{
public static T CloneEntity<T>(T source)
where T : IDynamicEntity
{
T target = EntityFactory.Create<T>();
foreach (PropertyInfo prop in source.GetType().GetProperties())
{
if (Attribute.GetCustomAttribute(prop, typeof(FieldAttribute)) != null)
{
target[prop.Name] = source[prop.Name];
}
}
return target;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Sage.Platform;
using Sage.Platform.Orm.Attributes;
using Sage.Platform.Orm.Interfaces;
using Sage.Platform.Orm.Services;
namespace OpenSlx.Lib.Utility
{
/// <summary>
/// Miscellaneous utilities dealing with SLX entities.
/// </summary>
public static class SlxEntityUtility
{
/// <summary>
/// Create a copy of an existing entity
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="source"></param>
/// <returns></returns>
public static T CloneEntity<T>(T source)
where T : IDynamicEntity
{
T target = EntityFactory.Create<T>();
CopyEntityProperties(target, source);
return target;
}
public static void CopyEntityProperties<T>(T target, T source)
where T : IDynamicEntity
{
foreach (PropertyInfo prop in source.GetType().GetProperties())
{
// only copy the ones associated with DB fields
// (note that this includes M-1 relationships)
if (Attribute.GetCustomAttribute(prop, typeof(FieldAttribute)) != null)
{
var extendedType =
(DynamicEntityDescriptorConfigurationService.ExtendedTypeInformationAttribute)
prop.GetCustomAttributes(
typeof(DynamicEntityDescriptorConfigurationService.ExtendedTypeInformationAttribute),
false).FirstOrDefault();
// don't copy ID fields - we'll pick up the reference properties instead
if (extendedType != null && extendedType.ExtendedTypeName ==
"Sage.Platform.Orm.DataTypes.StandardIdDataType, Sage.Platform")
{
continue;
}
target[prop.Name] = source[prop.Name];
}
}
}
}
}
|
Set Proxy to null when sending the No-Ip DNS Update request | using System;
using System.Net;
using System.Text;
using System.Threading;
using xServer.Settings;
namespace xServer.Core.Misc
{
public static class NoIpUpdater
{
private static bool _running;
public static void Start()
{
if (_running) return;
Thread updateThread = new Thread(BackgroundUpdater) {IsBackground = true};
updateThread.Start();
}
private static void BackgroundUpdater()
{
_running = true;
while (XMLSettings.IntegrateNoIP)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://dynupdate.no-ip.com/nic/update?hostname={0}", XMLSettings.NoIPHost));
request.UserAgent = string.Format("xRAT No-Ip Updater/2.0 {0}", XMLSettings.NoIPUsername);
request.Timeout = 10000;
request.Headers.Add(HttpRequestHeader.Authorization, string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", XMLSettings.NoIPUsername, XMLSettings.NoIPPassword)))));
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
}
}
catch
{
}
Thread.Sleep(TimeSpan.FromMinutes(10));
}
_running = false;
}
}
}
| using System;
using System.Net;
using System.Text;
using System.Threading;
using xServer.Settings;
namespace xServer.Core.Misc
{
public static class NoIpUpdater
{
private static bool _running;
public static void Start()
{
if (_running) return;
Thread updateThread = new Thread(BackgroundUpdater) {IsBackground = true};
updateThread.Start();
}
private static void BackgroundUpdater()
{
_running = true;
while (XMLSettings.IntegrateNoIP)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(string.Format("http://dynupdate.no-ip.com/nic/update?hostname={0}", XMLSettings.NoIPHost));
request.Proxy = null;
request.UserAgent = string.Format("xRAT No-Ip Updater/2.0 {0}", XMLSettings.NoIPUsername);
request.Timeout = 10000;
request.Headers.Add(HttpRequestHeader.Authorization, string.Format("Basic {0}", Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", XMLSettings.NoIPUsername, XMLSettings.NoIPPassword)))));
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
}
}
catch
{
}
Thread.Sleep(TimeSpan.FromMinutes(10));
}
_running = false;
}
}
}
|
Check to see if merge worked | using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
[Fact]
public void test_RemoveReport_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
}
}
}
| using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
AdminLogic admLogic = new AdminLogic();
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
//[Fact]
//public void test_RemoveReport_AdminLogic()
//{
// AdminLogic admLogic = new AdminLogic();
//}
}
}
|
Add comment to help find CAS url setting | using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = new PathString("/login");
o.Cookie = new CookieBuilder
{
Name = ".AspNet.CasSample"
};
})
.AddCAS(o =>
{
o.CasServerUrlBase = Configuration["CasBaseUrl"];
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
}
| using AspNetCore.Security.CAS;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace CookieSample
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(o =>
{
o.LoginPath = new PathString("/login");
o.Cookie = new CookieBuilder
{
Name = ".AspNet.CasSample"
};
})
.AddCAS(o =>
{
o.CasServerUrlBase = Configuration["CasBaseUrl"]; // Set in `appsettings.json` file.
o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
});
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvcWithDefaultRoute();
}
}
}
|
Change to InputObject naming convention | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;
namespace RedditSharp.PowerShell.Cmdlets.Posts
{
/// <summary>
/// <para type="description">Edit the text of a self post. Will not work on link posts.</para>
/// </summary>
[Cmdlet(VerbsData.Edit,"Post")]
[OutputType(typeof(Post))]
public class EditPost : Cmdlet
{
[Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
public Post Target { get; set; }
[Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
public string Body { get; set; }
protected override void BeginProcessing()
{
if (Session.Reddit == null)
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
ErrorCategory.InvalidOperation, Session.Reddit));
}
protected override void ProcessRecord()
{
try
{
Target.EditText(Body);
Target.SelfText = Body;
WriteObject(Target);
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, Target));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using RedditSharp.Things;
namespace RedditSharp.PowerShell.Cmdlets.Posts
{
/// <summary>
/// <para type="description">Edit the text of a self post. Will not work on link posts.</para>
/// </summary>
[Cmdlet(VerbsData.Edit,"Post")]
[OutputType(typeof(Post))]
public class EditPost : Cmdlet
{
[Parameter(Mandatory=true,Position = 0,HelpMessage = "Self post to edit")]
public Post InputObject { get; set; }
[Parameter(Mandatory = true,Position = 1,HelpMessage = "New body text/markdown.")]
public string Body { get; set; }
protected override void BeginProcessing()
{
if (Session.Reddit == null)
ThrowTerminatingError(new ErrorRecord(new InvalidOperationException(), "NoRedditSession",
ErrorCategory.InvalidOperation, Session.Reddit));
}
protected override void ProcessRecord()
{
try
{
InputObject.EditText(Body);
InputObject.SelfText = Body;
WriteObject(InputObject);
}
catch (Exception ex)
{
WriteError(new ErrorRecord(ex, "CantUpdateSelfText", ErrorCategory.InvalidOperation, InputObject));
}
}
}
}
|
Set VisualC warning level that a warning free compile occurs | using Bam.Core;
namespace boost
{
abstract class GenericBoostModule :
C.StaticLibrary
{
protected GenericBoostModule(
string name)
{
this.Name = name;
}
private string Name
{
get;
set;
}
protected C.Cxx.ObjectFileCollection BoostSource
{
get;
private set;
}
protected override void
Init(
Bam.Core.Module parent)
{
base.Init(parent);
this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");
this.BoostSource = this.CreateCxxSourceContainer();
this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
{
this.BoostSource.PrivatePatch(settings =>
{
var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
});
if (this.Librarian is VisualCCommon.Librarian)
{
this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
}
}
}
}
}
| using Bam.Core;
namespace boost
{
abstract class GenericBoostModule :
C.StaticLibrary
{
protected GenericBoostModule(
string name)
{
this.Name = name;
}
private string Name
{
get;
set;
}
protected C.Cxx.ObjectFileCollection BoostSource
{
get;
private set;
}
protected override void
Init(
Bam.Core.Module parent)
{
base.Init(parent);
this.Macros["OutputName"] = TokenizedString.CreateVerbatim(string.Format("boost_{0}-vc120-mt-1_60", this.Name));
this.Macros["libprefix"] = TokenizedString.CreateVerbatim("lib");
this.BoostSource = this.CreateCxxSourceContainer();
this.CompileAgainstPublicly<BoostHeaders>(this.BoostSource);
if (this.BuildEnvironment.Platform.Includes(EPlatform.Windows))
{
this.BoostSource.PrivatePatch(settings =>
{
var cxxCompiler = settings as C.ICxxOnlyCompilerSettings;
cxxCompiler.ExceptionHandler = C.Cxx.EExceptionHandler.Asynchronous;
var vcCompiler = settings as VisualCCommon.ICommonCompilerSettings;
if (null != vcCompiler)
{
vcCompiler.WarningLevel = VisualCCommon.EWarningLevel.Level2; // does not compile warning-free above this level
}
});
if (this.Librarian is VisualCCommon.Librarian)
{
this.CompileAgainst<WindowsSDK.WindowsSDK>(this.BoostSource);
}
}
}
}
}
|
Bump the version to v4.1.3 | /*
* ******************************************************************************
* Copyright 2014-2017 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("4.1.2.0")]
[assembly: AssemblyFileVersion("4.1.2.0")]
| /*
* ******************************************************************************
* Copyright 2014-2017 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("4.1.3.0")]
[assembly: AssemblyFileVersion("4.1.3.0")]
|
Add save UIElement to stream snippet | using System;
using System.Threading.Tasks;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
namespace TestAppUWP.Core
{
// ReSharper disable once InconsistentNaming
public static class UIElementExtension
{
public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement)
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uiElement);
return await renderTargetBitmap.GetPixelsAsync();
}
}
}
| using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Media.Imaging;
namespace TestAppUWP.Core
{
// ReSharper disable once InconsistentNaming
public static class UIElementExtension
{
public static async Task<IBuffer> RenderTargetBitmapBuffer(this UIElement uiElement)
{
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uiElement);
return await renderTargetBitmap.GetPixelsAsync();
}
public static async Task SaveUiElementToStream(this UIElement uiElement, IRandomAccessStream stream)
{
DisplayInformation displayInformation = DisplayInformation.GetForCurrentView();
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(uiElement);
IBuffer buffer = await renderTargetBitmap.GetPixelsAsync();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight, displayInformation.LogicalDpi, displayInformation.LogicalDpi,
buffer.ToArray());
await encoder.FlushAsync();
}
}
}
|
Use writeline instead of CursorTop++ | using System;
using System.IO;
namespace AppHarbor
{
public class ConsoleProgressBar
{
private const char ProgressBarCharacter = '\u2592';
public static void Render(double percentage, ConsoleColor color, string message)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.CursorLeft = 0;
try
{
Console.CursorVisible = false;
Console.ForegroundColor = color;
int width = Console.WindowWidth - 1;
int newWidth = (int)((width * percentage) / 100d);
string progressBar = string.Empty
.PadRight(newWidth, ProgressBarCharacter)
.PadRight(width - newWidth, ' ');
Console.Write(progressBar);
message = message ?? string.Empty;
Console.CursorTop++;
OverwriteConsoleMessage(message);
Console.CursorTop--;
}
finally
{
Console.ForegroundColor = originalColor;
Console.CursorVisible = true;
}
}
private static void OverwriteConsoleMessage(string message)
{
Console.CursorLeft = 0;
int maxCharacterWidth = Console.WindowWidth - 1;
if (message.Length > maxCharacterWidth)
{
message = message.Substring(0, maxCharacterWidth - 3) + "...";
}
message = message + new string(' ', maxCharacterWidth - message.Length);
Console.Write(message);
}
}
}
| using System;
using System.IO;
namespace AppHarbor
{
public class ConsoleProgressBar
{
private const char ProgressBarCharacter = '\u2592';
public static void Render(double percentage, ConsoleColor color, string message)
{
ConsoleColor originalColor = Console.ForegroundColor;
Console.CursorLeft = 0;
try
{
Console.CursorVisible = false;
Console.ForegroundColor = color;
int width = Console.WindowWidth - 1;
int newWidth = (int)((width * percentage) / 100d);
string progressBar = string.Empty
.PadRight(newWidth, ProgressBarCharacter)
.PadRight(width - newWidth, ' ');
Console.Write(progressBar);
message = message ?? string.Empty;
Console.WriteLine();
OverwriteConsoleMessage(message);
Console.CursorTop--;
}
finally
{
Console.ForegroundColor = originalColor;
Console.CursorVisible = true;
}
}
private static void OverwriteConsoleMessage(string message)
{
Console.CursorLeft = 0;
int maxCharacterWidth = Console.WindowWidth - 1;
if (message.Length > maxCharacterWidth)
{
message = message.Substring(0, maxCharacterWidth - 3) + "...";
}
message = message + new string(' ', maxCharacterWidth - message.Length);
Console.Write(message);
}
}
}
|
Remove validator methods, no longer needed. | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.ViewModels.Validation
{
public delegate void ValidateMethod(IErrorList errors);
public static class Validator
{
//public static IEnumerable<(string propertyName, ErrorDescriptors errors)> ValidateAllProperties(Dictionary<string, ValidateMethod> validationMethodCache)
//{
// if(validationMethodCache is null || validationMethodCache.Count == 0)
// {
// throw new Exception("Cant call ValidateAllProperties on ViewModels with no ValidateAttributes");
// }
// var result = new List<(string propertyName, ErrorDescriptors errors)>();
// foreach (var propertyName in validationMethodCache.Keys)
// {
// var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke();
// result.Add((propertyName, invokeRes));
// }
// return result;
//}
//public static ErrorDescriptors ValidateProperty(ViewModelBase viewModelBase, string propertyName,
// Dictionary<string, MethodInfo> validationMethodCache)
//{
// if (validationMethodCache is null)
// {
// return ErrorDescriptors.Empty;
// }
// ErrorDescriptors result = null;
// if(validationMethodCache.ContainsKey(propertyName))
// {
// var invokeRes = (ErrorDescriptors)validationMethodCache[propertyName].Invoke(viewModelBase, null);
// if (result is null)
// {
// result = new ErrorDescriptors();
// }
// result.AddRange(invokeRes);
// }
// return result ?? ErrorDescriptors.Empty;
//}
}
}
| using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using WalletWasabi.Models;
namespace WalletWasabi.Gui.ViewModels.Validation
{
public delegate void ValidateMethod(IErrorList errors);
}
|
Allow null string in langversion conversion (changeset 1252651) | // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
internal static class CompilationOptionsConversion
{
internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion)
{
switch (projectLanguageVersion.ToLowerInvariant())
{
case "iso-1":
return LanguageVersion.CSharp1;
case "iso-2":
return LanguageVersion.CSharp2;
case "experimental":
return LanguageVersion.Experimental;
default:
if (!string.IsNullOrEmpty(projectLanguageVersion))
{
int version;
if (int.TryParse(projectLanguageVersion, out version))
{
return (LanguageVersion)version;
}
}
// use default;
return null;
}
}
}
}
| // Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.CSharp.Utilities
{
internal static class CompilationOptionsConversion
{
internal static LanguageVersion? GetLanguageVersion(string projectLanguageVersion)
{
switch ((projectLanguageVersion ?? string.Empty).ToLowerInvariant())
{
case "iso-1":
return LanguageVersion.CSharp1;
case "iso-2":
return LanguageVersion.CSharp2;
case "experimental":
return LanguageVersion.Experimental;
default:
if (!string.IsNullOrEmpty(projectLanguageVersion))
{
int version;
if (int.TryParse(projectLanguageVersion, out version))
{
return (LanguageVersion)version;
}
}
// use default;
return null;
}
}
}
}
|
Create the download directory if it doesn't exist. | namespace net.opgenorth.yegvote.droid.Service
{
using System;
using System.IO;
using Android.Content;
using Environment = Android.OS.Environment;
/// <summary>
/// This class will figure out where to store files.
/// </summary>
/// <remarks>Different versions of Android have different diretories for storage.</remarks>
internal class ElectionServiceDownloadDirectory
{
private readonly Context _context;
public ElectionServiceDownloadDirectory(Context context)
{
_context = context;
}
public void EnsureExternalStorageIsUsable()
{
if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState))
{
throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null)));
}
if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState))
{
throw new ApplicationException("External storage is not mounted.");
}
}
public bool ResultsAreDownloaded
{
get
{
// TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false?
return File.Exists(GetResultsXmlFile());
}
}
public string GetResultsXmlFile()
{
var dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryDownloads).AbsolutePath;
return Path.Combine(dir, "election_results.xml");
}
}
}
| using Android.Runtime;
namespace net.opgenorth.yegvote.droid.Service
{
using System;
using System.IO;
using Android.Content;
using Environment = Android.OS.Environment;
/// <summary>
/// This class will figure out where to store files.
/// </summary>
/// <remarks>Different versions of Android have different diretories for storage.</remarks>
internal class ElectionServiceDownloadDirectory
{
private readonly Context _context;
public ElectionServiceDownloadDirectory(Context context)
{
_context = context;
}
public void EnsureExternalStorageIsUsable()
{
if (Environment.MediaMountedReadOnly.Equals(Environment.ExternalStorageState))
{
throw new ApplicationException(String.Format("External storage {0} is mounted read-only.", _context.GetExternalFilesDir(null)));
}
if (!Environment.MediaMounted.Equals(Environment.ExternalStorageState))
{
throw new ApplicationException("External storage is not mounted.");
}
}
public bool ResultsAreDownloaded
{
get
{
// TODO [TO201310041632] Maybe check to see how old the file is, > 30 minutes should return false?
return File.Exists(GetResultsXmlFileName());
}
}
public string GetResultsXmlFileName()
{
var dir = _context.ExternalCacheDir.AbsolutePath;
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
return Path.Combine(dir, "election_results.xml");
}
}
}
|
Refactor the tests in the LogoutHandler slightly. | using DavidLievrouw.Utils.ForTesting.DotNet;
using DavidLievrouw.Voter.Api.Users.Models;
using DavidLievrouw.Voter.Security;
using FakeItEasy;
using NUnit.Framework;
namespace DavidLievrouw.Voter.Api.Users.Handlers {
[TestFixture]
public class LogoutHandlerTests {
LogoutHandler _sut;
[SetUp]
public void SetUp() {
_sut = new LogoutHandler();
}
[Test]
public void ConstructorTests() {
Assert.That(_sut.NoDependenciesAreOptional());
}
[Test]
public void DelegatesControlToAuthenticatedUserApplyer() {
var securityContext = A.Fake<ISecurityContext>();
var command = new LogoutRequest {
SecurityContext = securityContext
};
_sut.Handle(command).Wait();
A.CallTo(() => securityContext.SetAuthenticatedUser(null))
.MustHaveHappened();
}
}
} | using DavidLievrouw.Utils.ForTesting.DotNet;
using DavidLievrouw.Voter.Api.Users.Models;
using DavidLievrouw.Voter.Security;
using FakeItEasy;
using NUnit.Framework;
namespace DavidLievrouw.Voter.Api.Users.Handlers {
[TestFixture]
public class LogoutHandlerTests {
LogoutHandler _sut;
[SetUp]
public void SetUp() {
_sut = new LogoutHandler();
}
[TestFixture]
public class Construction : LogoutHandlerTests {
[Test]
public void ConstructorTests() {
Assert.That(_sut.NoDependenciesAreOptional());
}
}
[TestFixture]
public class Handle : LogoutHandlerTests {
[Test]
public void DelegatesControlToAuthenticatedUserApplyer() {
var securityContext = A.Fake<ISecurityContext>();
var command = new LogoutRequest {
SecurityContext = securityContext
};
_sut.Handle(command).Wait();
A.CallTo(() => securityContext.SetAuthenticatedUser(null))
.MustHaveHappened();
}
}
}
} |
Add tests for Sha256 class | using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Algorithms
{
public static class Sha256Tests
{
public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
[Fact]
public static void HashEmpty()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = a.Hash(ReadOnlySpan<byte>.Empty);
Assert.Equal(a.DefaultHashSize, actual.Length);
Assert.Equal(expected, actual);
}
[Fact]
public static void HashEmptyWithSpan()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = new byte[expected.Length];
a.Hash(ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
}
}
| using System;
using NSec.Cryptography;
using Xunit;
namespace NSec.Tests.Algorithms
{
public static class Sha256Tests
{
public static readonly string HashOfEmpty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
[Fact]
public static void Properties()
{
var a = new Sha256();
Assert.Equal(32, a.MinHashSize);
Assert.True(a.DefaultHashSize >= a.MinHashSize);
Assert.True(a.MaxHashSize >= a.DefaultHashSize);
Assert.Equal(32, a.MaxHashSize);
}
[Fact]
public static void HashEmpty()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = a.Hash(ReadOnlySpan<byte>.Empty);
Assert.Equal(a.DefaultHashSize, actual.Length);
Assert.Equal(expected, actual);
}
[Fact]
public static void HashEmptyWithSize()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = a.Hash(ReadOnlySpan<byte>.Empty, a.MaxHashSize);
Assert.Equal(a.MaxHashSize, actual.Length);
Assert.Equal(expected, actual);
}
[Fact]
public static void HashEmptyWithSpan()
{
var a = new Sha256();
var expected = HashOfEmpty.DecodeHex();
var actual = new byte[expected.Length];
a.Hash(ReadOnlySpan<byte>.Empty, actual);
Assert.Equal(expected, actual);
}
}
}
|
Fix for 'everyone' account in other languages | namespace Nancy.Hosting.Self
{
/// <summary>
/// Configuration for automatic url reservation creation
/// </summary>
public class UrlReservations
{
public UrlReservations()
{
this.CreateAutomatically = false;
this.User = "Everyone";
}
/// <summary>
/// Gets or sets a value indicating whether url reservations
/// are automatically created when necessary.
/// Defaults to false.
/// </summary>
public bool CreateAutomatically { get; set; }
/// <summary>
/// Gets or sets a value for the user to use to create the url reservations for.
/// Defaults to the "Everyone" group.
/// </summary>
public string User { get; set; }
}
} | namespace Nancy.Hosting.Self
{
using System;
using System.Security.Principal;
/// <summary>
/// Configuration for automatic url reservation creation
/// </summary>
public class UrlReservations
{
private const string EveryoneAccountName = "Everyone";
private static readonly IdentityReference EveryoneReference =
new SecurityIdentifier(WellKnownSidType.WorldSid, null);
public UrlReservations()
{
this.CreateAutomatically = false;
this.User = GetEveryoneAccountName();
}
/// <summary>
/// Gets or sets a value indicating whether url reservations
/// are automatically created when necessary.
/// Defaults to false.
/// </summary>
public bool CreateAutomatically { get; set; }
/// <summary>
/// Gets or sets a value for the user to use to create the url reservations for.
/// Defaults to the "Everyone" group.
/// </summary>
public string User { get; set; }
private static string GetEveryoneAccountName()
{
try
{
var account = EveryoneReference.Translate(typeof(NTAccount)) as NTAccount;
if (account != null)
{
return account.Value;
}
return EveryoneAccountName;
}
catch (Exception)
{
return EveryoneAccountName;
}
}
}
} |
Add code documentation to the UIntPalmValue | using System;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
internal class UIntPalmValue : IPalmValue<uint>
{
public int Length { get; }
public UIntPalmValue(int length)
{
Guard.NotNegative(length, nameof(length));
this.Length = length;
}
public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
Array.Reverse(data);
Array.Resize(ref data, 4);
return BitConverter.ToUInt32(data, 0);
}
public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
{
Guard.NotNull(writer, nameof(writer));
var data = BitConverter.GetBytes(value);
Array.Reverse(data);
Array.Resize(ref data, this.Length);
await writer.WriteAsync(data);
}
}
} | using System;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
/// <summary>
/// Represents a <see cref="uint"/> value inside a palm database.
/// </summary>
internal class UIntPalmValue : IPalmValue<uint>
{
/// <summary>
/// Gets the length of this uint block.
/// </summary>
public int Length { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UIntPalmValue"/> class.
/// </summary>
/// <param name="length">The length of the uint block.</param>
public UIntPalmValue(int length)
{
Guard.NotNegative(length, nameof(length));
this.Length = length;
}
/// <summary>
/// Reads the <see cref="uint"/> using the specified <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The reader.</param>
public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
Array.Reverse(data);
Array.Resize(ref data, 4);
return BitConverter.ToUInt32(data, 0);
}
/// <summary>
/// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">The value.</param>
public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
{
Guard.NotNull(writer, nameof(writer));
var data = BitConverter.GetBytes(value);
Array.Reverse(data);
Array.Resize(ref data, this.Length);
await writer.WriteAsync(data);
}
}
} |
Adjust testcase sizing to match editor | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Screens.Compose;
using OpenTK;
namespace osu.Game.Tests.Visual
{
public class TestCaseBeatDivisorControl : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) };
[BackgroundDependencyLoader]
private void load()
{
Child = new BeatDivisorControl(new BindableBeatDivisor())
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Y = -200,
Size = new Vector2(100, 110)
};
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Screens.Edit.Screens.Compose;
using OpenTK;
namespace osu.Game.Tests.Visual
{
public class TestCaseBeatDivisorControl : OsuTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(BindableBeatDivisor) };
[BackgroundDependencyLoader]
private void load()
{
Child = new BeatDivisorControl(new BindableBeatDivisor())
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(90, 90)
};
}
}
}
|
Use AllowNull for appropriate parameters | using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using NullGuard;
namespace GitHub.VisualStudio.Converters
{
/// <summary>
/// Convert a count to visibility based on the following rule:
/// * If count == 0, return Visibility.Visible
/// * If count > 0, return Visibility.Collapsed
/// </summary>
public class CountToVisibilityConverter : IValueConverter
{
public object Convert([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
{
return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack([AllowNull] object value, [AllowNull] Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
{
return null;
}
}
}
| using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using NullGuard;
namespace GitHub.VisualStudio.Converters
{
/// <summary>
/// Convert a count to visibility based on the following rule:
/// * If count == 0, return Visibility.Visible
/// * If count > 0, return Visibility.Collapsed
/// </summary>
public class CountToVisibilityConverter : IValueConverter
{
public object Convert(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
{
return ((int)value == 0) ? Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType, [AllowNull] object parameter, [AllowNull] CultureInfo culture)
{
return null;
}
}
}
|
Create ReplayPlayer using Score from the dummy RulesetContainer | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual
{
[Description("Player instantiated with a replay.")]
public class TestCaseReplay : TestCasePlayer
{
protected override Player CreatePlayer(Ruleset ruleset)
{
// We create a dummy RulesetContainer just to get the replay - we don't want to use mods here
// to simulate setting a replay rather than having the replay already set for us
Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() });
var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value);
// Reset the mods
Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay));
return new ReplayPlayer(new Score { Replay = dummyRulesetContainer.ReplayScore.Replay });
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.ComponentModel;
using System.Linq;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Mods;
using osu.Game.Screens.Play;
namespace osu.Game.Tests.Visual
{
[Description("Player instantiated with a replay.")]
public class TestCaseReplay : TestCasePlayer
{
protected override Player CreatePlayer(Ruleset ruleset)
{
// We create a dummy RulesetContainer just to get the replay - we don't want to use mods here
// to simulate setting a replay rather than having the replay already set for us
Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Concat(new[] { ruleset.GetAutoplayMod() });
var dummyRulesetContainer = ruleset.CreateRulesetContainerWith(Beatmap.Value);
// Reset the mods
Beatmap.Value.Mods.Value = Beatmap.Value.Mods.Value.Where(m => !(m is ModAutoplay));
return new ReplayPlayer(dummyRulesetContainer.ReplayScore);
}
}
}
|
Add Custom Work Log field | using System;
using Newtonsoft.Json;
namespace AxosoftAPI.NET.Models
{
public class WorkLog : BaseModel
{
[JsonProperty("project")]
public Project Project { get; set; }
[JsonProperty("release")]
public Release Release { get; set; }
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("work_done")]
public DurationUnit WorkDone { get; set; }
[JsonProperty("item")]
public Item Item { get; set; }
[JsonProperty("work_log_type")]
public WorkLogType WorklogType { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("date_time")]
public DateTime? DateTime { get; set; }
}
}
| using System;
using Newtonsoft.Json;
using System.Collections.Generic;
namespace AxosoftAPI.NET.Models
{
public class WorkLog : BaseModel
{
[JsonProperty("project")]
public Project Project { get; set; }
[JsonProperty("release")]
public Release Release { get; set; }
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("work_done")]
public DurationUnit WorkDone { get; set; }
[JsonProperty("item")]
public Item Item { get; set; }
[JsonProperty("work_log_type")]
public WorkLogType WorklogType { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("date_time")]
public DateTime? DateTime { get; set; }
[JsonProperty("custom_fields")]
public IDictionary<string, object> CustomFields { get; set; }
}
}
|
Change time format for log entry | using System;
namespace DevelopmentInProgress.DipState
{
public class LogEntry
{
public LogEntry(string message)
{
Message = message;
Time = DateTime.Now;
}
public DateTime Time { get; private set; }
public string Message { get; private set; }
public override string ToString()
{
return String.Format("{0} {1}", Time.ToString("yy-mm-dd hhmmss"), Message);
}
}
}
| using System;
namespace DevelopmentInProgress.DipState
{
public class LogEntry
{
public LogEntry(string message)
{
Message = message;
Time = DateTime.Now;
}
public DateTime Time { get; private set; }
public string Message { get; private set; }
public override string ToString()
{
return String.Format("{0} {1}", Time.ToString("yyyy-MM-dd HH:mm:ss"), Message);
}
}
}
|
Use invariant culture when parsing floats. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SGEnviro.Utilities
{
public class NumberParseException : Exception
{
public NumberParseException(string message) { }
}
public class Parsing
{
public static void ParseFloatOrThrowException(string value, out float destination, string message)
{
if (!float.TryParse(value, out destination))
{
throw new Exception(message);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace SGEnviro.Utilities
{
public class NumberParseException : Exception
{
public NumberParseException(string message) { }
}
public class Parsing
{
public static void ParseFloatOrThrowException(string value, out float destination, string message)
{
if (!float.TryParse(value, NumberStyles.Any, CultureInfo.InvariantCulture, out destination))
{
throw new Exception(message);
}
}
}
}
|
Make option parsing output prettier | using System;
using System.Linq;
using Pixie;
using Pixie.Markup;
using Pixie.Options;
using Pixie.Terminal;
namespace ParseOptions
{
public static class Program
{
private static readonly FlagOption syntaxOnlyFlag = new FlagOption(
OptionForm.Short("fsyntax-only"),
OptionForm.Short("fno-syntax-only"),
false);
private static OptionSet parsedOptions;
public static void Main(string[] args)
{
// First, acquire a terminal log. You should acquire
// a log once and then re-use it in your application.
var log = TerminalLog.Acquire();
var allOptions = new Option[]
{
syntaxOnlyFlag
};
var parser = new GnuOptionSetParser(
allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]);
parsedOptions = parser.Parse(args, log);
foreach (var item in allOptions)
{
log.Log(
new LogEntry(
Severity.Info,
new BulletedList(
allOptions
.Select<Option, MarkupNode>(TypesetParsedOption)
.ToArray<MarkupNode>(),
true)));
}
}
private static MarkupNode TypesetParsedOption(Option opt)
{
return new Sequence(
new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold),
new Text(": "),
new Text(parsedOptions.GetValue<object>(opt).ToString()));
}
}
}
| using System;
using System.Linq;
using Pixie;
using Pixie.Markup;
using Pixie.Options;
using Pixie.Terminal;
using Pixie.Transforms;
namespace ParseOptions
{
public static class Program
{
private static readonly FlagOption syntaxOnlyFlag = new FlagOption(
OptionForm.Short("fsyntax-only"),
OptionForm.Short("fno-syntax-only"),
false);
private static OptionSet parsedOptions;
public static void Main(string[] args)
{
// First, acquire a terminal log. You should acquire
// a log once and then re-use it in your application.
ILog log = TerminalLog.Acquire();
log = new TransformLog(
log,
new Func<LogEntry, LogEntry>[]
{
MakeDiagnostic
});
var allOptions = new Option[]
{
syntaxOnlyFlag
};
var parser = new GnuOptionSetParser(
allOptions, syntaxOnlyFlag, syntaxOnlyFlag.PositiveForms[0]);
parsedOptions = parser.Parse(args, log);
foreach (var item in allOptions)
{
log.Log(
new LogEntry(
Severity.Info,
new BulletedList(
allOptions
.Select<Option, MarkupNode>(TypesetParsedOption)
.ToArray<MarkupNode>(),
true)));
}
}
private static MarkupNode TypesetParsedOption(Option opt)
{
return new Sequence(
new DecorationSpan(new Text(opt.Forms[0].ToString()), TextDecoration.Bold),
new Text(": "),
new Text(parsedOptions.GetValue<object>(opt).ToString()));
}
private static LogEntry MakeDiagnostic(LogEntry entry)
{
return DiagnosticExtractor.Transform(entry, new Text("program"));
}
}
}
|
Fix for attempting to permute singleton Points objects. | using System;
using System.Collections.Generic;
namespace Group.Net.Groups
{
public class PermutationGroup<T> where T : IComparable<T>
{
protected readonly IList<IList<int>> Generators;
public int GeneratorCount
{
get { return Generators.Count; }
}
public PermutationGroup(IList<IList<int>> generators)
{
Generators = generators;
}
public Points<T> Apply(int index, Points<T> points)
{
var permutedPoints = new Points<T>(points);
for (var i = 0; i < Generators[index].Count - 1; ++i)
permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]];
permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]];
return permutedPoints;
}
}
}
| using System;
using System.Collections.Generic;
namespace Group.Net.Groups
{
public class PermutationGroup<T> where T : IComparable<T>
{
protected readonly IList<IList<int>> Generators;
public int GeneratorCount
{
get { return Generators.Count; }
}
public PermutationGroup(IList<IList<int>> generators)
{
Generators = generators;
}
public Points<T> Apply(int index, Points<T> points)
{
var permutedPoints = new Points<T>(points);
if (permutedPoints.Count == 1)
return permutedPoints;
for (var i = 0; i < Generators[index].Count - 1; ++i)
permutedPoints[Generators[index][i + 1]] = points[Generators[index][i]];
permutedPoints[Generators[index][0]] = points[Generators[index][Generators[index].Count - 1]];
return permutedPoints;
}
}
}
|
Check parameter before actually using it | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Globalization;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Core
{
/// <summary>
/// Extensions for <see cref="IApplicationBuilder"/>
/// </summary>
static class ApplicationBuilderExtensions
{
/// <summary>
/// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s
/// </summary>
/// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param>
public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder) => applicationBuilder.Use(async (context, next) =>
{
if (applicationBuilder == null)
throw new ArgumentNullException(nameof(applicationBuilder));
try
{
await next().ConfigureAwait(false);
}
catch (DbUpdateException e)
{
await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext
{
HttpContext = context
}).ConfigureAwait(false);
}
});
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Globalization;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Host.Core
{
/// <summary>
/// Extensions for <see cref="IApplicationBuilder"/>
/// </summary>
static class ApplicationBuilderExtensions
{
/// <summary>
/// Return a <see cref="ConflictObjectResult"/> for <see cref="DbUpdateException"/>s
/// </summary>
/// <param name="applicationBuilder">The <see cref="IApplicationBuilder"/> to configure</param>
public static void UseDbConflictHandling(this IApplicationBuilder applicationBuilder)
{
if (applicationBuilder == null)
throw new ArgumentNullException(nameof(applicationBuilder));
applicationBuilder.Use(async (context, next) =>
{
try
{
await next().ConfigureAwait(false);
}
catch (DbUpdateException e)
{
await new ConflictObjectResult(new ErrorMessage { Message = String.Format(CultureInfo.InvariantCulture, "A database conflict has occurred: {0}", (e.InnerException ?? e).Message) }).ExecuteResultAsync(new ActionContext
{
HttpContext = context
}).ConfigureAwait(false);
}
});
}
}
}
|
Return IUnityContainer from unity extension methods | // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using Microsoft.Practices.Unity;
namespace EOLib
{
public static class UnityExtensions
{
public static void RegisterInstance<T>(this IUnityContainer container)
{
container.RegisterType<T>(new ContainerControlledLifetimeManager());
}
public static void RegisterInstance<T, U>(this IUnityContainer container) where U : T
{
container.RegisterType<T, U>(new ContainerControlledLifetimeManager());
}
public static void RegisterVaried<T, U>(this IUnityContainer container) where U : T
{
RegisterEnumerableIfNeeded<T, U>(container);
container.RegisterType<T, U>(typeof(U).Name);
}
public static void RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T
{
RegisterEnumerableIfNeeded<T, U>(container);
container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager());
}
private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T
{
if (!container.IsRegistered(typeof(IEnumerable<T>)))
{
container.RegisterType<IEnumerable<T>>(
new ContainerControlledLifetimeManager(),
new InjectionFactory(c => c.ResolveAll<T>()));
}
}
}
}
| // Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System.Collections.Generic;
using Microsoft.Practices.Unity;
namespace EOLib
{
public static class UnityExtensions
{
public static IUnityContainer RegisterInstance<T>(this IUnityContainer container)
{
return container.RegisterType<T>(new ContainerControlledLifetimeManager());
}
public static IUnityContainer RegisterInstance<T, U>(this IUnityContainer container) where U : T
{
return container.RegisterType<T, U>(new ContainerControlledLifetimeManager());
}
public static IUnityContainer RegisterVaried<T, U>(this IUnityContainer container) where U : T
{
RegisterEnumerableIfNeeded<T, U>(container);
return container.RegisterType<T, U>(typeof(U).Name);
}
public static IUnityContainer RegisterInstanceVaried<T, U>(this IUnityContainer container) where U : T
{
RegisterEnumerableIfNeeded<T, U>(container);
return container.RegisterType<T, U>(typeof(U).Name, new ContainerControlledLifetimeManager());
}
private static void RegisterEnumerableIfNeeded<T, U>(IUnityContainer container) where U : T
{
if (!container.IsRegistered(typeof(IEnumerable<T>)))
{
container.RegisterType<IEnumerable<T>>(
new ContainerControlledLifetimeManager(),
new InjectionFactory(c => c.ResolveAll<T>()));
}
}
}
}
|
Add puncts key value in context menu | using System.Windows.Input;
namespace RegEditor
{
public static class ComandsContextMenu
{
public static readonly RoutedUICommand CreateKey = new RoutedUICommand(
"Create Key", "CreateKey", typeof(MainWindow));
public static readonly RoutedUICommand UpdateKey = new RoutedUICommand(
"Update Key", "UpdateKey", typeof(MainWindow));
public static readonly RoutedUICommand DeleteKey = new RoutedUICommand(
"Delete Key", "DeleteKey", typeof(MainWindow));
}
}
| using System.Windows.Input;
namespace RegEditor
{
public static class ComandsContextMenu
{
public static readonly RoutedUICommand CreateKey = new RoutedUICommand(
"Create Key", "CreateKey", typeof(MainWindow));
public static readonly RoutedUICommand UpdateKey = new RoutedUICommand(
"Update Key", "UpdateKey", typeof(MainWindow));
public static readonly RoutedUICommand DeleteKey = new RoutedUICommand(
"Delete Key", "DeleteKey", typeof(MainWindow));
public static readonly RoutedUICommand DeleteKeyValue = new RoutedUICommand(
"Delete Key Value", "DeleteKeyValue", typeof(MainWindow));
public static readonly RoutedUICommand CreateKeyValue = new RoutedUICommand(
"Delete Key Value", "DeleteKeyValue", typeof(MainWindow));
public static readonly RoutedUICommand UpdateKeyValue = new RoutedUICommand(
"Update Key Value", "UpdateKeyValue", typeof(MainWindow));
}
}
|
Add param name to better readability | using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
{
public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base("")
{
Transaction = transaction;
UiConfig = uiConfig;
Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
}
public TransactionDetailsViewModel Transaction { get; }
public UiConfig UiConfig { get; }
public override void OnOpen(CompositeDisposable disposables)
{
UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
.DisposeWith(disposables);
base.OnOpen(disposables);
}
}
}
| using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using ReactiveUI;
using Splat;
using WalletWasabi.Gui.Controls.TransactionDetails.ViewModels;
using WalletWasabi.Gui.ViewModels;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class TransactionInfoTabViewModel : WasabiDocumentTabViewModel
{
public TransactionInfoTabViewModel(TransactionDetailsViewModel transaction, UiConfig uiConfig) : base(title: "")
{
Transaction = transaction;
UiConfig = uiConfig;
Title = $"Transaction ({transaction.TransactionId[0..10]}) Details";
}
public TransactionDetailsViewModel Transaction { get; }
public UiConfig UiConfig { get; }
public override void OnOpen(CompositeDisposable disposables)
{
UiConfig.WhenAnyValue(x => x.LurkingWifeMode)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x => Transaction.RaisePropertyChanged(nameof(Transaction.TransactionId)))
.DisposeWith(disposables);
base.OnOpen(disposables);
}
}
}
|
Fix mania editor null reference | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint
{
public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;
[Resolved]
private IScrollingInfo scrollingInfo { get; set; }
protected ManiaSelectionBlueprint(DrawableHitObject drawableObject)
: base(drawableObject)
{
RelativeSizeAxes = Axes.None;
}
protected override void Update()
{
base.Update();
Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
}
public override void Show()
{
DrawableObject.AlwaysAlive = true;
base.Show();
}
public override void Hide()
{
DrawableObject.AlwaysAlive = false;
base.Hide();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.UI.Scrolling;
using osuTK;
namespace osu.Game.Rulesets.Mania.Edit.Blueprints
{
public abstract class ManiaSelectionBlueprint : OverlaySelectionBlueprint
{
public new DrawableManiaHitObject DrawableObject => (DrawableManiaHitObject)base.DrawableObject;
[Resolved]
private IScrollingInfo scrollingInfo { get; set; }
// Overriding the base because this method is called right after `Column` is changed and `DrawableObject` is not yet loaded and Parent is not set.
public override Vector2 GetInstantDelta(Vector2 screenSpacePosition) => Parent.ToLocalSpace(screenSpacePosition) - Position;
protected ManiaSelectionBlueprint(DrawableHitObject drawableObject)
: base(drawableObject)
{
RelativeSizeAxes = Axes.None;
}
protected override void Update()
{
base.Update();
Position = Parent.ToLocalSpace(DrawableObject.ToScreenSpace(Vector2.Zero));
}
public override void Show()
{
DrawableObject.AlwaysAlive = true;
base.Show();
}
public override void Hide()
{
DrawableObject.AlwaysAlive = false;
base.Hide();
}
}
}
|
Use SongBar height instead of hard-coded dimensions | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Tournament.Components;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo
{
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[]
{
new TournamentLogo(),
new TourneyVideo("showcase")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
new Box
{
// chroma key area for stable gameplay
Name = "chroma",
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
Height = 695,
Width = 1366,
Colour = new Color4(0, 255, 0, 255),
}
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tournament.Components;
using osu.Framework.Graphics.Shapes;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens.Showcase
{
public class ShowcaseScreen : BeatmapInfoScreen, IProvideVideo
{
[BackgroundDependencyLoader]
private void load()
{
AddRangeInternal(new Drawable[]
{
new TournamentLogo(),
new TourneyVideo("showcase")
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
new Container
{
Padding = new MarginPadding { Bottom = SongBar.HEIGHT },
RelativeSizeAxes = Axes.Both,
Child = new Box
{
// chroma key area for stable gameplay
Name = "chroma",
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Both,
Colour = new Color4(0, 255, 0, 255),
}
}
});
}
}
}
|
Fix issue with mismatched parameter on AccountLinking Api | using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Alexa.NET.Management.AccountLinking;
using Refit;
namespace Alexa.NET.Management.Internals
{
[Headers("Authorization: Bearer")]
public interface IClientAccountLinkingApi
{
[Get("/skills/{skilIid}/accountLinkingClient")]
Task<AccountLinkInformation> Get(string skillId);
[Put("/skills/{skillId}/accountLinkingClient")]
Task Update(string skillId, [Body]AccountLinkUpdate information);
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Alexa.NET.Management.AccountLinking;
using Refit;
namespace Alexa.NET.Management.Internals
{
[Headers("Authorization: Bearer")]
public interface IClientAccountLinkingApi
{
[Get("/skills/{skillId}/accountLinkingClient")]
Task<AccountLinkInformation> Get(string skillId);
[Put("/skills/{skillId}/accountLinkingClient")]
Task Update(string skillId, [Body]AccountLinkUpdate information);
}
}
|
Update version to at least above published version on nuget.org | using System.Reflection;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
| using System.Reflection;
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
[assembly: AssemblyInformationalVersion("2.1.0")]
|
Raise exception when the kind of a DateTime is unspecified | using System;
using MessageBird.Utilities;
using Newtonsoft.Json;
namespace MessageBird.Json.Converters
{
class RFC3339DateTimeConverter : JsonConverter
{
private const string Format = "yyyy-MM-dd'T'HH:mm:ssK";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
var dateTime = (DateTime)value;
writer.WriteValue(dateTime.ToString(Format));
}
else
{
throw new JsonSerializationException("Expected value of type 'DateTime'.");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
}
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t == typeof(DateTime);
}
}
}
| using System;
using MessageBird.Utilities;
using Newtonsoft.Json;
namespace MessageBird.Json.Converters
{
class RFC3339DateTimeConverter : JsonConverter
{
private const string Format = "yyyy-MM-dd'T'HH:mm:ssK";
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is DateTime)
{
var dateTime = (DateTime)value;
if (dateTime.Kind == DateTimeKind.Unspecified)
{
throw new JsonSerializationException("Cannot convert date time with an unspecified kind");
}
string convertedDateTime = dateTime.ToString(Format);
writer.WriteValue(convertedDateTime);
}
else
{
throw new JsonSerializationException("Expected value of type 'DateTime'.");
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (reader.TokenType == JsonToken.Date)
{
return reader.Value;
}
throw new JsonSerializationException(String.Format("Unexpected token '{0}' when parsing date.", reader.TokenType));
}
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullable(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t == typeof(DateTime);
}
}
}
|
Save loaded textures in map. | using System;
using System.Collections.Generic;
using Engine.cgimin.texture;
using System.IO;
namespace Mugo
{
public static class TextureLoader
{
private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>();
public static TextureHolder Load(String path)
{
TextureHolder texture;
if(!textures.TryGetValue(path, out texture))
{
var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path));
var normalMapId = 0;
if (File.Exists(normalTexturePath)) {
normalMapId = TextureManager.LoadTexture(normalTexturePath);
}
texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId);
}
return texture;
}
}
public class TextureHolder
{
public TextureHolder(int textureId, int normalMapId)
{
TextureId = textureId;
NormalMapId = normalMapId;
}
public int TextureId {
get;
private set;
}
public int NormalMapId {
get;
private set;
}
}
}
| using System;
using System.Collections.Generic;
using Engine.cgimin.texture;
using System.IO;
namespace Mugo
{
public static class TextureLoader
{
private static readonly Dictionary<String, TextureHolder> textures = new Dictionary<string, TextureHolder>();
public static TextureHolder Load(String path)
{
TextureHolder texture;
if(!textures.TryGetValue(path, out texture))
{
var normalTexturePath = Path.ChangeExtension(path, "normals" + Path.GetExtension(path));
var normalMapId = 0;
if (File.Exists(normalTexturePath)) {
normalMapId = TextureManager.LoadTexture(normalTexturePath);
}
texture = new TextureHolder(TextureManager.LoadTexture(path), normalMapId);
textures[path] = texture;
}
return texture;
}
}
public class TextureHolder
{
public TextureHolder(int textureId, int normalMapId)
{
TextureId = textureId;
NormalMapId = normalMapId;
}
public int TextureId {
get;
private set;
}
public int NormalMapId {
get;
private set;
}
}
}
|
Add description to default Compliance slope | namespace DynamixelServo.Driver
{
public enum ComplianceSlope
{
S2 = 2,
S4 = 4,
S8 = 8,
S16 = 16,
S32 = 32,
Default = 32,
S64 = 64,
S128 = 128
}
}
| namespace DynamixelServo.Driver
{
public enum ComplianceSlope
{
S2 = 2,
S4 = 4,
S8 = 8,
S16 = 16,
S32 = 32,
/// <summary>
/// Same as S32
/// </summary>
Default = 32,
S64 = 64,
S128 = 128
}
}
|
Use env vars for test client | using System;
using Recurly;
using Recurly.Resources;
namespace RecurlyTestRig
{
class Program
{
static void Main(string[] args)
{
var client = new Recurly.Client("subdomain-client-lib-test", "382c053318a04154905c4d27a48f74a6");
var site = client.GetSite("subdomain-client-lib-test");
Console.WriteLine(site.Id);
var account = client.GetAccount("subdomain-client-lib-test", "code-benjamin-du-monde");
Console.WriteLine(account.CreatedAt);
var createAccount = new AccountCreate() {
Code = "abcsdaskdljsda",
Username = "myuser",
Address = new Address() {
City = "New Orleans",
Street1 = "1 Canal St.",
Region = "LA",
Country = "US",
PostalCode = "70115"
}
};
var createdAccount = client.CreateAccount("subdomain-client-lib-test", createAccount);
Console.WriteLine(createdAccount.CreatedAt);
try {
var nonexistentAccount = client.GetAccount("subdomain-client-lib-test", "idontexist");
} catch (Recurly.ApiError err) {
Console.WriteLine(err);
}
}
}
}
| using System;
using Recurly;
using Recurly.Resources;
namespace RecurlyTestRig
{
class Program
{
static void Main(string[] args)
{
try {
var subdomain = Environment.GetEnvironmentVariable("RECURLY_SUBDOMAIN");
var apiKey = Environment.GetEnvironmentVariable("RECURLY_API_KEY");
var client = new Recurly.Client(subdomain, apiKey);
var site = client.GetSite(subdomain);
Console.WriteLine(site.Id);
var account = client.GetAccount(subdomain, "code-benjamin-du-monde");
Console.WriteLine(account.CreatedAt);
var createAccount = new CreateAccount() {
Code = "abcsdaskdljsda",
Username = "myuser",
Address = new Address() {
City = "New Orleans",
Street1 = "1 Canal St.",
Region = "LA",
Country = "US",
PostalCode = "70115"
}
};
var createdAccount = client.CreateAccount(subdomain, createAccount);
Console.WriteLine(createdAccount.CreatedAt);
try {
var nonexistentAccount = client.GetAccount(subdomain, "idontexist");
} catch (Recurly.ApiError err) {
Console.WriteLine(err);
}
} catch (Recurly.ApiError err) {
Console.WriteLine(err);
}
}
}
}
|
Define a property for the connection string | using System.Collections.Generic;
using MongoDB.Driver;
namespace RapidCore.Mongo.Testing
{
/// <summary>
/// Base class for functional tests that need access to
/// a Mongo database.
///
/// It provides simple helpers that we use ourselves.
/// </summary>
public abstract class MongoConnectedTestBase
{
private MongoClient lowLevelClient;
private IMongoDatabase db;
private bool isConnected = false;
protected string GetDbName()
{
return GetType().Name;
}
protected void Connect(string connectionString = "mongodb://localhost:27017")
{
lowLevelClient = new MongoClient(connectionString);
lowLevelClient.DropDatabase(GetDbName());
db = lowLevelClient.GetDatabase(GetDbName());
}
protected MongoClient GetClient()
{
if (!isConnected)
{
Connect();
isConnected = true;
}
return lowLevelClient;
}
protected IMongoDatabase GetDb()
{
return GetClient().GetDatabase(GetDbName());
}
protected void EnsureEmptyCollection(string collectionName)
{
GetDb().DropCollection(collectionName);
}
protected void Insert<TDocument>(string collectionName, TDocument doc)
{
GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc);
}
protected IList<TDocument> GetAll<TDocument>(string collectionName)
{
return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList();
}
}
} | using System.Collections.Generic;
using MongoDB.Driver;
namespace RapidCore.Mongo.Testing
{
/// <summary>
/// Base class for functional tests that need access to
/// a Mongo database.
///
/// It provides simple helpers that we use ourselves.
/// </summary>
public abstract class MongoConnectedTestBase
{
private MongoClient lowLevelClient;
private IMongoDatabase db;
private bool isConnected = false;
protected string ConnectionString { get; set; } = "mongodb://localhost:27017";
protected string GetDbName()
{
return GetType().Name;
}
protected void Connect()
{
if (!isConnected)
{
lowLevelClient = new MongoClient(ConnectionString);
lowLevelClient.DropDatabase(GetDbName());
db = lowLevelClient.GetDatabase(GetDbName());
isConnected = true;
}
}
protected MongoClient GetClient()
{
Connect();
return lowLevelClient;
}
protected IMongoDatabase GetDb()
{
return GetClient().GetDatabase(GetDbName());
}
protected void EnsureEmptyCollection(string collectionName)
{
GetDb().DropCollection(collectionName);
}
protected void Insert<TDocument>(string collectionName, TDocument doc)
{
GetDb().GetCollection<TDocument>(collectionName).InsertOne(doc);
}
protected IList<TDocument> GetAll<TDocument>(string collectionName)
{
return GetDb().GetCollection<TDocument>(collectionName).Find(filter => true).ToList();
}
}
} |
Fix ordering of connection sections | using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;
namespace GitHub.VisualStudio.TeamExplorer.Connect
{
[TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 10)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class GitHubConnectSection1 : GitHubConnectSection
{
public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";
[ImportingConstructor]
public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
: base(apiFactory, holder, manager, 1)
{
}
}
}
| using GitHub.Api;
using GitHub.Models;
using GitHub.Services;
using Microsoft.TeamFoundation.Controls;
using System.ComponentModel.Composition;
namespace GitHub.VisualStudio.TeamExplorer.Connect
{
[TeamExplorerSection(GitHubConnectSection1Id, TeamExplorerPageIds.Connect, 11)]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class GitHubConnectSection1 : GitHubConnectSection
{
public const string GitHubConnectSection1Id = "519B47D3-F2A9-4E19-8491-8C9FA25ABE91";
[ImportingConstructor]
public GitHubConnectSection1(ISimpleApiClientFactory apiFactory, ITeamExplorerServiceHolder holder, IConnectionManager manager)
: base(apiFactory, holder, manager, 1)
{
}
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DynamicProxy2")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Extras.Tests.DynamicProxy2")]
|
Use TestID for N5 test description lookup | using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Testing;
using Arkivverket.Arkade.Core.Util;
using Serilog;
namespace Arkivverket.Arkade.Core.Base.Noark5
{
public abstract class Noark5BaseTest : IArkadeTest
{
private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
protected readonly Stopwatch Stopwatch = new Stopwatch();
public abstract TestId GetId();
public abstract string GetName();
public abstract TestType GetTestType();
public string GetDescription()
{
var description = Noark5TestDescriptions.ResourceManager.GetObject(GetName()) as string;
if (description == null)
{
Log.Debug($"Missing description of Noark5Test: {GetType().FullName}");
}
return description;
}
public TestRun GetTestRun()
{
Stopwatch.Start();
List<TestResult> testResults = GetTestResults();
Stopwatch.Stop();
return new TestRun(this)
{
Results = testResults,
TestDuration = Stopwatch.ElapsedMilliseconds
};
}
protected abstract List<TestResult> GetTestResults();
public int CompareTo(object obj)
{
var arkadeTest = (IArkadeTest) obj;
return GetId().CompareTo(arkadeTest.GetId());
}
}
}
| using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using Arkivverket.Arkade.Core.Resources;
using Arkivverket.Arkade.Core.Testing;
using Arkivverket.Arkade.Core.Util;
using Serilog;
namespace Arkivverket.Arkade.Core.Base.Noark5
{
public abstract class Noark5BaseTest : IArkadeTest
{
private static readonly ILogger Log = Serilog.Log.ForContext(MethodBase.GetCurrentMethod().DeclaringType);
protected readonly Stopwatch Stopwatch = new Stopwatch();
public abstract TestId GetId();
public abstract string GetName();
public abstract TestType GetTestType();
public string GetDescription()
{
var description = Noark5TestDescriptions.ResourceManager.GetObject(GetId().ToString()) as string;
if (description == null)
{
Log.Debug($"Missing description of Noark 5 test: {GetId()}");
}
return description;
}
public TestRun GetTestRun()
{
Stopwatch.Start();
List<TestResult> testResults = GetTestResults();
Stopwatch.Stop();
return new TestRun(this)
{
Results = testResults,
TestDuration = Stopwatch.ElapsedMilliseconds
};
}
protected abstract List<TestResult> GetTestResults();
public int CompareTo(object obj)
{
var arkadeTest = (IArkadeTest) obj;
return GetId().CompareTo(arkadeTest.GetId());
}
}
}
|
Update to remove WhistInfo constructor call | // Program.cs
// <copyright file="Program.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using CardsLibrary;
namespace ConsoleTesting
{
/// <summary>
/// The main program (for testing at the moment).
/// </summary>
public class Program
{
/// <summary>
/// The main entry point for the program.
/// </summary>
/// <param name="args"> Any arguments/commands that the program is run/compiled with. </param>
public static void Main(string[] args)
{
List<Card> deck = CardFactory.PopulateDeck(true);
List<CardGames.Whist.ConsolePlayer> players = new List<CardGames.Whist.ConsolePlayer>();
Card[][] tempPlayers = CardFactory.Deal(ref deck, 2, 7);
players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[0]));
players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[1]));
CardGames.Whist.WhistInfo gameInfo = new CardGames.Whist.WhistInfo(new List<Card>(), Suit.Clubs, Suit.Null);
players[0].MakeMove(gameInfo);
Console.WriteLine();
Console.WriteLine();
players[1].MakeMove(gameInfo);
}
}
}
| // Program.cs
// <copyright file="Program.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using CardsLibrary;
namespace ConsoleTesting
{
/// <summary>
/// The main program (for testing at the moment).
/// </summary>
public class Program
{
/// <summary>
/// The main entry point for the program.
/// </summary>
/// <param name="args"> Any arguments/commands that the program is run/compiled with. </param>
public static void Main(string[] args)
{
List<Card> deck = CardFactory.PopulateDeck(true);
List<CardGames.Whist.ConsolePlayer> players = new List<CardGames.Whist.ConsolePlayer>();
Card[][] tempPlayers = CardFactory.Deal(ref deck, 2, 7);
players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[0]));
players.Add(new CardGames.Whist.ConsolePlayer(tempPlayers[1]));
CardGames.Whist.WhistInfo gameInfo = new CardGames.Whist.WhistInfo();
gameInfo.CardsInPlay = new List<Card>();
gameInfo.Trumps = Suit.Clubs;
gameInfo.FirstSuitLaid = Suit.Null;
players[0].MakeMove(gameInfo);
Console.WriteLine();
Console.WriteLine();
players[1].MakeMove(gameInfo);
}
}
}
|
Call reset before calculating leaderboard | using System.Collections.Generic;
using System.Linq;
using PlayerRank.Scoring;
namespace PlayerRank
{
public class League
{
private readonly List<Game> m_Games = new List<Game>();
public IEnumerable<PlayerScore> GetLeaderBoard(IScoringStrategy scoringStrategy)
{
IList<PlayerScore> leaderBoard = new List<PlayerScore>();
m_Games.Aggregate(leaderBoard, scoringStrategy.UpdateScores);
return leaderBoard;
}
public void RecordGame(Game game)
{
m_Games.Add(game);
}
}
} | using System.Collections.Generic;
using System.Linq;
using PlayerRank.Scoring;
namespace PlayerRank
{
public class League
{
private readonly List<Game> m_Games = new List<Game>();
public IEnumerable<PlayerScore> GetLeaderBoard(IScoringStrategy scoringStrategy)
{
scoringStrategy.Reset();
IList<PlayerScore> leaderBoard = new List<PlayerScore>();
m_Games.Aggregate(leaderBoard, scoringStrategy.UpdateScores);
return leaderBoard;
}
public void RecordGame(Game game)
{
m_Games.Add(game);
}
}
} |
Make the tests pertaining to an empty sources collection pass. | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
throw new NotImplementedException();
}
}
} | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
throw new NotImplementedException();
}
}
} |
Make the tests pertaining to the test case discovery sink being null pass. | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
else if (logger == null)
{
throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
}
throw new NotImplementedException();
}
}
} | namespace NBench.VisualStudio.TestAdapter
{
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
public class NBenchTestDiscoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger logger, ITestCaseDiscoverySink discoverySink)
{
if (sources == null)
{
throw new ArgumentNullException("sources", "The sources collection you have passed in is null. The source collection must be populated.");
}
else if (!sources.Any())
{
throw new ArgumentException("The sources collection you have passed in is empty. The source collection must be populated.", "sources");
}
else if (discoveryContext == null)
{
throw new ArgumentNullException("discoveryContext", "The discovery context you have passed in is null. The discovery context must not be null.");
}
else if (logger == null)
{
throw new ArgumentNullException("logger", "The message logger you have passed in is null. The message logger must not be null.");
}
else if (discoverySink == null)
{
throw new ArgumentNullException(
"discoverySink",
"The test case discovery sink you have passed in is null. The test case discovery sink must not be null.");
}
throw new NotImplementedException();
}
}
} |
Add some more tests for PropertyBuilder.Name | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class PropertyBuilderTest9
{
public static IEnumerable<object[]> Names_TestData()
{
yield return new object[] { "TestName" };
yield return new object[] { "class" };
yield return new object[] { new string('a', short.MaxValue) };
}
[Theory]
[MemberData(nameof(Names_TestData))]
public void Name(string name)
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public);
PropertyBuilder property = type.DefineProperty(name, PropertyAttributes.None, typeof(int), null);
Assert.Equal(name, property.Name);
}
[Fact]
public void Name_InvalidString()
{
// TODO: move into Names_TestData when #7166 is fixed
Name("1A\0\t\v\r\n\n\uDC81\uDC91");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class PropertyBuilderTest9
{
public static IEnumerable<object[]> Names_TestData()
{
yield return new object[] { "TestName" };
yield return new object[] { "\uD800\uDC00" };
yield return new object[] { "привет" };
yield return new object[] { "class" };
yield return new object[] { new string('a', short.MaxValue) };
}
[Theory]
[MemberData(nameof(Names_TestData))]
public void Name(string name)
{
TypeBuilder type = Helpers.DynamicType(TypeAttributes.Class | TypeAttributes.Public);
PropertyBuilder property = type.DefineProperty(name, PropertyAttributes.None, typeof(int), null);
Assert.Equal(name, property.Name);
}
[Fact]
public void Name_InvalidString()
{
// TODO: move into Names_TestData when #7166 is fixed
Name("\uDC00");
Name("\uD800");
Name("1A\0\t\v\r\n\n\uDC81\uDC91");
}
}
}
|
Fix test failure on CI | // 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 PInvoke;
using Xunit;
using static PInvoke.DwmApi;
public class DwmApiFacts
{
[Fact]
public void Flush()
{
DwmFlush().ThrowOnFailure();
}
[Fact]
public void GetColorizationColor()
{
uint colorization;
bool opaqueBlend;
DwmGetColorizationColor(out colorization, out opaqueBlend).ThrowOnFailure();
Assert.NotEqual(colorization, 0u);
}
}
| // 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 PInvoke;
using Xunit;
using static PInvoke.DwmApi;
public class DwmApiFacts
{
[Fact]
public void Flush()
{
HResult hr = DwmFlush();
// Accept success, or "Desktop composition is disabled".
if (hr.AsUInt32 != 0x80263001)
{
hr.ThrowOnFailure();
}
}
[Fact]
public void GetColorizationColor()
{
uint colorization;
bool opaqueBlend;
DwmGetColorizationColor(out colorization, out opaqueBlend).ThrowOnFailure();
}
}
|
Make generate Excel action a button | @model CRP.Controllers.ViewModels.ReportViewModel
@{
ViewBag.Title = "ViewReport";
}
<div class="boundary">
<p>
@Html.ActionLink("Back to Item", "Details", "ItemManagement", null, null, "Reports", new { id = Model.ItemId }, null) |
@Html.ActionLink("Generate Excel Report", "CreateExcelReport", "Excel", new { id = Model.ItemReportId, itemId = Model.ItemId }, null)
</p>
<hr/>
<h2>@Model.ReportName</h2>
<table id="table" class="table table-bordered">
<thead>
<tr>
@foreach (var ch in Model.ColumnNames)
{
<td>@ch</td>
}
</tr>
</thead>
<tbody>
@foreach (var row in Model.RowValues)
{
<tr>
@foreach (var cell in row)
{
<td>@cell</td>
}
</tr>
}
</tbody>
</table>
</div>
@section AdditionalScripts
{
<script type="text/javascript">
$(function() {
$("#table").dataTable({
responsive: true
});
});
</script>
}
| @model CRP.Controllers.ViewModels.ReportViewModel
@{
ViewBag.Title = "ViewReport";
}
<div class="boundary">
<p>
@Html.ActionLink("Generate Excel Report", "CreateExcelReport", "Excel", new { id = Model.ItemReportId, itemId = Model.ItemId }, new { @class = "btn" })
</p>
<p>@Html.ActionLink("Back to Item", "Details", "ItemManagement", null, null, "Reports", new { id = Model.ItemId }, null)</p>
<hr/>
<h2>@Model.ReportName</h2>
<table id="table" class="table table-bordered">
<thead>
<tr>
@foreach (var ch in Model.ColumnNames)
{
<td>@ch</td>
}
</tr>
</thead>
<tbody>
@foreach (var row in Model.RowValues)
{
<tr>
@foreach (var cell in row)
{
<td>@cell</td>
}
</tr>
}
</tbody>
</table>
</div>
@section AdditionalScripts
{
<script type="text/javascript">
$(function() {
$("#table").dataTable({
responsive: true
});
});
</script>
}
|
Remove no longer valid comment | using MbCache.Logic;
namespace MbCache.Configuration
{
/// <summary>
/// Creates the proxy.
/// The implementation of this interface needs a default ctor
/// </summary>
public interface IProxyFactory
{
/// <summary>
/// Called once after this object is instansiated.
/// </summary>
void Initialize(CacheAdapter cache);
/// <summary>
/// Creates the proxy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="configurationForType">The method data.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
T CreateProxy<T>(ConfigurationForType configurationForType, params object[] parameters) where T : class;
/// <summary>
/// Creates the proxy with a specified target.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uncachedComponent"></param>
/// <param name="configurationForType"></param>
/// <returns></returns>
T CreateProxyWithTarget<T>(T uncachedComponent, ConfigurationForType configurationForType) where T : class;
}
} | using MbCache.Logic;
namespace MbCache.Configuration
{
/// <summary>
/// Creates the proxy.
/// </summary>
public interface IProxyFactory
{
/// <summary>
/// Called once after this object is instansiated.
/// </summary>
void Initialize(CacheAdapter cache);
/// <summary>
/// Creates the proxy.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="configurationForType">The method data.</param>
/// <param name="parameters">The parameters.</param>
/// <returns></returns>
T CreateProxy<T>(ConfigurationForType configurationForType, params object[] parameters) where T : class;
/// <summary>
/// Creates the proxy with a specified target.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="uncachedComponent"></param>
/// <param name="configurationForType"></param>
/// <returns></returns>
T CreateProxyWithTarget<T>(T uncachedComponent, ConfigurationForType configurationForType) where T : class;
}
} |
Disable test parallelization to avoid test failures | 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("libgit2sharp.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libgit2sharp.Tests")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("808554a4-f9fd-4035-8ab9-325793c7da51")]
// 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.InteropServices;
using Xunit;
// 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("libgit2sharp.Tests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("libgit2sharp.Tests")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("808554a4-f9fd-4035-8ab9-325793c7da51")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: CollectionBehavior(DisableTestParallelization = true)]
|
Handle application errors more gracefully | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// Program.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api
{
using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
public static void Main(string[] args)
{
// TODO Also use command-line arguments
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, e) =>
{
tokenSource.Cancel();
e.Cancel = true;
};
using (var host = builder.Build())
{
host.Run(tokenSource.Token);
}
}
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="https://martincostello.com/">
// Martin Costello (c) 2016
// </copyright>
// <summary>
// Program.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace MartinCostello.Api
{
using System;
using System.IO;
using System.Threading;
using Microsoft.AspNetCore.Hosting;
/// <summary>
/// A class representing the entry-point to the application. This class cannot be inherited.
/// </summary>
public static class Program
{
/// <summary>
/// The main entry-point to the application.
/// </summary>
/// <param name="args">The arguments to the application.</param>
/// <returns>
/// The exit code from the application.
/// </returns>
public static int Main(string[] args)
{
try
{
// TODO Also use command-line arguments
var builder = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>();
using (CancellationTokenSource tokenSource = new CancellationTokenSource())
{
Console.CancelKeyPress += (_, e) =>
{
tokenSource.Cancel();
e.Cancel = true;
};
using (var host = builder.Build())
{
host.Run(tokenSource.Token);
}
return 0;
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unhandled exception: {ex}");
return -1;
}
}
}
}
|
Add slot property changed notification | using System;
namespace Sakuno.ING.Game.Models
{
public sealed class PlayerShipSlot : Slot
{
public PlayerShip Owner { get; }
public int Index { get; }
public override SlotItem? Item => _slotItem;
private PlayerSlotItem? _slotItem;
public PlayerSlotItem? PlayerSlotItem
{
get => _slotItem;
internal set => Set(ref _slotItem, value);
}
public PlayerShipSlot(PlayerShip owner, int index)
{
Owner = owner;
Index = index;
}
}
}
| using System;
namespace Sakuno.ING.Game.Models
{
public sealed class PlayerShipSlot : Slot
{
public PlayerShip Owner { get; }
public int Index { get; }
public override SlotItem? Item => _slotItem;
private PlayerSlotItem? _slotItem;
public PlayerSlotItem? PlayerSlotItem
{
get => _slotItem;
internal set
{
Set(ref _slotItem, value);
NotifyPropertyChanged(nameof(Item));
}
}
public PlayerShipSlot(PlayerShip owner, int index)
{
Owner = owner;
Index = index;
}
}
}
|
Disable run/debug commands for Dart projects | namespace DanTup.DartVS.ProjectSystem
{
using Microsoft.VisualStudio.Project;
public class DartProjectConfig : ProjectConfig
{
internal DartProjectConfig(DartProjectNode project, string configuration, string platform)
: base(project, configuration, platform)
{
}
public new DartProjectNode ProjectManager
{
get
{
return (DartProjectNode)base.ProjectManager;
}
}
public override void Invalidate()
{
base.Invalidate();
}
}
}
| namespace DanTup.DartVS.ProjectSystem
{
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Project;
public class DartProjectConfig : ProjectConfig
{
internal DartProjectConfig(DartProjectNode project, string configuration, string platform)
: base(project, configuration, platform)
{
}
public new DartProjectNode ProjectManager
{
get
{
return (DartProjectNode)base.ProjectManager;
}
}
public override void Invalidate()
{
base.Invalidate();
}
public override int QueryDebugLaunch(uint flags, out int fCanLaunch)
{
fCanLaunch = 0;
return VSConstants.S_OK;
}
}
}
|
Move the blockingcollection take to inside the try catch | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace borkedLabs.CrestScribe
{
public class ScribeQueryWorker
{
private BlockingCollection<SsoCharacter> _queryQueue;
private CancellationToken _cancelToken;
public Thread Thread { get; private set; }
public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken)
{
_queryQueue = queryQueue;
_cancelToken = cancelToken;
Thread = new Thread(_worker);
Thread.Name = "scribe query worker";
Thread.IsBackground = true;
}
public void Start()
{
Thread.Start();
}
private void _worker()
{
while (!_cancelToken.IsCancellationRequested)
{
var character = _queryQueue.Take(_cancelToken);
if(character != null)
{
try
{
var t = Task.Run(character.Poll,_cancelToken);
t.Wait(_cancelToken);
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0: //no connect
case (int)MySql.Data.MySqlClient.MySqlErrorCode.UnableToConnectToHost:
//catch these silently, the main service thread will do magic to cancel out everything
break;
default:
throw ex;
break;
}
}
catch(System.OperationCanceledException)
{
break;
}
}
}
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace borkedLabs.CrestScribe
{
public class ScribeQueryWorker
{
private BlockingCollection<SsoCharacter> _queryQueue;
private CancellationToken _cancelToken;
public Thread Thread { get; private set; }
public ScribeQueryWorker(BlockingCollection<SsoCharacter> queryQueue, CancellationToken cancelToken)
{
_queryQueue = queryQueue;
_cancelToken = cancelToken;
Thread = new Thread(_worker);
Thread.Name = "scribe query worker";
Thread.IsBackground = true;
}
public void Start()
{
Thread.Start();
}
private void _worker()
{
while (!_cancelToken.IsCancellationRequested)
{
try
{
var character = _queryQueue.Take(_cancelToken);
if(character != null)
{
var t = Task.Run(character.Poll,_cancelToken);
t.Wait(_cancelToken);
}
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
switch (ex.Number)
{
case 0: //no connect
case (int)MySql.Data.MySqlClient.MySqlErrorCode.UnableToConnectToHost:
//catch these silently, the main service thread will do magic to cancel out everything
break;
default:
throw ex;
}
}
catch (System.OperationCanceledException)
{
break;
}
}
}
}
}
|
Fix AddTodoItem to autoincrement the item id | using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Okra.TodoSample.Data
{
[Export(typeof(ITodoRepository))]
public class TodoRepository : ITodoRepository
{
private IList<TodoItem> todoItems;
public TodoRepository()
{
this.todoItems = new List<TodoItem>
{
new TodoItem() { Id = "1", Title = "First item"},
new TodoItem() { Id = "2", Title = "Second item"},
new TodoItem() { Id = "3", Title = "Third item"}
};
}
public TodoItem GetTodoItemById(string id)
{
return todoItems.Where(item => item.Id == id).FirstOrDefault();
}
public IList<TodoItem> GetTodoItems()
{
return todoItems;
}
public void AddTodoItem(TodoItem todoItem)
{
this.todoItems.Add(todoItem);
}
public void RemoveTodoItem(TodoItem todoItem)
{
this.todoItems.Remove(todoItem);
}
}
}
| using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Okra.TodoSample.Data
{
[Export(typeof(ITodoRepository))]
public class TodoRepository : ITodoRepository
{
private IList<TodoItem> todoItems;
private int nextId = 4;
public TodoRepository()
{
this.todoItems = new List<TodoItem>
{
new TodoItem() { Id = "1", Title = "First item"},
new TodoItem() { Id = "2", Title = "Second item"},
new TodoItem() { Id = "3", Title = "Third item"}
};
}
public TodoItem GetTodoItemById(string id)
{
return todoItems.Where(item => item.Id == id).FirstOrDefault();
}
public IList<TodoItem> GetTodoItems()
{
return todoItems;
}
public void AddTodoItem(TodoItem todoItem)
{
todoItem.Id = (nextId++).ToString();
this.todoItems.Add(todoItem);
}
public void RemoveTodoItem(TodoItem todoItem)
{
this.todoItems.Remove(todoItem);
}
}
}
|
Fix "Value cannot be null." error | using System;
using System.Linq;
namespace Modix.Data.Utilities
{
public static class Extensions
{
public static string Truncate(this string value, int maxLength, int maxLines, string suffix = "…")
{
if (string.IsNullOrEmpty(value)) return value;
if (value.Length <= maxLength)
{
return value;
}
var lines = value.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
return lines.Length > maxLines ? string.Join("\n", lines.Take(maxLines)) : $"{value.Substring(0, maxLength).Trim()}{suffix}";
}
public static bool OrdinalContains(this string value, string search)
{
return value.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
| using System;
using System.Linq;
namespace Modix.Data.Utilities
{
public static class Extensions
{
public static string Truncate(this string value, int maxLength, int maxLines, string suffix = "…")
{
if (string.IsNullOrEmpty(value)) return value;
if (value.Length <= maxLength)
{
return value;
}
var lines = value.Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
return lines.Length > maxLines ? string.Join("\n", lines.Take(maxLines)) : $"{value.Substring(0, maxLength).Trim()}{suffix}";
}
public static bool OrdinalContains(this string value, string search)
{
if (value is null || search is null)
return false;
return value.IndexOf(search, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
|
Refactor to use own method for getting files recursively | 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)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries =
from x in sourceDirectory.GetFiles("*", SearchOption.AllDirectories)
select TarEntry.CreateEntryFromFile(x.FullName);
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
}
}
| 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)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory).Select(x => TarEntry.CreateEntryFromFile(x.FullName));
foreach (var entry in entries)
{
archive.WriteEntry(entry, true);
}
archive.Close();
}
private static FileInfo[] GetFiles(DirectoryInfo directory)
{
var files = directory.GetFiles("*", SearchOption.TopDirectoryOnly);
foreach (var nestedDirectory in directory.GetDirectories())
{
files.Concat(GetFiles(nestedDirectory));
}
return files;
}
}
}
|
Fix match footer test scene not working in visual testing | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
SelectedRoom.Value = new Room();
Child = new MultiplayerMatchFooter
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Height = 50
};
});
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Rooms;
using osu.Game.Screens.OnlinePlay.Multiplayer.Match;
namespace osu.Game.Tests.Visual.Multiplayer
{
public class TestSceneMultiplayerMatchFooter : MultiplayerTestScene
{
[SetUp]
public new void Setup() => Schedule(() =>
{
SelectedRoom.Value = new Room();
Child = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = 50,
Child = new MultiplayerMatchFooter()
};
});
}
}
|
Add basic bindable instantiation benchmark | // 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;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
public class BenchmarkBindableInstantiation
{
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
| // 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;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkBindableInstantiation
{
[Benchmark]
public Bindable<int> Instantiate() => new Bindable<int>();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
|
Use configureAwait(false) for sql server json log store | using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Bit.Data.Implementations
{
public class SqlServerJsonLogStore : ILogStore
{
public virtual AppEnvironment ActiveAppEnvironment { get; set; }
public virtual IContentFormatter Formatter { get; set; }
public void SaveLog(LogEntry logEntry)
{
using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring")))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)";
command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry));
connection.Open();
command.ExecuteNonQuery();
}
}
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring")))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)";
command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry));
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
}
}
}
}
}
| using Bit.Core.Contracts;
using Bit.Core.Models;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Bit.Data.Implementations
{
public class SqlServerJsonLogStore : ILogStore
{
public virtual AppEnvironment ActiveAppEnvironment { get; set; }
public virtual IContentFormatter Formatter { get; set; }
public void SaveLog(LogEntry logEntry)
{
using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring")))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)";
command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry));
connection.Open();
command.ExecuteNonQuery();
}
}
}
public virtual async Task SaveLogAsync(LogEntry logEntry)
{
using (SqlConnection connection = new SqlConnection(ActiveAppEnvironment.GetConfig<string>("AppConnectionstring")))
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = @"INSERT INTO [dbo].[Logs] ([Contents]) VALUES (@contents)";
command.Parameters.AddWithValue("@contents", Formatter.Serialize(logEntry));
await connection.OpenAsync().ConfigureAwait(false);
await command.ExecuteNonQueryAsync().ConfigureAwait(false);
}
}
}
}
}
|
Revert "Changed name for bitmap data from bitmapStream to bitmapData, because bitmapStream is misleading." | using System.IO;
using System.Text;
using Mapsui.Extensions;
using Mapsui.Styles;
using SkiaSharp;
using Svg.Skia;
namespace Mapsui.Rendering.Skia
{
public static class BitmapHelper
{
public static BitmapInfo LoadBitmap(object bitmapData)
{
// todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it
// which has all information. So we should have a SymbolImageRegistry in which we store a
// SymbolImage. Which holds the type, data and other parameters.
if (bitmapData is string str)
{
if (str.ToLower().Contains("<svg"))
{
var svg = new SKSvg();
svg.FromSvg(str);
return new BitmapInfo { Svg = svg };
}
}
if (bitmapData is Stream stream)
{
if (stream.IsSvg())
{
var svg = new SKSvg();
svg.Load(stream);
return new BitmapInfo {Svg = svg};
}
var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes()));
return new BitmapInfo {Bitmap = image};
}
if (bitmapData is Sprite sprite)
{
return new BitmapInfo {Sprite = sprite};
}
return null;
}
}
} | using System.IO;
using System.Text;
using Mapsui.Extensions;
using Mapsui.Styles;
using SkiaSharp;
using Svg.Skia;
namespace Mapsui.Rendering.Skia
{
public static class BitmapHelper
{
public static BitmapInfo LoadBitmap(object bitmapStream)
{
// todo: Our BitmapRegistry stores not only bitmaps. Perhaps we should store a class in it
// which has all information. So we should have a SymbolImageRegistry in which we store a
// SymbolImage. Which holds the type, data and other parameters.
if (bitmapStream is string str)
{
if (str.ToLower().Contains("<svg"))
{
var svg = new SKSvg();
svg.FromSvg(str);
return new BitmapInfo { Svg = svg };
}
}
if (bitmapStream is Stream stream)
{
if (stream.IsSvg())
{
var svg = new SKSvg();
svg.Load(stream);
return new BitmapInfo {Svg = svg};
}
var image = SKImage.FromEncodedData(SKData.CreateCopy(stream.ToBytes()));
return new BitmapInfo {Bitmap = image};
}
if (bitmapStream is Sprite sprite)
{
return new BitmapInfo {Sprite = sprite};
}
return null;
}
}
} |
Fix uninstall for project k projects | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NewPackageAction = NuGet.Client.Resolution.PackageAction;
namespace NuGet.Client.Installation
{
public class UninstallActionHandler : IActionHandler
{
public Task Execute(NewPackageAction action, IExecutionLogger logger, CancellationToken cancelToken)
{
return Task.Run(() =>
{
// Get the project manager
var projectManager = action.Target.GetRequiredFeature<IProjectManager>();
// Get the package out of the project manager
var package = projectManager.LocalRepository.FindPackage(
action.PackageIdentity.Id,
CoreConverters.SafeToSemVer(action.PackageIdentity.Version));
Debug.Assert(package != null);
// Add the package to the project
projectManager.Logger = new ShimLogger(logger);
projectManager.Execute(new PackageOperation(
package,
NuGet.PackageAction.Uninstall));
// Run uninstall.ps1 if present
ActionHandlerHelpers.ExecutePowerShellScriptIfPresent(
"uninstall.ps1",
action.Target,
package,
projectManager.PackageManager.PathResolver.GetInstallPath(package),
logger);
});
}
public Task Rollback(NewPackageAction action, IExecutionLogger logger)
{
// Just run the install action to undo a uninstall
return new InstallActionHandler().Execute(action, logger, CancellationToken.None);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NewPackageAction = NuGet.Client.Resolution.PackageAction;
namespace NuGet.Client.Installation
{
public class UninstallActionHandler : IActionHandler
{
public Task Execute(NewPackageAction action, IExecutionLogger logger, CancellationToken cancelToken)
{
var nugetAware = action.Target.TryGetFeature<NuGetAwareProject>();
if (nugetAware != null)
{
return nugetAware.UninstallPackage(
action.PackageIdentity,
logger,
cancelToken);
}
return Task.Run(() =>
{
// Get the project manager
var projectManager = action.Target.GetRequiredFeature<IProjectManager>();
// Get the package out of the project manager
var package = projectManager.LocalRepository.FindPackage(
action.PackageIdentity.Id,
CoreConverters.SafeToSemVer(action.PackageIdentity.Version));
Debug.Assert(package != null);
// Add the package to the project
projectManager.Logger = new ShimLogger(logger);
projectManager.Execute(new PackageOperation(
package,
NuGet.PackageAction.Uninstall));
// Run uninstall.ps1 if present
ActionHandlerHelpers.ExecutePowerShellScriptIfPresent(
"uninstall.ps1",
action.Target,
package,
projectManager.PackageManager.PathResolver.GetInstallPath(package),
logger);
});
}
public Task Rollback(NewPackageAction action, IExecutionLogger logger)
{
// Just run the install action to undo a uninstall
return new InstallActionHandler().Execute(action, logger, CancellationToken.None);
}
}
}
|
Create Error message in Title | using System;
using System.ComponentModel.DataAnnotations;
namespace SpaceBlog.Models
{
public class Article
{
public Article()
{
Date = DateTime.Now;
}
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public DateTime Date { get; set; }
//public virtual IEnumerable<Comment> Comments { get; set; }
//public Category Category { get; set; }
//public virtual IEnumerable<Tag> Tags { get; set; }
public ApplicationUser Author { get; set; }
}
} | using System;
using System.ComponentModel.DataAnnotations;
namespace SpaceBlog.Models
{
public class Article
{
public Article()
{
Date = DateTime.Now;
}
[Key]
public int Id { get; set; }
[Required]
[MaxLength(50, ErrorMessage = "The Title must be text with maximum 50 characters.")]
public string Title { get; set; }
[Required]
public string Content { get; set; }
public DateTime Date { get; set; }
//public virtual IEnumerable<Comment> Comments { get; set; }
//public Category Category { get; set; }
//public virtual IEnumerable<Tag> Tags { get; set; }
public ApplicationUser Author { get; set; }
}
} |
Change to jobs on resume page |
@{
ViewBag.Title = "Resume";
}
<div class="col-sm-8 col-sm-offset-2">
<div class="col-xs-12 col-sm-6 col-sm-offset-3 list-group" id="aboutButtonGroup">
<button type="button" class="list-group-item storyList" id="2015"><p class="text-center">2015</p></button>
<button type="button" class="list-group-item storyList" id="2014"><p class="text-center">2014</p></button>
<button type="button" class="list-group-item storyList" id="2013"><p class="text-center">2013</p></button>
<button type="button" class="list-group-item storyList" id="2012"><p class="text-center">2012</p></button>
<button type="button" class="list-group-item storyList" id="2011"><p class="text-center">2011</p></button>
</div>
</div>
<div class="col-xs-12 col-sm-10 col-sm-offset-1 text-center">
<p class="white">To view the PDF version of my resume click <a href="#" id="pdfLink">here</a>.</p>
</div>
<div></div> |
@{
ViewBag.Title = "Resume";
}
<div class="col-sm-8 col-sm-offset-2">
<div class="col-xs-12 col-sm-6 col-sm-offset-3 list-group" id="aboutButtonGroup">
<button type="button" class="list-group-item storyList" id="2015"><p class="text-center">Information Technology Intern</p></button>
<button type="button" class="list-group-item storyList" id="2014"><p class="text-center">Web Developer Intern</p></button>
<button type="button" class="list-group-item storyList" id="2013"><p class="text-center">Unit Deployment Manager</p></button>
<button type="button" class="list-group-item storyList" id="2012"><p class="text-center">Hydraulic Systems Journeyman</p></button>
</div>
</div>
<div class="col-xs-12 col-sm-10 col-sm-offset-1 text-center">
<p class="white">To view the PDF version of my resume click <a href="#" id="pdfLink">here</a>.</p>
</div>
<div></div> |
Move mouse state setting to SetHost. | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Platform;
using osu.Framework.Screens.Testing;
namespace osu.Framework.VisualTests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Host.Window.CursorState = CursorState.Hidden;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Platform;
using osu.Framework.Screens.Testing;
namespace osu.Framework.VisualTests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState = CursorState.Hidden;
}
}
}
|
Fix the wording at tx build | using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Gui.Helpers;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class BuildTabViewModel : SendControlViewModel
{
public override string DoButtonText => "Build Transaction";
public override string DoingButtonText => "Building Transaction...";
public BuildTabViewModel(WalletViewModel walletViewModel) : base(walletViewModel, "Build Transaction")
{
}
protected override Task DoAfterBuildTransaction(BuildTransactionResult result)
{
try
{
var txviewer = IoC.Get<IShell>().Documents?.OfType<TransactionViewerViewModel>()?.FirstOrDefault(x => x.Wallet.Id == Wallet.Id);
if (txviewer is null)
{
txviewer = new TransactionViewerViewModel(Wallet);
IoC.Get<IShell>().AddDocument(txviewer);
}
IoC.Get<IShell>().Select(txviewer);
txviewer.Update(result);
ResetUi();
NotificationHelpers.Success("Transaction is successfully built!", "");
}
catch (Exception ex)
{
return Task.FromException(ex);
}
return Task.CompletedTask;
}
}
}
| using AvalonStudio.Extensibility;
using AvalonStudio.Shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WalletWasabi.Blockchain.TransactionBuilding;
using WalletWasabi.Gui.Helpers;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class BuildTabViewModel : SendControlViewModel
{
public override string DoButtonText => "Build Transaction";
public override string DoingButtonText => "Building Transaction...";
public BuildTabViewModel(WalletViewModel walletViewModel) : base(walletViewModel, "Build Transaction")
{
}
protected override Task DoAfterBuildTransaction(BuildTransactionResult result)
{
try
{
var txviewer = IoC.Get<IShell>().Documents?.OfType<TransactionViewerViewModel>()?.FirstOrDefault(x => x.Wallet.Id == Wallet.Id);
if (txviewer is null)
{
txviewer = new TransactionViewerViewModel(Wallet);
IoC.Get<IShell>().AddDocument(txviewer);
}
IoC.Get<IShell>().Select(txviewer);
txviewer.Update(result);
ResetUi();
NotificationHelpers.Success("Transaction was built!");
}
catch (Exception ex)
{
return Task.FromException(ex);
}
return Task.CompletedTask;
}
}
}
|
Fix resource manifest for gallery -- should enable with the Gallery feature | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orchard.UI.Resources;
namespace Orchard.Packaging {
public class ResourceManifest : IResourceManifestProvider {
public void BuildManifests(ResourceManifestBuilder builder) {
builder.Add().DefineStyle("PackagingAdmin").SetUrl("admin.css");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Orchard.Environment.Extensions;
using Orchard.UI.Resources;
namespace Orchard.Packaging {
[OrchardFeature("Gallery")]
public class ResourceManifest : IResourceManifestProvider {
public void BuildManifests(ResourceManifestBuilder builder) {
builder.Add().DefineStyle("PackagingAdmin").SetUrl("admin.css");
}
}
}
|
Add `DeviceType` filter when listing Terminal `Reader`s | namespace Stripe.Terminal
{
using System;
using Newtonsoft.Json;
public class ReaderListOptions : ListOptions
{
/// <summary>
/// A location ID to filter the response list to only readers at the specific location.
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
/// <summary>
/// A status filter to filter readers to only offline or online readers. Possible values
/// are <c>offline</c> and <c>online</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
| namespace Stripe.Terminal
{
using System;
using Newtonsoft.Json;
public class ReaderListOptions : ListOptions
{
/// <summary>
/// Filters readers by device type.
/// </summary>
[JsonProperty("device_type")]
public string DeviceType { get; set; }
/// <summary>
/// A location ID to filter the response list to only readers at the specific location.
/// </summary>
[JsonProperty("location")]
public string Location { get; set; }
/// <summary>
/// A status filter to filter readers to only offline or online readers. Possible values
/// are <c>offline</c> and <c>online</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
|
Disable exit on mousemove/keypress in DEBUG | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _4OpEenRijScreensaver
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
App.Current.Shutdown();
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
App.Current.Shutdown();
}
Point _mousePos;
private void Window_MouseMove(object sender, MouseEventArgs e)
{
if (_mousePos != default(Point) && _mousePos != e.GetPosition(MainWindowWindow))
App.Current.Shutdown();
_mousePos = e.GetPosition(MainWindowWindow);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace _4OpEenRijScreensaver
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
#if !DEBUG
App.Current.Shutdown();
#endif
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
App.Current.Shutdown();
}
Point _mousePos;
private void Window_MouseMove(object sender, MouseEventArgs e)
{
#if !DEBUG
if (_mousePos != default(Point) && _mousePos != e.GetPosition(MainWindowWindow))
App.Current.Shutdown();
_mousePos = e.GetPosition(MainWindowWindow);
#endif
}
}
}
|
Fix instruction help when "Upcase OpCode" option is enabled | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace Msiler.AssemblyParser
{
public class OpCodeInfo
{
public string Name { get; set; }
public string Description { get; set; }
}
public static class Helpers
{
private static Dictionary<string, OpCodeInfo> ReadOpCodeInfoResource() {
var reader = new StringReader(Resources.Instructions);
var serializer = new XmlSerializer(typeof(List<OpCodeInfo>));
var list = (List<OpCodeInfo>)serializer.Deserialize(reader);
return list.ToDictionary(i => i.Name, i => i);
}
private static readonly Dictionary<string, OpCodeInfo> OpCodesInfoCache
= ReadOpCodeInfoResource();
public static OpCodeInfo GetInstructionInformation(string s) {
if (OpCodesInfoCache.ContainsKey(s)) {
return OpCodesInfoCache[s];
}
return null;
}
public static string ReplaceNewLineCharacters(this string str) {
return str.Replace("\n", @"\n").Replace("\r", @"\r");
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
namespace Msiler.AssemblyParser
{
public class OpCodeInfo
{
public string Name { get; set; }
public string Description { get; set; }
}
public static class Helpers
{
private static Dictionary<string, OpCodeInfo> ReadOpCodeInfoResource() {
var reader = new StringReader(Resources.Instructions);
var serializer = new XmlSerializer(typeof(List<OpCodeInfo>));
var list = (List<OpCodeInfo>)serializer.Deserialize(reader);
return list.ToDictionary(i => i.Name, i => i);
}
private static readonly Dictionary<string, OpCodeInfo> OpCodesInfoCache
= ReadOpCodeInfoResource();
public static OpCodeInfo GetInstructionInformation(string s) {
var instruction = s.ToLower();
if (OpCodesInfoCache.ContainsKey(instruction)) {
return OpCodesInfoCache[instruction];
}
return null;
}
public static string ReplaceNewLineCharacters(this string str) {
return str.Replace("\n", @"\n").Replace("\r", @"\r");
}
}
}
|
Clarify api a bit in readme.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Burr.Tests
{
public class Readme
{
public Readme()
{
// create an anonymous client
var client = new GitHubClient();
// create a client with basic auth
client = new GitHubClient { Username = "tclem", Password = "pwd" };
// create a client with an oauth token
client = new GitHubClient { Token = "oauthtoken" };
//// Authorizations API
//var authorizations = client.Authorizations.All();
//var authorization = client.Authorizations.Get(1);
//var authorization = client.Authorizations.Delete(1);
//var a = client.Authorizations.Update(1, scopes: new[] { "user", "repo" }, "notes", "http://notes_url");
//var token = client.Authorizations.Create(new[] { "user", "repo" }, "notes", "http://notes_url");
//var gists = client.Gists.All();
//var gists = client.Gists.All("user");
//var gists = client.Gists.Public();
//var gists = client.Gists.Starred();
//var gist = client.Gists.Get(1);
//client.Gists.Create();
}
public async Task UserApi()
{
var client = new GitHubClient();
var user = await client.GetUserAsync("octocat");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Burr.Tests
{
public class Readme
{
public Readme()
{
// create an anonymous client
var client = new GitHubClient();
// create a client with basic auth
client = new GitHubClient { Username = "tclem", Password = "pwd" };
// create a client with an oauth token
client = new GitHubClient { Token = "oauthtoken" };
//// Authorizations API
//var authorizations = client.Authorizations.All();
//var authorization = client.Authorizations.Get(1);
//var authorization = client.Authorizations.Delete(1);
//var a = client.Authorizations.Update(1, scopes: new[] { "user", "repo" }, "notes", "http://notes_url");
//var token = client.Authorizations.Create(new[] { "user", "repo" }, "notes", "http://notes_url");
//var gists = client.Gists.All();
//var gists = client.Gists.All("user");
//var gists = client.Gists.Public();
//var gists = client.Gists.Starred();
//var gist = client.Gists.Get(1);
//client.Gists.Create();
}
public async Task UserApi()
{
var client = new GitHubClient{ Username = "octocat", Password = "pwd" };
// Get the authenticated user
var authUser = await client.GetUserAsync();
// Get a user by username
var user = await client.GetUserAsync("tclem");
}
}
}
|
Check if calling thread is already GUI thread when showing the global exception handler dialog. | using System;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
namespace Homie.Common
{
public class ExceptionUtils
{
public enum ExitCodes
{
Ok = 0,
UnhandledException = 91,
UnobservedTaskException = 92,
DispatcherUnhandledException = 93
}
public static Exception UnwrapExceptionObject(object pException)
{
var lException = (Exception)pException;
if (lException is TargetInvocationException && lException.InnerException is AggregateException)
{
return lException.InnerException;
}
return lException;
}
public static void ShowException(Exception pException)
{
var exception = UnwrapExceptionObject(pException);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() =>
{
MessageBox.Show(String.Format("Unexpected error: {0}", exception.Message), Application.Current.MainWindow.GetType().Assembly.GetName().Name, MessageBoxButton.OK,
MessageBoxImage.Error);
}));
}
}
}
| using System;
using System.Reflection;
using System.Windows;
using System.Windows.Threading;
namespace Homie.Common
{
public class ExceptionUtils
{
public enum ExitCodes
{
Ok = 0,
UnhandledException = 91,
UnobservedTaskException = 92,
DispatcherUnhandledException = 93
}
public static Exception UnwrapExceptionObject(object pException)
{
var lException = (Exception)pException;
if (lException is TargetInvocationException && lException.InnerException is AggregateException)
{
return lException.InnerException;
}
return lException;
}
public static void ShowException(Exception pException)
{
var exception = UnwrapExceptionObject(pException);
if (!Application.Current.Dispatcher.CheckAccess())
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action) (() =>
{
ShowExceptionMessageDialog(exception.Message);
}));
}
else
{
ShowExceptionMessageDialog(exception.Message);
}
}
private static void ShowExceptionMessageDialog(string errorMessage)
{
MessageBox.Show
(
$"Unexpected error: {errorMessage}",
Application.Current.MainWindow.GetType().Assembly.GetName().Name,
MessageBoxButton.OK,
MessageBoxImage.Error
);
}
}
}
|
Write to Logger instead of Console | using System;
using EvilDICOM.Core.Enums;
namespace EvilDICOM.Core.IO.Data
{
public class DataRestriction
{
public static string EnforceLengthRestriction(uint lengthLimit, string data)
{
if (data.Length > lengthLimit)
{
Console.Write(
"Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.",
data.Length, lengthLimit);
return data;
}
return data;
}
public static byte[] EnforceEvenLength(byte[] data, VR vr)
{
switch (vr)
{
case VR.UniqueIdentifier:
case VR.OtherByteString:
case VR.Unknown:
return DataPadder.PadNull(data);
case VR.AgeString:
case VR.ApplicationEntity:
case VR.CodeString:
case VR.Date:
case VR.DateTime:
case VR.DecimalString:
case VR.IntegerString:
case VR.LongString:
case VR.LongText:
case VR.PersonName:
case VR.ShortString:
case VR.ShortText:
case VR.Time:
case VR.UnlimitedText:
return DataPadder.PadSpace(data);
default:
return data;
}
}
}
} | using System;
using EvilDICOM.Core.Enums;
using EvilDICOM.Core.Logging;
namespace EvilDICOM.Core.IO.Data
{
public class DataRestriction
{
public static string EnforceLengthRestriction(uint lengthLimit, string data)
{
if (data.Length > lengthLimit)
{
EvilLogger.Instance.Log(
"Not DICOM compliant. Attempted data input of {0} characters. Data size is limited to {1} characters. Read anyway.",
data.Length, lengthLimit);
return data;
}
return data;
}
public static byte[] EnforceEvenLength(byte[] data, VR vr)
{
switch (vr)
{
case VR.UniqueIdentifier:
case VR.OtherByteString:
case VR.Unknown:
return DataPadder.PadNull(data);
case VR.AgeString:
case VR.ApplicationEntity:
case VR.CodeString:
case VR.Date:
case VR.DateTime:
case VR.DecimalString:
case VR.IntegerString:
case VR.LongString:
case VR.LongText:
case VR.PersonName:
case VR.ShortString:
case VR.ShortText:
case VR.Time:
case VR.UnlimitedText:
return DataPadder.PadSpace(data);
default:
return data;
}
}
}
} |
Disable DTC tests since Npgsql support for it seems to be broken. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NHibernate.Test.TestDialects
{
public class PostgreSQL82TestDialect : TestDialect
{
public PostgreSQL82TestDialect(Dialect.Dialect dialect)
: base(dialect)
{
}
public override bool SupportsSelectForUpdateOnOuterJoin
{
get { return false; }
}
public override bool SupportsNullCharactersInUtfStrings
{
get { return false; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NHibernate.Test.TestDialects
{
public class PostgreSQL82TestDialect : TestDialect
{
public PostgreSQL82TestDialect(Dialect.Dialect dialect)
: base(dialect)
{
}
public override bool SupportsSelectForUpdateOnOuterJoin
{
get { return false; }
}
public override bool SupportsNullCharactersInUtfStrings
{
get { return false; }
}
/// <summary>
/// Npgsql's DTC code seems to be somewhat broken as of 2.0.11.
/// </summary>
public override bool SupportsDistributedTransactions
{
get { return false; }
}
}
}
|
Fix wrong type for linkbuttons | using System;
using System.Web.UI.WebControls;
namespace R7.HelpDesk
{
public partial class Comments
{
protected Panel pnlInsertComment;
protected Label lblAttachFile1;
protected FileUpload TicketFileUpload;
protected Label lblAttachFile2;
protected FileUpload fuAttachment;
protected Panel pnlTableHeader;
protected Panel pnlExistingComments;
protected Panel pnlEditComment;
protected CheckBox chkCommentVisible;
protected CheckBox chkCommentVisibleEdit;
protected HyperLink lnkDelete;
protected Image Image5;
protected HyperLink lnkUpdate;
protected Image Image4;
protected Panel pnlDisplayFile;
protected Panel pnlAttachFile;
protected Image imgDelete;
protected HyperLink lnkUpdateRequestor;
protected Image ImgEmailUser;
protected Button btnInsertCommentAndEmail;
protected TextBox txtComment;
protected Label lblError;
protected GridView gvComments;
protected Label lblDetailID;
protected TextBox txtDescription;
protected Label lblDisplayUser;
protected Label lblInsertDate;
protected LinkButton lnkFileAttachment;
//protected HyperLink lnkFileAttachment;
protected Label lblErrorEditComment;
}
}
| using System;
using System.Web.UI.WebControls;
namespace R7.HelpDesk
{
public partial class Comments
{
protected Panel pnlInsertComment;
protected Label lblAttachFile1;
protected FileUpload TicketFileUpload;
protected Label lblAttachFile2;
protected FileUpload fuAttachment;
protected Panel pnlTableHeader;
protected Panel pnlExistingComments;
protected Panel pnlEditComment;
protected CheckBox chkCommentVisible;
protected CheckBox chkCommentVisibleEdit;
protected LinkButton lnkDelete;
protected Image Image5;
protected LinkButton lnkUpdate;
protected Image Image4;
protected Panel pnlDisplayFile;
protected Panel pnlAttachFile;
protected Image imgDelete;
protected LinkButton lnkUpdateRequestor;
protected Image ImgEmailUser;
protected Button btnInsertCommentAndEmail;
protected TextBox txtComment;
protected Label lblError;
protected GridView gvComments;
protected Label lblDetailID;
protected TextBox txtDescription;
protected Label lblDisplayUser;
protected Label lblInsertDate;
protected LinkButton lnkFileAttachment;
//protected HyperLink lnkFileAttachment;
protected Label lblErrorEditComment;
}
}
|
Make server able to run as deamon on mono | /*
* Created by SharpDevelop.
* User: Lars Magnus
* Date: 12.06.2014
* Time: 20:52
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using Nancy.Hosting.Self;
namespace webstats
{
class Program
{
public static void Main(string[] args)
{
// Start web server
Console.WriteLine("Press enter to terminate server");
HostConfiguration hc = new HostConfiguration();
hc.UrlReservations.CreateAutomatically = true;
using (var host = new NancyHost(hc, new Uri("http://localhost:4444")))
{
host.Start();
Console.ReadLine();
}
Console.WriteLine("Server terminated");
}
}
} | /*
* Created by SharpDevelop.
* User: Lars Magnus
* Date: 12.06.2014
* Time: 20:52
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System;
using System.Linq;
using System.Threading;
using Nancy.Hosting.Self;
namespace webstats
{
class Program
{
public static void Main(string[] args)
{
// Start web server
Console.WriteLine("Press enter to terminate server");
HostConfiguration hc = new HostConfiguration();
hc.UrlReservations.CreateAutomatically = true;
var host = new NancyHost(hc, new Uri("http://localhost:8888"));
host.Start();
//Under mono if you deamonize a process a Console.ReadLine with cause an EOF
//so we need to block another way
if (args.Any(s => s.Equals("-d", StringComparison.CurrentCultureIgnoreCase)))
{
Thread.Sleep(Timeout.Infinite);
}
else
{
Console.ReadKey();
}
host.Stop();
Console.WriteLine("Server terminated");
}
}
} |
Correct searching config base on exe file name. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
namespace PCLAppConfig.FileSystemStream
{
public class UWPAppConfigPathExtractor : IAppConfigPathExtractor
{
public string Path
{
get
{
string rootPath = Package.Current.InstalledLocation.Path;
string exeConfig = System.IO.Path.Combine(rootPath, Package.Current.DisplayName + ".exe.config");
if (!File.Exists(exeConfig))
{
return System.IO.Path.Combine(rootPath, "App.config");
}
else
{
return exeConfig;
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel;
namespace PCLAppConfig.FileSystemStream
{
public class UWPAppConfigPathExtractor : IAppConfigPathExtractor
{
public string Path
{
get
{
string rootPath = Package.Current.InstalledLocation.Path;
string packageConfig = System.IO.Path.Combine(rootPath, Package.Current.DisplayName + ".exe.config");
string exeConfig = System.IO.Path.Combine(rootPath, System.AppDomain.CurrentDomain.FriendlyName + ".exe.config");
if (File.Exists(packageConfig))
{
return packageConfig;
}
else if (File.Exists(exeConfig))
{
return exeConfig;
}
else
{
return System.IO.Path.Combine(rootPath, "App.config");
}
}
}
}
}
|
Reset predict flag on mover updat.e | using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.Physics;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Physics;
using Robust.Client.Player;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.IoC;
using Robust.Shared.Physics;
#nullable enable
namespace Content.Client.GameObjects.EntitySystems
{
[UsedImplicitly]
public class MoverSystem : SharedMoverSystem
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
public override void Initialize()
{
base.Initialize();
UpdatesBefore.Add(typeof(PhysicsSystem));
}
public override void FrameUpdate(float frameTime)
{
var playerEnt = _playerManager.LocalPlayer?.ControlledEntity;
if (playerEnt == null || !playerEnt.TryGetComponent(out IMoverComponent mover))
{
return;
}
var physics = playerEnt.GetComponent<PhysicsComponent>();
playerEnt.TryGetComponent(out CollidableComponent? collidable);
UpdateKinematics(playerEnt.Transform, mover, physics, collidable);
}
public override void Update(float frameTime)
{
FrameUpdate(frameTime);
}
protected override void SetController(SharedPhysicsComponent physics)
{
((PhysicsComponent)physics).SetController<MoverController>();
}
}
}
| using Content.Shared.GameObjects.Components.Movement;
using Content.Shared.GameObjects.EntitySystems;
using Content.Shared.Physics;
using JetBrains.Annotations;
using Robust.Client.GameObjects;
using Robust.Client.Physics;
using Robust.Client.Player;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.IoC;
using Robust.Shared.Physics;
#nullable enable
namespace Content.Client.GameObjects.EntitySystems
{
[UsedImplicitly]
public class MoverSystem : SharedMoverSystem
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
public override void Initialize()
{
base.Initialize();
UpdatesBefore.Add(typeof(PhysicsSystem));
}
public override void FrameUpdate(float frameTime)
{
var playerEnt = _playerManager.LocalPlayer?.ControlledEntity;
if (playerEnt == null || !playerEnt.TryGetComponent(out IMoverComponent mover))
{
return;
}
var physics = playerEnt.GetComponent<PhysicsComponent>();
playerEnt.TryGetComponent(out CollidableComponent? collidable);
physics.Predict = true;
UpdateKinematics(playerEnt.Transform, mover, physics, collidable);
}
public override void Update(float frameTime)
{
FrameUpdate(frameTime);
}
protected override void SetController(SharedPhysicsComponent physics)
{
((PhysicsComponent)physics).SetController<MoverController>();
}
}
}
|
Change load event of UI component to from Awake to Start | using System.Collections;
using PatchKit.Api;
using UnityEngine;
namespace PatchKit.Unity.UI
{
public abstract class UIApiComponent : MonoBehaviour
{
private Coroutine _loadCoroutine;
private bool _isDirty;
private ApiConnection _apiConnection;
public bool LoadOnAwake = true;
protected ApiConnection ApiConnection
{
get { return _apiConnection; }
}
[ContextMenu("Reload")]
public void SetDirty()
{
_isDirty = true;
}
protected abstract IEnumerator LoadCoroutine();
private void Load()
{
try
{
if (_loadCoroutine != null)
{
StopCoroutine(_loadCoroutine);
}
_loadCoroutine = StartCoroutine(LoadCoroutine());
}
finally
{
_isDirty = false;
}
}
protected virtual void Awake()
{
_apiConnection = new ApiConnection(Settings.GetApiConnectionSettings());
if (LoadOnAwake)
{
Load();
}
}
protected virtual void Update()
{
if (_isDirty)
{
Load();
}
}
}
} | using System.Collections;
using PatchKit.Api;
using UnityEngine;
namespace PatchKit.Unity.UI
{
public abstract class UIApiComponent : MonoBehaviour
{
private Coroutine _loadCoroutine;
private bool _isDirty;
private ApiConnection _apiConnection;
public bool LoadOnStart = true;
protected ApiConnection ApiConnection
{
get { return _apiConnection; }
}
[ContextMenu("Reload")]
public void SetDirty()
{
_isDirty = true;
}
protected abstract IEnumerator LoadCoroutine();
private void Load()
{
try
{
if (_loadCoroutine != null)
{
StopCoroutine(_loadCoroutine);
}
_loadCoroutine = StartCoroutine(LoadCoroutine());
}
finally
{
_isDirty = false;
}
}
protected virtual void Awake()
{
_apiConnection = new ApiConnection(Settings.GetApiConnectionSettings());
}
protected virtual void Start()
{
if (LoadOnStart)
{
Load();
}
}
protected virtual void Update()
{
if (_isDirty)
{
Load();
}
}
}
} |
Remove the usage of Parallel to run the populators | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Examine;
namespace Umbraco.Examine
{
/// <summary>
/// Utility to rebuild all indexes ensuring minimal data queries
/// </summary>
public class IndexRebuilder
{
private readonly IEnumerable<IIndexPopulator> _populators;
public IExamineManager ExamineManager { get; }
public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
{
_populators = populators;
ExamineManager = examineManager;
}
public bool CanRebuild(IIndex index)
{
return _populators.Any(x => x.IsRegistered(index));
}
public void RebuildIndex(string indexName)
{
if (!ExamineManager.TryGetIndex(indexName, out var index))
throw new InvalidOperationException($"No index found with name {indexName}");
index.CreateIndex(); // clear the index
foreach (var populator in _populators)
{
populator.Populate(index);
}
}
public void RebuildIndexes(bool onlyEmptyIndexes)
{
var indexes = (onlyEmptyIndexes
? ExamineManager.Indexes.Where(x => !x.IndexExists())
: ExamineManager.Indexes).ToArray();
if (indexes.Length == 0) return;
foreach (var index in indexes)
{
index.CreateIndex(); // clear the index
}
//run the populators in parallel against all indexes
Parallel.ForEach(_populators, populator => populator.Populate(indexes));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Examine;
namespace Umbraco.Examine
{
/// <summary>
/// Utility to rebuild all indexes ensuring minimal data queries
/// </summary>
public class IndexRebuilder
{
private readonly IEnumerable<IIndexPopulator> _populators;
public IExamineManager ExamineManager { get; }
public IndexRebuilder(IExamineManager examineManager, IEnumerable<IIndexPopulator> populators)
{
_populators = populators;
ExamineManager = examineManager;
}
public bool CanRebuild(IIndex index)
{
return _populators.Any(x => x.IsRegistered(index));
}
public void RebuildIndex(string indexName)
{
if (!ExamineManager.TryGetIndex(indexName, out var index))
throw new InvalidOperationException($"No index found with name {indexName}");
index.CreateIndex(); // clear the index
foreach (var populator in _populators)
{
populator.Populate(index);
}
}
public void RebuildIndexes(bool onlyEmptyIndexes)
{
var indexes = (onlyEmptyIndexes
? ExamineManager.Indexes.Where(x => !x.IndexExists())
: ExamineManager.Indexes).ToArray();
if (indexes.Length == 0) return;
foreach (var index in indexes)
{
index.CreateIndex(); // clear the index
}
// run each populator over the indexes
foreach(var populator in _populators)
{
populator.Populate(indexes);
}
}
}
}
|
Improve naming of tests to clearly indicate the feature to be tested | #region Copyright and license
// // <copyright file="NotNullTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // 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.
// // </license>
#endregion
namespace Delizious.Filtering
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class NotNullTests
{
[TestMethod]
public void Fail__When_Value_Is_Null()
{
Assert.IsFalse(Match.NotNull<GenericParameterHelper>().Matches(null));
}
[TestMethod]
public void Succeed__When_Value_Is_An_Instance()
{
Assert.IsTrue(Match.NotNull<GenericParameterHelper>().Matches(new GenericParameterHelper()));
}
}
}
| #region Copyright and license
// // <copyright file="NotNullTests.cs" company="Oliver Zick">
// // Copyright (c) 2016 Oliver Zick. All rights reserved.
// // </copyright>
// // <author>Oliver Zick</author>
// // <license>
// // 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.
// // </license>
#endregion
namespace Delizious.Filtering
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public sealed class NotNullTests
{
[TestMethod]
public void Match_Fails_When_Value_To_Match_Is_Null()
{
Assert.IsFalse(Match.NotNull<GenericParameterHelper>().Matches(null));
}
[TestMethod]
public void Match_Succeeds_When_Value_To_Match_Is_An_Instance()
{
Assert.IsTrue(Match.NotNull<GenericParameterHelper>().Matches(new GenericParameterHelper()));
}
}
}
|
Extend the box/unbox test again | using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
object i = 42;
Console.WriteLine((int)i);
}
}
| using System;
public struct Foo : ICloneable
{
public int CloneCounter { get; private set; }
public object Clone()
{
CloneCounter++;
return this;
}
}
public static class Program
{
public static ICloneable BoxAndCast<T>(T Value)
{
return (ICloneable)Value;
}
public static T Unbox<T>(object Value)
{
return (T)Value;
}
public static void Main(string[] Args)
{
var foo = default(Foo);
Console.WriteLine(((Foo)foo.Clone()).CloneCounter);
Console.WriteLine(((Foo)BoxAndCast<Foo>(foo).Clone()).CloneCounter);
Console.WriteLine(foo.CloneCounter);
object i = 42;
Console.WriteLine((int)i);
Console.WriteLine(Unbox<int>(i));
}
}
|
Fix how to find TeamCity queued builds. | #region Usings
using System.Collections.Generic;
using System.Text.RegularExpressions;
#endregion
namespace Buildron.Infrastructure.BuildsProvider.TeamCity
{
/// <summary>
/// Build queue parser.
/// </summary>
public static class BuildQueueParser
{
#region Fields
private static Regex s_getBuildConfigurationIdsRegex = new Regex("name=\"ref(bt\\d+)\"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
#endregion
#region Methods
/// <summary>
/// Parses the build configurations identifiers from queue html (http://TeamCityServer/queue.html).
/// </summary>
/// <returns>
/// The build configurations identifiers from queue html.
/// </returns>
/// <param name='html'>
/// Html.
/// </param>
public static IList<string> ParseBuildConfigurationsIdsFromQueueHtml (string html)
{
var ids = new List<string> ();
var matches = s_getBuildConfigurationIdsRegex.Matches (html);
foreach (Match m in matches) {
ids.Add(m.Groups[1].Value);
}
return ids;
}
#endregion
}
} | #region Usings
using System.Collections.Generic;
using System.Text.RegularExpressions;
#endregion
namespace Buildron.Infrastructure.BuildsProvider.TeamCity
{
/// <summary>
/// Build queue parser.
/// </summary>
public static class BuildQueueParser
{
#region Fields
private static Regex s_getBuildConfigurationIdsRegex = new Regex("viewType\\.html\\?buildTypeId=(.+)\"", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
#endregion
#region Methods
/// <summary>
/// Parses the build configurations identifiers from queue html (http://TeamCityServer/queue.html).
/// </summary>
/// <returns>
/// The build configurations identifiers from queue html.
/// </returns>
/// <param name='html'>
/// Html.
/// </param>
public static IList<string> ParseBuildConfigurationsIdsFromQueueHtml (string html)
{
var ids = new List<string> ();
var matches = s_getBuildConfigurationIdsRegex.Matches (html);
foreach (Match m in matches) {
ids.Add(m.Groups[1].Value);
}
return ids;
}
#endregion
}
} |
Add missing file with benchmarks | using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Jobs;
using BenchmarkDotNet.Order;
namespace NHasher.Benchmarks
{
[ClrJob, CoreJob]
[MemoryDiagnoser]
public class Benchmarks
{
private const int N = 10000;
private readonly byte[] _data;
private readonly MurmurHash3X64L128 _murmurHash3X64L128 = new MurmurHash3X64L128();
private readonly XXHash32 _xxHash32 = new XXHash32();
private readonly XXHash64 _xxHash64 = new XXHash64();
public Benchmarks()
{
_data = new byte[N];
new Random(42).NextBytes(_data);
}
[Benchmark]
public byte[] MurmurHash3X64L128()
{
return _murmurHash3X64L128.ComputeHash(_data);
}
[Benchmark]
public byte[] XXHash32()
{
return _xxHash32.ComputeHash(_data);
}
[Benchmark]
public byte[] XXHash64()
{
return _xxHash64.ComputeHash(_data);
}
}
}
| using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Attributes.Jobs;
namespace NHasher.Benchmarks
{
[ClrJob, CoreJob]
[MemoryDiagnoser]
public class Benchmarks
{
private byte[] _data;
private readonly MurmurHash3X64L128 _murmurHash3X64L128 = new MurmurHash3X64L128();
private readonly XXHash32 _xxHash32 = new XXHash32();
private readonly XXHash64 _xxHash64 = new XXHash64();
[Params(4, 11, 25, 100, 1000, 10000)]
public int PayloadLength { get; set; }
[Setup]
public void SetupData()
{
_data = new byte[PayloadLength];
new Random(42).NextBytes(_data);
}
[Benchmark]
public byte[] MurmurHash3X64L128() => _murmurHash3X64L128.ComputeHash(_data);
[Benchmark]
public byte[] XXHash32() => _xxHash32.ComputeHash(_data);
[Benchmark]
public byte[] XXHash64() => _xxHash64.ComputeHash(_data);
}
}
|
Make assembly title match assembly name | using System.Reflection;
using System.Runtime.CompilerServices;
// Nuget: Title
[assembly: AssemblyTitle( "D2L Security For Web API" )]
// Nuget: Description
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
// Nuget: Author
[assembly: AssemblyCompany( "Desire2Learn" )]
// Nuget: Owners
[assembly: AssemblyProduct( "Brightspace" )]
// Nuget: Version
[assembly: AssemblyInformationalVersion( "5.2.0.0" )]
[assembly: AssemblyVersion( "5.2.0.0" )]
[assembly: AssemblyFileVersion( "5.2.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
| using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle( "D2L.Security.WebApi" )]
[assembly: AssemblyDescription( "A library that implements Web API components for authenticating D2L services." )]
[assembly: AssemblyCompany( "Desire2Learn" )]
[assembly: AssemblyProduct( "Brightspace" )]
[assembly: AssemblyInformationalVersion( "5.2.0.0" )]
[assembly: AssemblyVersion( "5.2.0.0" )]
[assembly: AssemblyFileVersion( "5.2.0.0" )]
[assembly: AssemblyCopyright( "Copyright © Desire2Learn" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.UnitTests" )]
[assembly: InternalsVisibleTo( "D2L.Security.OAuth2.WebApi.IntegrationTests" )]
|
Disable flaky XML encoding test | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Xml;
using Xunit;
public class XmlWriterTests
{
[Fact]
public static void WriteWithEncoding()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CloseOutput = false;
settings.Encoding = Encoding.GetEncoding("Windows-1252");
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
writer.WriteElementString("orderID", "1-456-ab\u0661");
writer.WriteElementString("orderID", "2-36-00a\uD800\uDC00\uD801\uDC01");
writer.Flush();
}
strm.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[strm.Length];
int bytesCount = strm.Read(bytes, 0, (int)strm.Length);
string s = settings.Encoding.GetString(bytes, 0, bytesCount);
Assert.Equal("<orderID>1-456-ab١</orderID><orderID>2-36-00a𐀀𐐁</orderID>", s);
}
} | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Text;
using System.Xml;
using Xunit;
public class XmlWriterTests
{
[Fact]
[ActiveIssue(1263)]
public static void WriteWithEncoding()
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
XmlWriterSettings settings = new XmlWriterSettings();
settings.OmitXmlDeclaration = true;
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.CloseOutput = false;
settings.Encoding = Encoding.GetEncoding("Windows-1252");
MemoryStream strm = new MemoryStream();
using (XmlWriter writer = XmlWriter.Create(strm, settings))
{
writer.WriteElementString("orderID", "1-456-ab\u0661");
writer.WriteElementString("orderID", "2-36-00a\uD800\uDC00\uD801\uDC01");
writer.Flush();
}
strm.Seek(0, SeekOrigin.Begin);
byte[] bytes = new byte[strm.Length];
int bytesCount = strm.Read(bytes, 0, (int)strm.Length);
string s = settings.Encoding.GetString(bytes, 0, bytesCount);
Assert.Equal("<orderID>1-456-ab١</orderID><orderID>2-36-00a𐀀𐐁</orderID>", s);
}
} |
Fix auto splitter settings scroll bar not always appearing | using LiveSplit.UI;
using LiveSplit.UI.Components;
using System;
using System.Windows.Forms;
using System.Xml;
namespace LiveSplit.View
{
public partial class ComponentSettingsDialog : Form
{
public XmlNode ComponentSettings { get; set; }
public IComponent Component { get; set; }
public ComponentSettingsDialog(IComponent component)
{
InitializeComponent();
Component = component;
AddComponent(component);
}
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Component.SetSettings(ComponentSettings);
DialogResult = DialogResult.Cancel;
Close();
}
protected void AddComponent(IComponent component)
{
var settingsControl = Component.GetSettingsControl(LayoutMode.Vertical);
AddControl(component.ComponentName, settingsControl);
ComponentSettings = component.GetSettings(new XmlDocument());
}
protected void AddControl(string name, Control control)
{
panel.Controls.Add(control);
Name = name + " Settings";
}
}
}
| using LiveSplit.UI;
using LiveSplit.UI.Components;
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Xml;
namespace LiveSplit.View
{
public partial class ComponentSettingsDialog : Form
{
public XmlNode ComponentSettings { get; set; }
public IComponent Component { get; set; }
public ComponentSettingsDialog(IComponent component)
{
InitializeComponent();
Component = component;
AddComponent(component);
}
private void btnOK_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.OK;
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Component.SetSettings(ComponentSettings);
DialogResult = DialogResult.Cancel;
Close();
}
protected void AddComponent(IComponent component)
{
var settingsControl = Component.GetSettingsControl(LayoutMode.Vertical);
AddControl(component.ComponentName, settingsControl);
ComponentSettings = component.GetSettings(new XmlDocument());
}
protected void AddControl(string name, Control control)
{
control.Location = new Point(0, 0);
panel.Controls.Add(control);
Name = name + " Settings";
}
}
}
|
Fix URI Is Not Responding test | using System;
using FluentAssertions;
using OpenMagic.Extensions;
using OpenMagic.Specifications.Helpers;
using TechTalk.SpecFlow;
namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions
{
[Binding]
public class IsReposondingSteps
{
private readonly GivenData _given;
private readonly ActualData _actual;
public IsReposondingSteps(GivenData given, ActualData actual)
{
_given = given;
_actual = actual;
}
[Given(@"URI is responding")]
public void GivenUriIsResponding()
{
_given.Uri = new Uri("http://www.google.com");
}
[Given(@"URI is not responding")]
public void GivenUriIsNotResponding()
{
_given.Uri = new Uri("http://" + Guid.NewGuid());
}
[When(@"I call IsResponding\(<uri>\)")]
public void WhenICallIsResponding()
{
_actual.GetResult(() => _given.Uri.IsResponding());
}
}
}
| using System;
using FluentAssertions;
using OpenMagic.Extensions;
using OpenMagic.Specifications.Helpers;
using TechTalk.SpecFlow;
namespace OpenMagic.Specifications.Steps.Extensions.UriExtensions
{
[Binding]
public class IsReposondingSteps
{
private readonly GivenData _given;
private readonly ActualData _actual;
public IsReposondingSteps(GivenData given, ActualData actual)
{
_given = given;
_actual = actual;
}
[Given(@"URI is responding")]
public void GivenUriIsResponding()
{
_given.Uri = new Uri("http://www.google.com");
}
[Given(@"URI is not responding")]
public void GivenUriIsNotResponding()
{
_given.Uri = new Uri("http://domainthat.doesnotexist");
}
[When(@"I call IsResponding\(<uri>\)")]
public void WhenICallIsResponding()
{
_actual.GetResult(() => _given.Uri.IsResponding());
}
}
}
|
Add missing header to MostPlayedBeatmapsContainer | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Users;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class PaginatedMostPlayedBeatmapContainer : PaginatedContainer<APIUserMostPlayedBeatmap>
{
public PaginatedMostPlayedBeatmapContainer(Bindable<User> user)
: base(user, "No records. :(")
{
ItemsPerPage = 5;
}
[BackgroundDependencyLoader]
private void load()
{
ItemsContainer.Direction = FillDirection.Vertical;
}
protected override APIRequest<List<APIUserMostPlayedBeatmap>> CreateRequest() =>
new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage);
protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) =>
new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Users;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class PaginatedMostPlayedBeatmapContainer : PaginatedContainer<APIUserMostPlayedBeatmap>
{
public PaginatedMostPlayedBeatmapContainer(Bindable<User> user)
: base(user, "No records. :(", "Most Played Beatmaps")
{
ItemsPerPage = 5;
}
[BackgroundDependencyLoader]
private void load()
{
ItemsContainer.Direction = FillDirection.Vertical;
}
protected override APIRequest<List<APIUserMostPlayedBeatmap>> CreateRequest() =>
new GetUserMostPlayedBeatmapsRequest(User.Value.Id, VisiblePages++, ItemsPerPage);
protected override Drawable CreateDrawableItem(APIUserMostPlayedBeatmap model) =>
new DrawableMostPlayedBeatmap(model.GetBeatmapInfo(Rulesets), model.PlayCount);
}
}
|
Update BlockType of switch statement. | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax>
{
protected override void CollectBlockSpans(
SwitchStatementSyntax node,
ArrayBuilder<BlockSpan> spans,
CancellationToken cancellationToken)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: TextSpan.FromBounds(node.CloseParenToken.Span.End, node.CloseBraceToken.Span.End),
hintSpan: node.Span,
type: BlockTypes.Statement));
}
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Structure;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Structure
{
internal class SwitchStatementStructureProvider : AbstractSyntaxNodeStructureProvider<SwitchStatementSyntax>
{
protected override void CollectBlockSpans(
SwitchStatementSyntax node,
ArrayBuilder<BlockSpan> spans,
CancellationToken cancellationToken)
{
spans.Add(new BlockSpan(
isCollapsible: true,
textSpan: TextSpan.FromBounds(node.CloseParenToken.Span.End, node.CloseBraceToken.Span.End),
hintSpan: node.Span,
type: BlockTypes.Conditional));
}
}
} |
Increase HP gain of bananas | // 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.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Catch.Judgements
{
public class CatchBananaJudgement : CatchJudgement
{
public override bool AffectsCombo => false;
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 1100;
}
}
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 0.01;
}
}
public override bool ShouldExplodeFor(JudgementResult result) => true;
}
}
| // 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.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Catch.Judgements
{
public class CatchBananaJudgement : CatchJudgement
{
public override bool AffectsCombo => false;
protected override int NumericResultFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return 1100;
}
}
protected override double HealthIncreaseFor(HitResult result)
{
switch (result)
{
default:
return 0;
case HitResult.Perfect:
return DEFAULT_MAX_HEALTH_INCREASE * 0.75;
}
}
public override bool ShouldExplodeFor(JudgementResult result) => true;
}
}
|
Fix trip cell distance label. | using Foundation;
using System;
using UIKit;
using MyTrips.ViewModel;
using Humanizer;
namespace MyTrips.iOS
{
public partial class TripsTableViewController : UITableViewController
{
const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER";
PastTripsViewModel ViewModel { get; set; }
public TripsTableViewController (IntPtr handle) : base (handle)
{
}
public override async void ViewDidLoad()
{
base.ViewDidLoad();
// TODO: Grab data for UITableView.
ViewModel = new PastTripsViewModel();
await ViewModel.ExecuteLoadPastTripsCommandAsync();
}
#region UITableViewSource
public override nint RowsInSection(UITableView tableView, nint section)
{
return ViewModel.Trips.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
// No need to check for null; storyboards always return a dequeable cell.
var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell;
if (cell == null)
{
cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER));
}
var trip = ViewModel.Trips[indexPath.Row];
cell.LocationName = trip.TripId;
cell.TimeAgo = trip.TimeAgo;
cell.Distance = $"{trip.TotalDistance} miles";
return cell;
}
#endregion
}
} | using Foundation;
using System;
using UIKit;
using MyTrips.ViewModel;
using Humanizer;
namespace MyTrips.iOS
{
public partial class TripsTableViewController : UITableViewController
{
const string TRIP_CELL_IDENTIFIER = "TRIP_CELL_IDENTIFIER";
PastTripsViewModel ViewModel { get; set; }
public TripsTableViewController (IntPtr handle) : base (handle)
{
}
public override async void ViewDidLoad()
{
base.ViewDidLoad();
// TODO: Grab data for UITableView.
ViewModel = new PastTripsViewModel();
await ViewModel.ExecuteLoadPastTripsCommandAsync();
}
#region UITableViewSource
public override nint RowsInSection(UITableView tableView, nint section)
{
return ViewModel.Trips.Count;
}
public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
{
// No need to check for null; storyboards always return a dequeable cell.
var cell = tableView.DequeueReusableCell(TRIP_CELL_IDENTIFIER) as TripTableViewCell;
if (cell == null)
{
cell = new TripTableViewCell(new NSString(TRIP_CELL_IDENTIFIER));
}
var trip = ViewModel.Trips[indexPath.Row];
cell.LocationName = trip.TripId;
cell.TimeAgo = trip.TimeAgo;
cell.Distance = trip.TotalDistance;
return cell;
}
#endregion
}
} |
Fix issue in a converter | using System;
using System.Globalization;
using System.Windows.Data;
namespace KodiRemote.Wp81.Converters
{
public class ShorterStringConverter : IValueConverter
{
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value.ToString();
int max;
if (!int.TryParse(parameter.ToString(), out max)) return str;
if (str.Length <= max) return str;
return str.Substring(0, max - 3) + "...";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} | using System;
using System.Globalization;
using System.Windows.Data;
namespace KodiRemote.Wp81.Converters
{
public class ShorterStringConverter : IValueConverter
{
public virtual object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null || parameter == null) return string.Empty;
int max;
if (!int.TryParse(parameter.ToString(), out max)) return value;
string str = value.ToString();
if (str.Length <= max) return str;
return str.Substring(0, max - 3) + "...";
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
} |
Clean up engine bindings assembly info. | 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("Urho3DNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Urho3D")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("58DA6FEF-5C52-4CB9-9E0E-C9621ABFAB76")]
// 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;
[assembly: AssemblyTitle("Urho3DNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Urho3D")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.