Instruction stringlengths 14 778 | input_code stringlengths 0 4.24k | output_code stringlengths 1 5.44k |
|---|---|---|
Make characterset serialisation test explicit | using System.Dynamic;
using System.Xml.Serialization;
using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;
namespace com.esendex.sdk.test.messaging
{
[TestFixture]
public class SmsMessageSerializationTests
{
[Test]
public void WhenCharacterSetIsDefaultItIsNotSerialised()
{
var message = new SmsMessage();
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialisedMessage, Is.Not.StringContaining("characterset"));
}
[Test]
public void WhenCharacterSetIsSetShouldBeSerialised([Values(CharacterSet.Auto, CharacterSet.GSM, CharacterSet.Unicode)] CharacterSet characterSet)
{
var message = new SmsMessage();
message.CharacterSet = characterSet;
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialiser.Deserialise<SmsMessage>(serialisedMessage).CharacterSet, Is.EqualTo(characterSet));
}
}
} | using com.esendex.sdk.core;
using com.esendex.sdk.messaging;
using com.esendex.sdk.utilities;
using NUnit.Framework;
namespace com.esendex.sdk.test.messaging
{
[TestFixture]
public class SmsMessageSerializationTests
{
[TestCase(CharacterSet.Auto, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Auto</characterset></message>")]
[TestCase(CharacterSet.GSM, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>GSM</characterset></message>")]
[TestCase(CharacterSet.Unicode, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity><characterset>Unicode</characterset></message>")]
[TestCase(CharacterSet.Default, @"<?xml version=""1.0"" encoding=""utf-8""?><message><type>SMS</type><validity>0</validity></message>")]
public void WhenSmsMessageIsSerializedThenTheCharacterSetIsSerialisedAsExpected(CharacterSet characterSet, string expectedXml)
{
var message = new SmsMessage {CharacterSet = characterSet};
var serialiser = new XmlSerialiser();
var serialisedMessage = serialiser.Serialise(message);
Assert.That(serialisedMessage, Is.EqualTo(expectedXml));
}
}
} |
Remove duplicate attribute that fails the build | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyDescription ("Clide.Vsix")]
[assembly: InternalsVisibleTo ("Clide.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d9776e258bdf5f7c38f3c880404b9861ebbd235d8198315cdfda0f0c25b18608bdfd03e34bac9d0ec95766e8c3928140c6eda581a9448066af7dfaf88d3b6cb71d45a094011209ff6e76713151b4f2ce469cd2886285f1bf565b7fa63dada9d2e9573b743d26daa608b4d0fdebc9daa907a52727448316816f9c05c6e5529b9f")] | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo ("Clide.IntegrationTests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100d9776e258bdf5f7c38f3c880404b9861ebbd235d8198315cdfda0f0c25b18608bdfd03e34bac9d0ec95766e8c3928140c6eda581a9448066af7dfaf88d3b6cb71d45a094011209ff6e76713151b4f2ce469cd2886285f1bf565b7fa63dada9d2e9573b743d26daa608b4d0fdebc9daa907a52727448316816f9c05c6e5529b9f")] |
Fix incorrect control display key | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ControlDisplay : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private SpriteRenderer controlRenderer;
[SerializeField]
private Text controlText;
#pragma warning restore 0649
public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
{
//TODO re-enable command warnings?
controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
controlText.text = TextHelper.getLocalizedTextNoWarnings("control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
}
string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
{
switch (controlScheme)
{
case (MicrogameTraits.ControlScheme.Key):
return "USE DA KEYZ";
case (MicrogameTraits.ControlScheme.Mouse):
return "USE DA MOUSE";
default:
return "USE SOMETHING";
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ControlDisplay : MonoBehaviour
{
#pragma warning disable 0649 //Serialized Fields
[SerializeField]
private SpriteRenderer controlRenderer;
[SerializeField]
private Text controlText;
#pragma warning restore 0649
public void setControlScheme(MicrogameTraits.ControlScheme controlScheme)
{
//TODO re-enable command warnings?
controlRenderer.sprite = GameController.instance.getControlSprite(controlScheme);
controlText.text = TextHelper.getLocalizedTextNoWarnings("stage.control." + controlScheme.ToString().ToLower(), getDefaultControlString(controlScheme));
}
string getDefaultControlString(MicrogameTraits.ControlScheme controlScheme)
{
switch (controlScheme)
{
case (MicrogameTraits.ControlScheme.Key):
return "USE DA KEYZ";
case (MicrogameTraits.ControlScheme.Mouse):
return "USE DA MOUSE";
default:
return "USE SOMETHING";
}
}
}
|
Fix incorrect default view names | // <copyright file="ViewResolver.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
namespace Stormpath.Owin.Common.Views.Precompiled
{
public static class ViewResolver
{
private static readonly Dictionary<string, Func<IView>> LookupTable =
new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
{
["change"] = () => new Change(),
["forgot"] = () => new Forgot(),
["login"] = () => new Login(),
["register"] = () => new Register(),
["verify"] = () => new Verify(),
};
public static IView GetView(string name)
{
Func<IView> foundViewFactory = null;
LookupTable.TryGetValue(name, out foundViewFactory);
return foundViewFactory == null
? null
: foundViewFactory();
}
}
}
| // <copyright file="ViewResolver.cs" company="Stormpath, Inc.">
// Copyright (c) 2016 Stormpath, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System;
using System.Collections.Generic;
namespace Stormpath.Owin.Common.Views.Precompiled
{
public static class ViewResolver
{
private static readonly Dictionary<string, Func<IView>> LookupTable =
new Dictionary<string, Func<IView>>(StringComparer.OrdinalIgnoreCase)
{
["change-password"] = () => new Change(),
["forgot-password"] = () => new Forgot(),
["login"] = () => new Login(),
["register"] = () => new Register(),
["verify"] = () => new Verify(),
};
public static IView GetView(string name)
{
Func<IView> foundViewFactory = null;
LookupTable.TryGetValue(name, out foundViewFactory);
return foundViewFactory == null
? null
: foundViewFactory();
}
}
}
|
Implement TrySaveToFile() by using File.WriteAllText(). | /*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
return UIActionVisibility.Enabled;
}
}
}
| /*********************************************************************************
* SettingsTextBox.UIActions.cs
*
* Copyright (c) 2004-2018 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*********************************************************************************/
using System;
using System.IO;
namespace Sandra.UI.WF
{
public partial class SettingsTextBox
{
public const string SettingsTextBoxUIActionPrefix = nameof(RichTextBoxBase) + ".";
public static readonly DefaultUIActionBinding SaveToFile = new DefaultUIActionBinding(
new UIAction(SettingsTextBoxUIActionPrefix + nameof(SaveToFile)),
new UIActionBinding()
{
ShowInMenu = true,
IsFirstInGroup = true,
MenuCaptionKey = LocalizedStringKeys.Save,
Shortcuts = new ShortcutKeys[] { new ShortcutKeys(KeyModifiers.Control, ConsoleKey.S), },
});
public UIActionState TrySaveToFile(bool perform)
{
if (ReadOnly) return UIActionVisibility.Hidden;
if (perform) File.WriteAllText(settingsFile.AbsoluteFilePath, Text);
return UIActionVisibility.Enabled;
}
}
}
|
Revert "Add option for allowed user roles" | using System;
using System.Collections.Generic;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public GlimpseServerWebOptions()
{
AllowedUserRoles = new List<string>();
}
public bool AllowRemote { get; set; }
public IList<string> AllowedUserRoles { get; }
}
} | using System;
namespace Glimpse.Server
{
public class GlimpseServerWebOptions
{
public bool AllowRemote { get; set; }
}
} |
Add dumping of solution based on dummy data | using System;
using System.Collections.Generic;
using System.Windows.Forms;
using UniProgramGen.Data;
namespace UniProgramGen
{
public partial class ResultsTab : UserControl
{
public ResultsTab()
{
InitializeComponent();
}
private List<Teacher> teachers;
private List<Room> rooms;
private List<Group> groups;
private List<Subject> subjects;
internal void InitializeBindingSources(
BindingSource teachersBS,
BindingSource roomsBS,
BindingSource groupsBS,
BindingSource subjectsBS)
{
teachers = (List<Teacher>)teachersBS.DataSource;
rooms = (List<Room>)roomsBS.DataSource;
groups = (List<Group>)groupsBS.DataSource;
subjects = (List<Subject>)subjectsBS.DataSource;
listBoxTeachers.DataSource = teachersBS;
listBoxRooms.DataSource = roomsBS;
listBoxGroups.DataSource = groupsBS;
}
private void buttonGenerate_Click(object sender, EventArgs e)
{
//new Generator.ProgramGenerator().GenerateProgram();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using UniProgramGen.Data;
namespace UniProgramGen
{
public partial class ResultsTab : UserControl
{
public ResultsTab()
{
InitializeComponent();
}
private List<Teacher> teachers;
private List<Room> rooms;
private List<Group> groups;
private List<Subject> subjects;
internal void InitializeBindingSources(
BindingSource teachersBS,
BindingSource roomsBS,
BindingSource groupsBS,
BindingSource subjectsBS)
{
teachers = (List<Teacher>)teachersBS.DataSource;
rooms = (List<Room>)roomsBS.DataSource;
groups = (List<Group>)groupsBS.DataSource;
subjects = (List<Subject>)subjectsBS.DataSource;
listBoxTeachers.DataSource = teachersBS;
listBoxRooms.DataSource = roomsBS;
listBoxGroups.DataSource = groupsBS;
}
private void buttonGenerate_Click(object sender, EventArgs e)
{
DumpExampleSolution();
return;
var generator = new Generator.ProgramGenerator();
var program = generator.GenerateProgram(rooms, subjects, teachers, groups);
}
private void DumpExampleSolution()
{
Data.DBManager db = new DBManager();
db.getTestData();
var program = new Generator.ProgramGenerator().GenerateProgram(db.rooms, db.subjects, db.teachers, db.groups);
var firstSolution = program.First();
string firstSolutionJson = Newtonsoft.Json.JsonConvert.SerializeObject(firstSolution);
System.IO.File.WriteAllText("../../datafiles/example_solution.json", firstSolutionJson);
}
}
}
|
Improve json conversion: support more types + cleanup code | using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace template_designer
{
public class JsonToDictionaryConverter
{
public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
{
var jObject = JObject.Parse(json);
var dict = ParseObject(jObject);
return dict;
}
private static Dictionary<string, object> ParseObject(JObject jObject)
{
var dict = new Dictionary<string, object>();
foreach (var property in jObject.Properties())
{
if (property.Value.Type == JTokenType.Array)
{
dict.Add(property.Name, ParseArray(property.Value.ToObject<JArray>()));
}
else if (property.Value.Type == JTokenType.Object)
{
dict.Add(property.Name, ParseObject(property.Value.ToObject<JObject>()));
}
else
{
dict.Add(property.Name, property.Value.ToString());
}
}
return dict;
}
private static List<object> ParseArray(JArray value)
{
var list = new List<object>();
foreach (var child in value.Children())
{
if (child.Type == JTokenType.Array)
{
list.Add(ParseArray(child.ToObject<JArray>()));
}
else if (child.Type == JTokenType.Object)
{
list.Add(ParseObject(child.ToObject<JObject>()));
}
else
{
list.Add(child.ToString());
}
}
return list;
}
}
} | using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;
namespace template_designer
{
public class JsonToDictionaryConverter
{
public static Dictionary<string, object> DeserializeJsonToDictionary(string json)
{
var jObject = JObject.Parse(json);
return ParseJObject(jObject);
}
private static Dictionary<string, object> ParseJObject(JObject jObject)
{
return jObject.Properties().ToDictionary(property => property.Name, property => ParseValue(property.Value));
}
private static object ParseValue(JToken value)
{
switch (value.Type)
{
case JTokenType.Array:
return ParseJArray(value.ToObject<JArray>());
case JTokenType.Object:
return ParseJObject(value.ToObject<JObject>());
case JTokenType.Boolean:
return value.ToObject<bool>();
case JTokenType.Integer:
return value.ToObject<int>();
case JTokenType.Float:
return value.ToObject<float>();
default:
return value.ToString();
}
}
private static List<object> ParseJArray(JArray value)
{
return value.Children().Select(ParseValue).ToList();
}
}
} |
Switch back to implicit operators for conversions to and from CodeStyleOption and CodeStyleOption2 respectively. These are needed to prevent InvalidCastException when user invokes `optionSet.WithChangedOption(..., new CodeStyleOption<bool>(...))` and any of our internal code base tries to fetch the option value with `optionSet.GetOption<T>(...)` where T is ` CodeStyleOption2<bool>`, and this helper attempts a direct cast from object to `T`. | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
public static explicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
}
public static explicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CodeStyle
{
internal partial class CodeStyleOption2<T>
{
public static implicit operator CodeStyleOption<T>(CodeStyleOption2<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption<T>(option.Value, (NotificationOption)option.Notification);
}
public static implicit operator CodeStyleOption2<T>(CodeStyleOption<T> option)
{
if (option == null)
{
return null;
}
return new CodeStyleOption2<T>(option.Value, (NotificationOption2)option.Notification);
}
}
}
|
Add option for only 1 hop propagation | using Plantain;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
/// <summary>
/// A list of GameObjects that will have the current GameObject's triggers passed on to.
/// </summary>
public List<GameObject> targets;
/// <summary>
/// Used to prevent infinite propagation by allowing only 1 pass on.
/// </summary>
protected bool procced = false;
public void PerformTrigger(TriggerOption tOption) {
if(!procced && isActive) {
procced = true;
foreach(GameObject gameObj in targets) {
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
}
procced = false;
}
}
void OnDrawGizmos() {
TriggerGizmos("Propagator");
Gizmos.color = Color.cyan;
GizmoTargetedObjects(targets);
}
}
| using Plantain;
using System.Collections.Generic;
using UnityEngine;
[AddComponentMenu("Plantain/Trigger/Propagator")]
public class TriggerPropagator : Trigger {
/// <summary>
/// Prevent a trigger from hopping any further than the targeted objects.
/// </summary>
public bool preventPropigation = false;
/// <summary>
/// A list of GameObjects that will have the current GameObject's triggers passed on to.
/// </summary>
public List<GameObject> targets;
/// <summary>
/// Used to prevent propigation for infinite loops, among other senarios.
/// </summary>
protected bool procced = false;
public void PerformTrigger(TriggerOption tOption) {
if(!procced && isActive) {
procced = true;
foreach(GameObject gameObj in targets) {
if(preventPropigation) {
TriggerPropagator[] propagators = gameObj.GetComponents<TriggerPropagator>();
foreach(TriggerPropagator propigator in propagators) {
propigator.procced = true;
}
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
foreach(TriggerPropagator propigator in propagators) {
propigator.procced = false;
}
} else {
gameObj.SendMessage("PerformTrigger", tOption, SendMessageOptions.DontRequireReceiver);
}
}
procced = false;
}
}
void OnDrawGizmos() {
TriggerGizmos("Propagator");
Gizmos.color = Color.cyan;
GizmoTargetedObjects(targets);
}
}
|
Add Database initializer to Global | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
}
}
}
| using Samesound.Data;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace Samesound
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Database.SetInitializer<SamesoundContext>(null);
}
}
}
|
Fix logout form input button | @using Microsoft.AspNet.Identity
<div class="row">
<div class="col-md-6">
<h1>
@ViewBag.Title
<small>
@ViewBag.Lead
</small>
</h1>
</div>
<div class="col-md-6">
<ul class="nav nav-pills pull-right">
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<li><a href="/">Home</a></li>
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
}
}
else
{
<li><a href="/">Home</a></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
}
</ul>
</div>
</div>
<br /><br />
| @using Microsoft.AspNet.Identity
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
}
<div class="row">
<div class="col-md-6">
<h1>
@ViewBag.Title
<small>
@ViewBag.Lead
</small>
</h1>
</div>
<div class="col-md-6">
<ul class="nav nav-pills pull-right">
@if (Request.IsAuthenticated)
{
<li><a href="/">Home</a></li>
<li>
@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
</li>
<li>
<a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
</li>
}
else
{
<li><a href="/">Home</a></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
}
</ul>
</div>
</div>
<br /><br />
|
Make tcpSocketManager writes async to avoid blocking everything else | using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace TcpSocketDataSender
{
public class TcpSocketManager : IDisposable
{
private TcpClient _tcpClient;
BinaryWriter _writer = null;
public int ServerPort = 7839;
public string ServerIp = "127.0.0.1";
public bool AutoReconnect = false;
public bool Connect()
{
if (_writer != null)
return true;
_tcpClient = new TcpClient();
try
{
_tcpClient.Connect(IPAddress.Parse(ServerIp), ServerPort);
_writer = new BinaryWriter(_tcpClient.GetStream());
}
catch (SocketException)
{
//No server avaliable, or it is busy/full.
return false;
}
return true;
}
public void Write(string data)
{
bool written = false;
try
{
if (_tcpClient?.Connected ?? false)
{
_writer?.Write(data);
written = true;
}
}
catch (IOException)
{
//connection most likely closed
_writer?.Dispose();
_writer = null;
((IDisposable)_tcpClient)?.Dispose();
}
if (!written && AutoReconnect)
{
if(Connect())
Write(data);
}
}
public void Dispose()
{
((IDisposable)_tcpClient)?.Dispose();
_writer?.Dispose();
}
}
} | using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
namespace TcpSocketDataSender
{
public class TcpSocketManager : IDisposable
{
private TcpClient _tcpClient;
BinaryWriter _writer = null;
public int ServerPort = 7839;
public string ServerIp = "127.0.0.1";
public bool AutoReconnect = false;
public async Task<bool> Connect()
{
if (_writer != null)
return true;
_tcpClient = new TcpClient();
try
{
await _tcpClient.ConnectAsync(IPAddress.Parse(ServerIp), ServerPort);
_writer = new BinaryWriter(_tcpClient.GetStream());
}
catch (SocketException)
{
//No server avaliable, or it is busy/full.
return false;
}
return true;
}
public async Task Write(string data)
{
bool written = false;
try
{
if (_tcpClient?.Connected ?? false)
{
_writer?.Write(data);
written = true;
}
}
catch (IOException)
{
//connection most likely closed
_writer?.Dispose();
_writer = null;
((IDisposable)_tcpClient)?.Dispose();
}
if (!written && AutoReconnect)
{
if(await Connect())
await Write(data);
}
}
public void Dispose()
{
((IDisposable)_tcpClient)?.Dispose();
_writer?.Dispose();
}
}
} |
Adjust accuracy display to match stable | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.75f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() =>
new LegacySpriteText(skin, "score" /*, true*/)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
using osuTK;
namespace osu.Game.Skinning
{
public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter
{
private readonly ISkin skin;
public LegacyAccuracyCounter(ISkin skin)
{
Anchor = Anchor.TopRight;
Origin = Anchor.TopRight;
Scale = new Vector2(0.6f);
Margin = new MarginPadding(10);
this.skin = skin;
}
[Resolved(canBeNull: true)]
private HUDOverlay hud { get; set; }
protected sealed override OsuSpriteText CreateSpriteText() =>
new LegacySpriteText(skin, "score" /*, true*/)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
};
protected override void Update()
{
base.Update();
if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score)
{
// for now align with the score counter. eventually this will be user customisable.
Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y;
}
}
}
}
|
Add message to exit in debug mode | using System;
using System.IO;
using System.Linq;
namespace Cams
{
class Program
{
static void Main(string[] args)
{
string rawDir = Path.Combine(Settings.Path, "raw");
string processedDir = Path.Combine(Settings.Path, "processed");
var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
foreach (var cam in cameras)
cam.Process(processedDir);
var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
foreach (var date in dates)
date.Summarize();
#if DEBUG
Console.ReadKey();
#endif
}
static Camera BuildCamera(string path)
{
bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));
if (isAmcrest)
return new AmcrestCamera(path);
return new FoscamCamera(path);
}
}
}
| using System;
using System.IO;
using System.Linq;
namespace Cams
{
class Program
{
static void Main(string[] args)
{
string rawDir = Path.Combine(Settings.Path, "raw");
string processedDir = Path.Combine(Settings.Path, "processed");
var cameras = Directory.GetDirectories(rawDir).Select(BuildCamera);
foreach (var cam in cameras)
cam.Process(processedDir);
var dates = Directory.GetDirectories(processedDir).Select(p => new VideoDate(p));
foreach (var date in dates)
date.Summarize();
#if DEBUG
Console.WriteLine();
Console.WriteLine("Press any key to exit");
Console.ReadKey();
#endif
}
static Camera BuildCamera(string path)
{
bool isAmcrest = File.Exists(Path.Combine(path, "DVRWorkDirectory"));
if (isAmcrest)
return new AmcrestCamera(path);
return new FoscamCamera(path);
}
}
}
|
Allow compiler to set assembly version. | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GitHubFeeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bradley Grainger")]
[assembly: AssemblyProduct("GitHubFeeds")]
[assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("GitHubFeeds")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Bradley Grainger")]
[assembly: AssemblyProduct("GitHubFeeds")]
[assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.0.*")]
|
Return now submits quick poll | <div ng-controller="CreateBasicPageController">
<div>
<h2>Regular Poller?</h2>
Register for more config options. It's free!
</div>
<form name="quickPollForm">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="inactive-btn shadowed" ng-click="createPoll(pollQuestion)" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
| <div ng-controller="CreateBasicPageController">
<div>
<h2>Regular Poller?</h2>
Register for more config options. It's free!
</div>
<form name="quickPollForm" ng-submit="createPoll(pollQuestion)">
<div id="question-block">
Your Question <br />
<input id="question" placeholder="E.g. Where should we go for lunch?" ng-model="pollQuestion" required />
</div>
<div id="quickpoll-block">
<button type="submit" class="inactive-btn shadowed" ng-disabled="quickPollForm.$invalid">Quick Poll</button>
</div>
</form>
<h3 class="centered-text horizontal-ruled">or</h3>
<div id="register-block">
<button class="active-btn shadowed" ng-click="openLoginDialog()">Sign In</button>
<button class="active-btn shadowed" ng-click="openRegisterDialog()">Register</button>
</div>
</div>
|
Add UserVoice widget to global footer. | | @using GiveCRM.Web.Infrastructure
@if (ConfigurationSettings.IsUserVoiceIntegrationEnabled)
{
<script type="text/javascript">
var uvOptions = { };
(function() {
var uv = document.createElement('script');
uv.type = 'text/javascript';
uv.async = true;
uv.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'widget.uservoice.com/XMFifLxGL4npm6SHybYvtw.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(uv, s);
})();
</script>
} |
Fix Log Out link so it works everywhere. | @if (Request.IsAuthenticated) {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> @Session["DisplayName"]<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Profile", "Profile", "User")</li>
<li class="divider"></li>
<li>@Html.ActionLink("Log Out", "Logout", "User")</li>
</ul>
} else {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> Log In<span class="caret"></span> </a>
<ul class="dropdown-menu">
<li><a href="@ViewBag.GoogleLoginUrl" id="googleLoginLink">Log in with Google</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="facebookLoginLink">Log in with Facebook</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="twitterLoginLink">Log in with Twitter</a></li>
<li><a data-toggle="modal" href="#openIdLogin">Log in with an OpenID</a></li>
<li class="divider"></li>
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
</ul>
} | @if (Request.IsAuthenticated) {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> @Session["DisplayName"]<span class="caret"></span></a>
<ul class="dropdown-menu">
<li>@Html.ActionLink("Profile", "Profile", "User")</li>
<li class="divider"></li>
<li>@Html.ActionLink("Log Out", "Logout", "User", new { Area = string.Empty }, htmlAttributes: null)</li>
</ul>
} else {
<a class="dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-user" style="color: #f2105c"></i> Log In<span class="caret"></span> </a>
<ul class="dropdown-menu">
<li><a href="@ViewBag.GoogleLoginUrl" id="googleLoginLink">Log in with Google</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="facebookLoginLink">Log in with Facebook</a></li>
<li><a href="@ViewBag.GoogleLoginUrl" id="twitterLoginLink">Log in with Twitter</a></li>
<li><a data-toggle="modal" href="#openIdLogin">Log in with an OpenID</a></li>
<li class="divider"></li>
<li>@Html.ActionLink("Register", "Register", "Account", htmlAttributes: new { id = "registerLink" })</li>
</ul>
} |
Refactor Expose parse operator to deriving tests. Use [SetUp] attribute to recreate parser for every test. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;
namespace fitSharp.Test.NUnit.Fit {
public class ParseOperatorTest<ParseOperatorType>
where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {
ParseOperatorType parser;
public ParseOperatorTest() {
// Parse operators are stateless, so no need to use SetUp.
parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
}
protected bool CanParse<T>(string cellContent) {
return parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
}
protected T Parse<T>(string cellContent) where T : class {
return Parse<T>(cellContent, TypedValue.Void);
}
protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
TypedValue result = parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
return result.GetValueAs<T>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fitSharp.Machine.Engine;
using fitSharp.Machine.Model;
using NUnit.Framework;
using fitSharp.Samples.Fit;
using fitSharp.Fit.Operators;
namespace fitSharp.Test.NUnit.Fit {
public class ParseOperatorTest<ParseOperatorType>
where ParseOperatorType : CellOperator, ParseOperator<Cell>, new() {
public ParseOperatorType Parser { get; private set; }
[SetUp]
public void SetUp() {
// Parse operators are stateless, but the processor may be mutated
// by Parse(), so recreate for every test
Parser = new ParseOperatorType { Processor = Builder.CellProcessor() };
}
protected bool CanParse<T>(string cellContent) {
return Parser.CanParse(typeof(T), TypedValue.Void, new CellTreeLeaf(cellContent));
}
protected T Parse<T>(string cellContent) where T : class {
return Parse<T>(cellContent, TypedValue.Void);
}
protected T Parse<T>(string cellContent, TypedValue instance) where T : class {
TypedValue result = Parser.Parse(typeof(string), TypedValue.Void, new CellTreeLeaf(cellContent));
return result.GetValueAs<T>();
}
}
}
|
Add implementation details to SQLiteSchema Aggregator | using System;
using System.Data;
namespace Gigobyte.Daterpillar.Data
{
public class SQLiteSchemaAggregator : SchemaAggregatorBase
{
public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override string GetColumnInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
throw new NotImplementedException();
}
}
} | using System;
using System.Data;
using Gigobyte.Daterpillar.Transformation;
using System.Text.RegularExpressions;
namespace Gigobyte.Daterpillar.Data
{
public class SQLiteSchemaAggregator : SchemaAggregatorBase
{
public SQLiteSchemaAggregator(IDbConnection connection) : base(connection)
{
}
protected override void LoadColumnInformationIntoSchema(Table table, DataTable columnInfo)
{
foreach (DataRow row in columnInfo.Rows)
{
string temp;
string typeName = Convert.ToString(row[ColumnName.Type]);
typeName = (typeName == "INTEGER" ? "int" : typeName.ToLower());
temp = _dataTypeRegex.Match(typeName)?.Groups["scale"]?.Value;
int scale = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));
temp = _dataTypeRegex.Match(typeName)?.Groups["precision"]?.Value;
int precision = Convert.ToInt32((string.IsNullOrEmpty(temp) ? "0" : temp));
string defaultValue = Convert.ToString(row["dflt_value"]);
var newColumn = new Column();
newColumn.Name = Convert.ToString(row[ColumnName.Name]);
newColumn.DataType = new DataType(typeName, scale, precision);
//newColumn.AutoIncrement = Convert.ToBoolean(row[ColumnName.Auto]);
newColumn.IsNullable = !Convert.ToBoolean(row["notnull"]);
if (!string.IsNullOrEmpty(defaultValue)) newColumn.Modifiers.Add(defaultValue);
table.Columns.Add(newColumn);
}
}
protected override void LoadForeignKeyInformationIntoSchema(Table table, DataTable foreignKeyInfo)
{
base.LoadForeignKeyInformationIntoSchema(table, foreignKeyInfo);
}
protected override string GetColumnInfoQuery(string tableName)
{
return $"PRAGMA table_info('{tableName}');";
}
protected override string GetForeignKeyInfoQuery(string tableName)
{
return $"PRAGMA foreign_key_list('{tableName}');";
}
protected override string GetIndexColumnsQuery(string indexIdentifier)
{
throw new NotImplementedException();
}
protected override string GetIndexInfoQuery(string tableName)
{
throw new NotImplementedException();
}
protected override string GetTableInfoQuery()
{
return $"select sm.tbl_name AS [Name], '' AS [Comment] from sqlite_master sm WHERE sm.sql IS NOT NULL AND sm.name <> 'sqlite_sequence' AND sm.type = 'table';";
}
#region Private Members
private Regex _dataTypeRegex = new Regex(@"\((?<scale>\d+),? ?(?<precision>\d+)\)", RegexOptions.Compiled);
#endregion
}
} |
Fix last remaining critical issue in sonar | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Psistats.App
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
// Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainScreen2());
}
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
{
DialogResult result = DialogResult.Abort;
try
{
result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
+ " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
"Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;
namespace Psistats.App
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainScreen2());
}
static void CurrentDomain_UnhandledException (object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
MessageBox.Show("CurrentDomain: Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
"Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
public static void Application_ThreadException (object sender, System.Threading.ThreadExceptionEventArgs e)
{
DialogResult result = DialogResult.Abort;
try
{
result = MessageBox.Show("Application: Whoops! Please contact the developers with the"
+ " following information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
"Application Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop);
}
finally
{
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
}
}
}
|
Replace hard coded string with field in utf8string tests where the value is irrelevant | using System.Reflection;
using Xunit;
namespace System.Text.Utf8.Tests
{
public class TypeConstraintsTests
{
[Fact]
public void Utf8StringIsAStruct()
{
var utf8String = "anyString"u8;
Assert.True(utf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodeUnitsEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodeUnitsEnumerator = utf8String.GetEnumerator();
Assert.True(utf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumerableIsAStruct()
{
var utf8String = "anyString"u8;
Assert.True(utf8String.CodePoints.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodePointEnumerator = utf8String.CodePoints.GetEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringReverseCodePointEnumeratorIsAStruct()
{
var utf8String = "anyString"u8;
var utf8CodePointEnumerator = utf8String.CodePoints.GetReverseEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
}
}
| using System.Reflection;
using Xunit;
namespace System.Text.Utf8.Tests
{
public class TypeConstraintsTests
{
private Utf8String _anyUtf8String;
public TypeConstraintsTests()
{
_anyUtf8String = "anyString"u8;
}
[Fact]
public void Utf8StringIsAStruct()
{
Assert.True(_anyUtf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodeUnitsEnumeratorIsAStruct()
{
var utf8CodeUnitsEnumerator = _anyUtf8String.GetEnumerator();
Assert.True(_anyUtf8String.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumerableIsAStruct()
{
Assert.True(_anyUtf8String.CodePoints.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringCodePointEnumeratorIsAStruct()
{
var utf8CodePointEnumerator = _anyUtf8String.CodePoints.GetEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
[Fact]
public void Utf8StringReverseCodePointEnumeratorIsAStruct()
{
var utf8CodePointEnumerator = _anyUtf8String.CodePoints.GetReverseEnumerator();
Assert.True(utf8CodePointEnumerator.GetType().GetTypeInfo().IsValueType);
}
}
}
|
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major. | using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.SignalR")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
[assembly: AssemblyTitle("Autofac.Tests.Integration.SignalR")]
|
Set correct base type for script instances. | using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
namespace IronAHK.Scripting
{
partial class Parser : ICodeParser
{
Dictionary<string, CodeMemberMethod> methods;
Type core;
const string mainScope = "";
CodeEntryPointMethod main;
/// <summary>
/// Return a DOM representation of a script.
/// </summary>
public CodeCompileUnit CompileUnit
{
get
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace space = new CodeNamespace(core.Namespace + ".Instance");
unit.Namespaces.Add(space);
var container = new CodeTypeDeclaration("Program");
container.BaseTypes.Add(core.BaseType);
//container.BaseTypes.Add(core);
container.Attributes = MemberAttributes.Private;
space.Types.Add(container);
foreach (CodeMemberMethod method in methods.Values)
container.Members.Add(method);
return unit;
}
}
public Parser()
{
main = new CodeEntryPointMethod();
main.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(STAThreadAttribute))));
methods = new Dictionary<string, CodeMemberMethod>();
methods.Add(mainScope, main);
core = typeof(Script);
internalID = 0;
}
public CodeCompileUnit Parse(TextReader codeStream)
{
var lines = Read(codeStream, null);
Compile(lines);
return CompileUnit;
}
}
}
| using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
namespace IronAHK.Scripting
{
partial class Parser : ICodeParser
{
Dictionary<string, CodeMemberMethod> methods;
Type core;
const string mainScope = "";
CodeEntryPointMethod main;
/// <summary>
/// Return a DOM representation of a script.
/// </summary>
public CodeCompileUnit CompileUnit
{
get
{
CodeCompileUnit unit = new CodeCompileUnit();
CodeNamespace space = new CodeNamespace(core.Namespace + ".Instance");
unit.Namespaces.Add(space);
var container = new CodeTypeDeclaration("Program");
container.BaseTypes.Add(typeof(Script));
container.Attributes = MemberAttributes.Private;
space.Types.Add(container);
foreach (CodeMemberMethod method in methods.Values)
container.Members.Add(method);
return unit;
}
}
public Parser()
{
main = new CodeEntryPointMethod();
main.CustomAttributes.Add(new CodeAttributeDeclaration(new CodeTypeReference(typeof(STAThreadAttribute))));
methods = new Dictionary<string, CodeMemberMethod>();
methods.Add(mainScope, main);
core = typeof(Script);
internalID = 0;
}
public CodeCompileUnit Parse(TextReader codeStream)
{
var lines = Read(codeStream, null);
Compile(lines);
return CompileUnit;
}
}
}
|
Change ui text "Package" to "Dataset" | @using CkanDotNet.Api.Model
@model Package
<div class="container">
<h2 class="container-title">Rate this Package</h2>
<div class="container-content">
@Html.Partial("~/Views/Shared/_Rating.cshtml", Model, new ViewDataDictionary { { "editable", true } })
</div>
</div>
| @using CkanDotNet.Api.Model
@model Package
<div class="container">
<h2 class="container-title">Rate this Dataset</h2>
<div class="container-content">
@Html.Partial("~/Views/Shared/_Rating.cshtml", Model, new ViewDataDictionary { { "editable", true } })
</div>
</div>
|
Use Regex in stead of string | using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class LineBreakParser : IParser<LineBreak>
{
public string StartsWithChars { get { return "\\ \n"; } }
public LineBreak Parse(ParserContext context, Subject subject)
{
if (!this.CanParse(subject)) return null;
string[] groups;
if (subject.IsMatch(@" +\n", 0, out groups))
{
subject.Advance(groups[0].Length);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith("\\\n", 0))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith(" \n", 0))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
else if (subject.Char == '\n')
{
subject.Advance();
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
return null;
}
}
}
| using CommonMarkSharp.Blocks;
using CommonMarkSharp.Inlines;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace CommonMarkSharp.InlineParsers
{
public class LineBreakParser : IParser<LineBreak>
{
private static readonly Regex _startsWithDoubleSpaceNewLine = RegexUtils.Create(@"\G +\n");
public string StartsWithChars { get { return "\\ \n"; } }
public LineBreak Parse(ParserContext context, Subject subject)
{
if (!this.CanParse(subject)) return null;
string[] groups;
if (subject.IsMatch(_startsWithDoubleSpaceNewLine, 0, out groups))
{
subject.Advance(groups[0].Length);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith("\\\n"))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new HardBreak();
}
else if (subject.StartsWith(" \n"))
{
subject.Advance(2);
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
else if (subject.Char == '\n')
{
subject.Advance();
subject.AdvanceWhile(c => c == ' ');
return new SoftBreak();
}
return null;
}
}
}
|
Make driver name and version static properties constants and use dictionary structure for connections to simplify their retrieval. | using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static List<Connection> _connections = new List<Connection>();
public static string DriverName
{
get { return "ArangoDB-NET"; }
}
public static string DriverVersion
{
get { return "0.7.0"; }
}
public static ArangoSettings Settings { get; set; }
static ArangoClient()
{
Settings = new ArangoSettings();
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
var connection = new Connection(hostname, port, isSecured, userName, password, alias);
_connections.Add(connection);
}
internal static Connection GetConnection(string alias)
{
return _connections.Where(connection => connection.Alias == alias).FirstOrDefault();
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Arango.Client.Protocol;
namespace Arango.Client
{
public static class ArangoClient
{
private static Dictionary<string, Connection> _connections = new Dictionary<string, Connection>();
public const string DriverName = "ArangoDB-NET";
public const string DriverVersion = "0.7.0";
public static ArangoSettings Settings { get; set; }
static ArangoClient()
{
Settings = new ArangoSettings();
}
public static void AddDatabase(string hostname, int port, bool isSecured, string userName, string password, string alias)
{
_connections.Add(
alias,
new Connection(hostname, port, isSecured, userName, password, alias)
);
}
internal static Connection GetConnection(string alias)
{
return _connections[alias];
}
}
}
|
Read in post data from the data store | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
namespace BlogTemplate.Pages
{
public class PostModel : PageModel
{
private Blog _blog;
public PostModel(Blog blog)
{
_blog = blog;
}
public Post Post { get; set; }
public void OnGet()
{
string slug = RouteData.Values["slug"].ToString();
Post = _blog.Posts.FirstOrDefault(p => p.Slug == slug);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using BlogTemplate.Models;
namespace BlogTemplate.Pages
{
public class PostModel : PageModel
{
private Blog _blog;
public PostModel(Blog blog)
{
_blog = blog;
}
public Post Post { get; set; }
public void OnGet()
{
string slug = RouteData.Values["slug"].ToString();
Post = _blog.Posts.FirstOrDefault(p => p.Slug == slug);
BlogDataStore dataStore = new BlogDataStore();
Post = dataStore.GetPost(slug);
if(Post == null)
{
RedirectToPage("/Index");
}
}
}
}
|
Add defulat constructor and add day as an attribute | namespace food_tracker {
public class NutritionItem {
public string name { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public NutritionItem(string name, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) {
this.name = name;
this.calories = calories;
this.carbohydrates = carbohydrates;
this.sugars = sugars;
this.fats = fats;
this.saturatedFats = satFat;
this.protein = protein;
this.salt = salt;
this.fibre = fibre;
}
}
}
| using System.ComponentModel.DataAnnotations;
namespace food_tracker {
public class NutritionItem {
[Key]
public int NutritionItemId { get; set; }
public string name { get; set; }
public string dayId { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
public NutritionItem() { }
public NutritionItem(string name, string day, double calories, double carbohydrates, double sugars, double fats, double satFat, double protein, double salt, double fibre) {
this.name = name;
this.dayId = day;
this.calories = calories;
this.carbohydrates = carbohydrates;
this.sugars = sugars;
this.fats = fats;
this.saturatedFats = satFat;
this.protein = protein;
this.salt = salt;
this.fibre = fibre;
}
}
}
|
Add before notify to client interface | using Bugsnag.Payload;
namespace Bugsnag
{
public interface IClient
{
void Notify(System.Exception exception, Request request = null);
void Notify(System.Exception exception, Severity severity, Request request = null);
void Notify(System.Exception exception, HandledState severity, Request request = null);
void Notify(Report report);
IBreadcrumbs Breadcrumbs { get; }
ISessionTracker SessionTracking { get; }
IConfiguration Configuration { get; }
}
}
| using Bugsnag.Payload;
namespace Bugsnag
{
public interface IClient
{
void Notify(System.Exception exception, Request request = null);
void Notify(System.Exception exception, Severity severity, Request request = null);
void Notify(System.Exception exception, HandledState severity, Request request = null);
void Notify(Report report);
IBreadcrumbs Breadcrumbs { get; }
ISessionTracker SessionTracking { get; }
IConfiguration Configuration { get; }
void BeforeNotify(Middleware middleware);
}
}
|
Add support to set thread priority | using System;
using System.Threading;
namespace SPAD.neXt.Interfaces.Base
{
public interface ISPADBackgroundThread
{
string WorkerName { get; }
bool IsRunning { get; }
TimeSpan Interval { get; }
bool ScheduleOnTimeout { get; }
EventWaitHandle SignalHandle { get; }
EventWaitHandle StopHandle { get; }
bool IsPaused { get; }
bool IsActive();
void Signal();
void Start();
void Start(uint waitInterval);
void Start(uint waitInterval, object argument);
void Pause();
void Continue();
bool CanContinue();
void Stop();
void Abort();
void SetImmuneToPreStop(bool v);
void SetArgument(object argument);
void SetContinousMode(bool mode);
void SetIntervall(TimeSpan newInterval);
void SetScheduleOnTimeout(bool mode);
}
public interface ISPADBackgroundWorker
{
void BackgroundProcessingStart(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingContinue(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingStop(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingDoWork(ISPADBackgroundThread workerThread, object argument);
}
}
| using System;
using System.Threading;
namespace SPAD.neXt.Interfaces.Base
{
public interface ISPADBackgroundThread
{
string WorkerName { get; }
bool IsRunning { get; }
TimeSpan Interval { get; }
bool ScheduleOnTimeout { get; }
EventWaitHandle SignalHandle { get; }
EventWaitHandle StopHandle { get; }
bool IsPaused { get; }
bool IsActive();
void Signal();
void Start();
void Start(uint waitInterval);
void Start(uint waitInterval, object argument);
void Pause();
void Continue();
bool CanContinue();
void Stop();
void Abort();
void SetImmuneToPreStop(bool v);
void SetArgument(object argument);
void SetContinousMode(bool mode);
void SetIntervall(TimeSpan newInterval);
void SetScheduleOnTimeout(bool mode);
void SetPriority(ThreadPriority priority);
}
public interface ISPADBackgroundWorker
{
void BackgroundProcessingStart(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingContinue(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingStop(ISPADBackgroundThread workerThread, object argument);
void BackgroundProcessingDoWork(ISPADBackgroundThread workerThread, object argument);
}
}
|
Update max combo test value | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, 151, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.7879104989252959d, 151, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mania.Difficulty;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Mania.Tests
{
public class ManiaDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Mania";
[TestCase(2.3449735700206298d, 242, "diffcalc-test")]
public void Test(double expectedStarRating, int expectedMaxCombo, string name)
=> base.Test(expectedStarRating, expectedMaxCombo, name);
[TestCase(2.7879104989252959d, 242, "diffcalc-test")]
public void TestClockRateAdjusted(double expectedStarRating, int expectedMaxCombo, string name)
=> Test(expectedStarRating, expectedMaxCombo, name, new ManiaModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => new ManiaDifficultyCalculator(new ManiaRuleset().RulesetInfo, beatmap);
protected override Ruleset CreateRuleset() => new ManiaRuleset();
}
}
|
Update build properties with correct data | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DataStats")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("DataStats")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26b9df58-5fa9-42e5-95b0-444a259a3e68")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("DataStats")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("J.D. Sandifer")]
[assembly: AssemblyProduct("DataStats")]
[assembly: AssemblyCopyright("© 2016 J.D. Sandifer")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26b9df58-5fa9-42e5-95b0-444a259a3e68")]
// 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.*")]
[assembly: AssemblyFileVersion("1.0.*")]
|
Remove duplicate line (copy paste bug). | using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetResponse : IResponse
{
private readonly HttpRequestBase _request;
private readonly HttpResponseBase _response;
public AspNetResponse(HttpRequestBase request, HttpResponseBase response)
{
_request = request;
_response = response;
}
public bool Buffer
{
get
{
return _response.Buffer;
}
set
{
_response.Buffer = value;
_response.Buffer = value;
_response.BufferOutput = value;
if (!value)
{
// This forces the IIS compression module to leave this response alone.
// If we don't do this, it will buffer the response to suit its own compression
// logic, resulting in partial messages being sent to the client.
_request.Headers.Remove("Accept-Encoding");
_response.CacheControl = "no-cache";
_response.AddHeader("Connection", "keep-alive");
}
}
}
public bool IsClientConnected
{
get
{
return _response.IsClientConnected;
}
}
public string ContentType
{
get
{
return _response.ContentType;
}
set
{
_response.ContentType = value;
}
}
public Task WriteAsync(string data)
{
_response.Write(data);
return TaskAsyncHelper.Empty;
}
}
}
| using System.Threading.Tasks;
using System.Web;
using SignalR.Abstractions;
namespace SignalR.AspNet
{
public class AspNetResponse : IResponse
{
private readonly HttpRequestBase _request;
private readonly HttpResponseBase _response;
public AspNetResponse(HttpRequestBase request, HttpResponseBase response)
{
_request = request;
_response = response;
}
public bool Buffer
{
get
{
return _response.Buffer;
}
set
{
_response.Buffer = value;
_response.BufferOutput = value;
if (!value)
{
// This forces the IIS compression module to leave this response alone.
// If we don't do this, it will buffer the response to suit its own compression
// logic, resulting in partial messages being sent to the client.
_request.Headers.Remove("Accept-Encoding");
_response.CacheControl = "no-cache";
_response.AddHeader("Connection", "keep-alive");
}
}
}
public bool IsClientConnected
{
get
{
return _response.IsClientConnected;
}
}
public string ContentType
{
get
{
return _response.ContentType;
}
set
{
_response.ContentType = value;
}
}
public Task WriteAsync(string data)
{
_response.Write(data);
return TaskAsyncHelper.Empty;
}
}
}
|
Add additional methods to interface | using System.Collections.Generic;
namespace DevelopmentInProgress.DipState
{
public interface IDipState
{
int Id { get; }
string Name { get; }
bool IsDirty { get; }
bool InitialiseWithParent { get; }
DipStateType Type { get; }
DipStateStatus Status { get; }
IDipState Parent { get; }
IDipState Antecedent { get; }
IDipState Transition { get; set; }
List<IDipState> Transitions { get; }
List<IDipState> Dependencies { get; }
List<IDipState> SubStates { get; }
List<StateAction> Actions { get; }
List<LogEntry> Log { get; }
bool CanComplete();
void Reset();
}
} | using System;
using System.Collections.Generic;
namespace DevelopmentInProgress.DipState
{
public interface IDipState
{
int Id { get; }
string Name { get; }
bool IsDirty { get; }
bool InitialiseWithParent { get; }
DipStateType Type { get; }
DipStateStatus Status { get; }
IDipState Parent { get; }
IDipState Antecedent { get; }
IDipState Transition { get; set; }
List<IDipState> Transitions { get; }
List<IDipState> Dependencies { get; }
List<IDipState> SubStates { get; }
List<StateAction> Actions { get; }
List<LogEntry> Log { get; }
bool CanComplete();
void Reset();
DipState AddTransition(IDipState transition);
DipState AddDependency(IDipState dependency);
DipState AddSubState(IDipState subState);
DipState AddAction(DipStateActionType actionType, Action<IDipState> action);
}
} |
Make sure file is open before getting on with it. | using System.IO;
namespace LINQToTreeHelpers.FutureUtils
{
/// <summary>
/// Future TFile - really just a normal TFile, but gets written out in the future...
/// </summary>
public class FutureTFile : FutureTDirectory
{
private static ROOTNET.Interface.NTFile CreateOpenFile(string name)
{
var f = ROOTNET.NTFile.Open(name, "RECREATE");
return f;
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(FileInfo outputRootFile)
: base(CreateOpenFile(outputRootFile.FullName))
{
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(string outputRootFile)
: base(CreateOpenFile(outputRootFile))
{
}
/// <summary>
/// Close this file. Resolves all futures, writes the directories, and closes the file
/// </summary>
public void Close()
{
//
// Write out this guy and close it!
//
Write();
Directory.Close();
}
}
}
| using System;
using System.IO;
namespace LINQToTreeHelpers.FutureUtils
{
/// <summary>
/// Future TFile - really just a normal TFile, but gets written out in the future...
/// </summary>
public class FutureTFile : FutureTDirectory
{
private static ROOTNET.Interface.NTFile CreateOpenFile(string name)
{
var f = ROOTNET.NTFile.Open(name, "RECREATE");
if (!f.IsOpen())
{
throw new InvalidOperationException(string.Format("Unable to create file '{0}'. It could be the file is locked by another process (like ROOT!!??)", name));
}
return f;
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(FileInfo outputRootFile)
: base(CreateOpenFile(outputRootFile.FullName))
{
}
/// <summary>
/// Creates a new ROOT file and attaches a future value container to it. This container
/// can be used to store future values that get evaluated at a later time.
/// </summary>
/// <param name="outputRootFile"></param>
public FutureTFile(string outputRootFile)
: base(CreateOpenFile(outputRootFile))
{
}
/// <summary>
/// Close this file. Resolves all futures, writes the directories, and closes the file
/// </summary>
public void Close()
{
//
// Write out this guy and close it!
//
Write();
Directory.Close();
}
}
}
|
Make the api changes public! | using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using ServiceFabric.Utilities;
namespace SceneSkope.ServiceFabric.EventHubs
{
public static class EventHubConfiguration
{
public static async Task<EventHubClient> GetEventHubClientAsync(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var inputConnectionString = await GetEventHubConnectionString(sectionName, onFailure, ct).ConfigureAwait(false);
return EventHubClient.CreateFromConnectionString(inputConnectionString);
}
private static async Task<string> GetEventHubConnectionString(string sectionName, Action<string> onFailure, CancellationToken ct)
{
return (await GetEventHubConnectionStringBuilder(sectionName, onFailure, ct).ConfigureAwait(false)).ToString();
}
private static async Task<EventHubsConnectionStringBuilder> GetEventHubConnectionStringBuilder(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var configuration = new FabricConfigurationProvider(sectionName);
if (!configuration.HasConfiguration)
{
await configuration.RejectConfigurationAsync($"No {sectionName} section", onFailure, ct).ConfigureAwait(false);
}
return new EventHubsConnectionStringBuilder(
new Uri(await configuration.TryReadConfigurationAsync("EndpointAddress", onFailure, ct).ConfigureAwait(false)),
await configuration.TryReadConfigurationAsync("EntityPath", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKeyName", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKey", onFailure, ct).ConfigureAwait(false)
);
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs;
using ServiceFabric.Utilities;
namespace SceneSkope.ServiceFabric.EventHubs
{
public static class EventHubConfiguration
{
public static async Task<EventHubClient> GetEventHubClientAsync(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var inputConnectionString = await GetEventHubConnectionString(sectionName, onFailure, ct).ConfigureAwait(false);
return EventHubClient.CreateFromConnectionString(inputConnectionString);
}
public static async Task<string> GetEventHubConnectionString(string sectionName, Action<string> onFailure, CancellationToken ct)
{
return (await GetEventHubConnectionStringBuilder(sectionName, onFailure, ct).ConfigureAwait(false)).ToString();
}
public static async Task<EventHubsConnectionStringBuilder> GetEventHubConnectionStringBuilder(string sectionName, Action<string> onFailure, CancellationToken ct)
{
var configuration = new FabricConfigurationProvider(sectionName);
if (!configuration.HasConfiguration)
{
await configuration.RejectConfigurationAsync($"No {sectionName} section", onFailure, ct).ConfigureAwait(false);
}
return new EventHubsConnectionStringBuilder(
new Uri(await configuration.TryReadConfigurationAsync("EndpointAddress", onFailure, ct).ConfigureAwait(false)),
await configuration.TryReadConfigurationAsync("EntityPath", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKeyName", onFailure, ct).ConfigureAwait(false),
await configuration.TryReadConfigurationAsync("SharedAccessKey", onFailure, ct).ConfigureAwait(false)
);
}
}
}
|
Fix CI complaining about no `ConfigureAwait()` | // 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.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.IO
{
public class DllResourceStoreTest
{
[Test]
public async Task TestSuccessfulAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3");
Assert.That(stream, Is.Not.Null);
}
[Test]
public async Task TestFailedAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5");
Assert.That(stream, Is.Null);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using NUnit.Framework;
using osu.Framework.IO.Stores;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.IO
{
public class DllResourceStoreTest
{
[Test]
public async Task TestSuccessfulAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp3").ConfigureAwait(false);
Assert.That(stream, Is.Not.Null);
}
[Test]
public async Task TestFailedAsyncLookup()
{
var resourceStore = new DllResourceStore(typeof(FrameworkTestScene).Assembly);
byte[]? stream = await resourceStore.GetAsync("Resources.Tracks.sample-track.mp5").ConfigureAwait(false);
Assert.That(stream, Is.Null);
}
}
}
|
Clean up Web Api Config Commit | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace NeedDotNet.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
namespace NeedDotNet.Web
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
Fix functions not being called | using UnityEngine;
using System.Collections;
using System;
namespace Lockstep
{
public class Buff
{
protected int Duration;
protected int Timer;
protected LSAgent Target;
internal int ID {get; set;}
public bool Active {get; private set;}
public void Initialize (int duration, LSAgent target) {
Duration = duration;
Timer = 0;
Target = target;
Target.AddBuff(this);
Active = true;
}
protected virtual void OnInitialize () {
}
public void Simulate () {
Timer++;
OnSimulate ();
if (Timer > Duration) {
Deactivate ();
}
}
protected virtual void OnSimulate () {
}
public void Deactivate () {
Target.RemoveBuff(this);
Active = false;
}
protected virtual void OnDeactivate () {
}
}
} | using UnityEngine;
using System.Collections;
using System;
namespace Lockstep
{
public class Buff
{
protected int Duration;
protected int Timer;
protected LSAgent Target;
internal int ID {get; set;}
public bool Active {get; private set;}
public void Initialize (int duration, LSAgent target) {
Duration = duration;
Timer = 0;
Target = target;
Target.AddBuff(this);
Active = true;
this.OnInitialize();
}
protected virtual void OnInitialize () {
}
public void Simulate () {
Timer++;
OnSimulate ();
if (Timer > Duration) {
Deactivate ();
}
}
protected virtual void OnSimulate () {
}
public void Deactivate () {
Target.RemoveBuff(this);
Active = false;
this.OnDeactivate();
}
protected virtual void OnDeactivate () {
}
}
} |
Add ISqlQuery<object> SqlQuery(this DatabaseFacade database, Type type, string sqlQuery, params SqlParameter[] parameters) | using EntityFrameworkCore.RawSQLExtensions.SqlQuery;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace EntityFrameworkCore.RawSQLExtensions.Extensions
{
public static class DatabaseFacadeExtensions
{
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, params SqlParameter[] parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, IEnumerable<SqlParameter> parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters.ToArray());
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, params SqlParameter[] parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters);
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, IEnumerable<SqlParameter> parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters.ToArray());
}
}
}
| using EntityFrameworkCore.RawSQLExtensions.SqlQuery;
using Microsoft.EntityFrameworkCore.Infrastructure;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
namespace EntityFrameworkCore.RawSQLExtensions.Extensions
{
public static class DatabaseFacadeExtensions
{
public static ISqlQuery<object> SqlQuery(this DatabaseFacade database, Type type, string sqlQuery, params SqlParameter[] parameters)
{
var tsrq = typeof(SqlRawQuery<>).MakeGenericType(type);
return (ISqlQuery<object>)Activator.CreateInstance(tsrq, database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, params SqlParameter[] parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters);
}
public static ISqlQuery<T> SqlQuery<T>(this DatabaseFacade database, string sqlQuery, IEnumerable<SqlParameter> parameters)
{
return new SqlRawQuery<T>(database, sqlQuery, parameters.ToArray());
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, params SqlParameter[] parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters);
}
public static ISqlQuery<T> StoredProcedure<T>(this DatabaseFacade database, string storedProcName, IEnumerable<SqlParameter> parameters)
{
return new StoredProcedure<T>(database, storedProcName, parameters.ToArray());
}
}
} |
Add an option to set the number of decimal places that will be used in the formatting | using System;
namespace GUtils.IO
{
public static class FileSizes
{
public const UInt64 B = 1024;
public const UInt64 KiB = 1024 * B;
public const UInt64 MiB = 1024 * KiB;
public const UInt64 GiB = 1024 * MiB;
public const UInt64 TiB = 1024 * GiB;
public const UInt64 PiB = 1024 * TiB;
private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
public static String Format ( UInt64 Size )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
}
}
}
| using System;
namespace GUtils.IO
{
public static class FileSizes
{
public const UInt64 B = 1024;
public const UInt64 KiB = 1024 * B;
public const UInt64 MiB = 1024 * KiB;
public const UInt64 GiB = 1024 * MiB;
public const UInt64 TiB = 1024 * GiB;
public const UInt64 PiB = 1024 * TiB;
private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" };
public static String Format ( UInt64 Size )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}";
}
public static String Format ( UInt64 Size, Int32 decimals )
{
var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) );
return $"{Math.Round ( Size / ( Math.Pow ( B, i ) ), decimals )} {_suffixes[i]}";
}
}
}
|
Remove population of Visual Studio's TestCase.DisplayName property during test discovery. This has no effect and is misleading. TestCase.FullyQualifiedName is set to the method group of a test method, but TestCase.DisplayName should only be set during execution time to the full name of a test case including input parameters. Setting TestCase.DisplayName at discovery time is meaningless. | using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Fixie.Execution;
namespace Fixie.VisualStudio.TestAdapter
{
[DefaultExecutorUri(Executor.Id)]
[FileExtension(".exe")]
[FileExtension(".dll")]
public class Discoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger log, ITestCaseDiscoverySink discoverySink)
{
RemotingUtility.CleanUpRegisteredChannels();
foreach (var source in sources)
{
log.Info("Processing " + source);
try
{
var assemblyFullPath = Path.GetFullPath(source);
using (var environment = new ExecutionEnvironment(assemblyFullPath))
{
var discovery = environment.Create<DiscoveryProxy>();
foreach (var methodGroup in discovery.TestMethodGroups(assemblyFullPath))
{
discoverySink.SendTestCase(new TestCase(methodGroup.FullName, Executor.Uri, source)
{
DisplayName = methodGroup.FullName
});
}
}
}
catch (Exception exception)
{
log.Error(exception);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Logging;
using Fixie.Execution;
namespace Fixie.VisualStudio.TestAdapter
{
[DefaultExecutorUri(Executor.Id)]
[FileExtension(".exe")]
[FileExtension(".dll")]
public class Discoverer : ITestDiscoverer
{
public void DiscoverTests(IEnumerable<string> sources, IDiscoveryContext discoveryContext, IMessageLogger log, ITestCaseDiscoverySink discoverySink)
{
RemotingUtility.CleanUpRegisteredChannels();
foreach (var source in sources)
{
log.Info("Processing " + source);
try
{
var assemblyFullPath = Path.GetFullPath(source);
using (var environment = new ExecutionEnvironment(assemblyFullPath))
{
var discovery = environment.Create<DiscoveryProxy>();
foreach (var methodGroup in discovery.TestMethodGroups(assemblyFullPath))
discoverySink.SendTestCase(new TestCase(methodGroup.FullName, Executor.Uri, source));
}
}
catch (Exception exception)
{
log.Error(exception);
}
}
}
}
}
|
Fix spinners not starting placement with the first click | // 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.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece(HitObject) { Alpha = 0.5f };
}
protected override bool OnClick(ClickEvent e)
{
if (isPlacingEnd)
{
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
HitObject.StartTime = EditorClock.CurrentTime;
isPlacingEnd = true;
piece.FadeTo(1f, 150, Easing.OutQuint);
}
return true;
}
}
}
| // 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.Graphics;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Edit;
using osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners.Components;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.UI;
namespace osu.Game.Rulesets.Osu.Edit.Blueprints.Spinners
{
public class SpinnerPlacementBlueprint : PlacementBlueprint
{
public new Spinner HitObject => (Spinner)base.HitObject;
private readonly SpinnerPiece piece;
private bool isPlacingEnd;
public SpinnerPlacementBlueprint()
: base(new Spinner { Position = OsuPlayfield.BASE_SIZE / 2 })
{
InternalChild = piece = new SpinnerPiece(HitObject) { Alpha = 0.5f };
}
protected override bool OnClick(ClickEvent e)
{
if (isPlacingEnd)
{
HitObject.EndTime = EditorClock.CurrentTime;
EndPlacement();
}
else
{
HitObject.StartTime = EditorClock.CurrentTime;
isPlacingEnd = true;
piece.FadeTo(1f, 150, Easing.OutQuint);
BeginPlacement();
}
return true;
}
}
}
|
Revert accidental change to @async flag. | using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: false);
}
return _wpfConsole;
}
}
}
} | using System;
using System.Diagnostics;
namespace NuGetConsole.Implementation.PowerConsole {
/// <summary>
/// Represents a host with extra info.
/// </summary>
class HostInfo : ObjectWithFactory<PowerConsoleWindow> {
Lazy<IHostProvider, IHostMetadata> HostProvider { get; set; }
public HostInfo(PowerConsoleWindow factory, Lazy<IHostProvider, IHostMetadata> hostProvider)
: base(factory) {
UtilityMethods.ThrowIfArgumentNull(hostProvider);
this.HostProvider = hostProvider;
}
/// <summary>
/// Get the HostName attribute value of this host.
/// </summary>
public string HostName {
get { return HostProvider.Metadata.HostName; }
}
IWpfConsole _wpfConsole;
/// <summary>
/// Get/create the console for this host. If not already created, this
/// actually creates the (console, host) pair.
///
/// Note: Creating the console is handled by this package and mostly will
/// succeed. However, creating the host could be from other packages and
/// fail. In that case, this console is already created and can be used
/// subsequently in limited ways, such as displaying an error message.
/// </summary>
public IWpfConsole WpfConsole {
get {
if (_wpfConsole == null) {
_wpfConsole = Factory.WpfConsoleService.CreateConsole(
Factory.ServiceProvider, PowerConsoleWindow.ContentType, HostName);
_wpfConsole.Host = HostProvider.Value.CreateHost(_wpfConsole, @async: true);
}
return _wpfConsole;
}
}
}
} |
Add a note about `OnlineID` potentially being zero in non-autoincrement cases | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID.
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
namespace osu.Game.Database
{
public interface IHasOnlineID
{
/// <summary>
/// The server-side ID representing this instance, if one exists. Any value 0 or less denotes a missing ID (except in special cases where autoincrement is not used, like rulesets).
/// </summary>
/// <remarks>
/// Generally we use -1 when specifying "missing" in code, but values of 0 are also considered missing as the online source
/// is generally a MySQL autoincrement value, which can never be 0.
/// </remarks>
int OnlineID { get; }
}
}
|
Fix refresh tokens not working correctly | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Globalization;
using Newtonsoft.Json;
using osu.Framework.Extensions;
namespace osu.Game.Online.API
{
[Serializable]
internal class OAuthToken
{
/// <summary>
/// OAuth 2.0 access token.
/// </summary>
[JsonProperty(@"access_token")]
public string AccessToken;
[JsonProperty(@"expires_in")]
public long ExpiresIn
{
get
{
return AccessTokenExpiry - DateTime.Now.ToUnixTimestamp();
}
set
{
AccessTokenExpiry = DateTime.Now.AddSeconds(value).ToUnixTimestamp();
}
}
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && ExpiresIn > 30;
public long AccessTokenExpiry;
/// <summary>
/// OAuth 2.0 refresh token.
/// </summary>
[JsonProperty(@"refresh_token")]
public string RefreshToken;
public override string ToString() => $@"{AccessToken}/{AccessTokenExpiry.ToString(NumberFormatInfo.InvariantInfo)}/{RefreshToken}";
public static OAuthToken Parse(string value)
{
try
{
string[] parts = value.Split('/');
return new OAuthToken
{
AccessToken = parts[0],
AccessTokenExpiry = long.Parse(parts[1], NumberFormatInfo.InvariantInfo),
RefreshToken = parts[2]
};
}
catch
{
}
return null;
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Globalization;
using Newtonsoft.Json;
using osu.Framework.Extensions;
namespace osu.Game.Online.API
{
[Serializable]
internal class OAuthToken
{
/// <summary>
/// OAuth 2.0 access token.
/// </summary>
[JsonProperty(@"access_token")]
public string AccessToken;
[JsonProperty(@"expires_in")]
public long ExpiresIn
{
get
{
return AccessTokenExpiry - DateTime.Now.ToUnixTimestamp();
}
set
{
AccessTokenExpiry = DateTime.Now.AddSeconds(value).ToUnixTimestamp();
}
}
public bool IsValid => !string.IsNullOrEmpty(AccessToken) && ExpiresIn > 30;
public long AccessTokenExpiry;
/// <summary>
/// OAuth 2.0 refresh token.
/// </summary>
[JsonProperty(@"refresh_token")]
public string RefreshToken;
public override string ToString() => $@"{AccessToken}|{AccessTokenExpiry.ToString(NumberFormatInfo.InvariantInfo)}|{RefreshToken}";
public static OAuthToken Parse(string value)
{
try
{
string[] parts = value.Split('|');
return new OAuthToken
{
AccessToken = parts[0],
AccessTokenExpiry = long.Parse(parts[1], NumberFormatInfo.InvariantInfo),
RefreshToken = parts[2]
};
}
catch
{
}
return null;
}
}
}
|
Clean up dependency node class | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NProcessPipe.DependencyAnalysis
{
public class Node<T>
{
public Node(T data)
{
//Index = -1;
Data = data;
}
public T Data { get; private set; }
public bool Equals(Node<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Data, Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Node<T>)) return false;
return Equals((Node<T>)obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public override string ToString()
{
return Data.ToString();
}
//public void SetIndex(int index)
//{
// Index = index;
//}
//public void SetLowLink(int lowlink)
//{
// LowLink = lowlink;
//}
//public int Index { get; private set; }
//public int LowLink { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NProcessPipe.DependencyAnalysis
{
public class Node<T>
{
public Node(T data)
{
Data = data;
}
public T Data { get; private set; }
public bool Equals(Node<T> other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Equals(other.Data, Data);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != typeof(Node<T>)) return false;
return Equals((Node<T>)obj);
}
public override int GetHashCode()
{
return (Data != null ? Data.GetHashCode() : 0);
}
public override string ToString()
{
return Data.ToString();
}
}
}
|
Update userHandle to be consistent in all examples instead of random | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CourseExerciseFiles.cs" company="CodeBlueDev">
// All rights reserved.
// </copyright>
// <summary>
// Represents a PluralSight Course's exercise files information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeBlueDev.PluralSight.Core.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents a PluralSight Course's exercise files information.
/// </summary>
/// <example>
/// {
/// "exerciseFilesUrl": "http://s.pluralsight.com/course-materials/windows-forms-best-practices/866AB96258/20140926213054/windows-forms-best-practices.zip?userHandle=aaf74aa9-49b7-415b-ba2d-bdc49b285671"
/// }
/// </example>
[DataContract]
[Serializable]
public class CourseExerciseFiles
{
/// <summary>
/// Gets or sets the Exercise Files Url for a PluralSight Course.
/// </summary>
[DataMember(Name = "exerciseFilesUrl")]
public string ExerciseFilesUrl { get; set; }
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CourseExerciseFiles.cs" company="CodeBlueDev">
// All rights reserved.
// </copyright>
// <summary>
// Represents a PluralSight Course's exercise files information.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace CodeBlueDev.PluralSight.Core.Models
{
using System;
using System.Runtime.Serialization;
/// <summary>
/// Represents a PluralSight Course's exercise files information.
/// </summary>
/// <example>
/// {
/// "exerciseFilesUrl": "http://s.pluralsight.com/course-materials/windows-forms-best-practices/866AB96258/20140926213054/windows-forms-best-practices.zip?userHandle=03b9fd64-819c-4def-a610-52457b0479ec"
/// }
/// </example>
[DataContract]
[Serializable]
public class CourseExerciseFiles
{
/// <summary>
/// Gets or sets the Exercise Files Url for a PluralSight Course.
/// </summary>
[DataMember(Name = "exerciseFilesUrl")]
public string ExerciseFilesUrl { get; set; }
}
}
|
Add extension method to translate text coordinates | using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
var lines = new List<string>();
using (var stringReader = new StringReader(text))
{
string line;
line = stringReader.ReadLine();
while (line != null)
{
yield return line;
line = stringReader.ReadLine();
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
var lines = new List<string>();
using (var stringReader = new StringReader(text))
{
string line;
line = stringReader.ReadLine();
while (line != null)
{
yield return line;
line = stringReader.ReadLine();
}
}
}
public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta)
{
var newStartLineNumber = extent.StartLineNumber + lineDelta;
if (newStartLineNumber < 1)
{
throw new ArgumentException(
"Invalid line delta. Resulting start line number must be greather than 1.");
}
var newStartColumnNumber = extent.StartColumnNumber + columnDelta;
var newEndColumnNumber = extent.EndColumnNumber + columnDelta;
if (newStartColumnNumber < 1 || newEndColumnNumber < 1)
{
throw new ArgumentException(@"Invalid column delta.
Resulting start column and end column number must be greather than 1.");
}
return new ScriptExtent(
new ScriptPosition(
extent.File,
newStartLineNumber,
newStartColumnNumber,
extent.StartScriptPosition.Line),
new ScriptPosition(
extent.File,
extent.EndLineNumber + lineDelta,
newEndColumnNumber,
extent.EndScriptPosition.Line));
}
}
}
|
Decrease number of socket instances in SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Sockets.Tests;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Performance.Tests
{
[Trait("Perf", "true")]
public class SocketPerformanceAsyncTests
{
private readonly ITestOutputHelper _log;
private readonly int _iterations = 1;
public SocketPerformanceAsyncTests(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
string env = Environment.GetEnvironmentVariable("SOCKETSTRESS_ITERATIONS");
if (env != null)
{
_iterations = int.Parse(env);
}
}
[ActiveIssue(13349, TestPlatforms.OSX)]
[OuterLoop]
[Fact]
public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync()
{
SocketImplementationType serverType = SocketImplementationType.Async;
SocketImplementationType clientType = SocketImplementationType.Async;
int iterations = 200 * _iterations;
int bufferSize = 256;
int socket_instances = 200;
var test = new SocketPerformanceTests(_log);
// Run in Stress mode no expected time to complete.
test.ClientServerTest(
serverType,
clientType,
iterations,
bufferSize,
socket_instances);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Net.Sockets.Tests;
using System.Net.Test.Common;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Performance.Tests
{
[Trait("Perf", "true")]
public class SocketPerformanceAsyncTests
{
private readonly ITestOutputHelper _log;
private readonly int _iterations = 1;
public SocketPerformanceAsyncTests(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
string env = Environment.GetEnvironmentVariable("SOCKETSTRESS_ITERATIONS");
if (env != null)
{
_iterations = int.Parse(env);
}
}
[ActiveIssue(13349, TestPlatforms.OSX)]
[OuterLoop]
[Fact]
public void SocketPerformance_MultipleSocketClientAsync_LocalHostServerAsync()
{
SocketImplementationType serverType = SocketImplementationType.Async;
SocketImplementationType clientType = SocketImplementationType.Async;
int iterations = 200 * _iterations;
int bufferSize = 256;
int socket_instances = 20;
var test = new SocketPerformanceTests(_log);
// Run in Stress mode no expected time to complete.
test.ClientServerTest(
serverType,
clientType,
iterations,
bufferSize,
socket_instances);
}
}
}
|
Clear CellsCollection on WorksheetInternals disposal to make it easier to GC to collect unused references | using System;
namespace ClosedXML.Excel
{
internal class XLWorksheetInternals : IDisposable
{
public XLWorksheetInternals(
XLCellsCollection cellsCollection,
XLColumnsCollection columnsCollection,
XLRowsCollection rowsCollection,
XLRanges mergedRanges
)
{
CellsCollection = cellsCollection;
ColumnsCollection = columnsCollection;
RowsCollection = rowsCollection;
MergedRanges = mergedRanges;
}
public XLCellsCollection CellsCollection { get; private set; }
public XLColumnsCollection ColumnsCollection { get; private set; }
public XLRowsCollection RowsCollection { get; private set; }
public XLRanges MergedRanges { get; internal set; }
public void Dispose()
{
ColumnsCollection.Clear();
RowsCollection.Clear();
MergedRanges.RemoveAll();
}
}
}
| using System;
namespace ClosedXML.Excel
{
internal class XLWorksheetInternals : IDisposable
{
public XLWorksheetInternals(
XLCellsCollection cellsCollection,
XLColumnsCollection columnsCollection,
XLRowsCollection rowsCollection,
XLRanges mergedRanges
)
{
CellsCollection = cellsCollection;
ColumnsCollection = columnsCollection;
RowsCollection = rowsCollection;
MergedRanges = mergedRanges;
}
public XLCellsCollection CellsCollection { get; private set; }
public XLColumnsCollection ColumnsCollection { get; private set; }
public XLRowsCollection RowsCollection { get; private set; }
public XLRanges MergedRanges { get; internal set; }
public void Dispose()
{
CellsCollection.Clear();
ColumnsCollection.Clear();
RowsCollection.Clear();
MergedRanges.RemoveAll();
}
}
}
|
Fix mania hold note heads hiding when frozen | // 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.
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The head of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteHead : DrawableNote
{
protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteHead;
public DrawableHoldNoteHead(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Head)
{
}
public void UpdateResult() => base.UpdateResult(true);
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
// This hitobject should never expire, so this is just a safe maximum.
LifetimeEnd = LifetimeStart + 30000;
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override void OnReleased(ManiaAction action)
{
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Rulesets.Objects.Drawables;
namespace osu.Game.Rulesets.Mania.Objects.Drawables
{
/// <summary>
/// The head of a <see cref="DrawableHoldNote"/>.
/// </summary>
public class DrawableHoldNoteHead : DrawableNote
{
protected override ManiaSkinComponents Component => ManiaSkinComponents.HoldNoteHead;
public DrawableHoldNoteHead(DrawableHoldNote holdNote)
: base(holdNote.HitObject.Head)
{
}
public void UpdateResult() => base.UpdateResult(true);
protected override void UpdateInitialTransforms()
{
base.UpdateInitialTransforms();
// This hitobject should never expire, so this is just a safe maximum.
LifetimeEnd = LifetimeStart + 30000;
}
protected override void UpdateHitStateTransforms(ArmedState state)
{
// suppress the base call explicitly.
// the hold note head should never change its visual state on its own due to the "freezing" mechanic
// (when hit, it remains visible in place at the judgement line; when dropped, it will scroll past the line).
// it will be hidden along with its parenting hold note when required.
}
public override bool OnPressed(ManiaAction action) => false; // Handled by the hold note
public override void OnReleased(ManiaAction action)
{
}
}
}
|
Add API to extract resource from assembly | using System.IO;
using Htc.Vita.Core.Runtime;
namespace Htc.Vita.Core.Util
{
public static partial class Extract
{
public static bool FromFileToIcon(FileInfo fromFile, FileInfo toIcon)
{
if (!Platform.IsWindows)
{
return false;
}
return Windows.FromFileToIconInPlatform(fromFile, toIcon);
}
}
}
| using System;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using Htc.Vita.Core.Log;
using Htc.Vita.Core.Runtime;
namespace Htc.Vita.Core.Util
{
public static partial class Extract
{
public static bool FromFileToIcon(
FileInfo fromFile,
FileInfo toIcon)
{
if (!Platform.IsWindows)
{
return false;
}
return Windows.FromFileToIconInPlatform(fromFile, toIcon);
}
public static bool FromAssemblyToFileByResourceName(
string byResourceName,
FileInfo toFile,
CompressionType compressionType)
{
if (string.IsNullOrWhiteSpace(byResourceName))
{
return false;
}
if (toFile == null)
{
return false;
}
try
{
var binaryDirectory = toFile.Directory;
if (binaryDirectory != null && !binaryDirectory.Exists)
{
binaryDirectory.Create();
}
var assembly = Assembly.GetCallingAssembly();
var doesResourceExist = false;
foreach (var name in assembly.GetManifestResourceNames())
{
if (byResourceName.Equals(name))
{
doesResourceExist = true;
}
}
if (!doesResourceExist)
{
return false;
}
using (var stream = assembly.GetManifestResourceStream(byResourceName))
{
if (stream == null)
{
return false;
}
if (compressionType == CompressionType.Gzip)
{
using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
{
using (var fileStream = toFile.OpenWrite())
{
gZipStream.CopyTo(fileStream);
}
}
}
else
{
using (var fileStream = toFile.OpenWrite())
{
stream.CopyTo(fileStream);
}
}
}
return true;
}
catch (Exception e)
{
Logger.GetInstance(typeof(Extract)).Error("Can not extract resource \"" + byResourceName + "\" to \"" + toFile + "\": " + e.Message);
}
return false;
}
public enum CompressionType
{
None,
Gzip
}
}
}
|
Append numbers to created playlist names if taken | using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamMusic.Interfaces;
using XamMusic.ViewModels;
namespace XamMusic.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CreatePlaylistPopup : PopupPage
{
public CreatePlaylistPopup()
{
InitializeComponent();
}
private async void CreatePlaylist(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(PlaylistNameEntry.Text))
{
DependencyService.Get<IPlaylistManager>().CreatePlaylist("Untitled Playlist");
}
else
{
DependencyService.Get<IPlaylistManager>().CreatePlaylist(PlaylistNameEntry.Text);
}
MenuViewModel.Instance.Refresh();
await Navigation.PopAllPopupAsync(true);
}
}
}
| using Rg.Plugins.Popup.Pages;
using Rg.Plugins.Popup.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamMusic.Interfaces;
using XamMusic.ViewModels;
namespace XamMusic.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class CreatePlaylistPopup : PopupPage
{
public CreatePlaylistPopup()
{
InitializeComponent();
}
private async void CreatePlaylist(object sender, EventArgs e)
{
string title;
if (String.IsNullOrWhiteSpace(PlaylistNameEntry.Text))
{
title = "Untitled Playlist";
}
else
{
title = PlaylistNameEntry.Text;
}
if (MenuViewModel.Instance.PlaylistItems.Where(r => r.Playlist?.Title == title).Count() > 0)
{
int i = 1;
while (MenuViewModel.Instance.PlaylistItems.Where(q => q.Playlist?.Title == $"{title}{i}").Count() > 0)
{
i++;
}
title = $"{title}{i}";
}
DependencyService.Get<IPlaylistManager>().CreatePlaylist(title);
MenuViewModel.Instance.Refresh();
await Navigation.PopAllPopupAsync(true);
}
}
}
|
Disable locally failiny npm command test | //*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NpmTests {
[TestClass]
public class NpmExecuteCommandTests {
// https://nodejstools.codeplex.com/workitem/1575
[TestMethod, Priority(0), Timeout(180000)]
public async Task TestNpmCommandProcessExitSucceeds() {
var npmPath = NpmHelpers.GetPathToNpm();
var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));
for (int j = 0; j < 200; j++) {
await NpmHelpers.ExecuteNpmCommandAsync(
redirector,
npmPath,
null,
new[] {"config", "get", "registry"},
null);
}
}
}
}
| //*********************************************************//
// Copyright (c) Microsoft. All rights reserved.
//
// Apache 2.0 License
//
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
//*********************************************************//
using System.Threading.Tasks;
using Microsoft.NodejsTools.Npm;
using Microsoft.NodejsTools.Npm.SPI;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace NpmTests {
[TestClass]
public class NpmExecuteCommandTests {
// https://nodejstools.codeplex.com/workitem/1575
[Ignore]
[TestMethod, Priority(0), Timeout(180000)]
public async Task TestNpmCommandProcessExitSucceeds() {
var npmPath = NpmHelpers.GetPathToNpm();
var redirector = new NpmCommand.NpmCommandRedirector(new NpmBinCommand(null, false));
for (int j = 0; j < 200; j++) {
await NpmHelpers.ExecuteNpmCommandAsync(
redirector,
npmPath,
null,
new[] {"config", "get", "registry"},
null);
}
}
}
}
|
Fix arg parsing for design time db contexts. | using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global
namespace Content.Server.Database;
public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
public PostgresServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
optionsBuilder.UseNpgsql(args[0]);
return new PostgresServerDbContext(optionsBuilder.Options);
}
}
public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
public SqliteServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
optionsBuilder.UseSqlite(args[0]);
return new SqliteServerDbContext(optionsBuilder.Options);
}
}
| using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
// ReSharper disable UnusedType.Global
namespace Content.Server.Database;
public sealed class DesignTimeContextFactoryPostgres : IDesignTimeDbContextFactory<PostgresServerDbContext>
{
public PostgresServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<PostgresServerDbContext>();
optionsBuilder.UseNpgsql("Server=localhost");
return new PostgresServerDbContext(optionsBuilder.Options);
}
}
public sealed class DesignTimeContextFactorySqlite : IDesignTimeDbContextFactory<SqliteServerDbContext>
{
public SqliteServerDbContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<SqliteServerDbContext>();
optionsBuilder.UseSqlite("Data Source=:memory:");
return new SqliteServerDbContext(optionsBuilder.Options);
}
}
|
Add inherit from Hub and Next | using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;
namespace MusicPickerService.Hubs
{
public class MusicHub
{
private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
private ApplicationDbContext dbContext = new ApplicationDbContext();
private IDatabase Store
{
get
{
return redis.GetDatabase();
}
}
public void Queue(int deviceId, int[] trackIds)
{
string queue = String.Format("musichub.device.{0}.queue", deviceId);
string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
Store.KeyDelete(queue);
Store.KeyDelete(deviceQueue);
foreach (int trackId in trackIds)
{
Store.ListRightPush(queue, trackId);
string trackDeviceId = (from dt in this.dbContext.DeviceTracks
where dt.DeviceId == deviceId && dt.TrackId == trackId
select dt.DeviceTrackId).First();
Store.ListRightPush(deviceQueue, trackDeviceId);
}
}
public void Play(int deviceId)
{
}
public void Pause(int deviceId)
{
}
public void Stop(int deviceId)
{
}
}
} | using System;
using System.Data.Entity;
using System.Linq;
using System.Web;
using MusicPickerService.Models;
using StackExchange.Redis;
using Microsoft.AspNet.SignalR;
namespace MusicPickerService.Hubs
{
public class MusicHub: Hub
{
private static ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("localhost");
private ApplicationDbContext dbContext = new ApplicationDbContext();
private IDatabase Store
{
get
{
return redis.GetDatabase();
}
}
public void Queue(int deviceId, int[] trackIds)
{
string queue = String.Format("musichub.device.{0}.queue", deviceId);
string deviceQueue = String.Format("musichub.device.{0}.queue.device", deviceId);
Store.KeyDelete(queue);
Store.KeyDelete(deviceQueue);
foreach (int trackId in trackIds)
{
Store.ListRightPush(queue, trackId);
string trackDeviceId = (from dt in this.dbContext.DeviceTracks
where dt.DeviceId == deviceId && dt.TrackId == trackId
select dt.DeviceTrackId).First();
Store.ListRightPush(deviceQueue, trackDeviceId);
}
}
public void Play(int deviceId)
{
}
public void Pause(int deviceId)
{
}
public void Next(int deviceId)
{
}
}
} |
Change tweet query to include fictional wizards | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;
namespace WizardWebApi.Controllers
{
public class TweetsController : ApiController
{
//
// GET: api/Tweets
public IHttpActionResult Get()
{
//
var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
{
Method = Method.POST
};
tokenRequest.AddHeader("Authorization",
ConfigurationManager.AppSettings["TwitterAuthKey"]);
tokenRequest.AddParameter("grant_type", "client_credentials");
var tokenResult = new RestClient().Execute(tokenRequest);
var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);
var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek&lang=en&result_type=recent&count=20")
{
Method = Method.GET
};
request.AddHeader("Authorization", "Bearer " + accessToken.token);
var result = new RestClient().Execute(request);
var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
return Ok(tweets.Statuses);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Mime;
using System.Web.Compilation;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharp;
using WizardCentralServer.Model.Dtos;
using WizardWebApi.Models.Objects;
namespace WizardWebApi.Controllers
{
public class TweetsController : ApiController
{
//
// GET: api/Tweets
public IHttpActionResult Get()
{
//
var tokenRequest = new RestRequest("https://api.twitter.com/oauth2/token")
{
Method = Method.POST
};
tokenRequest.AddHeader("Authorization",
ConfigurationManager.AppSettings["TwitterAuthKey"]);
tokenRequest.AddParameter("grant_type", "client_credentials");
var tokenResult = new RestClient().Execute(tokenRequest);
var accessToken = JsonConvert.DeserializeObject<AccessToken>(tokenResult.Content);
var request = new RestRequest(@"https://api.twitter.com/1.1/search/tweets.json?q=%23shrek%20OR%20%23dumbledore%20OR%20%23gandalf%20OR%20%23snape&lang=en&result_type=recent&count=20")
{
Method = Method.GET
};
request.AddHeader("Authorization", "Bearer " + accessToken.token);
var result = new RestClient().Execute(request);
var tweets = JsonConvert.DeserializeObject<TwitterStatusResults>(result.Content);
return Ok(tweets.Statuses);
}
}
}
|
Add AtataContextBuilder_OnDriverCreated and AtataContextBuilder_OnDriverCreated_RestartDriver tests | using System;
using NUnit.Framework;
namespace Atata.Tests
{
[TestFixture]
public class AtataContextBuilderTests
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
}
}
| using System;
using NUnit.Framework;
namespace Atata.Tests
{
public class AtataContextBuilderTests : UITestFixtureBase
{
[Test]
public void AtataContextBuilder_Build_WithoutDriver()
{
InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() =>
AtataContext.Configure().Build());
Assert.That(exception.Message, Does.Contain("no driver is specified"));
}
[Test]
public void AtataContextBuilder_OnDriverCreated()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(driver =>
{
executionsCount++;
}).
Build();
Assert.That(executionsCount, Is.EqualTo(1));
}
[Test]
public void AtataContextBuilder_OnDriverCreated_RestartDriver()
{
int executionsCount = 0;
AtataContext.Configure().
UseChrome().
OnDriverCreated(() =>
{
executionsCount++;
}).
Build();
AtataContext.Current.RestartDriver();
Assert.That(executionsCount, Is.EqualTo(2));
}
}
}
|
Change EnumerableExtensions to partial class | using System.Collections.Generic;
namespace Treenumerable
{
internal static class EnumerableExtensions
{
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
VirtualTree<T> virtualTree)
{
foreach (T node in source)
{
yield return virtualTree.ShallowCopy(node);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker,
IEqualityComparer<T> comparer)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root, comparer);
}
}
}
}
| using System.Collections.Generic;
namespace Treenumerable
{
internal static partial class EnumerableExtensions
{
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
VirtualTree<T> virtualTree)
{
foreach (T node in source)
{
yield return virtualTree.ShallowCopy(node);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root);
}
}
internal static IEnumerable<VirtualTree<T>> ToVirtualTrees<T>(
this IEnumerable<T> source,
ITreeWalker<T> walker,
IEqualityComparer<T> comparer)
{
foreach (T root in source)
{
yield return new VirtualTree<T>(walker, root, comparer);
}
}
}
}
|
Fix an inadvertent 204 in activator tests | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
namespace ActivatorWebSite
{
public class RegularController : Controller
{
public void Index()
{
// This verifies that ModelState and Context are activated.
if (ModelState.IsValid)
{
Context.Response.WriteAsync("Hello world").Wait();
}
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
namespace ActivatorWebSite
{
public class RegularController : Controller
{
public async Task<EmptyResult> Index()
{
// This verifies that ModelState and Context are activated.
if (ModelState.IsValid)
{
await Context.Response.WriteAsync("Hello world");
}
return new EmptyResult();
}
}
} |
Add titles to tutorial pages | using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
namespace StackExchange.DataExplorer.Controllers
{
public class TutorialController : StackOverflowController
{
[StackRoute("tutorial")]
public ActionResult Index()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/intro-to-databases")]
public ActionResult DatabasePrimer()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/intro-to-queries")]
public ActionResult Queries()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-basics")]
public ActionResult QueryBasics()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-joins")]
public ActionResult QueryJoins()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-parameters")]
public ActionResult QueryParameters()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/query-computations")]
public ActionResult QueryComputations()
{
SetHeader("Tutorial");
return View();
}
[StackRoute("tutorial/next-steps")]
public ActionResult NextSteps()
{
SetHeader("Tutorial");
return View();
}
}
} | using System.Web.Mvc;
using StackExchange.DataExplorer.Helpers;
namespace StackExchange.DataExplorer.Controllers
{
public class TutorialController : StackOverflowController
{
[StackRoute("tutorial")]
public ActionResult Index()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Tutorial - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/intro-to-databases")]
public ActionResult DatabasePrimer()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Introduction to Databases - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/intro-to-queries")]
public ActionResult Queries()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Introduction to Queries - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-basics")]
public ActionResult QueryBasics()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Basics - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-joins")]
public ActionResult QueryJoins()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Joins - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-parameters")]
public ActionResult QueryParameters()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Parameters - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/query-computations")]
public ActionResult QueryComputations()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Query Computations - Stack Exchange Data Explorer";
return View();
}
[StackRoute("tutorial/next-steps")]
public ActionResult NextSteps()
{
SetHeader("Tutorial");
ViewData["PageTitle"] = "Next Steps - Stack Exchange Data Explorer";
return View();
}
}
}
|
Add documentation and convenience func to interface | using System;
using System.Threading;
using System.Threading.Tasks;
namespace KafkaNet
{
public interface IKafkaTcpSocket : IDisposable
{
Uri ClientUri { get; }
Task<byte[]> ReadAsync(int readSize);
Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);
Task WriteAsync(byte[] buffer, int offset, int count);
Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace KafkaNet
{
public interface IKafkaTcpSocket : IDisposable
{
/// <summary>
/// The Uri to the connected server.
/// </summary>
Uri ClientUri { get; }
/// <summary>
/// Read a certain byte array size return only when all bytes received.
/// </summary>
/// <param name="readSize">The size in bytes to receive from server.</param>
/// <returns>Returns a byte[] array with the size of readSize.</returns>
Task<byte[]> ReadAsync(int readSize);
/// <summary>
/// Read a certain byte array size return only when all bytes received.
/// </summary>
/// <param name="readSize">The size in bytes to receive from server.</param>
/// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
/// <returns>Returns a byte[] array with the size of readSize.</returns>
Task<byte[]> ReadAsync(int readSize, CancellationToken cancellationToken);
/// <summary>
/// Convenience function to write full buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer);
/// <summary>
/// Write the buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <param name="offset">The offset to start the read from the buffer.</param>
/// <param name="count">The length of data to read off the buffer.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer, int offset, int count);
/// <summary>
/// Write the buffer data to the server.
/// </summary>
/// <param name="buffer">The buffer data to send.</param>
/// <param name="offset">The offset to start the read from the buffer.</param>
/// <param name="count">The length of data to read off the buffer.</param>
/// <param name="cancellationToken">A cancellation token which will cancel the request.</param>
/// <returns>Returns Task handle to the write operation.</returns>
Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken);
}
}
|
Add commandline switch to benchmark to avoid need for rebuilds | using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
//BenchmarkRunner.Run<MetricCreationBenchmarks>();
//BenchmarkRunner.Run<SerializationBenchmarks>();
//BenchmarkRunner.Run<LabelBenchmarks>();
//BenchmarkRunner.Run<HttpExporterBenchmarks>();
//BenchmarkRunner.Run<SummaryBenchmarks>();
BenchmarkRunner.Run<MetricPusherBenchmarks>();
}
}
}
| using BenchmarkDotNet.Running;
namespace Benchmark.NetCore
{
internal class Program
{
private static void Main(string[] args)
{
// Give user possibility to choose which benchmark to run.
// Can be overridden from the command line with the --filter option.
new BenchmarkSwitcher(typeof(Program).Assembly).Run(args);
}
}
}
|
Increase the default Cloud Files connection limit | namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
return new CloudFilesProvider(Identity, Endpoint.Region, null, null);
}
}
}
| namespace Rackspace.VisualStudio.CloudExplorer.Files
{
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VSDesigner.ServerExplorer;
using net.openstack.Core.Domain;
using net.openstack.Providers.Rackspace;
public class CloudFilesEndpointNode : EndpointNode
{
public CloudFilesEndpointNode(CloudIdentity identity, ServiceCatalog serviceCatalog, Endpoint endpoint)
: base(identity, serviceCatalog, endpoint)
{
}
protected override async Task<Node[]> CreateChildrenAsync(CancellationToken cancellationToken)
{
Tuple<CloudFilesProvider, Container[]> containers = await ListContainersAsync(cancellationToken);
return Array.ConvertAll(containers.Item2, i => CreateContainerNode(containers.Item1, i, null));
}
private CloudFilesContainerNode CreateContainerNode(CloudFilesProvider provider, Container container, ContainerCDN containerCdn)
{
return new CloudFilesContainerNode(provider, container, containerCdn);
}
private async Task<Tuple<CloudFilesProvider, Container[]>> ListContainersAsync(CancellationToken cancellationToken)
{
CloudFilesProvider provider = CreateProvider();
List<Container> containers = new List<Container>();
containers.AddRange(await Task.Run(() => provider.ListContainers()));
return Tuple.Create(provider, containers.ToArray());
}
private CloudFilesProvider CreateProvider()
{
CloudFilesProvider provider = new CloudFilesProvider(Identity, Endpoint.Region, null, null);
provider.ConnectionLimit = 50;
return provider;
}
}
}
|
Add non-generic polygon type that uses double type by default. | using System;
using System.Collections.Generic;
using System.Text;
namespace Geode.Geometry
{
public class Polygon<T> : IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<T>> coordinates)
{
Coordinates = coordinates;
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Geode.Geometry
{
public class Polygon: IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<double>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<double>> coordinates)
{
Coordinates = coordinates;
}
}
public class Polygon<T> : IGeoType
{
public string Type => "Polygon";
public IEnumerable<IEnumerable<T>> Coordinates { get; set; }
public Polygon(IEnumerable<IEnumerable<T>> coordinates)
{
Coordinates = coordinates;
}
}
}
|
Check for valid URI in publisher information. | using System;
using System.Security.Cryptography.Pkcs;
namespace AuthenticodeLint.Rules
{
public class PublisherInformationPresentRule : IAuthenticodeRule
{
public int RuleId { get; } = 10004;
public string RuleName { get; } = "Publisher Information Rule";
public string ShortDescription { get; } = "Checks that the signature provided publisher information.";
public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
{
var signatures = graph.VisitAll();
var result = RuleResult.Pass;
foreach(var signature in signatures)
{
PublisherInformation info = null;
foreach(var attribute in signature.SignedAttributes)
{
if (attribute.Oid.Value == KnownOids.OpusInfo)
{
info = new PublisherInformation(attribute.Values[0]);
break;
}
}
if (info == null)
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
}
if (string.IsNullOrWhiteSpace(info.Description))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
}
if (string.IsNullOrWhiteSpace(info.UrlLink))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
}
}
return result;
}
}
}
| using System;
using System.Security.Cryptography.Pkcs;
namespace AuthenticodeLint.Rules
{
public class PublisherInformationPresentRule : IAuthenticodeRule
{
public int RuleId { get; } = 10004;
public string RuleName { get; } = "Publisher Information Rule";
public string ShortDescription { get; } = "Checks that the signature provided publisher information.";
public RuleResult Validate(Graph<SignerInfo> graph, SignatureLoggerBase verboseWriter)
{
var signatures = graph.VisitAll();
var result = RuleResult.Pass;
foreach(var signature in signatures)
{
PublisherInformation info = null;
foreach(var attribute in signature.SignedAttributes)
{
if (attribute.Oid.Value == KnownOids.OpusInfo)
{
info = new PublisherInformation(attribute.Values[0]);
break;
}
}
if (info == null)
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have any publisher information.");
}
if (string.IsNullOrWhiteSpace(info.Description))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying description.");
}
if (string.IsNullOrWhiteSpace(info.UrlLink))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature does not have an accompanying URL.");
}
Uri uri;
if (!Uri.TryCreate(info.UrlLink, UriKind.Absolute, out uri))
{
result = RuleResult.Fail;
verboseWriter.LogMessage(signature, "Signature's accompanying URL is not a valid URI.");
}
}
return result;
}
}
}
|
Remove code involving MessageBox that did not belong in this class | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceProvider
{
public static class SettingsManager
{
internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
{
if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
{
messageForUser.Invoke("Please press OK and choose a folder to store your expenditure in", "Setup");
DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
DataStorage.Default.Save();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceProvider
{
public static class SettingsManager
{
internal static void CheckForXmlFileDirectory(Func<string> getXmlFilePath, Action<string, string> messageForUser)
{
if (string.IsNullOrEmpty(DataStorage.Default.xmlFileDirectory))
{
DataStorage.Default.xmlFileDirectory = getXmlFilePath.Invoke();
DataStorage.Default.Save();
}
}
}
}
|
Fix bug where ParseExpression doesn't parse an expression but a query | using System;
namespace NQuery.Language
{
public sealed class SyntaxTree
{
private readonly CompilationUnitSyntax _root;
private readonly TextBuffer _textBuffer;
private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
{
_root = root;
_textBuffer = textBuffer;
}
public static SyntaxTree ParseQuery(string source)
{
var parser = new Parser(source);
var query = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(query, textBuffer);
}
public static SyntaxTree ParseExpression(string source)
{
var parser = new Parser(source);
var expression = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(expression, textBuffer);
}
public CompilationUnitSyntax Root
{
get { return _root; }
}
public TextBuffer TextBuffer
{
get { return _textBuffer; }
}
}
} | using System;
namespace NQuery.Language
{
public sealed class SyntaxTree
{
private readonly CompilationUnitSyntax _root;
private readonly TextBuffer _textBuffer;
private SyntaxTree(CompilationUnitSyntax root, TextBuffer textBuffer)
{
_root = root;
_textBuffer = textBuffer;
}
public static SyntaxTree ParseQuery(string source)
{
var parser = new Parser(source);
var query = parser.ParseRootQuery();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(query, textBuffer);
}
public static SyntaxTree ParseExpression(string source)
{
var parser = new Parser(source);
var expression = parser.ParseRootExpression();
var textBuffer = new TextBuffer(source);
return new SyntaxTree(expression, textBuffer);
}
public CompilationUnitSyntax Root
{
get { return _root; }
}
public TextBuffer TextBuffer
{
get { return _textBuffer; }
}
}
} |
Fix test json file path on unix systems | using System.IO;
using Stranne.VasttrafikNET.Tests.Json;
namespace Stranne.VasttrafikNET.Tests.Helpers
{
public static class JsonHelper
{
public static string GetJson(JsonFile jsonFile)
{
var fileName = $"{jsonFile}.json";
var json = File.ReadAllText($@"Json\{fileName}");
return json;
}
}
}
| using System.IO;
using Stranne.VasttrafikNET.Tests.Json;
namespace Stranne.VasttrafikNET.Tests.Helpers
{
public static class JsonHelper
{
public static string GetJson(JsonFile jsonFile)
{
var fileName = $"{jsonFile}.json";
var json = File.ReadAllText($@"Json/{fileName}");
return json;
}
}
}
|
Fix for searching for basebuilder already defined on all assemblies | using AutoMapper;
namespace Caelan.Frameworks.Common.Classes
{
public static class GenericBuilder
{
public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
where TDestination : class, new()
where TSource : class, new()
{
var builder = new BaseBuilder<TSource, TDestination>();
if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);
return builder;
}
}
}
| using System;
using System.Linq;
using System.Reflection;
using AutoMapper;
namespace Caelan.Frameworks.Common.Classes
{
public static class GenericBuilder
{
public static BaseBuilder<TSource, TDestination> Create<TSource, TDestination>()
where TDestination : class, new()
where TSource : class, new()
{
var builder = new BaseBuilder<TSource, TDestination>();
var customBuilder = Assembly.GetExecutingAssembly().GetReferencedAssemblies().OrderBy(t => t.Name).Select(Assembly.Load).SelectMany(assembly => assembly.GetTypes().Where(t => t.BaseType == builder.GetType())).SingleOrDefault();
if (customBuilder != null) builder = Activator.CreateInstance(customBuilder) as BaseBuilder<TSource, TDestination>;
if (Mapper.FindTypeMapFor<TSource, TDestination>() == null) Mapper.AddProfile(builder);
return builder;
}
}
}
|
Add stream variant of GetFileHeader() | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(string file)
{
using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
fs.Read(Buffer, 0, maxBufferSize);
}
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
}
} | /*
* Programmed by Umut Celenli umut@celenli.com
*/
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace MimeBank
{
/// <summary>
/// This is the main class to check the file mime type
/// Header list is loaded once
/// </summary>
public class MimeChecker
{
private const int maxBufferSize = 256;
private static List<FileHeader> list { get; set; }
private List<FileHeader> List
{
get
{
if (list == null)
{
list = HeaderData.GetList();
}
return list;
}
}
private byte[] Buffer;
public MimeChecker()
{
Buffer = new byte[maxBufferSize];
}
public FileHeader GetFileHeader(Stream stream)
{
stream.Read(Buffer, 0, maxBufferSize);
return this.List.FirstOrDefault(mime => mime.Check(Buffer));
}
public FileHeader GetFileHeader(string file)
{
using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
{
return GetFileHeader(stream);
}
}
}
} |
Redact DB password in logging | using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;
namespace Ensconce.Cli
{
internal static class DatabaseInteraction
{
internal static void DoDeployment()
{
SqlConnectionStringBuilder connStr = null;
if (!string.IsNullOrEmpty(Arguments.ConnectionString))
{
connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
}
else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
{
connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
}
Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, connStr.ConnectionString);
var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
{
WithTransaction = Arguments.WithTransaction,
OutputPath = Arguments.RoundhouseOutputPath
};
database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
}
}
}
| using Ensconce.Database;
using Ensconce.Helpers;
using System.Data.SqlClient;
namespace Ensconce.Cli
{
internal static class DatabaseInteraction
{
internal static void DoDeployment()
{
SqlConnectionStringBuilder connStr = null;
if (!string.IsNullOrEmpty(Arguments.ConnectionString))
{
connStr = new SqlConnectionStringBuilder(Arguments.ConnectionString.Render());
}
else if (!string.IsNullOrEmpty(Arguments.DatabaseName))
{
connStr = Database.Database.GetLocalConnectionStringFromDatabaseName(Arguments.DatabaseName.Render());
}
Logging.Log("Deploying scripts from {0} using connection string {1}", Arguments.DeployFrom, RedactPassword(connStr));
var database = new Database.Database(connStr, Arguments.WarnOnOneTimeScriptChanges)
{
WithTransaction = Arguments.WithTransaction,
OutputPath = Arguments.RoundhouseOutputPath
};
database.Deploy(Arguments.DeployFrom, Arguments.DatabaseRepository.Render(), Arguments.DropDatabase, Arguments.DatabaseCommandTimeout);
}
private static SqlConnectionStringBuilder RedactPassword(SqlConnectionStringBuilder connStr)
{
return string.IsNullOrEmpty(connStr.Password) ?
connStr :
new SqlConnectionStringBuilder(connStr.ConnectionString)
{
Password = new string('*', connStr.Password.Length)
};
}
}
}
|
Disable the master mobile site. | using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
}
}
| using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Routing;
using Microsoft.AspNet.FriendlyUrls;
namespace TechProFantasySoccer
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
/*var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);*/
//Commenting the above code and using the below line gets rid of the master mobile site.
routes.EnableFriendlyUrls();
}
}
}
|
Make sure config exists by checking steam credentials | /*
* Copyright (c) 2013, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Future non-SteamKit stuff should go in this file.
*/
using System;
using System.Threading;
namespace PICSUpdater
{
class Program
{
static void Main(string[] args)
{
new Thread(new ThreadStart(Steam.Run)).Start();
//Steam.GetPICSChanges();
}
}
}
| /*
* Copyright (c) 2013, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*
* Future non-SteamKit stuff should go in this file.
*/
using System;
using System.Configuration;
using System.Threading;
namespace PICSUpdater
{
class Program
{
static void Main(string[] args)
{
if (ConfigurationManager.AppSettings["steam-username"] == null || ConfigurationManager.AppSettings["steam-password"] == null)
{
Console.WriteLine("Is config missing? It should be in " + ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).FilePath);
return;
}
//new Thread(new ThreadStart(Steam.Run)).Start();
Steam.Run();
}
}
}
|
Fix date 2008 -> 2009 | <p>Welcome! Codingteam is an open community of engineers and programmers.</p>
<p>And here're today's conference logs:</p>
<iframe class="logs" src="@ViewData["LogUrl"]"></iframe>
<a href="/old-logs/codingteam@conference.jabber.ru/">Older logs (mostly actual in period 2008-08-22 — 2016-12-09)</a>
| <p>Welcome! Codingteam is an open community of engineers and programmers.</p>
<p>And here're today's conference logs:</p>
<iframe class="logs" src="@ViewData["LogUrl"]"></iframe>
<a href="/old-logs/codingteam@conference.jabber.ru/">Older logs (mostly actual in period 2009-08-22 — 2016-12-09)</a>
|
Enforce single responsibility principle -- decorators can implement additional functionality. | namespace Bakery.Logging
{
using System;
using Time;
public class ConsoleLog
: ILog
{
private readonly IClock clock;
public ConsoleLog(IClock clock)
{
this.clock = clock;
}
public void Write(Level logLevel, String message)
{
const String FORMAT = "{0}: [{1}] {2}";
var textWriter = logLevel >= Level.Warning
? Console.Error
: Console.Out;
textWriter.WriteLine(
String.Format(
FORMAT,
clock.GetUniversalTime().ToString(),
logLevel,
message));
}
}
}
| namespace Bakery.Logging
{
using System;
public class ConsoleLog
: ILog
{
public void Write(Level logLevel, String message)
{
var textWriter = logLevel >= Level.Warning
? Console.Error
: Console.Out;
textWriter.WriteLine(message);
}
}
}
|
Improve test coverage for Parsed<T> by mirroring the test coverage for Error<T>. | namespace Parsley.Tests;
class ParsedTests
{
public void HasAParsedValue()
{
new Parsed<string>("parsed", new(1, 1)).Value.ShouldBe("parsed");
}
public void HasNoErrorMessageByDefault()
{
new Parsed<string>("x", new(1, 1)).ErrorMessages.ShouldBe(ErrorMessageList.Empty);
}
public void CanIndicatePotentialErrors()
{
var potentialErrors = ErrorMessageList.Empty
.With(ErrorMessage.Expected("A"))
.With(ErrorMessage.Expected("B"));
new Parsed<object>("x", new(1, 1), potentialErrors).ErrorMessages.ShouldBe(potentialErrors);
}
public void HasRemainingUnparsedInput()
{
var parsed = new Parsed<string>("parsed", new(12, 34));
parsed.Position.ShouldBe(new (12, 34));
}
public void ReportsNonerrorState()
{
new Parsed<string>("parsed", new(1, 1)).Success.ShouldBeTrue();
}
}
| namespace Parsley.Tests;
class ParsedTests
{
public void CanIndicateSuccessfullyParsedValueAtTheCurrentPosition()
{
var parsed = new Parsed<string>("parsed", new(12, 34));
parsed.Success.ShouldBe(true);
parsed.Value.ShouldBe("parsed");
parsed.ErrorMessages.ShouldBe(ErrorMessageList.Empty);
parsed.Position.ShouldBe(new(12, 34));
}
public void CanIndicatePotentialErrorMessagesAtTheCurrentPosition()
{
var potentialErrors = ErrorMessageList.Empty
.With(ErrorMessage.Expected("A"))
.With(ErrorMessage.Expected("B"));
var parsed = new Parsed<object>("parsed", new(12, 34), potentialErrors);
parsed.Success.ShouldBe(true);
parsed.Value.ShouldBe("parsed");
parsed.ErrorMessages.ShouldBe(potentialErrors);
parsed.Position.ShouldBe(new(12, 34));
}
}
|
Fix accidental type conversion breakage. | using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace clipr.Utils
{
/// <summary>
/// <para>
/// A TypeConverter that allows conversion of any object to System.Object.
/// Does not actually perform a conversion, just passes the value on
/// through.
/// </para>
/// <para>
/// Must be registered before parsing.
/// </para>
/// </summary>
internal class ObjectTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string
? value
: base.ConvertFrom(context, culture, value);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return value is string || base.IsValid(context, value);
}
public static void Register()
{
var attr = new Attribute[]
{
new TypeConverterAttribute(typeof(ObjectTypeConverter))
};
TypeDescriptor.AddAttributes(typeof(object), attr);
}
}
}
| using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
namespace clipr.Utils
{
/// <summary>
/// <para>
/// A TypeConverter that allows conversion of any object to System.Object.
/// Does not actually perform a conversion, just passes the value on
/// through.
/// </para>
/// <para>
/// Must be registered before parsing.
/// </para>
/// </summary>
internal class ObjectTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(String) || base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return value is string
? value
: base.ConvertFrom(context, culture, value);
}
public override bool IsValid(ITypeDescriptorContext context, object value)
{
return value is string || base.IsValid(context, value);
}
public static void Register()
{
var attr = new Attribute[]
{
new TypeConverterAttribute(typeof(ObjectTypeConverter))
};
//TypeDescriptor.AddAttributes(typeof(object), attr); //TODO this breaks most type conversion since we override object...
}
}
}
|
Allow $ as import root | using System;
using SourceSafeTypeLib;
namespace vsslib
{
public static class VssItemExtensions
{
/// <summary>
/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
/// This methor return case to normal -> $/Project1
/// </summary>
/// <param name="item">Item for normalize</param>
/// <returns>Normalized item</returns>
public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
{
IVSSItem current = db.VSSItem["$/"];
foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
{
IVSSItem next = null;
foreach (IVSSItem child in current.Items)
{
var parts = child.Spec.TrimEnd('/').Split('/');
var lastPart = parts[parts.Length - 1];
if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
{
next = child;
break;
}
}
if(next == null)
throw new ApplicationException("Can't normalize: " + item.Spec);
current = next;
}
return current;
}
}
}
| using System;
using SourceSafeTypeLib;
namespace vsslib
{
public static class VssItemExtensions
{
/// <summary>
/// If VSS conatins $/Project1 but requested $/project1, then case will not be fixed and $/project1 will be retuned.
/// This methor return case to normal -> $/Project1
/// </summary>
/// <param name="item">Item for normalize</param>
/// <returns>Normalized item</returns>
public static IVSSItem Normalize(this IVSSItem item, IVSSDatabase db)
{
IVSSItem current = db.VSSItem["$/"];
if (item.Spec.Replace('\\', '/').TrimEnd("/".ToCharArray()) == "$")
return current;
foreach (var pathPart in item.Spec.Replace('\\', '/').TrimStart("$/".ToCharArray()).TrimEnd('/').Split('/'))
{
IVSSItem next = null;
foreach (IVSSItem child in current.Items)
{
var parts = child.Spec.TrimEnd('/').Split('/');
var lastPart = parts[parts.Length - 1];
if(String.Compare(pathPart, lastPart, StringComparison.OrdinalIgnoreCase) == 0)
{
next = child;
break;
}
}
if(next == null)
throw new ApplicationException("Can't normalize: " + item.Spec);
current = next;
}
return current;
}
}
}
|
Use json in WCF REST response. | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}")]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
[WebInvoke(Method = "POST")]
public void PostSample(string postBody)
{
// DO NOTHING
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}", ResponseFormat = WebMessageFormat.Json)]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
[WebInvoke(Method = "POST")]
public void PostSample(string postBody)
{
// DO NOTHING
}
}
}
|
Change default popup title text | #region
using System.Windows;
#endregion
namespace SteamAccountSwitcher
{
internal class Popup
{
public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
{
return MessageBox.Show(text, "SteamAccountSwitcher", btn, img, defaultbtn);
}
}
} | #region
using System.Windows;
#endregion
namespace SteamAccountSwitcher
{
internal class Popup
{
public static MessageBoxResult Show(string text, MessageBoxButton btn = MessageBoxButton.OK,
MessageBoxImage img = MessageBoxImage.Information, MessageBoxResult defaultbtn = MessageBoxResult.OK)
{
return MessageBox.Show(text, "Steam Account Switcher", btn, img, defaultbtn);
}
}
} |
Adjust profile ruleset selector to new design | // 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.Sprites;
using osu.Game.Rulesets;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class ProfileRulesetTabItem : OverlayRulesetTabItem
{
private bool isDefault;
public bool IsDefault
{
get => isDefault;
set
{
if (isDefault == value)
return;
isDefault = value;
icon.FadeTo(isDefault ? 1 : 0, 200, Easing.OutQuint);
}
}
protected override Color4 AccentColour
{
get => base.AccentColour;
set
{
base.AccentColour = value;
icon.FadeColour(value, 120, Easing.OutQuint);
}
}
private readonly SpriteIcon icon;
public ProfileRulesetTabItem(RulesetInfo value)
: base(value)
{
Add(icon = new SpriteIcon
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0,
AlwaysPresent = true,
Icon = FontAwesome.Solid.Star,
Size = new Vector2(12),
});
}
}
}
| // 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.Sprites;
using osu.Game.Rulesets;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Overlays.Profile.Header.Components
{
public class ProfileRulesetTabItem : OverlayRulesetTabItem
{
private bool isDefault;
public bool IsDefault
{
get => isDefault;
set
{
if (isDefault == value)
return;
isDefault = value;
icon.Alpha = isDefault ? 1 : 0;
}
}
protected override Color4 AccentColour
{
get => base.AccentColour;
set
{
base.AccentColour = value;
icon.FadeColour(value, 120, Easing.OutQuint);
}
}
private readonly SpriteIcon icon;
public ProfileRulesetTabItem(RulesetInfo value)
: base(value)
{
Add(icon = new SpriteIcon
{
Origin = Anchor.Centre,
Anchor = Anchor.Centre,
Alpha = 0,
Icon = FontAwesome.Solid.Star,
Size = new Vector2(12),
});
}
}
}
|
Return exit values through wrapper. | using System.Linq;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal class Program
{
private static void Main(string[] args)
{
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
} | using System;
using System.IO;
using System.Reflection;
// ReSharper disable once CheckNamespace
internal static class Program
{
private static int Main(string[] args)
{
// Mono's XBuild uses assembly redirects to make sure it uses .NET 4.5 target binaries.
// We emulate it using our own assembly redirector.
AppDomain.CurrentDomain.AssemblyLoad += (sender, e) =>
{
var assemblyName = e.LoadedAssembly.GetName();
Console.WriteLine("Assembly load: {0}", assemblyName);
};
var mainAsm = Assembly.Load("citizenmp_server_updater");
mainAsm.GetType("Costura.AssemblyLoader")
.GetMethod("Attach")
.Invoke(null, null);
return (int) mainAsm.GetType("CitizenMP.Server.Installer.Program")
.GetMethod("Main", BindingFlags.NonPublic | BindingFlags.Static)
.Invoke(null, new object[] {args});
}
} |
Fix zero size parent container in visual tests | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : TestGame
{
[BackgroundDependencyLoader]
private void load()
{
Child = new SafeAreaSnappingContainer
{
SafeEdges = Edges.Left | Edges.Top | Edges.Right,
Child = new DrawSizePreservingFillContainer
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
},
}
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Graphics.Containers;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests
{
internal class VisualTestGame : TestGame
{
[BackgroundDependencyLoader]
private void load()
{
Child = new SafeAreaSnappingContainer
{
RelativeSizeAxes = Axes.Both,
SafeEdges = Edges.Left | Edges.Top | Edges.Right,
Child = new DrawSizePreservingFillContainer
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
},
}
};
}
public override void SetHost(GameHost host)
{
base.SetHost(host);
host.Window.CursorState |= CursorState.Hidden;
}
}
}
|
Add test case for open generics | using Ninject;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Ninject.Extensions.Conventions;
namespace FunWithNinject.Conventions
{
[TestFixture]
public class ConventionsTests
{
[Test]
public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
// Act
var face1 = kernel.Get<IFace1>();
var face2 = kernel.Get<IFace2>();
// Assemble
Assert.AreSame(face1, face2);
}
}
}
public interface IFace1 { }
public interface IFace2 { }
public class AllFaces : IFace1, IFace2 { }
}
| using Ninject;
using Ninject.Extensions.Conventions;
using NUnit.Framework;
namespace FunWithNinject.Conventions
{
[TestFixture]
public class ConventionsTests
{
[Test]
public void Bind_OneClassWithMultipleInterfaces_BindsOneInstanceToAll()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
// Act
var face1 = kernel.Get<IFace1>();
var face2 = kernel.Get<IFace2>();
// Assemble
Assert.AreSame(face1, face2);
}
}
[Test]
public void Bind_ResolveGenericType_Works()
{
// Assemble
using (var kernel = new StandardKernel())
{
kernel.Bind(k => k.FromThisAssembly()
.SelectAllClasses()
.InNamespaceOf<ConventionsTests>()
.BindAllInterfaces()
.Configure(b => b.InSingletonScope()));
kernel.Bind<int>().ToConstant(27);
kernel.Bind<string>().ToConstant("twenty seven");
// Act
var generic = kernel.Get<IGeneric<int, string>>();
// Assemble
Assert.AreEqual(27, generic.FirstProp);
Assert.AreEqual("twenty seven", generic.SecondProp);
}
}
#region Helper Classes/Interfaces
public interface IFace1 { }
public interface IFace2 { }
public interface IGeneric<T1, T2>
{
T1 FirstProp { get; set; }
T2 SecondProp { get; set; }
}
public class AllFaces : IFace1, IFace2 { }
public class Generic<T1, T2> : IGeneric<T1, T2>
{
public Generic(T1 first, T2 second)
{
FirstProp = first;
SecondProp = second;
}
public T1 FirstProp { get; set; }
public T2 SecondProp { get; set; }
}
#endregion Helper Classes/Interfaces
}
} |
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0. | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.34003
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18051
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyVersion("3.0.0.0")]
[assembly: AssemblyFileVersion("3.0.0.0")]
[assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")]
[assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")]
[assembly: AssemblyDescription("Autofac.Extras.DomainServices 3.0.0")]
|
Fix Razor tests broken by change to full string passing. | using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Cogito.Web.Razor.Tests
{
[TestClass]
public class RazorTemplateBuilderTests
{
TextReader LoadTemplateText(string name)
{
return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
.GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
}
[TestMethod]
public void Test_simple_code_generation()
{
var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("Simple.cshtml"));
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
[TestMethod]
public void Test_simple_helper_code_generation()
{
var t = RazorTemplateBuilder.ToCode(() => LoadTemplateText("SimpleWithHelper.cshtml"));
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
}
}
| using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Cogito.Web.Razor.Tests
{
[TestClass]
public class RazorTemplateBuilderTests
{
TextReader LoadTemplateText(string name)
{
return new StreamReader(typeof(RazorTemplateBuilderTests).Assembly
.GetManifestResourceStream(typeof(RazorTemplateBuilderTests).Namespace + ".Templates." + name));
}
[TestMethod]
public void Test_simple_code_generation()
{
var t = RazorTemplateBuilder.ToCode(LoadTemplateText("Simple.cshtml").ReadToEnd());
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
[TestMethod]
public void Test_simple_helper_code_generation()
{
var t = RazorTemplateBuilder.ToCode(LoadTemplateText("SimpleWithHelper.cshtml").ReadToEnd());
Assert.IsTrue(t.Contains(@"@__CompiledTemplate"));
}
}
}
|
Fix list view template for soldiers | @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "List";
}
<h2>List</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id })
</td>
</tr>
}
</table>
| @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "List";
}
<h2>@ViewBag.Title</h2>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Rank)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstOrDefault().Status)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Rank)
</td>
<td>
@Html.DisplayFor(modelItem => item.Status)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { soldierId = item.Id })
</td>
</tr>
}
</table>
|
Disable CS0660 where Full Solution Analysis produces a different result | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class TypeSymbol
{
/// <summary>
/// Represents the method by which this type implements a given interface type
/// and/or the corresponding diagnostics.
/// </summary>
protected class SymbolAndDiagnostics
{
public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);
public readonly Symbol Symbol;
public readonly ImmutableArray<Diagnostic> Diagnostics;
public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
{
this.Symbol = symbol;
this.Diagnostics = diagnostics;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
#pragma warning disable CS0660 // Warning is reported only for Full Solution Analysis
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal partial class TypeSymbol
{
/// <summary>
/// Represents the method by which this type implements a given interface type
/// and/or the corresponding diagnostics.
/// </summary>
protected class SymbolAndDiagnostics
{
public static readonly SymbolAndDiagnostics Empty = new SymbolAndDiagnostics(null, ImmutableArray<Diagnostic>.Empty);
public readonly Symbol Symbol;
public readonly ImmutableArray<Diagnostic> Diagnostics;
public SymbolAndDiagnostics(Symbol symbol, ImmutableArray<Diagnostic> diagnostics)
{
this.Symbol = symbol;
this.Diagnostics = diagnostics;
}
}
}
}
|
Remove the unused bindattrs parameter from the ShaderStageProcessor delegate. | using System;
namespace ChamberLib.Content
{
public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor, object bindattrs=null);
public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}
| using System;
namespace ChamberLib.Content
{
public delegate IModel ModelProcessor(ModelContent asset, IContentProcessor processor);
public delegate ITexture2D TextureProcessor(TextureContent asset, IContentProcessor processor);
public delegate IShaderStage ShaderStageProcessor(ShaderContent asset, IContentProcessor processor);
public delegate IFont FontProcessor(FontContent asset, IContentProcessor processor);
public delegate ISong SongProcessor(SongContent asset, IContentProcessor processor);
public delegate ISoundEffect SoundEffectProcessor(SoundEffectContent asset, IContentProcessor processor);
}
|
Fix nullref in date text box | // 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.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
namespace osu.Game.Tournament.Components
{
public class DateTextBox : SettingsTextBox
{
public new Bindable<DateTimeOffset> Bindable
{
get => bindable;
set
{
bindable = value.GetBoundCopy();
bindable.BindValueChanged(dto =>
base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
}
}
// hold a reference to the provided bindable so we don't have to in every settings section.
private Bindable<DateTimeOffset> bindable;
public DateTextBox()
{
base.Bindable = new Bindable<string>();
((OsuTextBox)Control).OnCommit = (sender, newText) =>
{
try
{
bindable.Value = DateTimeOffset.Parse(sender.Text);
}
catch
{
// reset textbox content to its last valid state on a parse failure.
bindable.TriggerChange();
}
};
}
}
}
| // 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.Bindables;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
namespace osu.Game.Tournament.Components
{
public class DateTextBox : SettingsTextBox
{
public new Bindable<DateTimeOffset> Bindable
{
get => bindable;
set
{
bindable = value.GetBoundCopy();
bindable.BindValueChanged(dto =>
base.Bindable.Value = dto.NewValue.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"), true);
}
}
// hold a reference to the provided bindable so we don't have to in every settings section.
private Bindable<DateTimeOffset> bindable = new Bindable<DateTimeOffset>();
public DateTextBox()
{
base.Bindable = new Bindable<string>();
((OsuTextBox)Control).OnCommit = (sender, newText) =>
{
try
{
bindable.Value = DateTimeOffset.Parse(sender.Text);
}
catch
{
// reset textbox content to its last valid state on a parse failure.
bindable.TriggerChange();
}
};
}
}
}
|
Extend character set of function names (including ".") (again) | using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), @"[^\w.](?<functionName>[\w.]*)$");
if (match.Success)
{
functionName = match.Groups["functionName"].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
| using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace ExcelDna.IntelliSense
{
static class FormulaParser
{
// Set from IntelliSenseDisplay.Initialize
public static char ListSeparator = ',';
// TODO: What's the Unicode situation?
public static string forbiddenNameCharacters = @"\ /\-:;!@\#\$%\^&\*\(\)\+=,<>\[\]{}|'\""";
public static string functionNameRegex = "[" + forbiddenNameCharacters + "](?<functionName>[^" + forbiddenNameCharacters + "]*)$";
public static string functionNameGroupName = "functionName";
internal static bool TryGetFormulaInfo(string formulaPrefix, out string functionName, out int currentArgIndex)
{
formulaPrefix = Regex.Replace(formulaPrefix, "(\"[^\"]*\")|(\\([^\\(\\)]*\\))| ", string.Empty);
while (Regex.IsMatch(formulaPrefix, "\\([^\\(\\)]*\\)"))
{
formulaPrefix = Regex.Replace(formulaPrefix, "\\([^\\(\\)]*\\)", string.Empty);
}
int lastOpeningParenthesis = formulaPrefix.LastIndexOf("(", formulaPrefix.Length - 1, StringComparison.Ordinal);
if (lastOpeningParenthesis > -1)
{
var match = Regex.Match(formulaPrefix.Substring(0, lastOpeningParenthesis), functionNameRegex);
if (match.Success)
{
functionName = match.Groups[functionNameGroupName].Value;
currentArgIndex = formulaPrefix.Substring(lastOpeningParenthesis, formulaPrefix.Length - lastOpeningParenthesis).Count(c => c == ListSeparator);
return true;
}
}
functionName = null;
currentArgIndex = -1;
return false;
}
}
}
|
Update to Unity 5.2 cleanup. | using UnityEngine;
using System.Collections;
public class ColliderFriction : GameObjectBehavior {
public float frictionValue=0;
// Use this for initialization
void Start () {
collider.material.staticFriction = frictionValue;
collider.material.staticFriction2 = frictionValue;
collider.material.dynamicFriction = frictionValue;
collider.material.dynamicFriction2 = frictionValue;
}
}
| using UnityEngine;
using System.Collections;
public class ColliderFriction : GameObjectBehavior {
public float frictionValue=0;
// Use this for initialization
void Start () {
collider.material.staticFriction = frictionValue;
//collider.material.staticFriction2 = frictionValue;
collider.material.dynamicFriction = frictionValue;
//collider.material.dynamicFriction2 = frictionValue;
}
}
|
Fix version of .NET Framework used to look up XML documentation | using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;
namespace SharpLab.Server.Owin.Platform {
public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
+ @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7";
public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
foreach (var xmlPath in GetCandidatePaths(assembly)) {
if (File.Exists(xmlPath))
return XmlDocumentationProvider.CreateFromFile(xmlPath);
}
return null;
}
private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
var file = assembly.GetAssemblyFileFromCodeBase();
yield return Path.ChangeExtension(file.FullName, ".xml");
yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using AshMind.Extensions;
using System;
using SharpLab.Server.Common.Internal;
namespace SharpLab.Server.Owin.Platform {
public class Net48AssemblyDocumentationResolver : IAssemblyDocumentationResolver {
private static readonly string ReferenceAssemblyRootPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
+ @"\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8";
public DocumentationProvider? GetDocumentation([NotNull] Assembly assembly) {
foreach (var xmlPath in GetCandidatePaths(assembly)) {
if (File.Exists(xmlPath))
return XmlDocumentationProvider.CreateFromFile(xmlPath);
}
return null;
}
private IEnumerable<string> GetCandidatePaths(Assembly assembly) {
var file = assembly.GetAssemblyFileFromCodeBase();
yield return Path.ChangeExtension(file.FullName, ".xml");
yield return Path.Combine(ReferenceAssemblyRootPath, Path.ChangeExtension(file.Name, ".xml"));
}
}
}
|
Fix output for overloaded operators | using System.Collections.Generic;
namespace PublicApiGenerator
{
internal static class CSharpOperatorKeyword
{
static readonly IDictionary<string, string> OperatorNameMap = new Dictionary<string, string>
{
{ "op_Addition", "+" },
{ "op_UnaryPlus", "+" },
{ "op_Subtraction", "-" },
{ "op_UnaryNegation", "-" },
{ "op_Multiply", "*" },
{ "op_Division", "/" },
{ "op_Modulus", "%" },
{ "op_Increment", "++" },
{ "op_Decrement", "--" },
{ "op_OnesComplement", "~" },
{ "op_LogicalNot", "!" },
{ "op_BitwiseAnd", "&" },
{ "op_BitwiseOr", "|" },
{ "op_ExclusiveOr", "^" },
{ "op_LeftShift", "<<" },
{ "op_RightShift", ">>" },
{ "op_Equality", "==" },
{ "op_Inequality", "!=" },
{ "op_GreaterThan", ">" },
{ "op_GreaterThanOrEqual", ">=" },
{ "op_LessThan", "<" },
{ "op_LessThanOrEqual", "<=" }
};
public static string Get(string memberName)
{
return OperatorNameMap.TryGetValue(memberName, out string mappedMemberName) ? mappedMemberName : memberName;
}
}
}
| using System.Collections.Generic;
namespace PublicApiGenerator
{
internal static class CSharpOperatorKeyword
{
static readonly IDictionary<string, string> OperatorNameMap = new Dictionary<string, string>
{
{ "op_False", "false" },
{ "op_True", "true" },
{ "op_Addition", "+" },
{ "op_UnaryPlus", "+" },
{ "op_Subtraction", "-" },
{ "op_UnaryNegation", "-" },
{ "op_Multiply", "*" },
{ "op_Division", "/" },
{ "op_Modulus", "%" },
{ "op_Increment", "++" },
{ "op_Decrement", "--" },
{ "op_OnesComplement", "~" },
{ "op_LogicalNot", "!" },
{ "op_BitwiseAnd", "&" },
{ "op_BitwiseOr", "|" },
{ "op_ExclusiveOr", "^" },
{ "op_LeftShift", "<<" },
{ "op_RightShift", ">>" },
{ "op_Equality", "==" },
{ "op_Inequality", "!=" },
{ "op_GreaterThan", ">" },
{ "op_GreaterThanOrEqual", ">=" },
{ "op_LessThan", "<" },
{ "op_LessThanOrEqual", "<=" }
};
public static string Get(string memberName)
{
return OperatorNameMap.TryGetValue(memberName, out string mappedMemberName) ? "operator " + mappedMemberName : memberName;
}
}
}
|
Make it possible to configure time to pulse | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public bool lowToThrow { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
vector.Add((byte)(lowToThrow ? 1 : 0));
return vector;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IPOCS_Programmer.ObjectTypes
{
public class PointsMotor_Pulse : PointsMotor
{
public override byte motorTypeId { get { return 1; } }
public byte ThrowLeftOutput { get; set; }
public byte ThrowRightOutput { get; set; }
public byte positionPin { get; set; }
public bool reverseStatus { get; set; }
public bool lowToThrow { get; set; }
public byte timeToPulse { get; set; }
public override List<byte> Serialize()
{
var vector = new List<byte>();
vector.Add(motorTypeId);
vector.Add(this.ThrowLeftOutput);
vector.Add(this.ThrowRightOutput);
vector.Add(positionPin);
vector.Add((byte)(reverseStatus ? 1 : 0));
vector.Add((byte)(lowToThrow ? 1 : 0));
vector.Add(this.timeToPulse);
return vector;
}
}
}
|
Tweak the Monokai color theme | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Graphics;
using Repository.EditorServices.SyntaxHighlighting;
namespace Repository.Internal.EditorServices.SyntaxHighlighting
{
internal class MonokaiColorTheme : IColorTheme
{
public Color BackgroundColor => Color.Black;
public Color GetForegroundColor(SyntaxKind kind)
{
// TODO: Based off VSCode's Monokai theme
switch (kind)
{
case SyntaxKind.Annotation: return Color.SkyBlue;
case SyntaxKind.BooleanLiteral: return Color.Purple;
case SyntaxKind.Comment: return Color.Gray;
case SyntaxKind.ConstructorDeclaration: return Color.LightGreen;
case SyntaxKind.Eof: return default(Color);
case SyntaxKind.Identifier: return Color.White;
case SyntaxKind.Keyword: return Color.HotPink;
case SyntaxKind.MethodDeclaration: return Color.LightGreen;
case SyntaxKind.MethodIdentifier: return Color.LightGreen;
case SyntaxKind.NullLiteral: return Color.Purple;
case SyntaxKind.NumericLiteral: return Color.Purple;
case SyntaxKind.ParameterDeclaration: return Color.Orange;
case SyntaxKind.Parenthesis: return Color.White;
case SyntaxKind.StringLiteral: return Color.Beige;
case SyntaxKind.TypeDeclaration: return Color.LightGreen;
case SyntaxKind.TypeIdentifier: return Color.LightGreen;
default: throw new NotSupportedException();
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Graphics;
using Repository.EditorServices.SyntaxHighlighting;
namespace Repository.Internal.EditorServices.SyntaxHighlighting
{
internal class MonokaiColorTheme : IColorTheme
{
public Color BackgroundColor => Color.Black;
public Color GetForegroundColor(SyntaxKind kind)
{
// TODO: Based off VSCode's Monokai theme
switch (kind)
{
case SyntaxKind.Annotation: return Color.SkyBlue;
case SyntaxKind.BooleanLiteral: return Color.MediumPurple;
case SyntaxKind.Comment: return Color.Gray;
case SyntaxKind.ConstructorDeclaration: return Color.LightGreen;
case SyntaxKind.Eof: return default(Color);
case SyntaxKind.Identifier: return Color.White;
case SyntaxKind.Keyword: return Color.HotPink;
case SyntaxKind.MethodDeclaration: return Color.LightGreen;
case SyntaxKind.MethodIdentifier: return Color.LightGreen;
case SyntaxKind.NullLiteral: return Color.MediumPurple;
case SyntaxKind.NumericLiteral: return Color.MediumPurple;
case SyntaxKind.ParameterDeclaration: return Color.Orange;
case SyntaxKind.Parenthesis: return Color.White;
case SyntaxKind.StringLiteral: return Color.SandyBrown;
case SyntaxKind.TypeDeclaration: return Color.LightGreen;
case SyntaxKind.TypeIdentifier: return Color.SkyBlue;
default: throw new NotSupportedException();
}
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.