Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Fix test data path when building in Unity plugin | using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ZoneDefinition]
public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
{
}
[SetUpFixture]
public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
{
}
}
| using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
// This attribute is marked obsolete but is still supported. Use is discouraged in preference to convention, but the
// convention doesn't work for us. That convention is to walk up the tree from the executing assembly and look for a
// relative path called "test/data". This doesn't work because our common "build" folder is one level above our
// "test/data" folder, so it doesn't get found. We want to keep the common "build" folder, but allow multiple "modules"
// with separate "test/data" folders. E.g. "resharper-unity" and "resharper-yaml"
// TODO: This makes things work when building as part of the Unity project, but breaks standalone
// Maybe it should be using product/subplatform markers?
#pragma warning disable 618
[assembly: TestDataPathBase("resharper-yaml/test/data")]
#pragma warning restore 618
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ZoneDefinition]
public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
{
}
[SetUpFixture]
public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
{
}
}
|
Add download_url and content_type for file upload questions | using Newtonsoft.Json;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class ResponseAnswer
{
public long? ChoiceId { get; set; }
public long? RowId { get; set; }
public long? ColId { get; set; }
public long? OtherId { get; set; }
public string Text { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public string SimpleText { get; set; }
[JsonIgnore]
internal object TagData { get; set; }
public ChoiceMetadata ChoiceMetadata { get; set; }
}
} | using Newtonsoft.Json;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class ResponseAnswer
{
public long? ChoiceId { get; set; }
public long? RowId { get; set; }
public long? ColId { get; set; }
public long? OtherId { get; set; }
public string Text { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public string DownloadUrl { get; set; }
public string ContentType { get; set; }
public string SimpleText { get; set; }
[JsonIgnore]
internal object TagData { get; set; }
public ChoiceMetadata ChoiceMetadata { get; set; }
}
} |
Revert "And we have the medium line working!" | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;
namespace WPAppStudio.Services
{
public class WordWrapService
{
private readonly ITextMeasurementService _tms;
public WordWrapService(ITextMeasurementService textMeasurementService)
{
_tms = textMeasurementService;
}
public string GetWords(string text, int wordCount)
{
StringBuilder result = new StringBuilder();
for (int word = 0; word < wordCount; word++)
{
int space = text.IndexOf(' ', 1);
//return text.Substring(0, space);
if (space == -1)
{
result.Append(text);
return result.ToString();
}
result.Append(text.Substring(0, space));
text = text.Substring(space);
}
return result.ToString();
}
public string GetLine(string text, int lineLength)
{
for (int wordCount = 10; wordCount > 0; wordCount--)
{
string line = GetWords(text, wordCount);
int width = _tms.GetTextWidth(line);
if (width <= lineLength)
{
return line;
}
}
return GetWords(text, 1);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;
namespace WPAppStudio.Services
{
public class WordWrapService
{
private readonly ITextMeasurementService _tms;
public WordWrapService(ITextMeasurementService textMeasurementService)
{
_tms = textMeasurementService;
}
public string GetWords(string text, int wordCount)
{
StringBuilder result = new StringBuilder();
for (int word = 0; word < wordCount; word++)
{
int space = text.IndexOf(' ', 1);
//return text.Substring(0, space);
if (space == -1)
{
result.Append(text);
return result.ToString();
}
result.Append(text.Substring(0, space));
text = text.Substring(space);
}
return result.ToString();
}
public string GetLine(string text, int lineLength)
{
string line = GetWords(text, 3);
int width = _tms.GetTextWidth(line);
if (width <= lineLength)
{
return line;
}
return GetWords(text, 1);
}
}
}
|
Revert "Removing 'zzz' from method name" | using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
| using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
|
Enable the GC to clean up the process list immediately. Fixed potential null reference when disposing before starting. | using System;
using System.Diagnostics;
using System.Threading;
namespace ProcessRelauncher
{
public class ProcessMonitor : IDisposable
{
private Timer _timer;
private readonly int _monitoringPollingIntervalMs;
private readonly ProcessStartInfo _processStartInfo;
private readonly string _processName;
public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
{
_processStartInfo = launcher;
_processName = processName.ToLower();
_monitoringPollingIntervalMs = monitoringPollingIntervalMs;
}
public void Monitor(object o)
{
Process[] processlist = Process.GetProcesses();
foreach(var p in processlist)
{
if (p.ProcessName.ToLower().Equals(_processName)) return;
}
Process.Start(_processStartInfo);
GC.Collect();
}
public void Start()
{
if (_timer != null) return;
_timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
}
public void Dispose()
{
_timer.Dispose();
}
}
} | using System;
using System.Diagnostics;
using System.Threading;
namespace ProcessRelauncher
{
public class ProcessMonitor : IDisposable
{
private Timer _timer;
private readonly int _monitoringPollingIntervalMs;
private readonly ProcessStartInfo _processStartInfo;
private readonly string _processName;
public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
{
_processStartInfo = launcher;
_processName = processName.ToLower();
_monitoringPollingIntervalMs = monitoringPollingIntervalMs;
}
public void Monitor(object o)
{
Process[] processlist = Process.GetProcesses();
foreach (var p in processlist)
{
if (p.ProcessName.ToLower().Equals(_processName)) return;
}
Process.Start(_processStartInfo);
processlist = null;
GC.Collect();
}
public void Start()
{
if (_timer != null) return;
_timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
}
public void Dispose()
{
if (_timer == null) return;
_timer.Dispose();
}
}
} |
Comment out the code in Hangman that uses Table | using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
Table table = new Table(2, 3);
string output = table.Draw();
Console.WriteLine(output);
}
}
}
| using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
|
Set LogLevel in master branch to Warning | namespace BaiduHiCrawler
{
using System;
static class Constants
{
public const string CommentRetrivalUrlPattern =
"http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";
public const string LocalArchiveFolder = @".\Archive\";
public const string LogsFolder = @".\Logs\";
public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");
public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");
public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
public static readonly LogLevel LogLevel = LogLevel.Verbose;
}
}
| namespace BaiduHiCrawler
{
using System;
static class Constants
{
public const string CommentRetrivalUrlPattern =
"http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";
public const string LocalArchiveFolder = @".\Archive\";
public const string LogsFolder = @".\Logs\";
public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");
public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");
public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
public static readonly LogLevel LogLevel = LogLevel.Warning;
}
}
|
Set default <UpdateFrameCount> to 10 | using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount;
public List<Region> Regions;
public string UrlOpenMessage;
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 1;
UrlOpenMessage = "Visit webpage";
}
}
}
| using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount;
public List<Region> Regions;
public string UrlOpenMessage;
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 10;
UrlOpenMessage = "Visit webpage";
}
}
}
|
Add "Input Mode", "File" options to "Popup" action | using System.ComponentModel;
using System.Windows;
namespace DesktopWidgets.Actions
{
internal class PopupAction : ActionBase
{
[DisplayName("Text")]
public string Text { get; set; } = "";
[DisplayName("Title")]
public string Title { get; set; } = "";
[DisplayName("Image")]
public MessageBoxImage Image { get; set; }
protected override void ExecuteAction()
{
base.ExecuteAction();
MessageBox.Show(Text, Title, MessageBoxButton.OK, Image);
}
}
} | using System.ComponentModel;
using System.IO;
using System.Windows;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Actions
{
internal class PopupAction : ActionBase
{
public FilePath FilePath { get; set; } = new FilePath();
[DisplayName("Text")]
public string Text { get; set; } = "";
[DisplayName("Input Mode")]
public InputMode InputMode { get; set; } = InputMode.Text;
[DisplayName("Title")]
public string Title { get; set; } = "";
[DisplayName("Image")]
public MessageBoxImage Image { get; set; }
protected override void ExecuteAction()
{
base.ExecuteAction();
var input = string.Empty;
switch (InputMode)
{
case InputMode.Clipboard:
input = Clipboard.GetText();
break;
case InputMode.File:
input = File.ReadAllText(FilePath.Path);
break;
case InputMode.Text:
input = Text;
break;
}
MessageBox.Show(input, Title, MessageBoxButton.OK, Image);
}
}
} |
Add version field and make CheckForErrors less accessible from outside. | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace GarrysMod.AddonCreator
{
public class AddonJson
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("ignore")]
public List<string> Ignores { get; set; }
public void CheckForErrors()
{
if (string.IsNullOrEmpty(Title))
{
throw new MissingFieldException("Title is empty or not specified.");
}
if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
{
throw new InvalidDataException("Description contains NULL character.");
}
if (string.IsNullOrEmpty(Type))
{
throw new MissingFieldException("Type is empty or not specified.");
}
}
public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
{
foreach (var key in files.Keys.ToArray())
// ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
{
if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
files.Remove(key);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace GarrysMod.AddonCreator
{
public class AddonJson
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("ignore")]
public List<string> Ignores { get; set; }
[JsonProperty("version")]
public int Version { get; set; }
internal void CheckForErrors()
{
if (string.IsNullOrEmpty(Title))
{
throw new MissingFieldException("Title is empty or not specified.");
}
if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
{
throw new InvalidDataException("Description contains NULL character.");
}
if (string.IsNullOrEmpty(Type))
{
throw new MissingFieldException("Type is empty or not specified.");
}
}
public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
{
foreach (var key in files.Keys.ToArray())
// ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
{
if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
files.Remove(key);
}
}
}
}
|
Remove unused Toolbar options until we actually make use of them | using System;
using System.Diagnostics;
using Xamarin.Forms;
using InteractApp;
namespace InteractApp
{
public class EventListPageBase : ViewPage<EventListPageViewModel>
{
}
public partial class EventListPage : EventListPageBase
{
public EventListPage ()
{
InitializeComponent ();
this.Title = "Events";
Padding = new Thickness (0, 0, 0, 0);
ToolbarItems.Add (new ToolbarItem {
Text = "My Info",
Order = ToolbarItemOrder.Primary,
Command = new Command (this.ShowMyInfoPage),
});
ToolbarItems.Add (new ToolbarItem {
Text = "My Events",
Order = ToolbarItemOrder.Primary,
});
//To hide iOS list seperator
EventList.SeparatorVisibility = SeparatorVisibility.None;
ViewModel.LoadEventsCommand.Execute (null);
EventList.ItemTapped += async (sender, e) => {
Event evt = (Event)e.Item;
Debug.WriteLine ("Tapped: " + (evt.Name));
var page = new EventInfoPage (evt);
((ListView)sender).SelectedItem = null;
await Navigation.PushAsync (page);
};
}
private void ShowMyInfoPage ()
{
Navigation.PushAsync (new MyInfoPage ());
}
}
}
| using System;
using System.Diagnostics;
using Xamarin.Forms;
using InteractApp;
namespace InteractApp
{
public class EventListPageBase : ViewPage<EventListPageViewModel>
{
}
public partial class EventListPage : EventListPageBase
{
public EventListPage ()
{
InitializeComponent ();
this.Title = "Events";
Padding = new Thickness (0, 0, 0, 0);
// ToolbarItems.Add (new ToolbarItem {
// Text = "My Info",
// Order = ToolbarItemOrder.Primary,
// Command = new Command (this.ShowMyInfoPage),
// });
// ToolbarItems.Add (new ToolbarItem {
// Text = "My Events",
// Order = ToolbarItemOrder.Primary,
// });
//To hide iOS list seperator
EventList.SeparatorVisibility = SeparatorVisibility.None;
ViewModel.LoadEventsCommand.Execute (null);
EventList.ItemTapped += async (sender, e) => {
Event evt = (Event)e.Item;
Debug.WriteLine ("Tapped: " + (evt.Name));
var page = new EventInfoPage (evt);
((ListView)sender).SelectedItem = null;
await Navigation.PushAsync (page);
};
}
private void ShowMyInfoPage ()
{
Navigation.PushAsync (new MyInfoPage ());
}
}
}
|
Write Position using the Position Writer Function | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;
namespace PolarisServer.Models
{
public class PSOObject
{
public struct PSOObjectThing
{
public UInt32 data;
}
public EntityHeader Header { get; set; }
public MysteryPositions Position { get; set; }
public string Name { get; set; }
public UInt32 ThingFlag { get; set; }
public PSOObjectThing[] things { get; set; }
public byte[] GenerateSpawnBlob()
{
PacketWriter writer = new PacketWriter();
writer.WriteStruct(Header);
writer.WriteStruct(Position);
writer.Seek(2, SeekOrigin.Current); // Padding I guess...
writer.WriteFixedLengthASCII(Name, 0x34);
writer.Write(ThingFlag);
writer.Write(things.Length);
foreach (PSOObjectThing thing in things)
{
writer.WriteStruct(thing);
}
return writer.ToArray();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;
namespace PolarisServer.Models
{
public class PSOObject
{
public struct PSOObjectThing
{
public UInt32 data;
}
public EntityHeader Header { get; set; }
public MysteryPositions Position { get; set; }
public string Name { get; set; }
public UInt32 ThingFlag { get; set; }
public PSOObjectThing[] things { get; set; }
public byte[] GenerateSpawnBlob()
{
PacketWriter writer = new PacketWriter();
writer.WriteStruct(Header);
writer.Write(Position);
writer.Seek(2, SeekOrigin.Current); // Padding I guess...
writer.WriteFixedLengthASCII(Name, 0x34);
writer.Write(ThingFlag);
writer.Write(things.Length);
foreach (PSOObjectThing thing in things)
{
writer.WriteStruct(thing);
}
return writer.ToArray();
}
}
}
|
Change comment test to reflect changed samples | using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class VorbisTests : IDisposable
{
private ITestOutputHelper Output { get; }
private VorbisReader Reader1 { get; }
private VorbisReader Reader2 { get; }
private VorbisWriter Writer { get; }
public VorbisTests(ITestOutputHelper output)
{
Output = output;
Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));
Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
}
[Fact]
public void TestReadComments()
{
Reader1.ReadPacket();
var commentPacket = Reader1.ReadPacket();
Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");
Assert.IsType<VorbisCommentHeader>(commentPacket);
var commentHeader = (VorbisCommentHeader)commentPacket;
Output.WriteLine("Comments in header:");
foreach (var userComment in commentHeader.UserComments)
{
Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
}
Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("genre", "Soundtrack")));
}
public void Dispose()
{
Reader1?.Dispose();
Reader2?.Dispose();
Writer?.Dispose();
}
}
} | using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class VorbisTests : IDisposable
{
private ITestOutputHelper Output { get; }
private VorbisReader Reader1 { get; }
private VorbisReader Reader2 { get; }
private VorbisWriter Writer { get; }
public VorbisTests(ITestOutputHelper output)
{
Output = output;
Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));
Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
}
[Fact]
public void TestReadComments()
{
Reader1.ReadPacket();
var commentPacket = Reader1.ReadPacket();
Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");
Assert.IsType<VorbisCommentHeader>(commentPacket);
var commentHeader = (VorbisCommentHeader)commentPacket;
Output.WriteLine("Comments in header:");
foreach (var userComment in commentHeader.UserComments)
{
Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
}
Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("DATE", "2012")));
}
public void Dispose()
{
Reader1?.Dispose();
Reader2?.Dispose();
Writer?.Dispose();
}
}
} |
Fix a little bug with the new counter. The rf frequency measurement is now tested and works. | using System;
using System.Collections.Generic;
using System.Text;
using DAQ.Environment;
namespace DAQ.HAL
{
public class Agilent53131A : FrequencyCounter
{
public Agilent53131A(String visaAddress) : base(visaAddress)
{}
public override double Frequency
{
get
{
if (!Environs.Debug)
{
Write(":FUNC 'FREQ 1'");
Write(":FREQ:ARM:STAR:SOUR IMM");
Write(":FREQ:ARM:STOP:SOUR TIM");
Write(":FREQ:ARM:STOP:TIM 1.0");
Write("READ:FREQ?");
string fr = Read();
return Double.Parse(fr);
}
else
{
return 170.730 + (new Random()).NextDouble();
}
}
}
public override double Amplitude
{
get { throw new Exception("The method or operation is not implemented."); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using DAQ.Environment;
namespace DAQ.HAL
{
public class Agilent53131A : FrequencyCounter
{
public Agilent53131A(String visaAddress) : base(visaAddress)
{}
public override double Frequency
{
get
{
if (!Environs.Debug)
{
Connect();
Write(":FUNC 'FREQ 1'");
Write(":FREQ:ARM:STAR:SOUR IMM");
Write(":FREQ:ARM:STOP:SOUR TIM");
Write(":FREQ:ARM:STOP:TIM 1.0");
Write("READ:FREQ?");
string fr = Read();
Disconnect();
return Double.Parse(fr);
}
else
{
return 170.730 + (new Random()).NextDouble();
}
}
}
public override double Amplitude
{
get { throw new Exception("The method or operation is not implemented."); }
}
}
}
|
Decrease bootstrap column sizes to improve mobile experience | @model Vaskelista.Models.Household
@{
ViewBag.Title = "Create";
}
<h2>Velkommen til vaskelista</h2>
<p>Her kan du velge hva vaskelisten din skal hete:</p>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12"><label>@Request.Url.ToString()</label></div>
<div class="col-md-12">
<ul class="form-option-list">
@foreach (string randomUrl in ViewBag.RandomUrls)
{
<li>
@using (Html.BeginForm("Create", "Household", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Token, new { Value = randomUrl })
<input type="submit" value="@randomUrl" class="btn btn-default" />
}
</li>
}
</ul>
</div>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
| @model Vaskelista.Models.Household
@{
ViewBag.Title = "Create";
}
<h2>Velkommen til vaskelista</h2>
<p>Her kan du velge hva vaskelisten din skal hete:</p>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-2"><label>@Request.Url.ToString()</label></div>
<div class="col-md-4">
<ul class="form-option-list">
@foreach (string randomUrl in ViewBag.RandomUrls)
{
<li>
@using (Html.BeginForm("Create", "Household", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Token, new { Value = randomUrl })
<input type="submit" value="@randomUrl" class="btn btn-default" />
}
</li>
}
</ul>
</div>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
|
Rename previously unknown GAF field | namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
| namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
|
Add change handling for sample section | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Timing
{
internal class SampleSection : Section<SampleControlPoint>
{
private LabelledTextBox bank;
private SliderWithTextBoxInput<int> volume;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new Drawable[]
{
bank = new LabelledTextBox
{
Label = "Bank Name",
},
volume = new SliderWithTextBoxInput<int>("Volume")
{
Current = new SampleControlPoint().SampleVolumeBindable,
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
{
if (point.NewValue != null)
{
bank.Current = point.NewValue.SampleBankBindable;
volume.Current = point.NewValue.SampleVolumeBindable;
}
}
protected override SampleControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);
return new SampleControlPoint
{
SampleBank = reference.SampleBank,
SampleVolume = reference.SampleVolume,
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Timing
{
internal class SampleSection : Section<SampleControlPoint>
{
private LabelledTextBox bank;
private SliderWithTextBoxInput<int> volume;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new Drawable[]
{
bank = new LabelledTextBox
{
Label = "Bank Name",
},
volume = new SliderWithTextBoxInput<int>("Volume")
{
Current = new SampleControlPoint().SampleVolumeBindable,
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
{
if (point.NewValue != null)
{
bank.Current = point.NewValue.SampleBankBindable;
bank.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
volume.Current = point.NewValue.SampleVolumeBindable;
volume.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override SampleControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);
return new SampleControlPoint
{
SampleBank = reference.SampleBank,
SampleVolume = reference.SampleVolume,
};
}
}
}
|
Tweak conventions for nservicebus messages to work in unobtrusive and normal mode | using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.Extensions
{
public static class EndpointConfigurationExtensions
{
public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
{
var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);
if (isDevelopment)
{
var transport = config.UseTransport<LearningTransport>();
transport.Transactions(TransportTransactionMode.ReceiveOnly);
ConfigureRouting(transport.Routing());
}
else
{
config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
}
return config;
}
private static void ConfigureRouting(RoutingSettings routing)
{
routing.RouteToEndpoint(
typeof(ImportLevyDeclarationsCommand).Assembly,
typeof(ImportLevyDeclarationsCommand).Namespace,
"SFA.DAS.EmployerFinance.MessageHandlers"
);
routing.RouteToEndpoint(
typeof(SendEmailCommand).Assembly,
typeof(SendEmailCommand).Namespace,
"SFA.DAS.Notifications.MessageHandlers"
);
}
}
} | using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.Extensions
{
public static class EndpointConfigurationExtensions
{
public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
{
var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);
if (isDevelopment)
{
var transport = config.UseTransport<LearningTransport>();
transport.Transactions(TransportTransactionMode.ReceiveOnly);
ConfigureRouting(transport.Routing());
}
else
{
config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
var conventions = config.Conventions();
conventions.DefiningCommandsAs(type =>
{
return type.Namespace == typeof(SendEmailCommand).Namespace || type.Namespace == typeof(ImportLevyDeclarationsCommand).Namespace;
});
}
return config;
}
private static void ConfigureRouting(RoutingSettings routing)
{
routing.RouteToEndpoint(
typeof(ImportLevyDeclarationsCommand).Assembly,
typeof(ImportLevyDeclarationsCommand).Namespace,
"SFA.DAS.EmployerFinance.MessageHandlers"
);
routing.RouteToEndpoint(
typeof(SendEmailCommand).Assembly,
typeof(SendEmailCommand).Namespace,
"SFA.DAS.Notifications.MessageHandlers"
);
}
}
} |
Use the logger for writing to the console. | using System;
using System.Threading;
using Flood.Editor.Server;
namespace Flood.Editor
{
public class ServerManager
{
public EditorServer Server { get; private set; }
private ManualResetEventSlim serverCreatedEvent;
private void RunBuiltinServer()
{
serverCreatedEvent.Set();
Server.Serve();
}
public void CreateBuiltinServer()
{
Console.WriteLine("Initializing the built-in editor server...");
serverCreatedEvent = new ManualResetEventSlim();
Server = new EditorServer();
System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
serverCreatedEvent.Wait();
}
}
} | using System;
using System.Threading;
using Flood.Editor.Server;
namespace Flood.Editor
{
public class ServerManager
{
public EditorServer Server { get; private set; }
private ManualResetEventSlim serverCreatedEvent;
private void RunBuiltinServer()
{
serverCreatedEvent.Set();
Server.Serve();
}
public void CreateBuiltinServer()
{
Log.Info("Initializing the built-in editor server...");
serverCreatedEvent = new ManualResetEventSlim();
Server = new EditorServer();
System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
serverCreatedEvent.Wait();
}
}
} |
Make bitmap loading cache the image | using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;
namespace WPFConverters
{
public class BitmapImageConverter : BaseConverter
{
protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute));
if (value is Uri)
return new BitmapImage((Uri)value);
return DependencyProperty.UnsetValue;
}
}
} | using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;
namespace WPFConverters
{
public class BitmapImageConverter : BaseConverter
{
protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
return LoadImage(new Uri((string)value, UriKind.RelativeOrAbsolute));
if (value is Uri)
return LoadImage((Uri)value);
return DependencyProperty.UnsetValue;
}
private BitmapImage LoadImage(Uri uri)
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = uri;
image.EndInit();
return image;
}
}
} |
Use google API key in async test. | using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;
namespace Geocoding.Tests
{
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
GoogleGeocoder geoCoder;
protected override IAsyncGeocoder CreateAsyncGeocoder()
{
geoCoder = new GoogleGeocoder();
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
public void CanParseAddressTypes(string address, GoogleAddressType type)
{
geoCoder.GeocodeAsync(address).ContinueWith(task =>
{
GoogleAddress[] addresses = task.Result.ToArray();
Assert.Equal(type, addresses[0].Type);
});
}
}
}
| using System.Configuration;
using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;
namespace Geocoding.Tests
{
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
GoogleGeocoder geoCoder;
protected override IAsyncGeocoder CreateAsyncGeocoder()
{
geoCoder = new GoogleGeocoder
{
ApiKey = ConfigurationManager.AppSettings["googleApiKey"]
};
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
public void CanParseAddressTypes(string address, GoogleAddressType type)
{
geoCoder.GeocodeAsync(address).ContinueWith(task =>
{
GoogleAddress[] addresses = task.Result.ToArray();
Assert.Equal(type, addresses[0].Type);
});
}
}
}
|
Allow for multiple instances of redis running on the same server but different ports. | using System.Configuration;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
/// <summary>
/// Configuration Element Collection for <see cref="RedisHost"/>
/// </summary>
public class RedisHostCollection : ConfigurationElementCollection
{
/// <summary>
/// Gets or sets the <see cref="RedisHost"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="RedisHost"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
public RedisHost this[int index]
{
get
{
return BaseGet(index) as RedisHost;
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Creates the new element.
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new RedisHost();
}
/// <summary>
/// Gets the element key.
/// </summary>
/// <param name="element">The element.</param>
/// <returns></returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((RedisHost)element).Host;
}
}
} | using System.Configuration;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
/// <summary>
/// Configuration Element Collection for <see cref="RedisHost"/>
/// </summary>
public class RedisHostCollection : ConfigurationElementCollection
{
/// <summary>
/// Gets or sets the <see cref="RedisHost"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="RedisHost"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
public RedisHost this[int index]
{
get
{
return BaseGet(index) as RedisHost;
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Creates the new element.
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new RedisHost();
}
/// <summary>
/// Gets the element key.
/// </summary>
/// <param name="element">The element.</param>
/// <returns></returns>
protected override object GetElementKey(ConfigurationElement element)
{
return string.Format("{0}:{1}", ((RedisHost)element).Host, ((RedisHost)element).CachePort);
}
}
} |
Fix up badly spelled test | using System;
using System.Diagnostics;
using System.Linq.Expressions;
using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Tests.ResultOperators
{
[TestClass]
[PexClass(typeof(SubExpressionReplacement))]
public partial class SubExpressionReplacementTest
{
[TestInitialize]
public void TestInit()
{
TestUtils.ResetLINQLibrary();
}
[TestCleanup]
public void TestDone()
{
MEFUtilities.MyClassDone();
}
[PexMethod, PexAllowedException(typeof(ArgumentNullException))]
public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
{
return source.ReplaceSubExpression(pattern, replacement);
}
[TestMethod]
public void TestSimpleReplacement()
{
var arr = Expression.Parameter(typeof(int[]), "myarr");
var param = Expression.Parameter(typeof(int), "dude");
var expr = Expression.ArrayIndex(arr, param);
var rep = Expression.Parameter(typeof(int), "fork");
var result = expr.ReplaceSubExpression(param, rep);
Debg.WriteLine("Expression: " + result.ToString());
Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
}
}
}
| using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace LINQToTTreeLib.Tests.ResultOperators
{
[TestClass]
[PexClass(typeof(SubExpressionReplacement))]
public partial class SubExpressionReplacementTest
{
[TestInitialize]
public void TestInit()
{
TestUtils.ResetLINQLibrary();
}
[TestCleanup]
public void TestDone()
{
MEFUtilities.MyClassDone();
}
[PexMethod, PexAllowedException(typeof(ArgumentNullException))]
public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
{
return source.ReplaceSubExpression(pattern, replacement);
}
[TestMethod]
public void TestSimpleReplacement()
{
var arr = Expression.Parameter(typeof(int[]), "myarr");
var param = Expression.Parameter(typeof(int), "dude");
var expr = Expression.ArrayIndex(arr, param);
var rep = Expression.Parameter(typeof(int), "fork");
var result = expr.ReplaceSubExpression(param, rep);
Debug.WriteLine("Expression: " + result.ToString());
Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
}
}
}
|
Use shell execute for run action. | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MediaCentreServer.Controllers
{
// Controller for running an application.
public class RunController : ApiController
{
// POST /api/run?path=...
public void Post(string path)
{
var startInfo = new ProcessStartInfo(path);
startInfo.UseShellExecute = false;
Process.Start(startInfo);
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MediaCentreServer.Controllers
{
// Controller for running an application.
public class RunController : ApiController
{
// POST /api/run?path=...
public HttpResponseMessage Post(string path)
{
var startInfo = new ProcessStartInfo(path);
try
{
Process.Start(startInfo);
return Request.CreateResponse(HttpStatusCode.NoContent);
}
catch (Exception)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to launch process");
}
}
}
}
|
Use a frozen clock for catcher trails | // 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.Graphics;
using osu.Framework.Graphics.Pooling;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
/// <summary>
/// A trail of the catcher.
/// It also represents a hyper dash afterimage.
/// </summary>
// TODO: Trails shouldn't be animated when the skin has an animated catcher.
// The animation should be frozen at the animation frame at the time of the trail generation.
public class CatcherTrail : PoolableDrawable
{
public CatcherAnimationState AnimationState
{
set => body.AnimationState.Value = value;
}
private readonly SkinnableCatcher body;
public CatcherTrail()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
Origin = Anchor.TopCentre;
Blending = BlendingParameters.Additive;
InternalChild = body = new SkinnableCatcher();
}
protected override void FreeAfterUse()
{
ClearTransforms();
base.FreeAfterUse();
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Timing;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
/// <summary>
/// A trail of the catcher.
/// It also represents a hyper dash afterimage.
/// </summary>
public class CatcherTrail : PoolableDrawable
{
public CatcherAnimationState AnimationState
{
set => body.AnimationState.Value = value;
}
private readonly SkinnableCatcher body;
public CatcherTrail()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
Origin = Anchor.TopCentre;
Blending = BlendingParameters.Additive;
InternalChild = body = new SkinnableCatcher
{
// Using a frozen clock because trails should not be animated when the skin has an animated catcher.
// TODO: The animation should be frozen at the animation frame at the time of the trail generation.
Clock = new FramedClock(new ManualClock()),
};
}
protected override void FreeAfterUse()
{
ClearTransforms();
base.FreeAfterUse();
}
}
}
|
Fix status label updating (update method not called if control is not visible) | // 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;
using EndlessClient.HUD;
using EndlessClient.Rendering;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1);
}
protected override void OnUpdateControl(GameTime gameTime)
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.OnUpdateControl(gameTime);
}
}
}
| // 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;
using EndlessClient.HUD;
using EndlessClient.Rendering;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1);
}
protected override bool ShouldUpdate()
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
return base.ShouldUpdate();
}
}
}
|
Add fields for PPU registers. | using System.Drawing;
namespace DanTup.DaNES.Emulation
{
class Ppu
{
public Memory Ram { get; }
public Bitmap Screen { get; }
public Ppu(Memory ram, Bitmap screen)
{
Ram = ram;
Screen = screen;
for (var x = 0; x < 256; x++)
{
for (var y = 0; y < 240; y++)
{
Screen.SetPixel(x, y, Color.FromArgb(x, y, 128));
}
}
}
public void Step()
{
}
}
}
| using System.Drawing;
namespace DanTup.DaNES.Emulation
{
class Ppu
{
public Memory Ram { get; }
public Bitmap Screen { get; }
// PPU Control
bool NmiEnable;
bool PpuMasterSlave;
bool SpriteHeight;
bool BackgroundTileSelect;
bool SpriteTileSelect;
bool IncrementMode;
bool NameTableSelect1;
bool NameTableSelect0;
// PPU Mask
bool TintBlue;
bool TintGreen;
bool TintRed;
bool ShowSprites;
bool ShowBackground;
bool ShowLeftSprites;
bool ShowLeftBackground;
bool Greyscale;
// PPU Status
bool VBlank;
bool Sprite0Hit;
bool SpriteOverflow;
byte OamAddress { get; }
byte OamData { get; }
byte PpuScroll { get; }
byte PpuAddr { get; }
byte PpuData { get; }
byte OamDma { get; }
public Ppu(Memory ram, Bitmap screen)
{
Ram = ram;
Screen = screen;
for (var x = 0; x < 256; x++)
{
for (var y = 0; y < 240; y++)
{
Screen.SetPixel(x, y, Color.FromArgb(x, y, 128));
}
}
}
public void Step()
{
}
}
}
|
Add back the default json converter locally to ensure it's actually used | // 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 Newtonsoft.Json;
namespace osu.Game.IO.Serialization
{
public interface IJsonSerializable
{
}
public static class JsonSerializableExtensions
{
public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings());
public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings());
public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings());
/// <summary>
/// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s.
/// </summary>
/// <returns></returns>
public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented,
ObjectCreationHandling = ObjectCreationHandling.Replace,
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
ContractResolver = new KeyContractResolver()
};
}
}
| // 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 Newtonsoft.Json;
using osu.Framework.IO.Serialization;
namespace osu.Game.IO.Serialization
{
public interface IJsonSerializable
{
}
public static class JsonSerializableExtensions
{
public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings());
public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings());
public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings());
/// <summary>
/// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s.
/// </summary>
/// <returns></returns>
public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented,
ObjectCreationHandling = ObjectCreationHandling.Replace,
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
Converters = new List<JsonConverter> { new Vector2Converter() },
ContractResolver = new KeyContractResolver()
};
}
}
|
Set Secret.cs so it will not be modified by default. This means we can put sensitive information in it, and it won't go into source control | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NetBotsHostProject.Models
{
public static class Secrets
{
private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>()
{
{"gitHubClientIdDev", "placeholder"},
{"gitHubClientSecretDev", "placeholder"}
};
public static string GetSecret(string key)
{
if (_secrets.ContainsKey(key))
{
return _secrets[key];
}
return null;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NetBotsHostProject.Models
{
public static class Secrets
{
private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>()
{
{"gitHubClientIdDev", "placeHolder"},
{"gitHubClientSecretDev", "placeHolder"}
};
public static string GetSecret(string key)
{
if (_secrets.ContainsKey(key))
{
return _secrets[key];
}
return null;
}
}
} |
Change version up to 1.1.1 | using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.1.0.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
| using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.1.1.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
|
Simplify foreach'es to a LINQ expression | using System;
using System.Collections.Generic;
using System.Linq;
using Grobid.PdfToXml;
namespace Grobid.NET
{
public class PdfBlockExtractor<T>
{
private readonly BlockStateFactory factory;
public PdfBlockExtractor()
{
this.factory = new BlockStateFactory();
}
public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform)
{
foreach (var block in blocks)
{
foreach (var textBlock in block.TextBlocks)
{
var tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize());
foreach (var tokenBlock in tokenBlocks)
{
var blockState = this.factory.Create(block, textBlock, tokenBlock);
yield return transform(blockState);
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Grobid.PdfToXml;
namespace Grobid.NET
{
public class PdfBlockExtractor<T>
{
private readonly BlockStateFactory factory;
public PdfBlockExtractor()
{
this.factory = new BlockStateFactory();
}
public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform)
{
return from block in blocks
from textBlock in block.TextBlocks
let tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize())
from tokenBlock in tokenBlocks
select this.factory.Create(block, textBlock, tokenBlock)
into blockState
select transform(blockState);
}
}
}
|
Add timer for email sending | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
{
this._twilioAccountSId = twilioAccountSid;
this._twilioAuthToken = twilioAuthToken;
this._twilioSourceNumber = twilioSourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
}
} | using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(TwilioConfig config)
{
this._twilioAccountSId = config.AccountSid;
this._twilioAuthToken = config.AuthToken;
this._twilioSourceNumber = config.SourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
public class TwilioConfig
{
public String AccountSid { get; set; }
public String AuthToken { get; set; }
public String SourceNumber { get; set; }
}
}
} |
Make Tablet and Desktop device types report as Desktop | using Windows.System.Profile;
using Windows.UI.ViewManagement;
namespace DigiTransit10.Helpers
{
public static class DeviceTypeHelper
{
public static DeviceFormFactorType GetDeviceFormFactorType()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Mobile":
return DeviceFormFactorType.Phone;
case "Windows.Desktop":
return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse
? DeviceFormFactorType.Desktop
: DeviceFormFactorType.Tablet;
case "Windows.Universal":
return DeviceFormFactorType.IoT;
case "Windows.Team":
return DeviceFormFactorType.SurfaceHub;
default:
return DeviceFormFactorType.Other;
}
}
}
public enum DeviceFormFactorType
{
Phone,
Desktop,
Tablet,
IoT,
SurfaceHub,
Other
}
}
| using Windows.System.Profile;
using Windows.UI.ViewManagement;
namespace DigiTransit10.Helpers
{
public static class DeviceTypeHelper
{
public static DeviceFormFactorType GetDeviceFormFactorType()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Mobile":
return DeviceFormFactorType.Phone;
case "Windows.Desktop":
return DeviceFormFactorType.Desktop;
case "Windows.Universal":
return DeviceFormFactorType.IoT;
case "Windows.Team":
return DeviceFormFactorType.SurfaceHub;
default:
return DeviceFormFactorType.Other;
}
}
}
public enum DeviceFormFactorType
{
Phone,
Desktop,
Tablet,
IoT,
SurfaceHub,
Other
}
}
|
Fix bug in test where key value was not being set. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;
using MusicStore.Models;
using Xunit;
namespace MusicStore.Components
{
public class GenreMenuComponentTest
{
private readonly IServiceProvider _serviceProvider;
public GenreMenuComponentTest()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());
_serviceProvider = services.BuildServiceProvider();
}
[Fact]
public async Task GenreMenuComponent_Returns_NineGenres()
{
// Arrange
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
var genreMenuComponent = new GenreMenuComponent(dbContext);
PopulateData(dbContext);
// Act
var result = await genreMenuComponent.InvokeAsync();
// Assert
Assert.NotNull(result);
var viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Null(viewResult.ViewName);
var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model);
Assert.Equal(9, genreResult.Count);
}
private static void PopulateData(MusicStoreContext context)
{
var genres = Enumerable.Range(1, 10).Select(n => new Genre());
context.AddRange(genres);
context.SaveChanges();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;
using MusicStore.Models;
using Xunit;
namespace MusicStore.Components
{
public class GenreMenuComponentTest
{
private readonly IServiceProvider _serviceProvider;
public GenreMenuComponentTest()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());
_serviceProvider = services.BuildServiceProvider();
}
[Fact]
public async Task GenreMenuComponent_Returns_NineGenres()
{
// Arrange
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
var genreMenuComponent = new GenreMenuComponent(dbContext);
PopulateData(dbContext);
// Act
var result = await genreMenuComponent.InvokeAsync();
// Assert
Assert.NotNull(result);
var viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Null(viewResult.ViewName);
var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model);
Assert.Equal(9, genreResult.Count);
}
private static void PopulateData(MusicStoreContext context)
{
var genres = Enumerable.Range(1, 10).Select(n => new Genre { GenreId = n });
context.AddRange(genres);
context.SaveChanges();
}
}
}
|
Use type filtering when searching matching content for BestBets | using System.Linq;
using EPiServer.Core;
using EPiServer.Find;
using EPiServer.Find.Framework;
using EPiServer.ServiceLocation;
using Vro.FindExportImport.Models;
namespace Vro.FindExportImport.Stores
{
public interface ISearchService
{
ContentReference FindMatchingContent(BestBetEntity bestBetEntity);
}
[ServiceConfiguration(typeof(ISearchService))]
public class SearchService : ISearchService
{
public ContentReference FindMatchingContent(BestBetEntity bestBetEntity)
{
var searchQuery = SearchClient.Instance
.Search<IContent>()
.Filter(x => x.Name.Match(bestBetEntity.TargetName));
if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector))
{
searchQuery = searchQuery.Filter(x => !x.ContentLink.ProviderName.Exists());
}
else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector))
{
searchQuery = searchQuery.Filter(x => x.ContentLink.ProviderName.Match("CatalogContent"));
}
var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult();
return searchResults.Hits.FirstOrDefault()?.Document;
}
}
} | using System;
using System.Linq;
using EPiServer;
using EPiServer.Core;
using EPiServer.Find;
using EPiServer.Find.Framework;
using EPiServer.ServiceLocation;
using Vro.FindExportImport.Models;
namespace Vro.FindExportImport.Stores
{
public interface ISearchService
{
ContentReference FindMatchingContent(BestBetEntity bestBetEntity);
}
[ServiceConfiguration(typeof(ISearchService))]
public class SearchService : ISearchService
{
public ContentReference FindMatchingContent(BestBetEntity bestBetEntity)
{
var searchQuery = SearchClient.Instance
.Search<IContent>()
.Filter(x => x.Name.Match(bestBetEntity.TargetName));
if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector))
{
searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(typeof(PageData)));
}
else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector))
{
// resolving type from string to avoid referencing Commerce assemblies
var commerceCatalogEntryType =
Type.GetType("EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase, EPiServer.Business.Commerce");
searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(commerceCatalogEntryType));
}
var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult();
return searchResults.Hits.FirstOrDefault()?.Document;
}
}
} |
Set cursor invisible in visual test game | // 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.Screens.Testing;
namespace osu.Framework.VisualTests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
}
}
| // 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;
}
}
}
|
Update tag helper usage from upstream breaking change | using System.Text;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Mvc.Rendering;
namespace Glimpse.Web.Common
{
[TargetElement("body")]
public class ScriptInjector : TagHelper
{
public override int Order => int.MaxValue;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var js = new StringBuilder();
js.AppendLine("var link = document.createElement('a');");
js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');");
js.AppendLine("link.setAttribute('target', '_blank');");
js.AppendLine("link.text = 'Open Glimpse';");
js.AppendLine("document.body.appendChild(link);");
var tag = new TagBuilder("script")
{
InnerHtml = new HtmlString(js.ToString()),
};
output.PostContent.Append(tag.ToHtmlContent(TagRenderMode.Normal));
}
}
}
| using System.Text;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Mvc.Rendering;
namespace Glimpse.Web.Common
{
[TargetElement("body")]
public class ScriptInjector : TagHelper
{
public override int Order => int.MaxValue;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var js = new StringBuilder();
js.AppendLine("var link = document.createElement('a');");
js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');");
js.AppendLine("link.setAttribute('target', '_blank');");
js.AppendLine("link.text = 'Open Glimpse';");
js.AppendLine("document.body.appendChild(link);");
var tag = new TagBuilder("script")
{
InnerHtml = new HtmlString(js.ToString()),
};
output.PostContent.Append(tag);
}
}
}
|
Add API comments for address | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CertiPay.Payroll.Common
{
[ComplexType]
public class Address
{
// Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes...
[StringLength(75)]
public String Address1 { get; set; }
[StringLength(75)]
public String Address2 { get; set; }
[StringLength(75)]
public String Address3 { get; set; }
[StringLength(50)]
public String City { get; set; }
public StateOrProvince State { get; set; }
[DataType(DataType.PostalCode)]
[StringLength(15)]
[Display(Name = "Postal Code")]
public String PostalCode { get; set; }
// TODO: international fields
public Address()
{
this.State = StateOrProvince.FL;
}
}
} | using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Represents a basic address format for the United States
/// </summary>
[ComplexType]
public class Address
{
// Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes...
/// <summary>
/// The first line of the address
/// </summary>
[StringLength(75)]
public String Address1 { get; set; }
/// <summary>
/// The second line of the address
/// </summary>
[StringLength(75)]
public String Address2 { get; set; }
/// <summary>
/// The third line of the address
/// </summary>
[StringLength(75)]
public String Address3 { get; set; }
/// <summary>
/// The city the address is located in
/// </summary>
[StringLength(50)]
public String City { get; set; }
/// <summary>
/// The state the address is located in
/// </summary>
public StateOrProvince State { get; set; }
/// <summary>
/// The postal "zip" code for the address, could include the additional four digits
/// </summary>
[DataType(DataType.PostalCode)]
[StringLength(15)]
[Display(Name = "Postal Code")]
public String PostalCode { get; set; }
public Address()
{
this.State = StateOrProvince.FL;
}
}
} |
Add warning about no edit/delete | @model alert_roster.web.Models.Message
@{
ViewBag.Title = "Post New Message";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true)
<div class="alert alert-info">
Please limit messages to < 160 characters.
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" })
@Html.ValidationMessageFor(model => model.Content)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Post" class="btn btn-default" />
</div>
</div>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
}
| @model alert_roster.web.Models.Message
@{
ViewBag.Title = "Post New Message";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true)
<div class="alert alert-info">
Please limit messages to < 160 characters. Note that, due to notifications being sent,
editing or deleting a post is currently unavailable.
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" })
@Html.ValidationMessageFor(model => model.Content)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Post" class="btn btn-default" />
</div>
</div>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
}
|
Optimize FutureProof to not load when the version is up to date | using System.Threading.Tasks;
using EE.FutureProof;
using JetBrains.Annotations;
using PlayerIOClient;
namespace BotBits
{
public class FutureProofLoginClient : LoginClient
{
private const int CurrentVersion = 218;
public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client)
{
}
protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version)
{
var versionLoader = version.HasValue
? TaskHelper.FromResult(version.Value)
: LoginUtils.GetVersionAsync(this.Client);
return versionLoader.Then(v =>
{
connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, v.Result), args);
});
}
}
}
| using System.Threading.Tasks;
using EE.FutureProof;
using JetBrains.Annotations;
using PlayerIOClient;
namespace BotBits
{
public class FutureProofLoginClient : LoginClient
{
private const int CurrentVersion = 218;
public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client)
{
}
protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version)
{
var versionLoader = version.HasValue
? TaskHelper.FromResult(version.Value)
: LoginUtils.GetVersionAsync(this.Client);
return versionLoader.Then(v =>
{
if (v.Result == CurrentVersion)
{
base.Attach(connectionManager, connection, args, v.Result);
}
else
{
this.FutureProofAttach(connectionManager, connection, args, v.Result);
}
});
}
// This line is separated into a function to prevent uncessarily loading FutureProof into memory.
private void FutureProofAttach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int version)
{
connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, version), args);
}
}
}
|
Fix not pasting stats with no boss name available. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
|
Throw exception on unsupported exception | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okanshi.Dashboard.Models;
namespace Okanshi.Dashboard
{
public interface IGetMetrics
{
IEnumerable<Metric> Execute(string instanceName);
}
public class GetMetrics : IGetMetrics
{
private readonly IStorage _storage;
public GetMetrics(IStorage storage)
{
_storage = storage;
}
public IEnumerable<Metric> Execute(string instanceName)
{
var webClient = new WebClient();
var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url);
var jObject = JObject.Parse(response);
JToken versionToken;
jObject.TryGetValue("version", out versionToken);
var version = "0";
if (versionToken != null && versionToken.HasValues)
{
version = versionToken.Value<string>();
}
if (version.Equals("0", StringComparison.OrdinalIgnoreCase))
{
var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
return deserializeObject
.Select(x => new Metric
{
Name = x.Key,
Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
WindowSize = x.Value.windowSize.ToObject<float>()
});
}
return Enumerable.Empty<Metric>();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okanshi.Dashboard.Models;
namespace Okanshi.Dashboard
{
public interface IGetMetrics
{
IEnumerable<Metric> Execute(string instanceName);
}
public class GetMetrics : IGetMetrics
{
private readonly IStorage _storage;
public GetMetrics(IStorage storage)
{
_storage = storage;
}
public IEnumerable<Metric> Execute(string instanceName)
{
var webClient = new WebClient();
var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url);
var jObject = JObject.Parse(response);
JToken versionToken;
jObject.TryGetValue("version", out versionToken);
var version = "0";
if (versionToken != null && versionToken.HasValues)
{
version = versionToken.Value<string>();
}
if (version.Equals("0", StringComparison.OrdinalIgnoreCase))
{
var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
return deserializeObject
.Select(x => new Metric
{
Name = x.Key,
Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
WindowSize = x.Value.windowSize.ToObject<float>()
});
}
throw new InvalidOperationException("Not supported version");
}
}
} |
Update comment for ClearMessages request | using Basic.Azure.Storage.Communications.Core;
using Basic.Azure.Storage.Communications.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations
{
/// <summary>
/// Deletes the specified queue item from the queue
/// http://msdn.microsoft.com/en-us/library/azure/dd179347.aspx
/// </summary>
public class ClearMessageRequest : RequestBase<EmptyResponsePayload>
{
private string _queueName;
public ClearMessageRequest(StorageAccountSettings settings, string queueName)
: base(settings)
{
//TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server
_queueName = queueName;
}
protected override string HttpMethod { get { return "DELETE"; } }
protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } }
protected override RequestUriBuilder GetUriBase()
{
var builder = new RequestUriBuilder(Settings.QueueEndpoint);
builder.AddSegment(_queueName);
builder.AddSegment("messages");
return builder;
}
}
}
| using Basic.Azure.Storage.Communications.Core;
using Basic.Azure.Storage.Communications.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations
{
/// <summary>
/// Clears the specified queue
/// http://msdn.microsoft.com/en-us/library/azure/dd179454.aspx
/// </summary>
public class ClearMessageRequest : RequestBase<EmptyResponsePayload>
{
private string _queueName;
public ClearMessageRequest(StorageAccountSettings settings, string queueName)
: base(settings)
{
//TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server
_queueName = queueName;
}
protected override string HttpMethod { get { return "DELETE"; } }
protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } }
protected override RequestUriBuilder GetUriBase()
{
var builder = new RequestUriBuilder(Settings.QueueEndpoint);
builder.AddSegment(_queueName);
builder.AddSegment("messages");
return builder;
}
}
}
|
Make scene asset / scene name deprecated | using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public class LiteNetLibScene
{
[SerializeField]
public Object sceneAsset;
[SerializeField]
public string sceneName = string.Empty;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
| using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public class LiteNetLibScene
{
[SerializeField]
private Object sceneAsset;
[SerializeField]
private string sceneName = string.Empty;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
|
Use the correct size for the symlink path buffer | using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Avalonia.FreeDesktop
{
internal static class NativeMethods
{
[DllImport("libc", SetLastError = true)]
private static extern long readlink([MarshalAs(UnmanagedType.LPArray)] byte[] filename,
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
long len);
public static string ReadLink(string path)
{
var symlinkMaxSize = Encoding.ASCII.GetMaxByteCount(path.Length);
var bufferSize = 4097; // PATH_MAX is (usually?) 4096, but we need to know if the result was truncated
var symlink = ArrayPool<byte>.Shared.Rent(symlinkMaxSize + 1);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
var symlinkSize = Encoding.UTF8.GetBytes(path, 0, path.Length, symlink, 0);
symlink[symlinkSize] = 0;
var size = readlink(symlink, buffer, bufferSize);
Debug.Assert(size < bufferSize); // if this fails, we need to increase the buffer size (dynamically?)
return Encoding.UTF8.GetString(buffer, 0, (int)size);
}
finally
{
ArrayPool<byte>.Shared.Return(symlink);
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
| using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Avalonia.FreeDesktop
{
internal static class NativeMethods
{
[DllImport("libc", SetLastError = true)]
private static extern long readlink([MarshalAs(UnmanagedType.LPArray)] byte[] filename,
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
long len);
public static string ReadLink(string path)
{
var symlinkSize = Encoding.UTF8.GetByteCount(path);
var bufferSize = 4097; // PATH_MAX is (usually?) 4096, but we need to know if the result was truncated
var symlink = ArrayPool<byte>.Shared.Rent(symlinkSize + 1);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
Encoding.UTF8.GetBytes(path, 0, path.Length, symlink, 0);
symlink[symlinkSize] = 0;
var size = readlink(symlink, buffer, bufferSize);
Debug.Assert(size < bufferSize); // if this fails, we need to increase the buffer size (dynamically?)
return Encoding.UTF8.GetString(buffer, 0, (int)size);
}
finally
{
ArrayPool<byte>.Shared.Return(symlink);
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
|
Work around broken mime-type detection. | using Hyena;
using TagLib;
using System;
using GLib;
namespace FSpot.Utils
{
public static class Metadata
{
public static TagLib.Image.File Parse (SafeUri uri)
{
// Detect mime-type
var gfile = FileFactory.NewForUri (uri);
var info = gfile.QueryInfo ("standard::content-type", FileQueryInfoFlags.None, null);
var mime = info.ContentType;
// Parse file
var res = new GIOTagLibFileAbstraction () { Uri = uri };
var sidecar_uri = uri.ReplaceExtension (".xmp");
var sidecar_res = new GIOTagLibFileAbstraction () { Uri = sidecar_uri };
TagLib.Image.File file = null;
try {
file = TagLib.File.Create (res, mime, ReadStyle.Average) as TagLib.Image.File;
} catch (Exception e) {
Hyena.Log.Exception (String.Format ("Loading of Metadata failed for file: {0}", uri.ToString ()), e);
return null;
}
// Load XMP sidecar
var sidecar_file = GLib.FileFactory.NewForUri (sidecar_uri);
if (sidecar_file.Exists) {
file.ParseXmpSidecar (sidecar_res);
}
return file;
}
}
}
| using Hyena;
using TagLib;
using System;
using GLib;
namespace FSpot.Utils
{
public static class Metadata
{
public static TagLib.Image.File Parse (SafeUri uri)
{
// Detect mime-type
var gfile = FileFactory.NewForUri (uri);
var info = gfile.QueryInfo ("standard::content-type", FileQueryInfoFlags.None, null);
var mime = info.ContentType;
if (mime.StartsWith ("application/x-extension-")) {
// Works around broken metadata detection - https://bugzilla.gnome.org/show_bug.cgi?id=624781
mime = String.Format ("taglib/{0}", mime.Substring (24));
}
// Parse file
var res = new GIOTagLibFileAbstraction () { Uri = uri };
var sidecar_uri = uri.ReplaceExtension (".xmp");
var sidecar_res = new GIOTagLibFileAbstraction () { Uri = sidecar_uri };
TagLib.Image.File file = null;
try {
file = TagLib.File.Create (res, mime, ReadStyle.Average) as TagLib.Image.File;
} catch (Exception e) {
Hyena.Log.Exception (String.Format ("Loading of Metadata failed for file: {0}", uri.ToString ()), e);
return null;
}
// Load XMP sidecar
var sidecar_file = GLib.FileFactory.NewForUri (sidecar_uri);
if (sidecar_file.Exists) {
file.ParseXmpSidecar (sidecar_res);
}
return file;
}
}
}
|
Add multiple response handling for diferente score levels | using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
using System.Diagnostics;
using FaqTemplate.Core.Services;
using FaqTemplate.Core.Domain;
namespace FaqTemplate.Bot
{
public class PlainTextMessageReceiver : IMessageReceiver
{
private readonly IFaqService<string> _faqService;
private readonly IMessagingHubSender _sender;
private readonly Settings _settings;
public PlainTextMessageReceiver(IMessagingHubSender sender, IFaqService<string> faqService, Settings settings)
{
_sender = sender;
_faqService = faqService;
_settings = settings;
}
public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
{
Trace.TraceInformation($"From: {message.From} \tContent: {message.Content}");
var request = new FaqRequest { Ask = message.Content.ToString() };
var result = await _faqService.AskThenIAnswer(request);
await _sender.SendMessageAsync($"{result.Score}: {result.Answer}", message.From, cancellationToken);
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
using System.Diagnostics;
using FaqTemplate.Core.Services;
using FaqTemplate.Core.Domain;
namespace FaqTemplate.Bot
{
public class PlainTextMessageReceiver : IMessageReceiver
{
private readonly IFaqService<string> _faqService;
private readonly IMessagingHubSender _sender;
private readonly Settings _settings;
public PlainTextMessageReceiver(IMessagingHubSender sender, IFaqService<string> faqService, Settings settings)
{
_sender = sender;
_faqService = faqService;
_settings = settings;
}
public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
{
Trace.TraceInformation($"From: {message.From} \tContent: {message.Content}");
var request = new FaqRequest { Ask = message.Content.ToString() };
var response = await _faqService.AskThenIAnswer(request);
if (response.Score >= 0.8)
{
await _sender.SendMessageAsync($"{response.Answer}", message.From, cancellationToken);
}
else if(response.Score >= 0.5)
{
await _sender.SendMessageAsync($"Eu acho que a resposta para o que voc precisa :", message.From, cancellationToken);
cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(1));
await _sender.SendMessageAsync($"{response.Answer}", message.From, cancellationToken);
}
else
{
await _sender.SendMessageAsync($"Infelizmente eu ainda no sei isso! Mas vou me aprimorar, prometo!", message.From, cancellationToken);
}
await _sender.SendMessageAsync($"{response.Score}: {response.Answer}", message.From, cancellationToken);
}
}
}
|
Move 'Empty Website' template to Default language | using System;
using System.Collections.Generic;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SimpleWAWS.Models
{
public class WebsiteTemplate : BaseTemplate
{
[JsonProperty(PropertyName="fileName")]
public string FileName { get; set; }
[JsonProperty(PropertyName="language")]
public string Language { get; set; }
public static WebsiteTemplate EmptySiteTemplate
{
get { return new WebsiteTemplate() { Name = "Empty Site", Language = "Empty Site", SpriteName = "sprite-Large" }; }
}
}
} | using System;
using System.Collections.Generic;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SimpleWAWS.Models
{
public class WebsiteTemplate : BaseTemplate
{
[JsonProperty(PropertyName="fileName")]
public string FileName { get; set; }
[JsonProperty(PropertyName="language")]
public string Language { get; set; }
public static WebsiteTemplate EmptySiteTemplate
{
get { return new WebsiteTemplate() { Name = "Empty Site", Language = "Default", SpriteName = "sprite-Large" }; }
}
}
} |
Fix minor issue with unix time calculation. | using System;
namespace Telegram.Bot.Helpers
{
/// <summary>
/// Extension Methods
/// </summary>
public static class Extensions
{
private static readonly DateTime UnixStart = new DateTime(1970, 1, 1);
/// <summary>
/// Convert a long into a DateTime
/// </summary>
public static DateTime FromUnixTime(this long dateTime)
=> UnixStart.AddSeconds(dateTime).ToLocalTime();
/// <summary>
/// Convert a DateTime into a long
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="OverflowException"></exception>
public static long ToUnixTime(this DateTime dateTime)
{
var utcDateTime = dateTime.ToUniversalTime();
if (utcDateTime == DateTime.MinValue)
return 0;
var delta = dateTime - UnixStart;
if (delta.TotalSeconds < 0)
throw new ArgumentOutOfRangeException(nameof(dateTime), "Unix epoch starts January 1st, 1970");
return Convert.ToInt64(delta.TotalSeconds);
}
}
}
| using System;
namespace Telegram.Bot.Helpers
{
/// <summary>
/// Extension Methods
/// </summary>
public static class Extensions
{
private static readonly DateTime UnixStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Convert a long into a DateTime
/// </summary>
public static DateTime FromUnixTime(this long unixTime)
=> UnixStart.AddSeconds(unixTime).ToLocalTime();
/// <summary>
/// Convert a DateTime into a long
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="OverflowException"></exception>
public static long ToUnixTime(this DateTime dateTime)
{
if (dateTime == DateTime.MinValue)
return 0;
var utcDateTime = dateTime.ToUniversalTime();
var delta = (utcDateTime - UnixStart).TotalSeconds;
if (delta < 0)
throw new ArgumentOutOfRangeException(nameof(dateTime), "Unix epoch starts January 1st, 1970");
return Convert.ToInt64(delta);
}
}
}
|
Remove unused RoleProvider setting from authentication configuration | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
public static string RoleProvider { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
RoleProvider = ConfigurationManager.AppSettings["RoleProvider"];
}
}
} | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
}
}
} |
Update tests for new url resolution behavior | using System.Net;
using FluentAssertions;
using NUnit.Framework;
namespace Durwella.UrlShortening.Tests
{
public class WebClientUrlUnwrapperTest
{
[Test]
public void ShouldGetResourceLocation()
{
var wrappedUrl = "http://goo.gl/mSkqOi";
var subject = new WebClientUrlUnwrapper();
var directUrl = subject.GetDirectUrl(wrappedUrl);
directUrl.Should().Be("http://example.com/");
}
[Test]
public void ShouldReturnGivenLocationIfAuthenticationRequired()
{
var givenUrl = "http://durwella.com/testing/does-not-exist";
var subject = new WebClientUrlUnwrapper
{
IgnoreErrorCodes = new[] { HttpStatusCode.NotFound }
};
var directUrl = subject.GetDirectUrl(givenUrl);
directUrl.Should().Be(givenUrl);
}
}
}
| using System.Net;
using FluentAssertions;
using NUnit.Framework;
namespace Durwella.UrlShortening.Tests
{
public class WebClientUrlUnwrapperTest
{
[Test]
public void ShouldGetResourceLocation()
{
var wrappedUrl = "http://goo.gl/mSkqOi";
var subject = new WebClientUrlUnwrapper();
WebClientUrlUnwrapper.ResolveUrls = true;
var directUrl = subject.GetDirectUrl(wrappedUrl);
directUrl.Should().Be("http://example.com/");
WebClientUrlUnwrapper.ResolveUrls = false;
}
[Test]
public void ShouldReturnGivenLocationIfAuthenticationRequired()
{
var givenUrl = "http://durwella.com/testing/does-not-exist";
var subject = new WebClientUrlUnwrapper
{
IgnoreErrorCodes = new[] { HttpStatusCode.NotFound }
};
WebClientUrlUnwrapper.ResolveUrls = true;
var directUrl = subject.GetDirectUrl(givenUrl);
directUrl.Should().Be(givenUrl);
WebClientUrlUnwrapper.ResolveUrls = false;
}
}
}
|
Use 8192u as lowestBufferSize; Remove tests for LocalMaxChunkCount and MaxMessageSize | using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Workstation.ServiceModel.Ua;
using Xunit;
namespace Workstation.UaClient.UnitTests
{
public class UaApplicationOptionsTests
{
[Fact]
public void UaTcpTransportChannelOptionsDefaults()
{
var lowestBufferSize = 1024u;
var options = new UaTcpTransportChannelOptions();
options.LocalMaxChunkCount
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalMaxMessageSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalReceiveBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalSendBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
}
[Fact]
public void UaTcpSecureChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSecureChannelOptions();
TimeSpan.FromMilliseconds(options.TimeoutHint)
.Should().BeGreaterOrEqualTo(shortestTimespan);
options.DiagnosticsHint
.Should().Be(0);
}
[Fact]
public void UaTcpSessionChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSessionChannelOptions();
TimeSpan.FromMilliseconds(options.SessionTimeout)
.Should().BeGreaterOrEqualTo(shortestTimespan);
}
}
}
| using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Workstation.ServiceModel.Ua;
using Xunit;
namespace Workstation.UaClient.UnitTests
{
public class UaApplicationOptionsTests
{
[Fact]
public void UaTcpTransportChannelOptionsDefaults()
{
var lowestBufferSize = 8192u;
var options = new UaTcpTransportChannelOptions();
options.LocalReceiveBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalSendBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
}
[Fact]
public void UaTcpSecureChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSecureChannelOptions();
TimeSpan.FromMilliseconds(options.TimeoutHint)
.Should().BeGreaterOrEqualTo(shortestTimespan);
options.DiagnosticsHint
.Should().Be(0);
}
[Fact]
public void UaTcpSessionChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSessionChannelOptions();
TimeSpan.FromMilliseconds(options.SessionTimeout)
.Should().BeGreaterOrEqualTo(shortestTimespan);
}
}
}
|
Revert "Fix mono compilation error" | using System;
namespace SharpHaven.Resources
{
public struct ResourceRef
{
public ResourceRef(string name, ushort version)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.Version = version;
}
public string Name { get; }
public ushort Version { get; }
public override int GetHashCode()
{
return Name.GetHashCode() ^ Version.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ResourceRef))
return false;
var other = (ResourceRef)obj;
return string.Equals(Name, other.Name) && Version == other.Version;
}
}
}
| using System;
namespace SharpHaven.Resources
{
public struct ResourceRef
{
public ResourceRef(string name, ushort version)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Name = name;
Version = version;
}
public string Name { get; }
public ushort Version { get; }
public override int GetHashCode()
{
return Name.GetHashCode() ^ Version.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ResourceRef))
return false;
var other = (ResourceRef)obj;
return string.Equals(Name, other.Name) && Version == other.Version;
}
}
}
|
Remove test that is checked by analyzer. | namespace Gu.Wpf.Geometry.Tests
{
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Markup;
using NUnit.Framework;
public class NamespacesTests
{
private const string Uri = "http://gu.se/Geometry";
private readonly Assembly assembly;
public NamespacesTests()
{
this.assembly = typeof(GradientPath).Assembly;
}
[Test]
public void XmlnsDefinitions()
{
string[] skip = { ".Annotations", ".Properties", "XamlGeneratedNamespace" };
var strings = this.assembly.GetTypes()
.Select(x => x.Namespace)
.Distinct()
.Where(x => x != null && !skip.Any(x.EndsWith))
.OrderBy(x => x)
.ToArray();
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsDefinitionAttribute))
.ToArray();
var actuals = attributes.Select(a => a.ConstructorArguments[1].Value)
.OrderBy(x => x);
foreach (var s in strings)
{
Console.WriteLine(@"[assembly: XmlnsDefinition(""{0}"", ""{1}"")]", Uri, s);
}
Assert.AreEqual(strings, actuals);
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
[Test]
public void XmlnsPrefix()
{
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsPrefixAttribute));
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
}
}
| namespace Gu.Wpf.Geometry.Tests
{
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Markup;
using NUnit.Framework;
public class NamespacesTests
{
private const string Uri = "http://gu.se/Geometry";
private readonly Assembly assembly;
public NamespacesTests()
{
this.assembly = typeof(GradientPath).Assembly;
}
[Test]
public void XmlnsPrefix()
{
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsPrefixAttribute));
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
}
}
|
Make test file path OS-agnostic | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OMF
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string baseDir = System.AppDomain.CurrentDomain.BaseDirectory;
string file = System.IO.Path.Combine(baseDir, "..\\..\\test.omf");
if (System.IO.File.Exists(file) == false)
{
Console.WriteLine(string.Format("File '{0}' does not exist.", file));
Console.ReadLine();
return;
}
OMF torun = new OMF();
torun.Execute(file);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OMF
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string baseDir = System.AppDomain.CurrentDomain.BaseDirectory;
string file = System.IO.Path.Combine(baseDir, "..", "..", "test.omf");
if (System.IO.File.Exists(file) == false)
{
Console.WriteLine(string.Format("File '{0}' does not exist.", file));
Console.ReadLine();
return;
}
OMF torun = new OMF();
torun.Execute(file);
}
}
}
|
Remove machine name from method calls since it is no longer needed after refactoring implementation | namespace PS.Mothership.Core.Common.SignalRConnectionHandling
{
public interface IClientsCollection
{
ISignalRUser Get(string machineName, string username);
ISignalRUser GetOrAdd(string machineName, string username);
void AddOrReplace(ISignalRUser inputUser);
}
}
| namespace PS.Mothership.Core.Common.SignalRConnectionHandling
{
public interface IClientsCollection
{
ISignalRUser Get(string username);
ISignalRUser GetOrAdd(string username);
void AddOrReplace(ISignalRUser inputUser);
}
}
|
Expand delayed calls in console interpreter | namespace AjErl.Console
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjErl.Compiler;
using AjErl.Expressions;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("AjErl alfa 0.0.1");
Lexer lexer = new Lexer(Console.In);
Parser parser = new Parser(lexer);
Machine machine = new Machine();
while (true)
try
{
ProcessExpression(parser, machine.RootContext);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
Console.Error.WriteLine(ex.StackTrace);
}
}
private static void ProcessExpression(Parser parser, Context context)
{
IExpression expression = parser.ParseExpression();
object result = expression.Evaluate(context);
if (result == null)
return;
Console.Write("> ");
Console.WriteLine(result);
}
}
}
| namespace AjErl.Console
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjErl.Compiler;
using AjErl.Expressions;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("AjErl alfa 0.0.1");
Lexer lexer = new Lexer(Console.In);
Parser parser = new Parser(lexer);
Machine machine = new Machine();
while (true)
try
{
ProcessExpression(parser, machine.RootContext);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
Console.Error.WriteLine(ex.StackTrace);
}
}
private static void ProcessExpression(Parser parser, Context context)
{
IExpression expression = parser.ParseExpression();
object result = Machine.ExpandDelayedCall(expression.Evaluate(context));
if (result == null)
return;
Console.Write("> ");
Console.WriteLine(result);
}
}
}
|
Fix typo in assembly description | using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Engine is an open-source, plataform agnostic C# and Python algorithmic trading engine. " +
"Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")]
[assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")]
[assembly: AssemblyCompany("QuantConnect Corporation")]
[assembly: AssemblyVersion("2.4")]
// Configuration used to build the assembly is by defaulting 'Debug'.
// To create a package using a Release configuration, -properties Configuration=Release on the command line must be use.
// source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens | using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Engine is an open-source, platform agnostic C# and Python algorithmic trading engine. " +
"Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")]
[assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")]
[assembly: AssemblyCompany("QuantConnect Corporation")]
[assembly: AssemblyVersion("2.4")]
// Configuration used to build the assembly is by defaulting 'Debug'.
// To create a package using a Release configuration, -properties Configuration=Release on the command line must be use.
// source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens |
Update Roslyn version number for assembly loading | namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "2.1.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
| namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "2.3.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
|
Use updated TagHelper on home page | @{
ViewData["Title"] = "Home Page";
}
.<div class="row">
<div class="col-xs-12">
<div bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4">
</div>
</div>
</div>
| @{
ViewData["Title"] = "Home Page";
}
<div class="row">
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Default</h3>
<p>
<code>progress-bar</code>
</p>
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="45">
</div>
<pre class="pre-scrollable">
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="45">
</div></pre>
</div>
</div>
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Animated</h3>
<p>
<code>progress-bar progress-bar-success progress-bar-striped active</code>
</p>
<div bs-progress-style="success"
bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4"
bs-progress-active="true">
</div>
<pre class="pre-scrollable">
<div bs-progress-style="success"
bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4"
bs-progress-active="true">
</div></pre>
</div>
</div>
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Striped</h3>
<p>
<code>progress-bar progress-bar-danger progress-bar-striped</code>
</p>
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="80"
bs-progress-style="danger"
bs-progress-striped="true"
bs-progress-label-visible="false">
</div>
<pre class="pre-scrollable">
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="80"
bs-progress-style="danger"
bs-progress-striped="true"
bs-progress-label-visible="false">
</div></pre>
</div>
</div>
</div>
|
Update status message for last guess | using System;
using System.Collections.Generic;
using System.Text;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
private string StatusMessage;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
StatusMessage = "Press any letter to guess!";
}
public string ShownWord() {
var obscuredWord = new StringBuilder();
foreach (char letter in Word) {
obscuredWord.Append(ShownLetterFor(letter));
}
return obscuredWord.ToString();
}
public string Status() {
return StatusMessage;
}
public bool GuessLetter(char letter) {
GuessedLetters.Add(letter);
return LetterIsCorrect(letter);
}
private char ShownLetterFor(char originalLetter) {
if (LetterWasGuessed(originalLetter) || originalLetter == ' ') {
return originalLetter;
} else {
return '_';
}
}
private bool LetterWasGuessed(char letter) {
return GuessedLetters.Contains(letter);
}
private bool LetterIsCorrect(char letter) {
return Word.Contains(letter.ToString());
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
private string StatusMessage;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
StatusMessage = "Press any letter to guess!";
}
public string ShownWord() {
var obscuredWord = new StringBuilder();
foreach (char letter in Word) {
obscuredWord.Append(ShownLetterFor(letter));
}
return obscuredWord.ToString();
}
public string Status() {
return StatusMessage;
}
public bool GuessLetter(char letter) {
GuessedLetters.Add(letter);
bool correct = LetterIsCorrect(letter);
if (correct) {
StatusMessage = "Correct! Guess again!";
} else {
StatusMessage = "Incorrect! Try again!";
}
// CheckGameOver();
return correct;
}
private char ShownLetterFor(char originalLetter) {
if (LetterWasGuessed(originalLetter) || originalLetter == ' ') {
return originalLetter;
} else {
return '_';
}
}
private bool LetterWasGuessed(char letter) {
return GuessedLetters.Contains(letter);
}
private bool LetterIsCorrect(char letter) {
return Word.Contains(letter.ToString());
}
}
}
|
Add test for authorization requirement in TraktUserCustomListAddRequest | namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
[TestClass]
public class TraktUserCustomListAddRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsNotAbstract()
{
typeof(TraktUserCustomListAddRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSealed()
{
typeof(TraktUserCustomListAddRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSubclassOfATraktSingleItemPostRequest()
{
typeof(TraktUserCustomListAddRequest).IsSubclassOf(typeof(ATraktSingleItemPostRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
}
}
| namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserCustomListAddRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsNotAbstract()
{
typeof(TraktUserCustomListAddRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSealed()
{
typeof(TraktUserCustomListAddRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSubclassOfATraktSingleItemPostRequest()
{
typeof(TraktUserCustomListAddRequest).IsSubclassOf(typeof(ATraktSingleItemPostRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestHasAuthorizationRequired()
{
var request = new TraktUserCustomListAddRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
|
Create new instance of KeyHandler on every call to Read method | using System;
namespace ReadLine
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
static ReadLine()
{
_keyHandler = new KeyHandler();
}
public static string Read()
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
return _keyHandler.Text;
}
}
}
| using System;
namespace ReadLine
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
public static string Read()
{
_keyHandler = new KeyHandler();
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
return _keyHandler.Text;
}
}
}
|
Add missing constructor for derived tracking events | using System;
namespace Totem.Tracking
{
/// <summary>
/// A timeline event tracked by an index
/// </summary>
public class TrackedEvent
{
public TrackedEvent(string eventType, long eventPosition, Id userId, DateTime eventWhen, string keyType, string keyValue)
{
EventType = eventType;
EventPosition = eventPosition;
UserId = userId;
EventWhen = eventWhen;
KeyType = keyType;
KeyValue = keyValue;
}
public string EventType;
public long EventPosition;
public Id UserId;
public DateTime EventWhen;
public string KeyType;
public string KeyValue;
}
} | using System;
namespace Totem.Tracking
{
/// <summary>
/// A timeline event tracked by an index
/// </summary>
public class TrackedEvent
{
protected TrackedEvent()
{}
public TrackedEvent(string eventType, long eventPosition, Id userId, DateTime eventWhen, string keyType, string keyValue)
{
EventType = eventType;
EventPosition = eventPosition;
UserId = userId;
EventWhen = eventWhen;
KeyType = keyType;
KeyValue = keyValue;
}
public string EventType;
public long EventPosition;
public Id UserId;
public DateTime EventWhen;
public string KeyType;
public string KeyValue;
}
} |
Move log files to local application data. | using NLog;
using NLog.Config;
using NLog.Targets;
namespace CoCo
{
internal static class NLog
{
internal static void Initialize()
{
LoggingConfiguration config = new LoggingConfiguration();
FileTarget fileTarget = new FileTarget("File");
FileTarget fileDebugTarget = new FileTarget("File debug");
fileTarget.Layout = "${date}___${level}___${message}";
fileTarget.FileName = @"${nlogdir}\file.log";
fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}";
fileDebugTarget.FileName = @"${nlogdir}\file_debug.log";
config.AddTarget(fileTarget);
config.AddTarget(fileDebugTarget);
config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*");
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*");
//LogManager.ThrowConfigExceptions = true;
//LogManager.ThrowExceptions = true;
LogManager.Configuration = config;
}
}
} | using System;
using System.IO;
using NLog;
using NLog.Config;
using NLog.Targets;
namespace CoCo
{
internal static class NLog
{
internal static void Initialize()
{
string appDataLocal = $"{Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)}\\CoCo";
if (!Directory.Exists(appDataLocal))
{
Directory.CreateDirectory(appDataLocal);
}
LoggingConfiguration config = new LoggingConfiguration();
FileTarget fileTarget = new FileTarget("File");
FileTarget fileDebugTarget = new FileTarget("File debug");
fileTarget.Layout = "${date}___${level}___${message}";
fileTarget.FileName = $"{appDataLocal}\\file.log";
fileDebugTarget.Layout = "${date}___${level}___${message}${newline}${stacktrace}";
fileDebugTarget.FileName = $"{appDataLocal}\\file_debug.log";
config.AddTarget(fileTarget);
config.AddTarget(fileDebugTarget);
config.AddRule(LogLevel.Debug, LogLevel.Debug, fileDebugTarget, "*");
config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget, "*");
//LogManager.ThrowConfigExceptions = true;
//LogManager.ThrowExceptions = true;
LogManager.Configuration = config;
}
}
} |
Update grubconfig according to osdev.org | using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Cosmos.Build.Tasks
{
public class CreateGrubConfig: Task
{
[Required]
public string TargetDirectory { get; set; }
[Required]
public string BinName { get; set; }
private string Indentation = " ";
public override bool Execute()
{
if (!Directory.Exists(TargetDirectory))
{
Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'");
return false;
}
var xBinName = BinName;
var xLabelName = Path.GetFileNameWithoutExtension(xBinName);
using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg")))
{
xWriter.WriteLine("insmod vbe");
xWriter.WriteLine("insmod vga");
xWriter.WriteLine("insmod video_bochs");
xWriter.WriteLine("insmod video_cirrus");
xWriter.WriteLine("set root='(hd0,msdos1)'");
xWriter.WriteLine();
xWriter.WriteLine("menuentry '" + xLabelName + "' {");
WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName + " vid=preset,1024,768 hdd=0");
WriteIndentedLine(xWriter, "set gfxpayload=800x600x32");
WriteIndentedLine(xWriter, "boot");
xWriter.WriteLine("}");
}
return true;
}
private void WriteIndentedLine(TextWriter aWriter, string aText)
{
aWriter.WriteLine(Indentation + aText);
}
}
}
| using System.Diagnostics;
using System.IO;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Cosmos.Build.Tasks
{
public class CreateGrubConfig: Task
{
[Required]
public string TargetDirectory { get; set; }
[Required]
public string BinName { get; set; }
private string Indentation = " ";
public override bool Execute()
{
if (!Directory.Exists(TargetDirectory))
{
Log.LogError($"Invalid target directory! Target directory: '{TargetDirectory}'");
return false;
}
var xBinName = BinName;
var xLabelName = Path.GetFileNameWithoutExtension(xBinName);
using (var xWriter = File.CreateText(Path.Combine(TargetDirectory + "/boot/grub/", "grub.cfg")))
{
xWriter.WriteLine("menuentry '" + xLabelName + "' {");
WriteIndentedLine(xWriter, "multiboot /boot/" + xBinName);
xWriter.WriteLine("}");
}
return true;
}
private void WriteIndentedLine(TextWriter aWriter, string aText)
{
aWriter.WriteLine(Indentation + aText);
}
}
}
|
Simplify Hosting's shutdown handling. Don't require a TTY on Unix. | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Logging;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Hosting
{
public class Program
{
private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
private readonly IServiceProvider _serviceProvider;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
var config = new Configuration();
if (File.Exists(HostingIniFile))
{
config.AddIniFile(HostingIniFile);
}
config.AddEnvironmentVariables();
config.AddCommandLine(args);
var host = new WebHostBuilder(_serviceProvider, config).Build();
var serverShutdown = host.Start();
var loggerFactory = host.ApplicationServices.GetRequiredService<ILoggerFactory>();
var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>();
var shutdownHandle = new ManualResetEvent(false);
appShutdownService.ShutdownRequested.Register(() =>
{
try
{
serverShutdown.Dispose();
}
catch (Exception ex)
{
var logger = loggerFactory.CreateLogger<Program>();
logger.LogError("Dispose threw an exception.", ex);
}
shutdownHandle.Set();
});
var ignored = Task.Run(() =>
{
Console.WriteLine("Started");
Console.ReadLine();
appShutdownService.RequestShutdown();
});
shutdownHandle.WaitOne();
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using Microsoft.AspNet.Hosting.Internal;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime;
namespace Microsoft.AspNet.Hosting
{
public class Program
{
private const string HostingIniFile = "Microsoft.AspNet.Hosting.ini";
private readonly IServiceProvider _serviceProvider;
public Program(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public void Main(string[] args)
{
var config = new Configuration();
if (File.Exists(HostingIniFile))
{
config.AddIniFile(HostingIniFile);
}
config.AddEnvironmentVariables();
config.AddCommandLine(args);
var host = new WebHostBuilder(_serviceProvider, config).Build();
using (host.Start())
{
var appShutdownService = host.ApplicationServices.GetRequiredService<IApplicationShutdown>();
Console.CancelKeyPress += delegate { appShutdownService.RequestShutdown(); };
appShutdownService.ShutdownRequested.WaitHandle.WaitOne();
}
}
}
}
|
Simplify ternary operation (not !) | using System;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
return !logger.IsEnabled(level)
? logger
: logger.ForContext(propertyName, value, destructureObjects);
}
}
}
| using System;
using Serilog.Events;
namespace Serilog
{
/// <summary>
/// Extension method 'ForContext' for ILogger.
/// </summary>
public static class ForContextExtension
{
/// <summary>
/// Create a logger that enriches log events with the specified property based on log event level.
/// </summary>
/// <typeparam name="TValue"> The type of the property value. </typeparam>
/// <param name="logger">The logger</param>
/// <param name="level">The log event level used to determine if log is enriched with property.</param>
/// <param name="propertyName">The name of the property. Must be non-empty.</param>
/// <param name="value">The property value.</param>
/// <param name="destructureObjects">If true, the value will be serialized as a structured
/// object if possible; if false, the object will be recorded as a scalar or simple array.</param>
/// <returns>A logger that will enrich log events as specified.</returns>
/// <returns></returns>
public static ILogger ForContext<TValue>(
this ILogger logger,
LogEventLevel level,
string propertyName,
TValue value,
bool destructureObjects = false)
{
if (logger == null)
throw new ArgumentNullException(nameof(logger));
return logger.IsEnabled(level)
? logger.ForContext(propertyName, value, destructureObjects)
: logger;
}
}
}
|
Fix text input for SDL | // 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 osu.Framework.Extensions;
using osu.Framework.Platform;
namespace osu.Framework.Input
{
public class GameWindowTextInput : ITextInputSource
{
private readonly IWindow window;
private string pending = string.Empty;
public GameWindowTextInput(IWindow window)
{
this.window = window;
}
protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar;
public bool ImeActive => false;
public string GetPendingText()
{
try
{
return pending;
}
finally
{
pending = string.Empty;
}
}
public void Deactivate(object sender)
{
window.AsLegacyWindow().KeyPress -= HandleKeyPress;
}
public void Activate(object sender)
{
window.AsLegacyWindow().KeyPress += HandleKeyPress;
}
private void imeCompose()
{
//todo: implement
OnNewImeComposition?.Invoke(string.Empty);
}
private void imeResult()
{
//todo: implement
OnNewImeResult?.Invoke(string.Empty);
}
public event Action<string> OnNewImeComposition;
public event Action<string> OnNewImeResult;
}
}
| // 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 osu.Framework.Extensions;
using osu.Framework.Platform;
namespace osu.Framework.Input
{
public class GameWindowTextInput : ITextInputSource
{
private readonly IWindow window;
private string pending = string.Empty;
public GameWindowTextInput(IWindow window)
{
this.window = window;
}
protected virtual void HandleKeyPress(object sender, osuTK.KeyPressEventArgs e) => pending += e.KeyChar;
protected virtual void HandleKeyTyped(char c) => pending += c;
public bool ImeActive => false;
public string GetPendingText()
{
try
{
return pending;
}
finally
{
pending = string.Empty;
}
}
public void Deactivate(object sender)
{
if (window is Window win)
win.KeyTyped -= HandleKeyTyped;
else
window.AsLegacyWindow().KeyPress -= HandleKeyPress;
}
public void Activate(object sender)
{
if (window is Window win)
win.KeyTyped += HandleKeyTyped;
else
window.AsLegacyWindow().KeyPress += HandleKeyPress;
}
private void imeCompose()
{
//todo: implement
OnNewImeComposition?.Invoke(string.Empty);
}
private void imeResult()
{
//todo: implement
OnNewImeResult?.Invoke(string.Empty);
}
public event Action<string> OnNewImeComposition;
public event Action<string> OnNewImeResult;
}
}
|
Fix console application window title | namespace Albireo.Otp.ConsoleApplication
{
using System;
public static class Program
{
public static void Main()
{
Console.Title = "One-Time Password Generator";
}
}
}
| namespace Albireo.Otp.ConsoleApplication
{
using System;
public static class Program
{
public static void Main()
{
Console.Title = "C# One-Time Password";
}
}
}
|
Fix the bug in the binary search | using System;
using System.Security.Cryptography;
using Algorithms.Utils;
namespace Algorithms.Search
{
public class BinarySearch
{
public static int IndexOf<T>(T[] a, T v) where T: IComparable<T>
{
var lo = 0;
var hi = a.Length - 1;
int comparison(T a1, T a2) => a1.CompareTo(a2);
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid;
else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid;
}
return -1;
}
}
} | using System;
using System.Security.Cryptography;
using Algorithms.Utils;
namespace Algorithms.Search
{
public class BinarySearch
{
public static int IndexOf<T>(T[] a, T v) where T: IComparable<T>
{
var lo = 0;
var hi = a.Length - 1;
int comparison(T a1, T a2) => a1.CompareTo(a2);
while (lo <= hi)
{
int mid = lo + (hi - lo) / 2;
if (SortUtil.IsLessThan(a[mid], v, comparison)) lo = mid+1;
else if (SortUtil.IsGreaterThan(a[mid], v, comparison)) hi = mid - 1;
else return mid;
}
return -1;
}
}
} |
Read reviews from the database. | // -----------------------------------------------------------------------
// <copyright file="ReviewController.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview.Controllers
{
using System.Web.Http;
using GitReview.Models;
/// <summary>
/// Provides an API for working with reviews.
/// </summary>
public class ReviewController : ApiController
{
/// <summary>
/// Gets the specified review.
/// </summary>
/// <param name="id">The ID of the review to find.</param>
/// <returns>The specified review.</returns>
[Route("reviews/{id}")]
public object Get(string id)
{
return new
{
Reviews = new[]
{
new Review { Id = id },
}
};
}
}
}
| // -----------------------------------------------------------------------
// <copyright file="ReviewController.cs" company="(none)">
// Copyright © 2015 John Gietzen. All Rights Reserved.
// This source is subject to the MIT license.
// Please see license.md for more information.
// </copyright>
// -----------------------------------------------------------------------
namespace GitReview.Controllers
{
using System.Net;
using System.Threading.Tasks;
using System.Web.Http;
/// <summary>
/// Provides an API for working with reviews.
/// </summary>
public class ReviewController : ApiController
{
/// <summary>
/// Gets the specified review.
/// </summary>
/// <param name="id">The ID of the review to find.</param>
/// <returns>The specified review.</returns>
[Route("reviews/{id}")]
public async Task<object> Get(string id)
{
using (var ctx = new ReviewContext())
{
var review = await ctx.Reviews.FindAsync(id);
if (review == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return new
{
Reviews = new[] { review },
};
}
}
}
}
|
Set DoubleBuffered property via reflection | using System;
using System.Windows.Forms;
namespace CSharpEx.Forms
{
/// <summary>
/// Control extensions
/// </summary>
public static class ControlEx
{
/// <summary>
/// Invoke action if Invoke is requiered.
/// </summary>
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
}
}
| using System;
using System.Windows.Forms;
namespace CSharpEx.Forms
{
/// <summary>
/// Control extensions
/// </summary>
public static class ControlEx
{
/// <summary>
/// Invoke action if Invoke is requiered.
/// </summary>
public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
/// <summary>
/// Set DoubleBuffered property using reflection.
/// Call this in the constructor just after InitializeComponent().
/// </summary>
public static void SetDoubleBuffered(this Control control, bool enabled)
{
typeof (Control).InvokeMember("DoubleBuffered",
System.Reflection.BindingFlags.SetProperty |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic,
null,
control,
new object[] {enabled});
}
}
}
|
Add remote rf enable function | using System;
using DAQ.Environment;
namespace DAQ.HAL
{
/// <summary>
/// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth
/// interface.
/// </summary>
class Gigatronics7100Synth : Synth
{
public Gigatronics7100Synth(String visaAddress)
: base(visaAddress)
{ }
override public double Frequency
{
set
{
if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz
}
}
public override double Amplitude
{
set
{
if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in MHz
} // do nothing
}
public override double DCFM
{
set { } // do nothing
}
public override bool DCFMEnabled
{
set { } // do nothing
}
public override bool Enabled
{
set { } // do nothing
}
public double PulseDuration
{
set
{
if (!Environs.Debug)
{
Write("PM4");
Write("PW" + value + "US");
}
}
}
}
}
| using System;
using DAQ.Environment;
namespace DAQ.HAL
{
/// <summary>
/// This class represents a GPIB controlled Gigatronics 7100 arbitrary waveform generator. It conforms to the Synth
/// interface.
/// </summary>
public class Gigatronics7100Synth : Synth
{
public Gigatronics7100Synth(String visaAddress)
: base(visaAddress)
{ }
override public double Frequency
{
set
{
if (!Environs.Debug) Write("CW" + value + "MZ"); // the value is entered in MHz
}
}
public override double Amplitude
{
set
{
if (!Environs.Debug) Write("PL" + value + "DM"); // the value is entered in dBm
} // do nothing
}
public override double DCFM
{
set { } // do nothing
}
public override bool DCFMEnabled
{
set { } // do nothing
}
public override bool Enabled
{
set
{
if (value)
{
if (!Environs.Debug) Write("RF1");
}
else
{
if (!Environs.Debug) Write("RF0");
}
}
}
public double PulseDuration
{
set
{
if (!Environs.Debug)
{
Write("PM4");
Write("PW" + value + "US");
}
}
}
}
}
|
Select Bundle dialog looks for zip files | using System;
using System.Windows.Forms;
namespace ProtoScript.Dialogs
{
class SelectBundleDialog : IDisposable
{
private const string kResourceBundleExtension = ".bun";
private readonly OpenFileDialog m_fileDialog;
public SelectBundleDialog()
{
m_fileDialog = new OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Filter = "Bundle files|*" + kResourceBundleExtension
};
}
public void ShowDialog()
{
if (m_fileDialog.ShowDialog() == DialogResult.OK)
FileName = m_fileDialog.FileName;
}
public string FileName { get; private set; }
public void Dispose()
{
m_fileDialog.Dispose();
}
}
}
| using System;
using System.Windows.Forms;
namespace ProtoScript.Dialogs
{
class SelectBundleDialog : IDisposable
{
private const string kResourceBundleExtension = ".zip";
private readonly OpenFileDialog m_fileDialog;
public SelectBundleDialog()
{
m_fileDialog = new OpenFileDialog
{
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
Filter = "Zip files|*" + kResourceBundleExtension
};
}
public void ShowDialog()
{
if (m_fileDialog.ShowDialog() == DialogResult.OK)
FileName = m_fileDialog.FileName;
}
public string FileName { get; private set; }
public void Dispose()
{
m_fileDialog.Dispose();
}
}
}
|
Fix example that caused exception | namespace ExampleGenerator
{
using OxyPlot;
public static class BindingExamples
{
[Export(@"BindingExamples\Example1")]
public static PlotModel Example1()
{
return null;
}
}
} | namespace ExampleGenerator
{
using OxyPlot;
public static class BindingExamples
{
[Export(@"BindingExamples\Example1")]
public static PlotModel Example1()
{
return new PlotModel { Title = "TODO" };
}
}
} |
Add AsReadOnlyList; Remove obsolete method | using System.Collections.Generic;
using System.Linq;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static IEnumerable<T> Append<T>(this IEnumerable<T> items, T value)
{
foreach (T item in items)
yield return item;
yield return value;
}
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items)
{
return items.Where(x => x != null);
}
public static IEnumerable<T> Enumerate<T>(params T[] items)
{
return items;
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace GoldenAnvil.Utility
{
public static class EnumerableUtility
{
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items)
{
return items ?? Enumerable.Empty<T>();
}
public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items)
{
return items.Where(x => x != null);
}
public static IEnumerable<T> Enumerate<T>(params T[] items)
{
return items;
}
public static IReadOnlyList<T> AsReadOnlyList<T>(this IEnumerable<T> items)
{
return items as IReadOnlyList<T> ??
(items is IList<T> list ? (IReadOnlyList<T>) new ReadOnlyListAdapter<T>(list) : items.ToList().AsReadOnly());
}
private sealed class ReadOnlyListAdapter<T> : IReadOnlyList<T>
{
public ReadOnlyListAdapter(IList<T> list) => m_list = list ?? throw new ArgumentNullException(nameof(list));
public int Count => m_list.Count;
public T this[int index] => m_list[index];
public IEnumerator<T> GetEnumerator() => m_list.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) m_list).GetEnumerator();
readonly IList<T> m_list;
}
}
}
|
Check for empty array on food record | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EvoNet.Controls;
using Graph;
using EvoNet.Map;
namespace EvoNet.Forms
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
foodValueList.Color = Color.Green;
FoodGraph.Add("Food", foodValueList);
evoSimControl1.OnUpdate += EvoSimControl1_OnUpdate;
}
private void EvoSimControl1_OnUpdate(Microsoft.Xna.Framework.GameTime obj)
{
}
GraphValueList foodValueList = new GraphValueList();
int lastFoodIndex = 0;
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Close();
}
private TileMap TileMap
{
get
{
return evoSimControl1.sim.TileMap;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
float Value = TileMap.FoodRecord.Skip(lastFoodIndex).Average();
lastFoodIndex = TileMap.FoodRecord.Count;
foodValueList.Add(new GraphTimeDoubleValue(DateTime.Now, Value));
FoodGraph.Refresh();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EvoNet.Controls;
using Graph;
using EvoNet.Map;
namespace EvoNet.Forms
{
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
foodValueList.Color = Color.Green;
FoodGraph.Add("Food", foodValueList);
evoSimControl1.OnUpdate += EvoSimControl1_OnUpdate;
}
private void EvoSimControl1_OnUpdate(Microsoft.Xna.Framework.GameTime obj)
{
}
GraphValueList foodValueList = new GraphValueList();
int lastFoodIndex = 0;
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Close();
}
private TileMap TileMap
{
get
{
return evoSimControl1.sim.TileMap;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (TileMap.FoodRecord.Count > lastFoodIndex)
{
float Value = TileMap.FoodRecord.Skip(lastFoodIndex).Average();
lastFoodIndex = TileMap.FoodRecord.Count;
foodValueList.Add(new GraphTimeDoubleValue(DateTime.Now, Value));
FoodGraph.Refresh();
}
}
}
}
|
Replace the polling with an event handler | using System;
using System.Diagnostics;
using System.Threading;
namespace RedGate.AppHost.Client
{
internal class ParentProcessMonitor
{
private readonly Action m_OnParentMissing;
private readonly int m_PollingIntervalInSeconds;
private Thread m_PollingThread;
public ParentProcessMonitor(Action onParentMissing, int pollingIntervalInSeconds = 10)
{
if (onParentMissing == null)
{
throw new ArgumentNullException("onParentMissing");
}
m_OnParentMissing = onParentMissing;
m_PollingIntervalInSeconds = pollingIntervalInSeconds;
}
public void Start()
{
m_PollingThread = new Thread(PollForParentProcess);
m_PollingThread.Start();
}
private void PollForParentProcess()
{
var currentProcess = Process.GetCurrentProcess();
var parentProcessId = currentProcess.GetParentProcessId();
try
{
while (true)
{
Process.GetProcessById(parentProcessId);
Thread.Sleep(m_PollingIntervalInSeconds * 1000);
}
}
catch
{
m_OnParentMissing();
}
}
}
}
| using System;
using System.Diagnostics;
using System.Runtime.Remoting.Channels;
using System.Threading;
namespace RedGate.AppHost.Client
{
internal class ParentProcessMonitor
{
private readonly Action m_OnParentMissing;
public ParentProcessMonitor(Action onParentMissing)
{
if (onParentMissing == null)
{
throw new ArgumentNullException("onParentMissing");
}
m_OnParentMissing = onParentMissing;
}
public void Start()
{
var currentProcess = Process.GetCurrentProcess();
var parentProcessId = currentProcess.GetParentProcessId();
var parentProcess = Process.GetProcessById(parentProcessId);
parentProcess.EnableRaisingEvents = true;
parentProcess.Exited += (sender, e) => { m_OnParentMissing(); };
}
}
}
|
Tweak some of the list page formatting | @model IEnumerable<alert_roster.web.Models.Message>
@{
ViewBag.Title = "Messages";
}
<div class="jumbotron">
<h1>@ViewBag.Title</h1>
</div>
@foreach (var message in Model)
{
<div class="row">
<div class="col-md-4">
<fieldset>
<legend>
<script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script>
</legend>
@message.Content
</fieldset>
</div>
</div>
} | @model IEnumerable<alert_roster.web.Models.Message>
@{
ViewBag.Title = "Notices";
}
<h2>@ViewBag.Title</h2>
@foreach (var message in Model)
{
<div class="row">
<div class="col-md-5">
<fieldset>
<legend>
Posted <script>var d = moment.utc('@message.PostedDate').local(); document.write(d);</script>
</legend>
@message.Content
</fieldset>
</div>
</div>
} |
Use null-conditional operator when checking against UpdateManager | // 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;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Updater;
namespace osu.Game.Overlays.Settings.Sections.General
{
public class UpdateSettings : SettingsSubsection
{
[Resolved(CanBeNull = true)]
private UpdateManager updateManager { get; set; }
protected override string Header => "Updates";
[BackgroundDependencyLoader]
private void load(Storage storage, OsuConfigManager config, OsuGameBase game)
{
Add(new SettingsEnumDropdown<ReleaseStream>
{
LabelText = "Release stream",
Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream),
});
// We should only display the button for UpdateManagers that do update the client
if (updateManager != null && updateManager.CanPerformUpdate)
{
Add(new SettingsButton
{
Text = "Check for updates",
Action = updateManager.CheckForUpdate,
Enabled = { Value = game.IsDeployedBuild }
});
}
if (RuntimeInfo.IsDesktop)
{
Add(new SettingsButton
{
Text = "Open osu! folder",
Action = storage.OpenInNativeExplorer,
});
}
}
}
}
| // 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;
using osu.Framework.Allocation;
using osu.Framework.Platform;
using osu.Game.Configuration;
using osu.Game.Updater;
namespace osu.Game.Overlays.Settings.Sections.General
{
public class UpdateSettings : SettingsSubsection
{
[Resolved(CanBeNull = true)]
private UpdateManager updateManager { get; set; }
protected override string Header => "Updates";
[BackgroundDependencyLoader]
private void load(Storage storage, OsuConfigManager config, OsuGameBase game)
{
Add(new SettingsEnumDropdown<ReleaseStream>
{
LabelText = "Release stream",
Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream),
});
// We should only display the button for UpdateManagers that do update the client
if (updateManager?.CanPerformUpdate == true)
{
Add(new SettingsButton
{
Text = "Check for updates",
Action = updateManager.CheckForUpdate,
Enabled = { Value = game.IsDeployedBuild }
});
}
if (RuntimeInfo.IsDesktop)
{
Add(new SettingsButton
{
Text = "Open osu! folder",
Action = storage.OpenInNativeExplorer,
});
}
}
}
}
|
Tidy of the login page | @model dynamic
@{
ViewBag.Title = "login";
}
<h2>Log in!</h2>
<form method="POST">
@Html.AntiForgeryToken()
Username: @Html.TextBox("Username")<br/>
Password: @Html.Password("Password")<br/>
Remember me @Html.CheckBox("RememberMe")<br />
<input type="submit" value="Log in"/>
</form> | @model dynamic
@{
ViewBag.Title = "login";
}
<h2>Log in!</h2>
<form method="POST" role="form" id="loginForm" name="loginForm">
@Html.AntiForgeryToken()
<div class="form-group" ng-class="{'has-error': addForm.name.$invalid && addForm.name.$pristine && submitted}">
<label class="col-sm-2 control-label" for="Username">Username</label>
@Html.TextBox("Username", "", new { required = "required", @class = "form-control" })
<span class="help-block" ng-show="loginForm.Username.$error.required && loginform.Username.$pristine">Required</span>
</div>
<div class="form-group" ng-class="{'has-error': addForm.name.$invalid && addForm.name.$pristine && submitted}">
<label class="col-sm-2 control-label" for="Password">Password</label>
@Html.Password("Password", "", new { required = "required", @class = "form-control" })
<span class="help-block" ng-show="loginForm.Password.$error.required && loginform.Password.$pristine">Required</span>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
@Html.CheckBox("RememberMe") Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button class="btn btn-default" type="submit">Log in</button>
</div>
</div>
</form> |
Use AttributeNullException instead of an InvalidOperationException. | using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Web.Portal.Service;
namespace Premotion.Mansion.Web.Portal.ScriptTags
{
/// <summary>
/// Renders the specified block.
/// </summary>
[ScriptTag(Constants.TagNamespaceUri, "renderBlock")]
public class RenderBlockTag : ScriptTag
{
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="context"></param>
protected override void DoExecute(IMansionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var blockProperties = GetAttributes(context);
string targetField;
if (!blockProperties.TryGetAndRemove(context, "targetField", out targetField) || string.IsNullOrEmpty(targetField))
throw new InvalidOperationException("The target attribute is manditory");
var portalService = context.Nucleus.ResolveSingle<IPortalService>();
portalService.RenderBlockToOutput(context, blockProperties, targetField);
}
#endregion
}
} | using System;
using Premotion.Mansion.Core;
using Premotion.Mansion.Core.Scripting.TagScript;
using Premotion.Mansion.Web.Portal.Service;
namespace Premotion.Mansion.Web.Portal.ScriptTags
{
/// <summary>
/// Renders the specified block.
/// </summary>
[ScriptTag(Constants.TagNamespaceUri, "renderBlock")]
public class RenderBlockTag : ScriptTag
{
#region Constructors
/// <summary>
///
/// </summary>
/// <param name="context"></param>
protected override void DoExecute(IMansionContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var blockProperties = GetAttributes(context);
string targetField;
if (!blockProperties.TryGetAndRemove(context, "targetField", out targetField) || string.IsNullOrEmpty(targetField))
throw new AttributeNullException("targetField", this);
var portalService = context.Nucleus.ResolveSingle<IPortalService>();
portalService.RenderBlockToOutput(context, blockProperties, targetField);
}
#endregion
}
} |
Change back to use EF initializer to drop db | namespace Tools.Test.Database.Model.Tasks
{
public class DropDatabaseTask : DatabaseTask
{
private readonly string _connectionString;
public DropDatabaseTask(string connectionString)
: base(connectionString)
{
_connectionString = connectionString;
}
public override bool Execute()
{
System.Data.Entity.Database.Delete(_connectionString);
return true;
}
}
}
| using System.Data.Entity;
using Infrastructure.DataAccess;
namespace Tools.Test.Database.Model.Tasks
{
public class DropDatabaseTask : DatabaseTask
{
private readonly string _connectionString;
public DropDatabaseTask(string connectionString)
: base(connectionString)
{
_connectionString = connectionString;
}
public override bool Execute()
{
System.Data.Entity.Database.SetInitializer(new DropCreateDatabaseAlways<KitosContext>());
using (var context = CreateKitosContext())
{
context.Database.Initialize(true);
}
return true;
}
}
}
|
Add Save method. bugid: 928 | //-----------------------------------------------------------------------
// <copyright file="ViewModelBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Base class used to create ViewModel objects that contain the Model object and related elements.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Csla.Web.Mvc
{
/// <summary>
/// Base class used to create ViewModel objects that
/// contain the Model object and related elements.
/// </summary>
/// <typeparam name="T">Type of the Model object.</typeparam>
public abstract class ViewModelBase<T> : IViewModel where T : class
{
object IViewModel.ModelObject
{
get { return ModelObject; }
set { ModelObject = (T)value; }
}
/// <summary>
/// Gets or sets the Model object.
/// </summary>
public T ModelObject { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="ViewModelBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>Base class used to create ViewModel objects that contain the Model object and related elements.</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
namespace Csla.Web.Mvc
{
/// <summary>
/// Base class used to create ViewModel objects that
/// contain the Model object and related elements.
/// </summary>
/// <typeparam name="T">Type of the Model object.</typeparam>
public abstract class ViewModelBase<T> : IViewModel where T : class
{
object IViewModel.ModelObject
{
get { return ModelObject; }
set { ModelObject = (T)value; }
}
/// <summary>
/// Gets or sets the Model object.
/// </summary>
public T ModelObject { get; set; }
/// <summary>
/// Saves the current Model object if the object
/// implements Csla.Core.ISavable.
/// </summary>
/// <param name="modelState">Controller's ModelState object.</param>
/// <returns>true if the save succeeds.</returns>
public virtual bool Save(ModelStateDictionary modelState, bool forceUpdate)
{
try
{
var savable = ModelObject as Csla.Core.ISavable;
if (savable == null)
throw new InvalidOperationException("Save");
ModelObject = (T)savable.Save(forceUpdate);
return true;
}
catch (Csla.DataPortalException ex)
{
if (ex.BusinessException != null)
modelState.AddModelError("", ex.BusinessException.Message);
else
modelState.AddModelError("", ex.Message);
return false;
}
catch (Exception ex)
{
modelState.AddModelError("", ex.Message);
return false;
}
}
}
}
|
Use nameof on argument check in the template project. |
using System;
using XPNet;
namespace XPNet.CLR.Template
{
[XPlanePlugin(
name: "My Plugin",
signature: "you.plugins.name",
description: "Describe your plugin here."
)]
public class Plugin : IXPlanePlugin
{
private readonly IXPlaneApi m_api;
public Plugin(IXPlaneApi api)
{
m_api = api ?? throw new ArgumentNullException("api");
}
public void Dispose()
{
// Clean up whatever we attached / registered for / etc.
}
public void Enable()
{
// Called when the plugin is enabled in X-Plane.
}
public void Disable()
{
// Called when the plugin is disabled in X-Plane.
}
}
}
|
using System;
using XPNet;
namespace XPNet.CLR.Template
{
[XPlanePlugin(
name: "My Plugin",
signature: "you.plugins.name",
description: "Describe your plugin here."
)]
public class Plugin : IXPlanePlugin
{
private readonly IXPlaneApi m_api;
public Plugin(IXPlaneApi api)
{
m_api = api ?? throw new ArgumentNullException(nameof(api));
}
public void Dispose()
{
// Clean up whatever we attached / registered for / etc.
}
public void Enable()
{
// Called when the plugin is enabled in X-Plane.
}
public void Disable()
{
// Called when the plugin is disabled in X-Plane.
}
}
}
|
Comment removal in prep for newer commenting | using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class PlainTextOutputSpeech : IOutputSpeech
{
/// <summary>
/// A string containing the type of output speech to render. Valid types are:
/// - "PlainText" - Indicates that the output speech is defined as plain text.
/// - "SSML" - Indicates that the output speech is text marked up with SSML.
/// </summary>
[JsonProperty("type")]
[JsonRequired]
public string Type
{
get { return "PlainText"; }
}
/// <summary>
/// A string containing the speech to render to the user. Use this when type is "PlainText"
/// </summary>
[JsonRequired]
[JsonProperty("text")]
public string Text { get; set; }
}
} | using Newtonsoft.Json;
namespace Alexa.NET.Response
{
public class PlainTextOutputSpeech : IOutputSpeech
{
[JsonProperty("type")]
[JsonRequired]
public string Type
{
get { return "PlainText"; }
}
[JsonRequired]
[JsonProperty("text")]
public string Text { get; set; }
}
} |
Use an array of directories instead of just one. | using System.IO;
namespace Nustache.Core
{
public class FileSystemTemplateLocator
{
private readonly string _extension;
private readonly string _directory;
public FileSystemTemplateLocator(string extension, string directory)
{
_extension = extension;
_directory = directory;
}
public Template GetTemplate(string name)
{
string path = Path.Combine(_directory, name + _extension);
if (File.Exists(path))
{
string text = File.ReadAllText(path);
var reader = new StringReader(text);
var template = new Template();
template.Load(reader);
return template;
}
return null;
}
}
} | using System.IO;
namespace Nustache.Core
{
public class FileSystemTemplateLocator
{
private readonly string _extension;
private readonly string[] _directories;
public FileSystemTemplateLocator(string extension, params string[] directories)
{
_extension = extension;
_directories = directories;
}
public Template GetTemplate(string name)
{
foreach (var directory in _directories)
{
var path = Path.Combine(directory, name + _extension);
if (File.Exists(path))
{
var text = File.ReadAllText(path);
var reader = new StringReader(text);
var template = new Template();
template.Load(reader);
return template;
}
}
return null;
}
}
} |
Remove the nullable disable annotation in the mania ruleset. | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Rulesets.Mania
{
public class ManiaFilterCriteria : IRulesetFilterCriteria
{
private FilterCriteria.OptionalRange<float> keys;
public bool Matches(BeatmapInfo beatmapInfo)
{
return !keys.HasFilter || (beatmapInfo.Ruleset.OnlineID == new ManiaRuleset().LegacyID && keys.IsInRange(ManiaBeatmapConverter.GetColumnCountForNonConvert(beatmapInfo)));
}
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
switch (key)
{
case "key":
case "keys":
return FilterQueryParser.TryUpdateCriteriaRange(ref keys, op, value);
}
return false;
}
}
}
| // 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.Beatmaps;
using osu.Game.Rulesets.Filter;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Screens.Select;
using osu.Game.Screens.Select.Filter;
namespace osu.Game.Rulesets.Mania
{
public class ManiaFilterCriteria : IRulesetFilterCriteria
{
private FilterCriteria.OptionalRange<float> keys;
public bool Matches(BeatmapInfo beatmapInfo)
{
return !keys.HasFilter || (beatmapInfo.Ruleset.OnlineID == new ManiaRuleset().LegacyID && keys.IsInRange(ManiaBeatmapConverter.GetColumnCountForNonConvert(beatmapInfo)));
}
public bool TryParseCustomKeywordCriteria(string key, Operator op, string value)
{
switch (key)
{
case "key":
case "keys":
return FilterQueryParser.TryUpdateCriteriaRange(ref keys, op, value);
}
return false;
}
}
}
|
Fix SchedulerAutorRemove to work correctly. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class SchedulerAutoremove : SchedulerTestLayer
{
public virtual void onEnter()
{
base.OnEnter();
Schedule(autoremove, 0.5f);
Schedule(tick, 0.5f);
accum = 0;
}
public override string title()
{
return "Self-remove an scheduler";
}
public override string subtitle()
{
return "1 scheduler will be autoremoved in 3 seconds. See console";
}
public void autoremove(float dt)
{
accum += dt;
CCLog.Log("Time: %f", accum);
if (accum > 3)
{
Unschedule(autoremove);
CCLog.Log("scheduler removed");
}
}
public void tick(float dt)
{
CCLog.Log("This scheduler should not be removed");
}
private float accum;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
public class SchedulerAutoremove : SchedulerTestLayer
{
private float accum;
public override void OnEnter ()
{
base.OnEnter();
Schedule(autoremove, 0.5f);
Schedule(tick, 0.5f);
accum = 0;
}
public override string title()
{
return "Self-remove an scheduler";
}
public override string subtitle()
{
return "1 scheduler will be autoremoved in 3 seconds. See console";
}
public void autoremove(float dt)
{
accum += dt;
CCLog.Log("Time: {0}", accum);
if (accum > 3)
{
Unschedule(autoremove);
CCLog.Log("scheduler removed");
}
}
public void tick(float dt)
{
CCLog.Log("This scheduler should not be removed");
}
}
}
|
Simplify debug view prop body | /*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Iced is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Iced. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
namespace Iced.Intel {
sealed class InstructionListDebugView {
readonly InstructionList list;
public InstructionListDebugView(InstructionList list) =>
this.list = list ?? throw new ArgumentNullException(nameof(list));
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Instruction[] Items {
get {
var instructions = new Instruction[list.Count];
list.CopyTo(instructions, 0);
return instructions;
}
}
}
}
| /*
Copyright (C) 2018 de4dot@gmail.com
This file is part of Iced.
Iced is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Iced is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Iced. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Diagnostics;
namespace Iced.Intel {
sealed class InstructionListDebugView {
readonly InstructionList list;
public InstructionListDebugView(InstructionList list) =>
this.list = list ?? throw new ArgumentNullException(nameof(list));
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public Instruction[] Items => list.ToArray();
}
}
|
Apply a saving option only at it needed. | using System;
using System.Runtime.InteropServices;
using System.Windows;
using CoCo.UI;
using CoCo.UI.ViewModels;
using Microsoft.VisualStudio.Shell;
namespace CoCo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading =true)]
[ProvideOptionPage(typeof(DialogOption), "CoCo", "CoCo", 0, 0, true)]
[Guid("b933474d-306e-434f-952d-a820c849ed07")]
public sealed class VsPackage : Package
{
}
public class DialogOption : UIElementDialogPage
{
private OptionViewModel _view;
private OptionControl _child;
protected override UIElement Child
{
get
{
if (_child != null) return _child;
_view = new OptionViewModel(new OptionProvider());
_child = new OptionControl
{
DataContext = _view
};
return _child;
}
}
protected override void OnClosed(EventArgs e)
{
_view.SaveOption();
base.OnClosed(e);
}
}
} | using System;
using System.Runtime.InteropServices;
using System.Windows;
using CoCo.UI;
using CoCo.UI.ViewModels;
using Microsoft.VisualStudio.Shell;
namespace CoCo
{
[PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
[ProvideOptionPage(typeof(DialogOption), "CoCo", "CoCo", 0, 0, true)]
[Guid("b933474d-306e-434f-952d-a820c849ed07")]
public sealed class VsPackage : Package
{
}
public class DialogOption : UIElementDialogPage
{
private OptionViewModel _view;
private OptionControl _child;
protected override UIElement Child
{
get
{
if (_child != null) return _child;
_view = new OptionViewModel(new OptionProvider());
_child = new OptionControl
{
DataContext = _view
};
return _child;
}
}
protected override void OnApply(PageApplyEventArgs e)
{
if (e.ApplyBehavior == ApplyKind.Apply)
{
_view.SaveOption();
}
base.OnApply(e);
}
}
} |
Fix wrong render order key bit shift | using System;
using System.Runtime.CompilerServices;
#if NETFX_CORE
namespace HelixToolkit.UWP.Model
#else
namespace HelixToolkit.Wpf.SharpDX.Model
#endif
{
/// <summary>
/// Render order key
/// </summary>
public struct OrderKey : IComparable<OrderKey>
{
public uint Key;
public OrderKey(uint key)
{
Key = key;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OrderKey Create(ushort order, ushort materialID)
{
return new OrderKey(((uint)order << 32) | materialID);
}
public int CompareTo(OrderKey other)
{
return Key.CompareTo(other.Key);
}
}
}
| using System;
using System.Runtime.CompilerServices;
#if NETFX_CORE
namespace HelixToolkit.UWP.Model
#else
namespace HelixToolkit.Wpf.SharpDX.Model
#endif
{
/// <summary>
/// Render order key
/// </summary>
public struct OrderKey : IComparable<OrderKey>
{
public uint Key;
public OrderKey(uint key)
{
Key = key;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static OrderKey Create(ushort order, ushort materialID)
{
return new OrderKey(((uint)order << 16) | materialID);
}
public int CompareTo(OrderKey other)
{
return Key.CompareTo(other.Key);
}
}
}
|
Add placeholder for testing retrieving POs | using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using Xunit;
namespace BatteryCommander.Tests
{
public class AirTableServiceTests
{
private const String AppKey = "";
private const String BaseId = "";
[Fact]
public async Task Try_Get_Records()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var records = await service.GetRecords();
// Assert
Assert.NotEmpty(records);
}
}
} | using BatteryCommander.Web.Models;
using BatteryCommander.Web.Services;
using Microsoft.Extensions.Options;
using System;
using System.Threading.Tasks;
using Xunit;
namespace BatteryCommander.Tests
{
public class AirTableServiceTests
{
private const String AppKey = "";
private const String BaseId = "";
[Fact]
public async Task Try_Get_Records()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var records = await service.GetRecords();
// Assert
Assert.NotEmpty(records);
}
[Fact]
public async Task Get_Purchase_Order()
{
if (String.IsNullOrWhiteSpace(AppKey)) return;
// Arrange
var options = Options.Create(new AirTableSettings { AppKey = AppKey, BaseId = BaseId });
var service = new AirTableService(options);
// Act
var order = await service.GetPurchaseOrder(id: "reclJK6G3IFjFlXE1");
// Assert
// TODO
}
}
} |
Address PR feedback and add comment | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Test.Extensions
{
public static class SemanticModelExtensions
{
public static IOperation GetOperationInternal(this SemanticModel model, SyntaxNode node)
{
return model.GetOperationInternal(node);
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Test.Extensions
{
public static class SemanticModelExtensions
{
public static IOperation GetOperationInternal(this SemanticModel model, SyntaxNode node)
{
// Invoke the GetOperationInternal API to by-pass the IOperation feature flag check.
return model.GetOperationInternal(node);
}
}
}
|
Fix category of revision log RSS feeds. | <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Report</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
| <?xml version="1.0"?>
<!-- RSS generated by Trac v<?cs var:trac.version ?> on <?cs var:trac.time ?> -->
<rss version="2.0">
<channel><?cs
if:project.name_encoded ?>
<title><?cs var:project.name_encoded ?>: Revisions of <?cs var:log.path ?></title><?cs
else ?>
<title>Revisions of <?cs var:log.path ?></title><?cs
/if ?>
<link><?cs var:base_host ?><?cs var:log.log_href ?></link>
<description>Trac Log - Revisions of <?cs var:log.path ?></description>
<language>en-us</language>
<generator>Trac v<?cs var:trac.version ?></generator><?cs
each:item = log.items ?><?cs
with:change = log.changes[item.rev] ?>
<item>
<author><?cs var:change.author ?></author>
<pubDate><?cs var:change.date ?></pubDate>
<title>Revision <?cs var:item.rev ?>: <?cs var:change.shortlog ?></title>
<link><?cs var:base_host ?><?cs var:item.changeset_href ?></link>
<description><?cs var:change.message ?></description>
<category>Log</category>
</item><?cs
/with ?><?cs
/each ?>
</channel>
</rss>
|
Update nuget package version to beta02 | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta01")] | using System.Reflection;
// 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("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta02")] |
Update visual style to match new notes | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Scale = note.Scale;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Allocation;
using osu.Game.Graphics;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Mania.Objects.Drawables;
using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays
{
public class NoteMask : HitObjectMask
{
public NoteMask(DrawableNote note)
: base(note)
{
Scale = note.Scale;
CornerRadius = 5;
Masking = true;
AddInternal(new NotePiece());
note.HitObject.ColumnChanged += _ => Position = note.Position;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
Colour = colours.Yellow;
}
protected override void Update()
{
base.Update();
Size = HitObject.DrawSize;
Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft);
}
}
}
|
Switch around registration order for signalr | using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
namespace Glimpse
{
public static class GlimpseServerServiceCollectionExtensions
{
public static IServiceCollection RunningServer(this IServiceCollection services)
{
UseSignalR(services, null);
return services.Add(GlimpseServerServices.GetDefaultServices());
}
public static IServiceCollection RunningServer(this IServiceCollection services, IConfiguration configuration)
{
UseSignalR(services, configuration);
return services.Add(GlimpseServerServices.GetDefaultServices(configuration));
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services)
{
return services.Add(GlimpseServerServices.GetPublisherServices());
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services, IConfiguration configuration)
{
return services.Add(GlimpseServerServices.GetPublisherServices(configuration));
}
// TODO: Confirm that this is where this should be registered
private static void UseSignalR(IServiceCollection services, IConfiguration configuration)
{
// TODO: Config isn't currently being handled - https://github.com/aspnet/SignalR-Server/issues/51
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
}
} | using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using System;
namespace Glimpse
{
public static class GlimpseServerServiceCollectionExtensions
{
public static IServiceCollection RunningServer(this IServiceCollection services)
{
services.Add(GlimpseServerServices.GetDefaultServices());
UseSignalR(services, null);
return services;
}
public static IServiceCollection RunningServer(this IServiceCollection services, IConfiguration configuration)
{
services.Add(GlimpseServerServices.GetDefaultServices(configuration));
UseSignalR(services, configuration);
return services;
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services)
{
return services.Add(GlimpseServerServices.GetPublisherServices());
}
public static IServiceCollection WithLocalAgent(this IServiceCollection services, IConfiguration configuration)
{
return services.Add(GlimpseServerServices.GetPublisherServices(configuration));
}
// TODO: Confirm that this is where this should be registered
private static void UseSignalR(IServiceCollection services, IConfiguration configuration)
{
// TODO: Config isn't currently being handled - https://github.com/aspnet/SignalR-Server/issues/51
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
}
}
} |
Swap out IgnoreLayerCollisions for new custom version. | using UnityEngine;
using System.Collections;
using DG.Tweening;
public class GameInit : MonoBehaviour
{
void Awake()
{
// seed Random with current seconds;
Random.seed = (int)System.DateTime.Now.Ticks;
// initialize DOTween before first use.
DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);
DOTween.SetTweensCapacity(2000, 100);
// ignore collisions between
Physics2D.IgnoreLayerCollision(LayerID("BodyCollider"), LayerID("One-Way Platform"), true);
Physics2D.IgnoreLayerCollision(LayerID("WeaponCollider"), LayerID("Enemies"), true);
Physics2D.IgnoreLayerCollision(LayerID("WeaponCollider"), LayerID("Collectables"), true);
}
int LayerID(string layerName)
{
return LayerMask.NameToLayer(layerName);
}
}
| using UnityEngine;
using System.Collections;
using DG.Tweening;
using Matcha.Lib;
public class GameInit : MonoBehaviour
{
void Awake()
{
// seed Random with current seconds;
Random.seed = (int)System.DateTime.Now.Ticks;
// initialize DOTween before first use.
DOTween.Init(true, true, LogBehaviour.Verbose).SetCapacity(200, 10);
DOTween.SetTweensCapacity(2000, 100);
// ignore collisions between
MLib.IgnoreLayerCollision2D("BodyCollider", "One-Way Platform", true);
MLib.IgnoreLayerCollision2D("WeaponCollider", "Enemies", true);
MLib.IgnoreLayerCollision2D("WeaponCollider", "Collectables", true);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.