commit
stringlengths 40
40
| subject
stringlengths 4
1.73k
| repos
stringlengths 5
127k
| old_file
stringlengths 2
751
| new_file
stringlengths 2
751
| new_contents
stringlengths 1
8.98k
| old_contents
stringlengths 0
6.59k
| license
stringclasses 13
values | lang
stringclasses 23
values |
---|---|---|---|---|---|---|---|---|
7e4d41313dbf60faed9e1542232b660ffd5eecb1 | Fix ICollection | owolp/Telerik-Academy,owolp/Telerik-Academy,owolp/Telerik-Academy,owolp/Telerik-Academy | Modul-1/OOP/Exam-Preparation/SoftwareAcademy/Course.cs | Modul-1/OOP/Exam-Preparation/SoftwareAcademy/Course.cs | namespace SoftwareAcademy
{
using System.Collections.Generic;
using System.Text;
public abstract class Course : ICourse
{
private string name;
private ICollection<string> topics;
public Course(string name, ITeacher teacher)
{
this.Name = name;
this.Teacher = teacher;
// this.Topics = new List<string>();
this.topics = new List<string>();
}
public string Name
{
get
{
return this.name;
}
set
{
Validator.CheckIfStringIsNullOrEmpty(
value,
string.Format(
GlobalErrorMessages.StringCannotBeNullOrEmpty,
"Course name"));
this.name = value;
}
}
public ITeacher Teacher { get; set; }
//public IList<string> topics { get; private set; }
public void AddTopic(string topic)
{
Validator.CheckIfStringIsNullOrEmpty(
topic,
string.Format(
GlobalErrorMessages.StringCannotBeNullOrEmpty,
"Topic name"));
this.topics.Add(topic);
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendFormat("{0}: Name={1}", this.GetType().Name, this.Name);
if (this.Teacher != null)
{
result.AppendFormat("; Teacher={0}", this.Teacher.Name);
}
if (this.topics.Count != 0)
{
result.AppendFormat("; Topics=[{0}]", string.Join(", ", this.topics));
}
return result.ToString().Trim();
}
}
}
| namespace SoftwareAcademy
{
using System.Collections.Generic;
using System.Text;
public abstract class Course : ICourse
{
private string name;
public Course(string name, ITeacher teacher)
{
this.Name = name;
this.Teacher = teacher;
this.Topics = new List<string>();
}
public string Name
{
get
{
return this.name;
}
set
{
Validator.CheckIfStringIsNullOrEmpty(
value,
string.Format(
GlobalErrorMessages.StringCannotBeNullOrEmpty,
"Course name"));
this.name = value;
}
}
public ITeacher Teacher { get; set; }
public IList<string> Topics { get; private set; }
public void AddTopic(string topic)
{
Validator.CheckIfStringIsNullOrEmpty(
topic,
string.Format(
GlobalErrorMessages.StringCannotBeNullOrEmpty,
"Topic name"));
this.Topics.Add(topic);
}
public override string ToString()
{
StringBuilder result = new StringBuilder();
result.AppendFormat("{0}: Name={1}", this.GetType().Name, this.Name);
if (this.Teacher != null)
{
result.AppendFormat("; Teacher={0}", this.Teacher.Name);
}
if (this.Topics.Count != 0)
{
result.AppendFormat("; Topics=[{0}]", string.Join(", ", this.Topics));
}
return result.ToString().Trim();
}
}
}
| mit | C# |
035a11082e681629da5c8ffe6e1e74226c023791 | Fix deserialize bug on SerializableDictionary. | soygul/NBug,furesoft/NBug,JuliusSweetland/NBug,Stef569/NBug | NBug/Core/Util/Serialization/SerializableDictionary.cs | NBug/Core/Util/Serialization/SerializableDictionary.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializableDictionary.cs" company="NBusy Project">
// Copyright (c) 2010 - 2011 Teoman Soygul. Licensed under LGPLv3 (http://www.gnu.org/licenses/lgpl.html).
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NBug.Core.Util.Serialization
{
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
[Serializable]
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="SerializableDictionary{TKey,TValue}"/> class.
/// This is the default constructor provided for XML serializer.
/// </summary>
public SerializableDictionary()
{
}
public SerializableDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException();
}
foreach (var pair in dictionary)
{
this.Add(pair.Key, pair.Value);
}
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
/*if (reader.IsEmptyElement)
{
return;
}*/
var xElement = XElement.Load(reader.ReadSubtree());
if (xElement.HasElements)
{
foreach (var element in xElement.Elements())
{
this.Add((TKey)Convert.ChangeType(element.Name.ToString(), typeof(TKey)), (TValue)Convert.ChangeType(element.Value, typeof(TValue)));
}
}
reader.ReadEndElement();
}
public void WriteXml(XmlWriter writer)
{
foreach (var key in this.Keys)
{
writer.WriteStartElement(key.ToString());
writer.WriteValue(this[key]);
writer.WriteEndElement();
}
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializableDictionary.cs" company="NBusy Project">
// Copyright (c) 2010 - 2011 Teoman Soygul. Licensed under LGPLv3 (http://www.gnu.org/licenses/lgpl.html).
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace NBug.Core.Util.Serialization
{
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
[Serializable]
[XmlRoot("dictionary")]
public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
/// <summary>
/// Initializes a new instance of the <see cref="SerializableDictionary{TKey,TValue}"/> class.
/// This is the default constructor provided for XML serializer.
/// </summary>
public SerializableDictionary()
{
}
public SerializableDictionary(IDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException();
}
foreach (var pair in dictionary)
{
this.Add(pair.Key, pair.Value);
}
}
public XmlSchema GetSchema()
{
return null;
}
public void ReadXml(XmlReader reader)
{
/*if (reader.IsEmptyElement)
{
return;
}*/
var xElement = XElement.Load(reader.ReadSubtree());
if (xElement.HasElements)
{
foreach (var element in xElement.Elements())
{
this.Add((TKey)Convert.ChangeType(element.Name.ToString(), typeof(TKey)), (TValue)Convert.ChangeType(element.Value, typeof(TValue)));
}
}
}
public void WriteXml(XmlWriter writer)
{
foreach (var key in this.Keys)
{
writer.WriteStartElement(key.ToString());
writer.WriteValue(this[key]);
writer.WriteEndElement();
}
}
}
}
| mit | C# |
9def9702f184ca1622fc24443991ec372ea484d8 | implement LostItemsCount and SentItemsCount properties. | vostok/core | Vostok.Airlock.Client/ParallelAirlockClient.cs | Vostok.Airlock.Client/ParallelAirlockClient.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Vostok.Commons.Utilities;
using Vostok.Logging;
namespace Vostok.Airlock
{
public class ParallelAirlockClient : IAirlockClient, IDisposable
{
private readonly AirlockClient[] clients;
public ParallelAirlockClient(AirlockConfig config, int parallelism, ILog log = null)
{
clients = new AirlockClient[parallelism];
for (var i = 0; i < parallelism; i++)
{
clients[i] = new AirlockClient(config, log);
}
}
public long LostItemsCount => clients.Sum(client => client.LostItemsCount);
public long SentItemsCount => clients.Sum(client => client.SentItemsCount);
public void Push<T>(string routingKey, T item, DateTimeOffset? timestamp = null)
{
clients[ThreadSafeRandom.Next(clients.Length)].Push(routingKey, item, timestamp);
}
public Task FlushAsync()
{
return Task.WhenAll(clients.Select(client => client.FlushAsync()));
}
public void Dispose()
{
foreach (var client in clients)
{
client.Dispose();
}
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Vostok.Commons.Utilities;
using Vostok.Logging;
namespace Vostok.Airlock
{
public class ParallelAirlockClient : IAirlockClient, IDisposable
{
private readonly AirlockClient[] clients;
public ParallelAirlockClient(AirlockConfig config, int parallelism, ILog log = null)
{
clients = new AirlockClient[parallelism];
for (var i = 0; i < parallelism; i++)
{
clients[i] = new AirlockClient(config, log);
}
}
public void Push<T>(string routingKey, T item, DateTimeOffset? timestamp = null)
{
clients[ThreadSafeRandom.Next(clients.Length)].Push(routingKey, item, timestamp);
}
public Task FlushAsync()
{
return Task.WhenAll(clients.Select(client => client.FlushAsync()));
}
public void Dispose()
{
foreach (var client in clients)
{
client.Dispose();
}
}
}
} | mit | C# |
c268d73f81c0963e2998c4bd81d8d0b2a50f1463 | Make Registrar code thread-safe on our end | mono/xwt,antmicro/xwt | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | Xwt.XamMac/Xwt.Mac/NSApplicationInitializer.cs | //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
using Foundation;
using ObjCRuntime;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
static readonly object lockObject = new object();
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
// Setup a registration handler that does not let Xamarin.Mac register assemblies by default.
Runtime.AssemblyRegistration += Runtime_AssemblyRegistration;
NSApplication.Init ();
// Register a callback when an assembly is loaded so it's registered in the xammac registrar.
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
// Manually register all the currently loaded assemblies.
lock (lockObject)
{
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Runtime.RegisterAssembly(assembly);
}
}
}
}
private static void Runtime_AssemblyRegistration(object sender, AssemblyRegistrationEventArgs args)
{
// If we don't do this, Xamarin.Mac will forcefully load all the assemblies referenced from the app startup assembly.
args.Register = false;
}
private static void CurrentDomain_AssemblyLoad (object sender, AssemblyLoadEventArgs args)
{
lock (lockObject)
{
Runtime.RegisterAssembly(args.LoadedAssembly);
}
}
}
}
| //
// NSApplicationInitializer.cs
//
// Author:
// Lluis Sanchez Gual <[email protected]>
//
// Copyright (c) 2016 Xamarin, Inc (http://www.xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using AppKit;
using Foundation;
using ObjCRuntime;
namespace Xwt.Mac
{
static class NSApplicationInitializer
{
public static void Initialize ()
{
var ds = System.Threading.Thread.GetNamedDataSlot ("NSApplication.Initialized");
if (System.Threading.Thread.GetData (ds) == null) {
System.Threading.Thread.SetData (ds, true);
NSApplication.IgnoreMissingAssembliesDuringRegistration = true;
// Setup a registration handler that does not let Xamarin.Mac register assemblies by default.
Runtime.AssemblyRegistration += Runtime_AssemblyRegistration;
NSApplication.Init ();
// Register a callback when an assembly is loaded so it's registered in the xammac registrar.
AppDomain.CurrentDomain.AssemblyLoad += CurrentDomain_AssemblyLoad;
// Manually register all the currently loaded assemblies.
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
Runtime.RegisterAssembly(assembly);
}
}
}
private static void Runtime_AssemblyRegistration(object sender, AssemblyRegistrationEventArgs args)
{
// If we don't do this, Xamarin.Mac will forcefully load all the assemblies referenced from the app startup assembly.
args.Register = false;
}
private static void CurrentDomain_AssemblyLoad (object sender, AssemblyLoadEventArgs args)
{
Runtime.RegisterAssembly(args.LoadedAssembly);
}
}
}
| mit | C# |
12b09a32ea867f349276da34329f63fdcd3217a0 | fix formatting | hal-ler/omnisharp-roslyn,fishg/omnisharp-roslyn,haled/omnisharp-roslyn,khellang/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,hitesh97/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,haled/omnisharp-roslyn,sreal/omnisharp-roslyn,sriramgd/omnisharp-roslyn,hal-ler/omnisharp-roslyn,nabychan/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,sriramgd/omnisharp-roslyn,jtbm37/omnisharp-roslyn,khellang/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,hitesh97/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,fishg/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,hach-que/omnisharp-roslyn,nabychan/omnisharp-roslyn,jtbm37/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,hach-que/omnisharp-roslyn,sreal/omnisharp-roslyn | src/OmniSharp/Api/Diagnostics/OmnisharpController.Diagnostics.cs | src/OmniSharp/Api/Diagnostics/OmnisharpController.Diagnostics.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("codecheck")]
public async Task<IActionResult> CodeCheck(Request request)
{
var quickFixes = new List<QuickFix>();
var documents = _workspace.GetDocuments(request.FileName);
foreach (var document in documents)
{
var semanticModel = await document.GetSemanticModelAsync();
foreach (var quickFix in semanticModel.GetDiagnostics().Select(MakeQuickFix))
{
var existingQuickFix = quickFixes.FirstOrDefault(q => q.Equals(quickFix));
if (existingQuickFix == null)
{
quickFix.Projects.Add(document.Project.Name);
quickFixes.Add(quickFix);
}
else
{
existingQuickFix.Projects.Add(document.Project.Name);
}
}
}
return new ObjectResult(new { QuickFixes = quickFixes });
}
private static QuickFix MakeQuickFix(Diagnostic diagnostic)
{
var span = diagnostic.Location.GetMappedLineSpan();
return new DiagnosticLocation
{
FileName = span.Path,
Line = span.StartLinePosition.Line + 1,
Column = span.StartLinePosition.Character + 1,
EndLine = span.EndLinePosition.Line + 1,
EndColumn = span.EndLinePosition.Character + 1,
Text = diagnostic.GetMessage(),
LogLevel = diagnostic.Severity.ToString()
};
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using Microsoft.CodeAnalysis;
using OmniSharp.Models;
namespace OmniSharp
{
public partial class OmnisharpController
{
[HttpPost("codecheck")]
public async Task<IActionResult> CodeCheck(Request request)
{
var quickFixes = new List<QuickFix>();
var documents = _workspace.GetDocuments(request.FileName);
foreach (var document in documents)
{
var semanticModel = await document.GetSemanticModelAsync();
foreach (var quickFix in semanticModel.GetDiagnostics().Select(MakeQuickFix))
{
var existingQuickFix = quickFixes.FirstOrDefault(q => q.Equals(quickFix));
if (existingQuickFix == null)
{
quickFix.Projects.Add(document.Project.Name);
quickFixes.Add(quickFix);
}
else
{
existingQuickFix.Projects.Add(document.Project.Name);
}
}
}
return new ObjectResult(new { QuickFixes = quickFixes });
}
private static QuickFix MakeQuickFix(Diagnostic diagnostic)
{
var span = diagnostic.Location.GetMappedLineSpan();
return new DiagnosticLocation {
FileName = span.Path,
Line = span.StartLinePosition.Line + 1,
Column = span.StartLinePosition.Character + 1,
EndLine = span.EndLinePosition.Line + 1,
EndColumn = span.EndLinePosition.Character + 1,
Text = diagnostic.GetMessage(),
LogLevel = diagnostic.Severity.ToString()
};
}
}
} | mit | C# |
5a90e5e240b6d6464b0ab8c0e560bbe359c84774 | add the icon | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Web/Views/Shared/Components/TagsCloud/Default.cshtml | src/Tugberk.Web/Views/Shared/Components/TagsCloud/Default.cshtml | @model IEnumerable<Tugberk.Web.Controllers.TagViewModel>
<ul class="none-style-list inline-list labeled-list">
@foreach (var tag in Model)
{
<li>
<span class="badge badge-light">
<i class="fa fa-tag"></i> @tag.Name
</span>
</li>
}
</ul> | @model IEnumerable<Tugberk.Web.Controllers.TagViewModel>
<ul class="none-style-list inline-list labeled-list">
@foreach (var tag in Model)
{
<li>
<span class="badge badge-light">@tag.Name</span>
</li>
}
</ul> | agpl-3.0 | C# |
cda96d4d496180735b82c062a3f69006d2eff055 | Apply CR | akromm/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,akromm/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools | WindowsAzurePowershell/src/Management.Utilities/Common/WindowsAzureEnvironment.cs | WindowsAzurePowershell/src/Management.Utilities/Common/WindowsAzureEnvironment.cs | // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities.Common
{
using System;
using System.Collections.Generic;
[Serializable]
public class WindowsAzureEnvironment
{
/// <summary>
/// The Windows Azure environment name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The management portal endpoint.
/// </summary>
public string PortalEndpoint { get; set; }
public static Dictionary<string, WindowsAzureEnvironment> PublicEnvironments
{
get { return environments; }
private set;
}
private static Dictionary<string, WindowsAzureEnvironment> environments =
new Dictionary<string, WindowsAzureEnvironment>()
{
{
EnvironmentName.Azure,
new WindowsAzureEnvironment()
{
Name = EnvironmentName.Azure,
PortalEndpoint = EnvironmentPortalEndpoint.Azure
}
},
{
EnvironmentName.China,
new WindowsAzureEnvironment()
{
Name = EnvironmentName.China,
PortalEndpoint = EnvironmentPortalEndpoint.China
}
}
};
}
class EnvironmentName
{
public const string Azure = "Azure";
public const string China = "China";
}
class EnvironmentPortalEndpoint
{
public const string Azure = "https://manage.windowsazure.com/publishsettings/index/";
public const string China = "https://manage.windowsazure.cn/publishsettings/index/";
}
}
| // ----------------------------------------------------------------------------------
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.Utilities.Common
{
using System;
using System.Collections.Generic;
[Serializable]
public class WindowsAzureEnvironment
{
/// <summary>
/// The Windows Azure environment name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// The management portal endpoint.
/// </summary>
public string PortalEndpoint { get; set; }
public static Dictionary<string, WindowsAzureEnvironment> PublicEnvironments =
new Dictionary<string, WindowsAzureEnvironment>()
{
{
EnvironmentName.Azure,
new WindowsAzureEnvironment()
{
Name = EnvironmentName.Azure,
PortalEndpoint = EnvironmentPortalEndpoint.Azure
}
},
{
EnvironmentName.China,
new WindowsAzureEnvironment()
{
Name = EnvironmentName.China,
PortalEndpoint = EnvironmentPortalEndpoint.China
}
}
};
}
class EnvironmentName
{
public const string Azure = "Azure";
public const string China = "China";
}
class EnvironmentPortalEndpoint
{
public const string Azure = "https://manage.windowsazure.com/publishsettings/index/";
public const string China = "https://manage.windowsazure.cn/publishsettings/index/";
}
}
| apache-2.0 | C# |
07ec884632d03e3eaeb802f58c1e4bf61151502b | Implement tower | emazzotta/unity-tower-defense | Assets/Scripts/TowerController.cs | Assets/Scripts/TowerController.cs | using UnityEngine;
using System.Collections;
public class TowerController : MonoBehaviour {
Transform towerTransform;
public float range = 10f;
public GameObject bulletPrefab;
public int cost = 5;
float fireCooldown = 0.5f;
float fireCooldownLeft = 0;
public float damage = 1;
public float radius = 0;
void Start () {
towerTransform = transform.Find("Tower");
}
void Update () {
// TODO: Optimize this!
Metallkefer[] enemies = GameObject.FindObjectsOfType<Metallkefer>();
Metallkefer nearestMetallkefer = null;
float dist = Mathf.Infinity;
foreach(Metallkefer e in enemies) {
float d = Vector3.Distance(this.transform.position, e.transform.position);
if(nearestMetallkefer == null || d < dist) {
nearestMetallkefer = e;
dist = d;
}
}
if(nearestMetallkefer == null) {
Debug.Log("No enemies?");
return;
}
Vector3 dir = nearestMetallkefer.transform.position - this.transform.position;
Quaternion lookRot = Quaternion.LookRotation( dir );
//Debug.Log(lookRot.eulerAngles.y);
towerTransform.rotation = Quaternion.Euler( 0, lookRot.eulerAngles.y, 0 );
fireCooldownLeft -= Time.deltaTime;
if(fireCooldownLeft <= 0 && dir.magnitude <= range) {
fireCooldownLeft = fireCooldown;
ShootAt(nearestMetallkefer);
}
}
void ShootAt(Metallkefer e) {
GameObject bulletGO = (GameObject)Instantiate(bulletPrefab, this.transform.position, this.transform.rotation);
Bullet b = bulletGO.GetComponent<Bullet>();
b.target = e.transform;
b.damage = damage;
b.radius = radius;
}
}
| using UnityEngine;
using System.Collections;
public class TowerController : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
| mit | C# |
577f0e7aeb2888727bc1fe58f987e30df7c5236b | modify implement of RunCommand in test | hakomikan/CommandUtility | CommandInterfaceTest/SpikeTest.cs | CommandInterfaceTest/SpikeTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.IO;
using System.Reflection;
using CommandInterface;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace CommandInterfaceTest
{
[TestClass]
public class SpikeTest : CommandInterfaceTestBase
{
[TestMethod]
public async Task TestMethod1()
{
Assert.AreEqual(await CSharpScript.EvaluateAsync<int>("1 + 2"), 3);
}
[TestMethod]
public void InterfaceTest()
{
RunCommand("create", "new-command");
RunCommand("edit", "new-command");
RunCommand("list", "new-command");
RunCommand("delete", "new-command");
}
public int RunCommand(string commandName, params string[] parameters)
{
return CommandManager.Execute(commandName, parameters);
}
[TestMethod]
public void SubCommandTest()
{
Assert.AreEqual(333, RunCommand("test-script"));
Assert.AreEqual(666, RunCommand("test-script2"));
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.CSharp;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using System.IO;
using System.Reflection;
using CommandInterface;
using static CommandInterfaceTest.CommandRunner;
using Microsoft.CodeAnalysis.Scripting.Hosting;
namespace CommandInterfaceTest
{
public class CommandRunner
{
public static int RunCommand(string commandName, params string[] parameters)
{
return 1;
}
}
[TestClass]
public class SpikeTest : CommandInterfaceTestBase
{
[TestMethod]
public async Task TestMethod1()
{
Assert.AreEqual(await CSharpScript.EvaluateAsync<int>("1 + 2"), 3);
}
[TestMethod]
public void InterfaceTest()
{
RunCommand("create", "new-command");
RunCommand("edit", "new-command");
RunCommand("list", "new-command");
RunCommand("delete", "new-command");
}
[TestMethod]
public void SubCommandTest()
{
Assert.AreEqual(333, RunCommand("TestScript"));
Assert.AreEqual(666, RunCommand("TestScript2"));
}
}
}
| bsd-2-clause | C# |
e868753b96ee44c8b15472f64c89a5b6256bf001 | fix tab issue | dicko2/nunit,jnm2/nunit,akoeplinger/nunit,Therzok/nunit,jeremymeng/nunit,modulexcite/nunit,nunit/nunit,acco32/nunit,jadarnel27/nunit,passaro/nunit,acco32/nunit,NarohLoyahl/nunit,OmicronPersei/nunit,cPetru/nunit-params,danielmarbach/nunit,Green-Bug/nunit,JustinRChou/nunit,michal-franc/nunit,dicko2/nunit,ArsenShnurkov/nunit,nivanov1984/nunit,agray/nunit,Suremaker/nunit,agray/nunit,mjedrzejek/nunit,jnm2/nunit,appel1/nunit,mikkelbu/nunit,elbaloo/nunit,zmaruo/nunit,akoeplinger/nunit,nivanov1984/nunit,jhamm/nunit,ggeurts/nunit,elbaloo/nunit,jadarnel27/nunit,ChrisMaddock/nunit,Green-Bug/nunit,pflugs30/nunit,agray/nunit,JohanO/nunit,NikolayPianikov/nunit,pflugs30/nunit,passaro/nunit,elbaloo/nunit,modulexcite/nunit,jhamm/nunit,jhamm/nunit,jeremymeng/nunit,modulexcite/nunit,michal-franc/nunit,Therzok/nunit,NarohLoyahl/nunit,NarohLoyahl/nunit,zmaruo/nunit,JohanO/nunit,zmaruo/nunit,ArsenShnurkov/nunit,akoeplinger/nunit,acco32/nunit,mikkelbu/nunit,appel1/nunit,jeremymeng/nunit,ArsenShnurkov/nunit,Green-Bug/nunit,Therzok/nunit,NikolayPianikov/nunit,Suremaker/nunit,passaro/nunit,JustinRChou/nunit,pcalin/nunit,cPetru/nunit-params,JohanO/nunit,OmicronPersei/nunit,danielmarbach/nunit,mjedrzejek/nunit,pcalin/nunit,nunit/nunit,michal-franc/nunit,dicko2/nunit,ggeurts/nunit,ChrisMaddock/nunit,danielmarbach/nunit,pcalin/nunit | src/NUnitFramework/testdata/PropertyAttributeTests.cs | src/NUnitFramework/testdata/PropertyAttributeTests.cs | // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework;
namespace NUnit.TestData.PropertyAttributeTests
{
[TestFixture, Property("ClassUnderTest","SomeClass" )]
public class FixtureWithProperties
{
[Test, Property("user","Charlie")]
public void Test1() { }
[Test, Property("X",10.0), Property("Y",17.0)]
public void Test2() { }
[Test, Priority(5)]
public void Test3() { }
[Test, CustomProperty]
public void Test4() { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class PriorityAttribute : PropertyAttribute
{
public PriorityAttribute( int level ) : base( level ) { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CustomPropertyAttribute : PropertyAttribute
{
public CustomPropertyAttribute() :base(new SomeClass())
{
}
}
public class SomeClass
{
}
}
| // ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework;
namespace NUnit.TestData.PropertyAttributeTests
{
[TestFixture, Property("ClassUnderTest","SomeClass" )]
public class FixtureWithProperties
{
[Test, Property("user","Charlie")]
public void Test1() { }
[Test, Property("X",10.0), Property("Y",17.0)]
public void Test2() { }
[Test, Priority(5)]
public void Test3() { }
[Test, CustomProperty]
public void Test4() { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=false)]
public class PriorityAttribute : PropertyAttribute
{
public PriorityAttribute( int level ) : base( level ) { }
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class CustomPropertyAttribute : PropertyAttribute
{
public CustomPropertyAttribute() :base(new SomeClass())
{
}
}
public class SomeClass
{
}
}
| mit | C# |
603f1fb0e50e9a46bd021094d6286d5a124c8ee8 | Replace line and character counting (fails in iOS 12) with a check that the tapped character is within the length of all text. | matteobortolazzo/HtmlLabelPlugin | src/HtmlLabel/iOS/LinkTapHelper.cs | src/HtmlLabel/iOS/LinkTapHelper.cs | using CoreGraphics;
using Foundation;
using LabelHtml.Forms.Plugin.Abstractions;
using System;
using UIKit;
namespace LabelHtml.Forms.Plugin.iOS
{
internal static class LinkTapHelper
{
public static readonly NSString CustomLinkAttribute = new NSString("LabelLink");
public static void HandleLinkTap(this UILabel control, HtmlLabel element)
{
void TapHandler(UITapGestureRecognizer tap)
{
var detectedUrl = DetectTappedUrl(tap, (UILabel)tap.View);
RendererHelper.HandleUriClick(element, detectedUrl);
}
var tapGesture = new UITapGestureRecognizer(TapHandler);
control.AddGestureRecognizer(tapGesture);
control.UserInteractionEnabled = true;
}
private static string DetectTappedUrl(UIGestureRecognizer tap, UILabel control)
{
CGRect bounds = control.Bounds;
NSAttributedString attributedText = control.AttributedText;
// Setup containers
using var textContainer = new NSTextContainer(bounds.Size)
{
LineFragmentPadding = 0,
LineBreakMode = control.LineBreakMode,
MaximumNumberOfLines = (nuint)control.Lines
};
using var layoutManager = new NSLayoutManager();
layoutManager.AddTextContainer(textContainer);
using var textStorage = new NSTextStorage();
textStorage.SetString(attributedText);
using var fontAttributeName = new NSString("NSFont");
var textRange = new NSRange(0, control.AttributedText.Length);
textStorage.AddAttribute(fontAttributeName, control.Font, textRange);
textStorage.AddLayoutManager(layoutManager);
CGRect textBoundingBox = layoutManager.GetUsedRectForTextContainer(textContainer);
// Calculate align offset
static nfloat GetAlignOffset(UITextAlignment textAlignment) => textAlignment switch
{
UITextAlignment.Center => 0.5f,
UITextAlignment.Right => 1f,
_ => 0.0f,
};
nfloat alignmentOffset = GetAlignOffset(control.TextAlignment);
nfloat xOffset = (bounds.Size.Width - textBoundingBox.Size.Width) * alignmentOffset - textBoundingBox.Location.X;
nfloat yOffset = (bounds.Size.Height - textBoundingBox.Size.Height) * alignmentOffset - textBoundingBox.Location.Y;
// Find tapped character
CGPoint locationOfTouchInLabel = tap.LocationInView(control);
var locationOfTouchInTextContainer = new CGPoint(locationOfTouchInLabel.X - xOffset, locationOfTouchInLabel.Y - yOffset);
var characterIndex = (nint)layoutManager.GetCharacterIndex(locationOfTouchInTextContainer, textContainer);
if (characterIndex >= attributedText.Length)
{
return null;
}
// Try to get the URL
NSObject linkAttributeValue = attributedText.GetAttribute(CustomLinkAttribute, characterIndex, out NSRange range);
return linkAttributeValue is NSUrl url ? url.AbsoluteString : null;
}
}
}
| using CoreGraphics;
using Foundation;
using LabelHtml.Forms.Plugin.Abstractions;
using System;
using UIKit;
namespace LabelHtml.Forms.Plugin.iOS
{
internal static class LinkTapHelper
{
public static readonly NSString CustomLinkAttribute = new NSString("LabelLink");
public static void HandleLinkTap(this UILabel control, HtmlLabel element)
{
void TapHandler(UITapGestureRecognizer tap)
{
var detectedUrl = DetectTappedUrl(tap, (UILabel)tap.View);
RendererHelper.HandleUriClick(element, detectedUrl);
}
var tapGesture = new UITapGestureRecognizer(TapHandler);
control.AddGestureRecognizer(tapGesture);
control.UserInteractionEnabled = true;
}
private static string DetectTappedUrl(UIGestureRecognizer tap, UILabel control)
{
CGRect bounds = control.Bounds;
NSAttributedString attributedText = control.AttributedText;
// Setup containers
using var textContainer = new NSTextContainer(bounds.Size)
{
LineFragmentPadding = 0,
LineBreakMode = control.LineBreakMode,
MaximumNumberOfLines = (nuint)control.Lines
};
using var layoutManager = new NSLayoutManager();
layoutManager.AddTextContainer(textContainer);
using var textStorage = new NSTextStorage();
textStorage.SetString(attributedText);
using var fontAttributeName = new NSString("NSFont");
var textRange = new NSRange(0, control.AttributedText.Length);
textStorage.AddAttribute(fontAttributeName, control.Font, textRange);
textStorage.AddLayoutManager(layoutManager);
CGRect textBoundingBox = layoutManager.GetUsedRectForTextContainer(textContainer);
// Calculate align offset
static nfloat GetAlignOffset(UITextAlignment textAlignment) => textAlignment switch
{
UITextAlignment.Center => 0.5f,
UITextAlignment.Right => 1f,
_ => 0.0f,
};
nfloat alignmentOffset = GetAlignOffset(control.TextAlignment);
nfloat xOffset = (bounds.Size.Width - textBoundingBox.Size.Width) * alignmentOffset - textBoundingBox.Location.X;
nfloat yOffset = (bounds.Size.Height - textBoundingBox.Size.Height) * alignmentOffset - textBoundingBox.Location.Y;
// Find tapped character
CGPoint locationOfTouchInLabel = tap.LocationInView(control);
var locationOfTouchInTextContainer = new CGPoint(locationOfTouchInLabel .X - xOffset, locationOfTouchInLabel .Y - yOffset);
var characterIndex = (nint)layoutManager.GetCharacterIndex(locationOfTouchInTextContainer, textContainer);
var lineTapped = ((int)Math.Ceiling(locationOfTouchInLabel.Y / control.Font.LineHeight)) - 1;
var rightMostPointInLineTapped = new CGPoint(bounds.Size.Width, control.Font.LineHeight * lineTapped);
var charsInLineTapped = (nint)layoutManager.GetCharacterIndex(rightMostPointInLineTapped, textContainer);
if (characterIndex > charsInLineTapped)
{
return null;
}
// Try to get the URL
NSObject linkAttributeValue = attributedText.GetAttribute(CustomLinkAttribute, characterIndex, out NSRange range);
return linkAttributeValue is NSUrl url ? url.AbsoluteString : null;
}
}
}
| mit | C# |
d559150eea5f96a9beeabdfc1d2eaeb5be3182ab | Update Startup.cs | PomeloIDE/Pomelo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PomeloIDE/Pomelo.NetCore.Node,PolemoIDE/Polemo.NetCore.Node | src/Polemo.NetCore.Node/Startup.cs | src/Polemo.NetCore.Node/Startup.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Polemo.NetCore.Node
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(c => c.AddPolicy("Polemo", x =>
x.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
));
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
services.AddAesCrypto();
services.AddSmtpEmailSender("smtp.exmail.qq.com", 25, "码锋科技", "[email protected]", "[email protected]", "Yuuko19931101");
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Debug);
app.UseCors("Polemo");
app.UseSignalR();
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Polemo.NetCore.Node
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(c => c.AddPolicy("Polemo", x =>
x.AllowCredentials()
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
));
services.AddSignalR(options =>
{
options.Hubs.EnableDetailedErrors = true;
});
services.AddAesCrypto();
services.AddSmtpEmailSender("smtp.exmail.qq.com", 25, "码锋科技", "[email protected]", "[email protected]", "Yuuko19931101");
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(LogLevel.Debug);
app.UseCors("Polemo");
app.UseWebSockets();
app.UseSignalR();
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| mit | C# |
648fff7f24e009358e610e32d57bb66826ed4a52 | include sample usage | dgg/rvn-izr | src/Rvn.Izr.Tests/IndexesTester.cs | src/Rvn.Izr.Tests/IndexesTester.cs | using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using NUnit.Framework;
using Raven.Client;
using Raven.Client.Document;
using Raven.Client.Indexes;
using Rvn.Izr.Tests.Support;
namespace Rvn.Izr.Tests
{
[TestFixture]
public class IndexesTester
{
[Test]
public void Builder_MyDb_ReturnsDecoratedIndexesForThatDatabase()
{
ExportProvider export = Indexes.ContainedBesides(typeof (IndexesTester))
.For("my_db");
IEnumerable<AbstractIndexCreationTask> myDbIndexes = export
.GetExportedValues<AbstractIndexCreationTask>();
Assert.That(myDbIndexes, Has
.Exactly(1).Matches(Is.InstanceOf<Decorated_MyDb>()).And
.None.Matches(Is.InstanceOf<NotDecorated>()).And
.None.Matches(Is.InstanceOf<Decorated_YourDb>()));
}
[Test, Category("usage"), Ignore]
public void IndexesBuilder()
{
string aDatabase = "a_database";
IDocumentStore initializedStore = new DocumentStore()
{
DefaultDatabase = aDatabase
};
ExportProvider export = Indexes.ContainedBesides(typeof(IndexesTester))
.For(aDatabase);
IndexCreation.CreateIndexes(export, initializedStore);
}
}
} | using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using NUnit.Framework;
using Raven.Client.Indexes;
using Rvn.Izr.Tests.Support;
namespace Rvn.Izr.Tests
{
[TestFixture]
public class IndexesTester
{
[Test]
public void Builder_MyDb_ReturnsDecoratedIndexesForThatDatabase()
{
ExportProvider export = Indexes.ContainedBesides(typeof (IndexesTester))
.For("my_db");
IEnumerable<AbstractIndexCreationTask> myDbIndexes = export
.GetExportedValues<AbstractIndexCreationTask>();
Assert.That(myDbIndexes, Has
.Exactly(1).Matches(Is.InstanceOf<Decorated_MyDb>()).And
.None.Matches(Is.InstanceOf<NotDecorated>()).And
.None.Matches(Is.InstanceOf<Decorated_YourDb>()));
}
}
} | bsd-2-clause | C# |
b28933d819a52fa65a6c0e8a8a6edf940ac393fe | Update Contact.cshtml | TravisAndLeo/HawkWingForge,TravisAndLeo/HawkWingForge,TravisAndLeo/HawkWingForge | src/HawkWingForge/Views/Home/Contact.cshtml | src/HawkWingForge/Views/Home/Contact.cshtml | <link rel="stylesheet" href="~/css/contact.css" />
<script src="~/js/contact.js" asp-append-version="true"></script>
@{
ViewData["Title"] = "Contact";
}
<div class="container body-content">
<h1>@ViewData["Title"]</h1>
<form id="gform" method="POST" class="pure-form pure-form-stacked"
action="https://script.google.com/macros/s/AKfycbx2ukV9lKHvhgo9rgNZOk2S_fWs2cMRRN2ClncuH-i1S1I5OmG8/exec">
<div id="emailForm">
<div class="form-group">
<label for="email">Email address <span style="color:red">*</span></label>
<input type="email" class="form-control" id="email" placeholder=@("[email protected]") pattern=@(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$") required />
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Full Name" />
</div>
<div class="form-group">
<label for="name">Telephone</label>
<input type="tel" class="form-control" id="telephone" placeholder="555-555-5555" />
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="3" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
<div style="display:none;" id="thankyouMessage">
<div class="alert alert-success"><strong>Thank you!</strong>Your message was sent succefully! We will get back to you as soon as possible!</div>
</div>
<address>
Ste. Genevieve, MO 63670<br />
<abbr title="Phone">P:</abbr>
573.535.9735
</address>
<address>
<strong>Email:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
</address>
</div>
| <link rel="stylesheet" href="~/css/contact.css" />
<script src="~/js/contact.js" asp-append-version="true"></script>
@{
ViewData["Title"] = "Contact";
}
<div class="container body-content">
<h1>@ViewData["Title"]</h1>
<form id="gform" method="POST" class="pure-form pure-form-stacked"
action="https://script.google.com/macros/s/AKfycbx2ukV9lKHvhgo9rgNZOk2S_fWs2cMRRN2ClncuH-i1S1I5OmG8/exec">
<div id="emailForm">
<div class="form-group">
<label for="email">Email address <span style="color:red">*</span></label>
<input type="email" class="form-control" id="email" placeholder=@("[email protected]") pattern=@(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$") required />
</div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Full Name" />
</div>
<div class="form-group">
<label for="name">Telehpone</label>
<input type="tel" class="form-control" id="telephone" placeholder="555-555-5555" />
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" rows="3" id="message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
<div style="display:none;" id="thankyouMessage">
<div class="alert alert-success"><strong>Thank you!</strong>Your message was sent succefully! We will get back to you as soon as possible!</div>
</div>
<address>
Ste. Genevieve, MO 63670<br />
<abbr title="Phone">P:</abbr>
573.535.9735
</address>
<address>
<strong>Email:</strong> <a href="mailto:[email protected]">[email protected]</a><br />
</address>
</div> | mit | C# |
a10c6096cd6c4e2cb54d6a8df18baa2f8b11c3d1 | remove temporarly actual xunit tests | rhwy/iago | src/lib/tests/describe.tests.cs | src/lib/tests/describe.tests.cs | namespace Iago.Tests
{
using Xunit;
using NFluent;
using System;
using System.Collections.Generic;
using System.Reflection;
using static Iago.Specs;
using static System.Console;
public class CoffeeMachineSpecsTests
{
/* [Fact]
public void run_the_specs()
{
var specs = new CoffeeMachineSpecs();
FieldInfo myFieldInfo1 = specs.GetType().GetField("that",
BindingFlags.NonPublic | BindingFlags.Instance);
var specMessage = myFieldInfo1.GetValue(specs) as Specify;
WriteLine("[spec] " + specMessage());
specs.Run();
}*/
}
}
| using Xunit;
using NFluent;
using System;
using System.Collections.Generic;
using System.Reflection;
using static NDescribe.Specs;
using static System.Console;
namespace NDescribe.Tests
{
public class CoffeeMachineSpecs
{
Specify that = () =>
"CoffeeMachine Sould automate the production of coffee";
public void Run()
{
When("coffee machine is started", ()=> {
var machine = new CoffeeMachine();
machine.Start();
Then("screen must be equal to 'Welcome'", ()=>{
Check.That(machine.Screen).IsEqualTo("Welcome");
});
});
}
}
public class CoffeeMachineSpecsTests
{
[Fact]
public void run_the_specs()
{
var specs = new CoffeeMachineSpecs();
FieldInfo myFieldInfo1 = specs.GetType().GetField("that",
BindingFlags.NonPublic | BindingFlags.Instance);
var specMessage = myFieldInfo1.GetValue(specs) as Specify;
WriteLine("[spec] " + specMessage());
specs.Run();
}
}
public class CoffeeMachine{
public void Start(){}
public string Screen {get;} = "Welcome";
}
}
| mit | C# |
41d5e3b235778f1abccc9eb96432fbb4a3ef6f1c | Make assert stronger | mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,dotnet/roslyn,mavasani/roslyn | src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisState.AnalyzerStateData.cs | src/Compilers/Core/Portable/DiagnosticAnalyzer/AnalysisState.AnalyzerStateData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalysisState
{
/// <summary>
/// Stores the partial analysis state for a specific event/symbol/tree for a specific analyzer.
/// </summary>
internal class AnalyzerStateData
{
/// <summary>
/// Current state of analysis.
/// </summary>
public StateKind StateKind { get; private set; }
/// <summary>
/// Set of completed actions.
/// </summary>
public HashSet<AnalyzerAction> ProcessedActions { get; }
public static readonly AnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance();
public AnalyzerStateData()
{
StateKind = StateKind.InProcess;
ProcessedActions = new HashSet<AnalyzerAction>();
}
private static AnalyzerStateData CreateFullyProcessedInstance()
{
var instance = new AnalyzerStateData();
instance.SetStateKind(StateKind.FullyProcessed);
return instance;
}
public virtual void SetStateKind(StateKind stateKind)
{
StateKind = stateKind;
}
/// <summary>
/// Resets the <see cref="StateKind"/> from <see cref="StateKind.InProcess"/> to <see cref="StateKind.ReadyToProcess"/>.
/// This method must be invoked after successful analysis completion AND on analysis cancellation.
/// </summary>
public void ResetToReadyState()
{
SetStateKind(StateKind.ReadyToProcess);
}
public virtual void Free()
{
Debug.Assert(StateKind == StateKind.ReadyToProcess);
this.ProcessedActions.Clear();
}
}
}
}
| // 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.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal partial class AnalysisState
{
/// <summary>
/// Stores the partial analysis state for a specific event/symbol/tree for a specific analyzer.
/// </summary>
internal class AnalyzerStateData
{
/// <summary>
/// Current state of analysis.
/// </summary>
public StateKind StateKind { get; private set; }
/// <summary>
/// Set of completed actions.
/// </summary>
public HashSet<AnalyzerAction> ProcessedActions { get; }
public static readonly AnalyzerStateData FullyProcessedInstance = CreateFullyProcessedInstance();
public AnalyzerStateData()
{
StateKind = StateKind.InProcess;
ProcessedActions = new HashSet<AnalyzerAction>();
}
private static AnalyzerStateData CreateFullyProcessedInstance()
{
var instance = new AnalyzerStateData();
instance.SetStateKind(StateKind.FullyProcessed);
return instance;
}
public virtual void SetStateKind(StateKind stateKind)
{
StateKind = stateKind;
}
/// <summary>
/// Resets the <see cref="StateKind"/> from <see cref="StateKind.InProcess"/> to <see cref="StateKind.ReadyToProcess"/>.
/// This method must be invoked after successful analysis completion AND on analysis cancellation.
/// </summary>
public void ResetToReadyState()
{
SetStateKind(StateKind.ReadyToProcess);
}
public virtual void Free()
{
Debug.Assert(StateKind != StateKind.InProcess);
this.StateKind = StateKind.ReadyToProcess;
this.ProcessedActions.Clear();
}
}
}
}
| mit | C# |
f89097d574fdede47da36b573c065001821152b9 | Update millipede.cs | getmillipede/millipede-csharp | millipede.cs | millipede.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace millipede
{
class Program
{
static void Main(string[] args)
{
int[] padding_offsets = new int[] { 2, 1, 0, 1, 2, 3, 4, 4, 3 };
int i = 0;
int size = 20;
bool isReverse = false;
string head = "╚⊙ ⊙╝";
string body = "╚═(███)═╝";
if (args.Length > 0)
{
for (i = 0; i < args.Length; i++)
{
string tok = args[i];
int tmp = 0;
if (!int.TryParse(tok, out tmp))
isReverse = tok == "-r";
else
size = tmp;
}
}
if (isReverse)
{
head = "╔⊙ ⊙╗";
body = "╔═(███)═╗";
for (i = size; i > 0; i--)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
Console.WriteLine(new string(' ', padding_offsets[i % 9]+1) + head);
}
else
{
Console.WriteLine(new string(' ', padding_offsets[0]+1) + head);
for (i = 1; i < size; i++)
{
Console.WriteLine(new string(' ', padding_offsets[i % 9]) + body);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace millipede
{
class Program
{
static void Main(string[] args)
{
int[] padding_offsets = new int[] { 2, 1, 0, 1, 2, 3, 4, 4, 3 };
int size = 20;
if (args.Length > 1)
{
size = int.Parse(args[1]);
}
Console.WriteLine(" ╚⊙ ⊙╝");
for (int i = 0; i < size; i++)
{
Console.WriteLine(new string(' ', padding_offsets[i%9]) + "╚═(███)═╝");
}
}
}
}
| mit | C# |
92e65c8ac823def2ce76081640b734fdf09ce661 | Fix method name. | andrewdavey/witness,andrewdavey/witness,andrewdavey/witness | src/Witness/RequestHandlers/ProxyHandler.cs | src/Witness/RequestHandlers/ProxyHandler.cs | using System.Net;
using System.Web;
using System.Web.Routing;
namespace Witness.RequestHandlers
{
/// <summary>
/// Forwards any request to the web server under test and returns
/// that response as if it was it's own.
/// </summary>
public class ProxyHandler : WitnessRequestHandlerBase
{
public override void ProcessRequest(RequestContext requestContext)
{
var context = requestContext.HttpContext;
var urlString = GetTargetUrlString(context);
var targetRequest = HttpWebRequest.Create(urlString);
AddRequestHeaders(context, targetRequest);
var targetResponse = targetRequest.GetResponse();
AddResponseHeaders(context, targetResponse);
using (var stream = targetResponse.GetResponseStream())
{
// TODO: If stream is HTML, parse and replace absolute URLs to use proxy URLs instead.
stream.CopyTo(context.Response.OutputStream);
}
context.Response.End();
}
string GetTargetUrlString(HttpContextBase context)
{
var cookie = context.Request.Cookies["_witness"];
var pathAndQuery = context.Request.Url.PathAndQuery;
var urlString = cookie.Values["url"] + pathAndQuery;
return urlString;
}
void AddRequestHeaders(HttpContextBase context, WebRequest targetRequest)
{
targetRequest.Headers.Add(context.Request.Headers);
}
void AddResponseHeaders(HttpContextBase context, WebResponse targetResponse)
{
context.Response.Headers.Add(targetResponse.Headers);
}
}
} | using System.Net;
using System.Web;
using System.Web.Routing;
namespace Witness.RequestHandlers
{
/// <summary>
/// Forwards any request to the web server under test and returns
/// that response as if it was it's own.
/// </summary>
public class ProxyHandler : WitnessRequestHandlerBase
{
public override void ProcessRequest(RequestContext requestContext)
{
var context = requestContext.HttpContext;
var urlString = GetTargetUrlString(context);
var targetRequest = HttpWebRequest.Create(urlString);
AddRequestHeaders(context, targetRequest);
var targetResponse = targetRequest.GetResponse();
AddResponseHeader(context, targetResponse);
using (var stream = targetResponse.GetResponseStream())
{
// TODO: If stream is HTML, parse and replace absolute URLs to use proxy URLs instead.
stream.CopyTo(context.Response.OutputStream);
}
context.Response.End();
}
string GetTargetUrlString(HttpContextBase context)
{
var cookie = context.Request.Cookies["_witness"];
var pathAndQuery = context.Request.Url.PathAndQuery;
var urlString = cookie.Values["url"] + pathAndQuery;
return urlString;
}
void AddRequestHeaders(HttpContextBase context, WebRequest targetRequest)
{
targetRequest.Headers.Add(context.Request.Headers);
}
void AddResponseHeader(HttpContextBase context, WebResponse targetResponse)
{
context.Response.Headers.Add(targetResponse.Headers);
}
}
} | bsd-2-clause | C# |
15b4334f8fc5456a97ceb692504f67d1e936651f | Remove extra spaces from mods path | edwinj85/ezDoom | ezDoom/Code/GameProcessHandler.cs | ezDoom/Code/GameProcessHandler.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ezDoom.Code
{
/// <summary>
/// This class handles launching the doom engine with chosen settings.
/// </summary>
public static class GameProcessHandler
{
/// <summary>
/// This method launches the doom engine with chosen settings.
/// </summary>
public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods)
{
//use a string builder to take all the chosen mods and turn them into a string we can pass as an argument.
StringBuilder sb = new StringBuilder();
foreach (GamePackage item in mods)
{
sb.Append($"\"../{ConstStrings.ModsFolderName}/{item.FullName}\" ");
}
string chosenPackages = sb.ToString();
//create process to launch the game.
var details = new ProcessStartInfo(Path.Combine(ConstStrings.EngineFolderName, ConstStrings.GzDoomExeName));
details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder.
//Store game saves in the user's saved games folder.
var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var savesDirectoryRaw = Path.Combine(userDirectory, ConstStrings.GameSaveFolderName);
var savesDirectory = $"\"{savesDirectoryRaw}\"".Replace(@"\", "/");
//launch GZDoom with the correct args.
details.Arguments = $@"-iwad ../iwads/{IWADPath} -file {chosenPackages} -savedir {savesDirectory}";
//we wrap the process in a using statement to make sure the handle is always disposed after use.
using (Process process = Process.Start(details)) { };
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ezDoom.Code
{
/// <summary>
/// This class handles launching the doom engine with chosen settings.
/// </summary>
public static class GameProcessHandler
{
/// <summary>
/// This method launches the doom engine with chosen settings.
/// </summary>
public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods)
{
//use a string builder to take all the chosen mods and turn them into a string we can pass as an argument.
StringBuilder sb = new StringBuilder();
foreach (GamePackage item in mods)
{
sb.AppendFormat(" \"../{0}/{1}\" ", ConstStrings.ModsFolderName, item.FullName);
}
string chosenPackages = sb.ToString();
//create process to launch the game.
var details = new ProcessStartInfo(Path.Combine(ConstStrings.EngineFolderName, ConstStrings.GzDoomExeName));
details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder.
//Store game saves in the user's saved games folder.
var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var savesDirectoryRaw = Path.Combine(userDirectory, ConstStrings.GameSaveFolderName);
var savesDirectory = string.Format("\"{0}\"", savesDirectoryRaw).Replace(@"\", "/");
//launch GZDoom with the correct args.
details.Arguments = $@"-iwad ../iwads/{IWADPath} -file {chosenPackages} -savedir {savesDirectory}";
//we wrap the process in a using statement to make sure the handle is always disposed after use.
using (Process process = Process.Start(details)) { };
}
}
}
| apache-2.0 | C# |
58ad9955a74adfb12f77567f2b5a16b4aec0f36e | update Json class | marihachi/MSharp | src/MSharp/Core/Utility/Json.cs | src/MSharp/Core/Utility/Json.cs | using System.Json;
namespace MSharp.Core.Utility
{
/// <summary>
/// JSON形式のデータを扱うクラスです。
/// </summary>
public static class Json
{
/// <summary>
/// JSON の形式にシリアライズされた文字列を動的なJSONオブジェクトに変換します。
/// <para>また、このメソッドについては例外が発生しないことが保障されています。</para>
/// </summary>
/// <param name="json">JSON形式の文字列</param>
public static dynamic Parse(string json)
{
if (json == null || string.IsNullOrEmpty(json) || string.IsNullOrWhiteSpace(json))
return null;
dynamic res = null;
try
{
res = JsonObject.Parse(json).AsDynamic();
}
catch { }
return res;
}
}
}
| using System.Json;
namespace MSharp.Core.Utility
{
/// <summary>
/// JSON形式のデータを扱うクラスです。
/// </summary>
public static class Json
{
/// <summary>
/// JSON の形式にシリアライズされた文字列を動的なJSONオブジェクトに変換します。
/// <para>また、このメソッドについては例外が発生しないことが保障されています。</para>
/// </summary>
/// <param name="json">JSON形式の文字列</param>
public static dynamic Parse(string json)
{
dynamic res;
if (json == null || string.IsNullOrEmpty(json) || string.IsNullOrWhiteSpace(json))
res = null;
try
{
res = JsonObject.Parse(json).AsDynamic();
}
catch
{
res = null;
}
return res;
}
}
}
| mit | C# |
0a27c4e1551b1d6e0742198dbf3d697048fd5d87 | Make sure the app crash nicely if configuration is invalid | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer/Program.cs | NBXplorer/Program.cs | using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using NBXplorer.Configuration;
using NBXplorer.Logging;
using NBitcoin.Protocol;
using System.Collections;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore;
using NBitcoin;
using System.Text;
using System.Net;
using CommandLine;
namespace NBXplorer
{
public class Program
{
public static void Main(string[] args)
{
var processor = new ConsoleLoggerProcessor();
Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false, processor)));
IWebHost host = null;
try
{
var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args);
if(conf == null)
return;
// Sanity check of the config, this is not strictly needed as it would happen down the line when the host is built
// However, a bug in .NET Core fixed in 2.1 will prevent the app from stopping if an exception is thrown by the host
// at startup. We need to remove this line later
new ExplorerConfiguration().LoadArgs(conf);
ConfigurationBuilder builder = new ConfigurationBuilder();
host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseConfiguration(conf)
.UseApplicationInsights()
.ConfigureLogging(l =>
{
l.AddFilter("Microsoft", LogLevel.Error);
l.AddFilter("NBXplorer.Authentication.BasicAuthenticationHandler", LogLevel.Critical);
if(conf.GetOrDefault<bool>("verbose", false))
{
l.SetMinimumLevel(LogLevel.Debug);
}
l.AddProvider(new CustomConsoleLogProvider(processor));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Configuration.LogError(ex.Message);
}
catch(CommandParsingException parsing)
{
Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message);
}
finally
{
processor.Dispose();
if(host != null)
host.Dispose();
}
}
}
}
| using System;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using NBXplorer.Configuration;
using NBXplorer.Logging;
using NBitcoin.Protocol;
using System.Collections;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore;
using NBitcoin;
using System.Text;
using System.Net;
using CommandLine;
namespace NBXplorer
{
public class Program
{
public static void Main(string[] args)
{
var processor = new ConsoleLoggerProcessor();
Logs.Configure(new FuncLoggerFactory(i => new CustomerConsoleLogger(i, (a, b) => true, false, processor)));
IWebHost host = null;
try
{
var conf = new DefaultConfiguration() { Logger = Logs.Configuration }.CreateConfiguration(args);
if(conf == null)
return;
ConfigurationBuilder builder = new ConfigurationBuilder();
host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseConfiguration(conf)
.UseApplicationInsights()
.ConfigureLogging(l =>
{
l.AddFilter("Microsoft", LogLevel.Error);
l.AddFilter("NBXplorer.Authentication.BasicAuthenticationHandler", LogLevel.Critical);
if(conf.GetOrDefault<bool>("verbose", false))
{
l.SetMinimumLevel(LogLevel.Debug);
}
l.AddProvider(new CustomConsoleLogProvider(processor));
})
.UseStartup<Startup>()
.Build();
host.Run();
}
catch(ConfigException ex)
{
if(!string.IsNullOrEmpty(ex.Message))
Logs.Configuration.LogError(ex.Message);
}
catch(CommandParsingException parsing)
{
Logs.Explorer.LogError(parsing.HelpText + "\r\n" + parsing.Message);
}
finally
{
processor.Dispose();
if(host != null)
host.Dispose();
}
}
}
}
| mit | C# |
bdeec8593cb011b667d0c3b93ad55d81230858c7 | Add cast extensions | mruhul/Bolt.MayBe | src/Bolt.MayBe/Properties/AssemblyInfo.cs | src/Bolt.MayBe/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Bolt.Monad")]
[assembly: AssemblyDescription("Simple monad library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mohammad Ruhul Amin")]
[assembly: AssemblyProduct("Bolt.Monad")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("25fda22e-754a-4fe4-8e0a-2b010514ee44")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.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("Bolt.Monad")]
[assembly: AssemblyDescription("Simple monad library")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mohammad Ruhul Amin")]
[assembly: AssemblyProduct("Bolt.Monad")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("25fda22e-754a-4fe4-8e0a-2b010514ee44")]
// 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.2.0")]
[assembly: AssemblyFileVersion("1.0.2.0")]
| apache-2.0 | C# |
6abcfb7ba0182c6bd59807be4daa65afa7a83c31 | add okstats. | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/DotNetCore.CAP/Dashboard/JsonStats.cs | src/DotNetCore.CAP/Dashboard/JsonStats.cs | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace DotNetCore.CAP.Dashboard
{
internal class JsonStats : IDashboardDispatcher
{
public async Task Dispatch(DashboardContext context)
{
var requestedMetrics = await context.Request.GetFormValuesAsync("metrics[]");
var page = new StubPage();
page.Assign(context);
var metrics = DashboardMetrics.GetMetrics().Where(x => requestedMetrics.Contains(x.Name));
var result = new Dictionary<string, Metric>();
foreach (var metric in metrics)
{
var value = metric.Func(page);
result.Add(metric.Name, value);
}
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new JsonConverter[] { new StringEnumConverter { CamelCaseText = true } }
};
var serialized = JsonConvert.SerializeObject(result, settings);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(serialized);
}
private class StubPage : RazorPage
{
public override void Execute()
{
}
}
}
internal class OkStats : IDashboardDispatcher
{
public Task Dispatch(DashboardContext context)
{
context.Response.StatusCode = 200;
return Task.CompletedTask;
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
namespace DotNetCore.CAP.Dashboard
{
internal class JsonStats : IDashboardDispatcher
{
public async Task Dispatch(DashboardContext context)
{
var requestedMetrics = await context.Request.GetFormValuesAsync("metrics[]");
var page = new StubPage();
page.Assign(context);
var metrics = DashboardMetrics.GetMetrics().Where(x => requestedMetrics.Contains(x.Name));
var result = new Dictionary<string, Metric>();
foreach (var metric in metrics)
{
var value = metric.Func(page);
result.Add(metric.Name, value);
}
var settings = new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new JsonConverter[] { new StringEnumConverter { CamelCaseText = true } }
};
var serialized = JsonConvert.SerializeObject(result, settings);
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(serialized);
}
private class StubPage : RazorPage
{
public override void Execute()
{
}
}
}
} | mit | C# |
9bae23a6bf1723a3aa8ff2d70acd7b47c4fdb481 | Reformate code. | maraf/Money,maraf/Money,maraf/Money | src/Money.UI.Blazor/Shared/_Layout.cshtml | src/Money.UI.Blazor/Shared/_Layout.cshtml | @implements ILayoutComponent
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand">Money</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="/">Summary</a>
</li>
<li>
<a href="/categories">Categories</a>
</li>
<li>
<a href="/currencies">Currencies</a>
</li>
<li>
<a href="/about">About</a>
</li>
</ul>
<LoginInfo />
</div>
</div>
</nav>
<div class="container body-content">
<ExceptionPanel />
@Body
<hr />
<footer>
<p>© 2018 - Money</p>
</footer>
</div>
@functions
{
public RenderFragment Body { get; set; }
}
| @implements ILayoutComponent
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand">Money</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="/">Summary</a>
</li>
<li>
<a href="/categories">Categories</a>
</li>
<li>
<a href="/currencies">Currencies</a>
</li>
<li>
<a href="/about">About</a>
</li>
</ul>
<LoginInfo />
</div>
</div>
</nav>
<div class="container body-content">
<ExceptionPanel />
@Body
<hr />
<footer>
<p>© 2018 - Money</p>
</footer>
</div>
@functions {
public RenderFragment Body { get; set; }
}
| apache-2.0 | C# |
54206d39cb4aa7b54c3c5adb6d214ff6af327576 | Add access to ByteArrayChunk's data | ZixiangBoy/dnlib,jorik041/dnlib,Arthur2e5/dnlib,modulexcite/dnlib,picrap/dnlib,kiootic/dnlib,yck1509/dnlib,0xd4d/dnlib,ilkerhalil/dnlib | src/DotNet/Writer/ByteArrayChunk.cs | src/DotNet/Writer/ByteArrayChunk.cs | using System.IO;
using dot10.IO;
using dot10.PE;
namespace dot10.DotNet.Writer {
/// <summary>
/// Stores a byte array
/// </summary>
public sealed class ByteArrayChunk : IChunk {
byte[] array;
FileOffset offset;
RVA rva;
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <summary>
/// Gets the data
/// </summary>
public byte[] Data {
get { return array; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="array">The data (now owned by us and can't be modified by the caller)</param>
public ByteArrayChunk(byte[] array) {
this.array = array ?? new byte[0];
}
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
/// <inheritdoc/>
public uint GetFileLength() {
return (uint)array.Length;
}
/// <inheritdoc/>
public uint GetVirtualSize() {
return GetFileLength();
}
/// <inheritdoc/>
public void WriteTo(BinaryWriter writer) {
writer.Write(array);
}
/// <inheritdoc/>
public override int GetHashCode() {
return Utils.GetHashCode(array);
}
/// <inheritdoc/>
public override bool Equals(object obj) {
var other = obj as ByteArrayChunk;
return other != null && Utils.Equals(array, other.array);
}
}
}
| using System.IO;
using dot10.IO;
using dot10.PE;
namespace dot10.DotNet.Writer {
/// <summary>
/// Stores a byte array
/// </summary>
public sealed class ByteArrayChunk : IChunk {
byte[] array;
FileOffset offset;
RVA rva;
/// <inheritdoc/>
public FileOffset FileOffset {
get { return offset; }
}
/// <inheritdoc/>
public RVA RVA {
get { return rva; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="array">The data (now owned by us and can't be modified by the caller)</param>
public ByteArrayChunk(byte[] array) {
this.array = array ?? new byte[0];
}
/// <inheritdoc/>
public void SetOffset(FileOffset offset, RVA rva) {
this.offset = offset;
this.rva = rva;
}
/// <inheritdoc/>
public uint GetFileLength() {
return (uint)array.Length;
}
/// <inheritdoc/>
public uint GetVirtualSize() {
return GetFileLength();
}
/// <inheritdoc/>
public void WriteTo(BinaryWriter writer) {
writer.Write(array);
}
/// <inheritdoc/>
public override int GetHashCode() {
return Utils.GetHashCode(array);
}
/// <inheritdoc/>
public override bool Equals(object obj) {
var other = obj as ByteArrayChunk;
return other != null && Utils.Equals(array, other.array);
}
}
}
| mit | C# |
5c2730ce214a2f234bafc1187cd392eb96a47af2 | Update AssemblyVersion | kiyokura/SSDTHelper | src/SSDTHelper/Properties/AssemblyInfo.cs | src/SSDTHelper/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("SSDTHelper")]
[assembly: AssemblyDescription("Support Libraly for SQL Server Data Tools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SSDTHelper")]
[assembly: AssemblyCopyright("Copyright © 2016 Narami Kiyokura")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("eb7dcd12-dba9-4841-820a-143601794d20")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("SSDTHelper")]
[assembly: AssemblyDescription("Support Libraly for SQL Server Data Tools")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SSDTHelper")]
[assembly: AssemblyCopyright("Copyright © 2016 Narami Kiyokura")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("eb7dcd12-dba9-4841-820a-143601794d20")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: NeutralResourcesLanguage("en-US")]
| mit | C# |
4a162e6f788d393ac827c824fd3517efbaa41591 | Test full serialization, not just building checksums | KevinRansom/roslyn,pdelvo/roslyn,gafter/roslyn,orthoxerox/roslyn,dpoeschl/roslyn,tannergooding/roslyn,lorcanmooney/roslyn,VSadov/roslyn,srivatsn/roslyn,CaptainHayashi/roslyn,xasx/roslyn,tvand7093/roslyn,MichalStrehovsky/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,abock/roslyn,MattWindsor91/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,jamesqo/roslyn,Giftednewt/roslyn,tmat/roslyn,MattWindsor91/roslyn,jkotas/roslyn,tvand7093/roslyn,tmat/roslyn,bartdesmet/roslyn,robinsedlaczek/roslyn,panopticoncentral/roslyn,heejaechang/roslyn,stephentoub/roslyn,robinsedlaczek/roslyn,dpoeschl/roslyn,cston/roslyn,TyOverby/roslyn,aelij/roslyn,sharwell/roslyn,mavasani/roslyn,AlekseyTs/roslyn,sharwell/roslyn,mavasani/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,CaptainHayashi/roslyn,pdelvo/roslyn,jcouv/roslyn,wvdd007/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,genlu/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,tmeschter/roslyn,bartdesmet/roslyn,tannergooding/roslyn,aelij/roslyn,dotnet/roslyn,dotnet/roslyn,AnthonyDGreen/roslyn,CyrusNajmabadi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,aelij/roslyn,KirillOsenkov/roslyn,tmeschter/roslyn,dpoeschl/roslyn,kelltrick/roslyn,VSadov/roslyn,TyOverby/roslyn,DustinCampbell/roslyn,davkean/roslyn,paulvanbrenk/roslyn,weltkante/roslyn,DustinCampbell/roslyn,physhi/roslyn,gafter/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,davkean/roslyn,jmarolf/roslyn,paulvanbrenk/roslyn,jasonmalinowski/roslyn,tvand7093/roslyn,khyperia/roslyn,cston/roslyn,CaptainHayashi/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,Giftednewt/roslyn,jkotas/roslyn,paulvanbrenk/roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,OmarTawfik/roslyn,AmadeusW/roslyn,Hosch250/roslyn,tmeschter/roslyn,kelltrick/roslyn,AnthonyDGreen/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,orthoxerox/roslyn,DustinCampbell/roslyn,tannergooding/roslyn,nguerrera/roslyn,TyOverby/roslyn,Hosch250/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,khyperia/roslyn,diryboy/roslyn,swaroop-sridhar/roslyn,diryboy/roslyn,jamesqo/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,genlu/roslyn,agocke/roslyn,mattscheffer/roslyn,khyperia/roslyn,OmarTawfik/roslyn,lorcanmooney/roslyn,brettfo/roslyn,bkoelman/roslyn,reaction1989/roslyn,cston/roslyn,srivatsn/roslyn,weltkante/roslyn,stephentoub/roslyn,jkotas/roslyn,mavasani/roslyn,agocke/roslyn,srivatsn/roslyn,AnthonyDGreen/roslyn,nguerrera/roslyn,VSadov/roslyn,mmitche/roslyn,pdelvo/roslyn,eriawan/roslyn,abock/roslyn,tmat/roslyn,Giftednewt/roslyn,swaroop-sridhar/roslyn,eriawan/roslyn,brettfo/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,lorcanmooney/roslyn,mmitche/roslyn,physhi/roslyn,KevinRansom/roslyn,jamesqo/roslyn,mmitche/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,jmarolf/roslyn,gafter/roslyn,heejaechang/roslyn,bkoelman/roslyn,AmadeusW/roslyn,MichalStrehovsky/roslyn,robinsedlaczek/roslyn,nguerrera/roslyn,bartdesmet/roslyn,xasx/roslyn,reaction1989/roslyn,MattWindsor91/roslyn,jmarolf/roslyn,xasx/roslyn,genlu/roslyn,bkoelman/roslyn,heejaechang/roslyn,mattscheffer/roslyn,davkean/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,mattscheffer/roslyn,kelltrick/roslyn,KirillOsenkov/roslyn,jcouv/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,abock/roslyn,MattWindsor91/roslyn,diryboy/roslyn,orthoxerox/roslyn,OmarTawfik/roslyn,ErikSchierboom/roslyn,brettfo/roslyn | src/VisualStudio/Core/Test.Next/Services/VisualStudioSnapshotSerializationTests.cs | src/VisualStudio/Core/Test.Next/Services/VisualStudioSnapshotSerializationTests.cs | using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Execution;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Moq;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
public class VisualStudioSnapshotSerializationTests : SnapshotSerializationTestBase
{
[Fact, WorkItem(466282, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/466282")]
public async Task TestUnresolvedAnalyzerReference()
{
var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp);
var mockFileChangeService = new Mock<IVsFileChangeEx>();
var analyzer = new VisualStudioAnalyzer(
@"PathToAnalyzer",
fileChangeService: mockFileChangeService.Object,
hostDiagnosticUpdateSource: null,
projectId: project.Id,
workspace: workspace,
loader: null,
language: project.Language);
var analyzerReference = analyzer.GetReference();
project = project.WithAnalyzerReferences(new AnalyzerReference[]
{
analyzerReference,
});
var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false);
Assert.NotNull(checksum);
var assetBuilder = new CustomAssetBuilder(workspace);
var serializer = new Serializer(workspace);
var asset = assetBuilder.Build(analyzerReference, CancellationToken.None);
using (var stream = SerializableBytes.CreateWritableStream())
using (var writer = new ObjectWriter(stream))
{
await asset.WriteObjectToAsync(writer, CancellationToken.None).ConfigureAwait(false);
stream.Position = 0;
using (var reader = ObjectReader.TryGetReader(stream))
{
var recovered = serializer.Deserialize<AnalyzerReference>(asset.Kind, reader, CancellationToken.None);
var assetFromStorage = assetBuilder.Build(recovered, CancellationToken.None);
Assert.Equal(asset.Checksum, assetFromStorage.Checksum);
// This won't round trip, but we should get an UnresolvedAnalyzerReference, with the same path
Assert.Equal(analyzerReference.FullPath, recovered.FullPath);
}
}
}
}
}
| using System.Threading.Tasks;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Roslyn.VisualStudio.Next.UnitTests.Services
{
public class VisualStudioSnapshotSerializationTests : SnapshotSerializationTestBase
{
[Fact, WorkItem(466282, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/466282")]
public async Task TestUnresolvedAnalyzerReference()
{
var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("empty", "empty", LanguageNames.CSharp);
var mockFileChangeService = new Mock<IVsFileChangeEx>();
var analyzer = new VisualStudioAnalyzer(
@"PathToAnalyzer",
fileChangeService: mockFileChangeService.Object,
hostDiagnosticUpdateSource: null,
projectId: project.Id,
workspace: workspace,
loader: null,
language: project.Language);
project = project.WithAnalyzerReferences(new AnalyzerReference[]
{
analyzer.GetReference(),
});
var checksum = await project.State.GetChecksumAsync(CancellationToken.None).ConfigureAwait(false);
Assert.NotNull(checksum);
}
}
}
| mit | C# |
1b38ee05367c3272b9c0cc57d8a5f5ac27d2c4f3 | Fix line ending | SixLabors/Fonts | src/SixLabors.Fonts/Tables/Table.cs | src/SixLabors.Fonts/Tables/Table.cs | // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts.Tables
{
internal abstract class Table
{
}
}
| // Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
namespace SixLabors.Fonts.Tables
{
internal abstract class Table
{
}
} | apache-2.0 | C# |
bdc5ba3545b732ca9d726a9694a74e6847b626d1 | Allow application startup with inherited startup class | aruss/IdentityBase,aruss/IdentityBase,IdentityBaseNet/IdentityBase,IdentityBaseNet/IdentityBase,aruss/IdentityBase,aruss/IdentityBase,IdentityBaseNet/IdentityBase,IdentityBaseNet/IdentityBase | src/IdentityBase.Public/Program.cs | src/IdentityBase.Public/Program.cs | using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceBase.Configuration;
using ServiceBase.Extensions;
using System;
using System.IO;
namespace IdentityBase.Public
{
public class Program
{
public static void Main(string[] args)
{
RunIdentityBase<Startup>(Directory.GetCurrentDirectory(), args);
}
public static void RunIdentityBase<TStartup>(string contentRoot, string[] args) where TStartup : Startup
{
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = ConfigurationSetup.Configure(contentRoot, environment, (confBuilder) =>
{
if ("Development".Equals(environment, StringComparison.OrdinalIgnoreCase))
{
confBuilder.AddUserSecrets<TStartup>();
}
confBuilder.AddCommandLine(args);
});
var configHost = configuration.GetSection("Host");
var configLogging = configuration.GetSection("Logging");
var hostBuilder = new WebHostBuilder()
.UseKestrel()
.UseUrls(configHost["Urls"])
.UseContentRoot(contentRoot)
.ConfigureLogging(f => f.AddConsole(configLogging))
.UseStartup<TStartup>();
if (configHost["UseIISIntegration"].ToBoolean())
{
hostBuilder = hostBuilder.UseIISIntegration();
}
hostBuilder.Build().Run();
}
}
}
| using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using ServiceBase.Configuration;
using System;
using System.IO;
using ServiceBase.Extensions;
namespace IdentityBase.Public
{
public class Program
{
public static void Main(string[] args)
{
var contentRoot = Directory.GetCurrentDirectory();
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
var configuration = ConfigurationSetup.Configure(contentRoot, environment, (confBuilder) =>
{
if ("Development".Equals(environment, StringComparison.OrdinalIgnoreCase))
{
confBuilder.AddUserSecrets<Startup>();
}
confBuilder.AddCommandLine(args);
});
var configHost = configuration.GetSection("Host");
var configLogging = configuration.GetSection("Logging");
var hostBuilder = new WebHostBuilder()
.UseKestrel()
.UseUrls(configHost["Urls"])
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureLogging(f => f.AddConsole(configLogging))
.UseStartup<Startup>();
if (configHost["UseIISIntegration"].ToBoolean())
{
hostBuilder = hostBuilder.UseIISIntegration();
}
hostBuilder.Build().Run();
}
}
}
| apache-2.0 | C# |
da9c4898d2570367dfe074c92f3f50c7a8f20e84 | add enum value for the volume flag that indicates short file name creation is disabled. | drebrez/DiscUtils,quamotion/discutils,breezechen/DiscUtils,breezechen/DiscUtils | src/Ntfs/VolumeInformationFlags.cs | src/Ntfs/VolumeInformationFlags.cs | //
// Copyright (c) 2008-2009, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
namespace DiscUtils.Ntfs
{
[Flags]
enum VolumeInformationFlags : ushort
{
None = 0x00,
Dirty = 0x01,
ResizeLogFile = 0x02,
UpgradeOnMount = 0x04,
MountedOnNT4 = 0x08,
DeleteUSNUnderway = 0x10,
RepairObjectIds = 0x20,
DisableShortNameCreation = 0x80,
ModifiedByChkDsk = 0x8000
}
}
| //
// Copyright (c) 2008-2009, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
using System;
namespace DiscUtils.Ntfs
{
[Flags]
enum VolumeInformationFlags : ushort
{
None = 0x00,
Dirty = 0x01,
ResizeLogFile = 0x02,
UpgradeOnMount = 0x04,
MountedOnNT4 = 0x08,
DeleteUSNUnderway = 0x10,
RepairObjectIds = 0x20,
ModifiedByChkDsk = 0x8000
}
}
| mit | C# |
facd2cc3efadf87893a25698900bd75482982d72 | Change ZBase32Encoding.Alphabet constant to a readonly property. | wiry-net/Base32,wiry-net/Wiry.Base32,wiry-net/Wiry.Base32,wiry-net/Base32 | src/Wiry.Base32/ZBase32Encoding.cs | src/Wiry.Base32/ZBase32Encoding.cs | // Copyright (c) Dmitry Razumikhin, 2016-2019.
// Licensed under the MIT License.
// See LICENSE in the project root for license information.
namespace Wiry.Base32
{
internal sealed class ZBase32Encoding : Base32Encoding
{
private string Alphabet => "ybndrfg8ejkmcpqxot1uwisza345h769";
public override string GetString(byte[] bytes, int index, int count)
{
return ToBase32(bytes, index, count, Alphabet, null);
}
public override byte[] ToBytes(string encoded, int index, int length)
{
return ToBytes(encoded, index, length, null, GetOrCreateLookupTable(Alphabet));
}
public override ValidationResult Validate(string encoded, int index, int length)
{
return Validate(encoded, index, length, null, GetOrCreateLookupTable(Alphabet));
}
}
} | // Copyright (c) Dmitry Razumikhin, 2016-2019.
// Licensed under the MIT License.
// See LICENSE in the project root for license information.
namespace Wiry.Base32
{
internal sealed class ZBase32Encoding : Base32Encoding
{
private const string Alphabet = "ybndrfg8ejkmcpqxot1uwisza345h769";
public override string GetString(byte[] bytes, int index, int count)
{
return ToBase32(bytes, index, count, Alphabet, null);
}
public override byte[] ToBytes(string encoded, int index, int length)
{
return ToBytes(encoded, index, length, null, GetOrCreateLookupTable(Alphabet));
}
public override ValidationResult Validate(string encoded, int index, int length)
{
return Validate(encoded, index, length, null, GetOrCreateLookupTable(Alphabet));
}
}
} | mit | C# |
6323c956cf2aa9cfc7b57a0e3ab63adc9922d057 | Fix damagestatevisualizer (#8876) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Client/MobState/DamageStateVisualizerSystem.cs | Content.Client/MobState/DamageStateVisualizerSystem.cs | using Content.Shared.MobState;
using Robust.Client.GameObjects;
using DrawDepth = Content.Shared.DrawDepth.DrawDepth;
namespace Content.Client.MobState;
public sealed class DamageStateVisualizerSystem : VisualizerSystem<DamageStateVisualsComponent>
{
protected override void OnAppearanceChange(EntityUid uid, DamageStateVisualsComponent component, ref AppearanceChangeEvent args)
{
var sprite = args.Sprite;
if (sprite == null || !args.Component.TryGetData(DamageStateVisuals.State, out DamageState data))
{
return;
}
if (!component.States.TryGetValue(data, out var layers))
{
return;
}
if (component.Rotate)
{
sprite.NoRotation = data switch
{
DamageState.Critical => false,
DamageState.Dead => false,
_ => true
};
}
// Brain no worky rn so this was just easier.
foreach (var layer in sprite.AllLayers)
{
layer.Visible = false;
}
foreach (var (key, state) in layers)
{
// Inheritance moment.
if (!sprite.LayerMapTryGet(key, out _)) continue;
sprite.LayerSetVisible(key, true);
sprite.LayerSetState(key, state);
}
// So they don't draw over mobs anymore
if (data == DamageState.Dead && sprite.DrawDepth > (int) DrawDepth.Items)
{
component.OriginalDrawDepth = sprite.DrawDepth;
sprite.DrawDepth = (int) DrawDepth.Items;
}
else if (component.OriginalDrawDepth != null)
{
sprite.DrawDepth = component.OriginalDrawDepth.Value;
component. OriginalDrawDepth = null;
}
}
}
| using Content.Shared.MobState;
using Robust.Client.GameObjects;
using DrawDepth = Content.Shared.DrawDepth.DrawDepth;
namespace Content.Client.MobState;
public sealed class DamageStateVisualizerSystem : VisualizerSystem<DamageStateVisualsComponent>
{
protected override void OnAppearanceChange(EntityUid uid, DamageStateVisualsComponent component, ref AppearanceChangeEvent args)
{
var sprite = args.Sprite;
if (sprite == null || !args.Component.TryGetData(DamageStateVisuals.State, out DamageState data))
{
return;
}
if (!component.States.TryGetValue(data, out var layers))
{
return;
}
if (component.Rotate)
{
sprite.NoRotation = data switch
{
DamageState.Critical => false,
DamageState.Dead => false,
_ => true
};
}
// Brain no worky rn so this was just easier.
foreach (var layer in sprite.AllLayers)
{
layer.Visible = false;
}
foreach (var (key, state) in layers)
{
sprite.LayerSetVisible(key, true);
sprite.LayerSetState(key, state);
}
// So they don't draw over mobs anymore
if (data == DamageState.Dead && sprite.DrawDepth > (int) DrawDepth.Items)
{
component.OriginalDrawDepth = sprite.DrawDepth;
sprite.DrawDepth = (int) DrawDepth.Items;
}
else if (component.OriginalDrawDepth != null)
{
sprite.DrawDepth = component.OriginalDrawDepth.Value;
component. OriginalDrawDepth = null;
}
}
}
| mit | C# |
bc67a80a51ef1a726d7292a424854479238b7358 | Add a check for api keys in query parameters. | DimensionDataCBUSydney/jab | jab/jab/TestExample.cs | jab/jab/TestExample.cs | using jab.Attributes;
using NSwag;
using Xunit;
using System.Linq;
namespace jab
{
public partial class TestExample
{
const string testDefinition = "samples/example.json";
[Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)]
public void DeleteMethodsShouldNotTakeFormEncodedData(
SwaggerService service,
string path,
SwaggerOperationMethod method,
SwaggerOperation operation)
{
if (method == SwaggerOperationMethod.Delete)
{
Assert.Null(operation.ActualConsumes);
} else
{
Assert.True(true);
}
}
/// <summary>
/// You should not ask for api keys in query parameters.
/// https://www.owasp.org/index.php/REST_Security_Cheat_Sheet#Authentication_and_session_management
/// </summary>
/// <param name="service"></param>
/// <param name="path"></param>
/// <param name="method"></param>
/// <param name="operation"></param>
[Theory, ParameterisedClassData(typeof(ApiOperations), testDefinition)]
public void NoApiKeysInParameters(
SwaggerService service,
string path,
SwaggerOperationMethod method,
SwaggerOperation operation)
{
if (operation.ActualParameters.Count > 0)
{
Assert.False(
operation.Parameters.Count(
c => ((c.Name.ToLower() == "apikey") || (c.Name.ToLower() == "api_key"))
&& c.Kind == SwaggerParameterKind.Query) > 0);
}
else
{
Assert.True(true);
}
}
}
}
| using jab.Attributes;
using NSwag;
using Xunit;
using System.Linq;
namespace jab
{
public class TestExample
{
[Theory, ParameterisedClassData(typeof(ApiOperations), "samples/example.json")]
public void DeleteMethodsShouldNotTakeFormEncodedData(
SwaggerService service,
string path,
SwaggerOperationMethod method,
SwaggerOperation operation)
{
if (method == SwaggerOperationMethod.Delete)
{
Assert.Null(operation.ActualConsumes);
} else
{
Assert.True(true);
}
}
}
}
| apache-2.0 | C# |
4dad1039b2581e6a782e3d2f6bd57796a0ae1515 | Add global keyboard shortcut listener | Schlechtwetterfront/snipp | Settings/Keyboard.cs | Settings/Keyboard.cs | using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Windows.Input;
using System.Windows.Interop;
namespace clipman.Settings
{
public static class Keyboard
{
public static Key ClearTextboxKey = Key.Escape;
}
public class KeyboardMonitor : IDisposable
{
private bool disposed = false;
private static class NativeMethods
{
[DllImport("User32.dll")]
public static extern bool RegisterHotKey(
[In] IntPtr hWnd,
[In] int id,
[In] uint fsModifiers,
[In] uint vk
);
[DllImport("User32.dll")]
public static extern bool UnregisterHotKey(
[In] IntPtr hWnd,
[In] int id
);
public const int WM_HOTKEY = 0x0312;
/// <summary>
/// To find message-only windows, specify HWND_MESSAGE in the hwndParent parameter of the FindWindowEx function.
/// </summary>
public static IntPtr HWND_MESSAGE = new IntPtr(-3);
}
public class HotkeyEventArgs : EventArgs
{
public int HotkeyId
{
get;
set;
}
}
private HwndSource hwndSource = new HwndSource(0, 0, 0, 0, 0, 0, 0, null, NativeMethods.HWND_MESSAGE);
private List<int> hotkeyIds = new List<int>();
public KeyboardMonitor()
{
hwndSource.AddHook(WndProc);
}
public int AddHotkey(int modifier, int key)
{
int id = hotkeyIds.Count + 9000;
hotkeyIds.Add(id);
NativeMethods.RegisterHotKey(hwndSource.Handle, id, (uint)modifier, (uint)key);
return id;
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == NativeMethods.WM_HOTKEY)
{
Utility.Logging.Log("WM_HOTKEY");
if (hotkeyIds.Contains(wParam.ToInt32()))
{
handled = true;
var args = new HotkeyEventArgs();
args.HotkeyId = wParam.ToInt32();
KeyPressed?.Invoke(this, args);
}
}
return IntPtr.Zero;
}
public void Dispose()
{
if (!disposed)
{
foreach (var id in hotkeyIds) {
NativeMethods.UnregisterHotKey(hwndSource.Handle, id);
}
}
}
public event EventHandler<HotkeyEventArgs> KeyPressed;
}
}
| using System.Windows.Input;
namespace clipman.Settings
{
public static class Keyboard
{
public static Key ClearTextboxKey = Key.Escape;
}
}
| apache-2.0 | C# |
1f85d83a1727e756bee33f169aadfbf333ad8278 | Fix IConfigurationSectionHandler signature | gboucher90/system-configuration-netcore,gboucher90/system-configuration-netcore | src/System.Configuration/System.Configuration/IConfigurationSectionHandler.cs | src/System.Configuration/System.Configuration/IConfigurationSectionHandler.cs | //
// System.Configuration.IConfigurationSectionHandler.cs
//
// Author:
// Christopher Podurgiel ([email protected])
//
// (C) Chris Podurgiel
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Xml;
namespace System.Configuration
{
/// <summary>
/// Summary description for IConfigurationSectionHandler.
/// </summary>
public interface IConfigurationSectionHandler
{
/// <summary>
/// Creates a new configuration handler and adds the specified configuration object to the collection.
/// </summary>
/// <param name="parent">Composed from the configuration settings in a corresponding parent configuration section.</param>
/// <param name="configContext">
/// Provides access to the virtual path for which the configuration section handler computes
/// configuration values. Normally this parameter is reserved and is null.
/// </param>
/// <param name="section">
/// The XML node that contains the configuration information to be handled. section provides direct
/// access to the XML contents of the configuration section.
/// </param>
/// <returns></returns>
object Create(object parent, object configContext, XmlNode section);
}
} | //
// System.Configuration.IConfigurationSectionHandler.cs
//
// Author:
// Christopher Podurgiel ([email protected])
//
// (C) Chris Podurgiel
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Configuration
{
/// <summary>
/// Summary description for IConfigurationSectionHandler.
/// </summary>
public interface IConfigurationSectionHandler
{
/// <summary>
/// Creates a new configuration handler and adds the specified configuration object to the collection.
/// </summary>
/// <param name="parent">Composed from the configuration settings in a corresponding parent configuration section.</param>
/// <param name="configContext">
/// Provides access to the virtual path for which the configuration section handler computes
/// configuration values. Normally this parameter is reserved and is null.
/// </param>
/// <param name="section">
/// The XML node that contains the configuration information to be handled. section provides direct
/// access to the XML contents of the configuration section.
/// </param>
/// <returns></returns>
object Create(object parent, object configContext, object section);
}
} | mit | C# |
763bb82b93d47135dbd25b69a76e2f664abf8bf1 | Fix credentials error | joelverhagen/tostorage | ToStorage/Program.cs | ToStorage/Program.cs | using System;
using System.Threading.Tasks;
using CommandLine;
using Knapcode.ToStorage.Core.AzureBlobStorage;
namespace Knapcode.ToStorage
{
class Program
{
static int Main(string[] args)
{
return MainAsync(args).Result;
}
public static async Task<int> MainAsync(string[] args)
{
// parse options
var result = Parser.Default.ParseArguments<AzureBlobStorage.Options>(args);
if (result.Tag == ParserResultType.NotParsed)
{
return 1;
}
var options = result.MapResult(o => o, e => null);
if ((options.Account == null || options.Key == null) && options.ConnectionString == null)
{
Console.WriteLine("Either a connection string must be specified, or the account and key.");
return 1;
}
// build the implementation models
var client = new Client();
using (var stdin = Console.OpenStandardInput())
{
var request = new UploadRequest
{
Container = options.Container,
ContentType = options.ContentType,
PathFormat = options.PathFormat,
UpdateLatest = options.UpdateLatest,
Stream = stdin,
Trace = Console.Out
};
// upload
if (options.ConnectionString != null)
{
await client.UploadAsync(options.ConnectionString, request).ConfigureAwait(false);
}
else
{
await client.UploadAsync(options.Account, options.Key, request).ConfigureAwait(false);
}
}
return 0;
}
}
}
| using System;
using System.Threading.Tasks;
using CommandLine;
using Knapcode.ToStorage.Core.AzureBlobStorage;
namespace Knapcode.ToStorage
{
class Program
{
static int Main(string[] args)
{
return MainAsync(args).Result;
}
public static async Task<int> MainAsync(string[] args)
{
// parse options
var result = Parser.Default.ParseArguments<AzureBlobStorage.Options>(args);
if (result.Tag == ParserResultType.NotParsed)
{
return 1;
}
var options = result.MapResult(o => o, e => null);
if ((options.Account == null && options.Key == null) || options.ConnectionString == null)
{
Console.WriteLine("Either a connection string must be specified, or the account and key.");
return 1;
}
// build the implementation models
var client = new Client();
using (var stdin = Console.OpenStandardInput())
{
var request = new UploadRequest
{
Container = options.Container,
ContentType = options.ContentType,
PathFormat = options.PathFormat,
UpdateLatest = options.UpdateLatest,
Stream = stdin,
Trace = Console.Out
};
// upload
if (options.ConnectionString != null)
{
await client.UploadAsync(options.ConnectionString, request).ConfigureAwait(false);
}
else
{
await client.UploadAsync(options.Account, options.Key, request).ConfigureAwait(false);
}
}
return 0;
}
}
}
| mit | C# |
0de2411bcb48b8ba0d37f0435d64080a19381c74 | rename test according to naming convention | dfch/biz.dfch.CS.System.Utilities | src/biz.dfch.CS.System.Utilities.Tests/Contracts/Endpoint/IODataEndpointDataTest.cs | src/biz.dfch.CS.System.Utilities.Tests/Contracts/Endpoint/IODataEndpointDataTest.cs | /**
* Copyright 2015 Marc Rufer, d-fens GmbH
*
* 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 biz.dfch.CS.Utilities.Contracts.Endpoint;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace biz.dfch.CS.Utilities.Tests.Contracts.Endpoint
{
[TestClass]
public class IODataEndpointDataTest : IODataEndpointData
{
private ServerRole _serverRole;
public ServerRole ServerRole
{
get
{
return _serverRole;
}
}
[TestMethod]
public void ServerRoleReturnsName()
{
_serverRole = ServerRole.WORKER;
Assert.AreEqual(ServerRole.WORKER, this.ServerRole);
}
[TestMethod]
public void DefaultPriorityIsZero()
{
// Arrange
var exptectedPriority = 0;
var endpointData = new ODataEndpointDataWithPriority();
// Act
var result = endpointData.Priority;
// Assert
Assert.AreEqual(exptectedPriority, result);
}
[TestMethod]
public void GetPriorityReturnsPriority()
{
// Arrange
var exptectedPriority = 42;
var endpointData = new ODataEndpointDataWithPriority(exptectedPriority);
// Act
var result = endpointData.Priority;
// Assert
Assert.AreEqual(exptectedPriority, result);
}
}
}
| /**
* Copyright 2015 Marc Rufer, d-fens GmbH
*
* 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 biz.dfch.CS.Utilities.Contracts.Endpoint;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace biz.dfch.CS.Utilities.Tests.Contracts.Endpoint
{
[TestClass]
public class IODataEndpointDataTest : IODataEndpointData
{
private ServerRole _serverRole;
public ServerRole ServerRole
{
get
{
return _serverRole;
}
}
[TestMethod]
public void IODataEndpointDataServerRoleReturnsName()
{
_serverRole = ServerRole.WORKER;
Assert.AreEqual(ServerRole.WORKER, this.ServerRole);
}
}
}
| apache-2.0 | C# |
3e271c0875d8b3003ab9d5e1831aaff9593e55d9 | Fix test which relies on reflection over the code fixes assembly | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test/ExportCodeFixProviderAttributeNameTest.cs | StyleCop.Analyzers/StyleCop.Analyzers.Test/ExportCodeFixProviderAttributeNameTest.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Analyzers.SpacingRules;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Xunit;
public class ExportCodeFixProviderAttributeNameTest
{
public static IEnumerable<object[]> CodeFixProviderTypeData
{
get
{
var codeFixProviders = typeof(TokenSpacingCodeFixProvider)
.Assembly
.GetTypes()
.Where(t => typeof(CodeFixProvider).IsAssignableFrom(t));
return codeFixProviders.Select(x => new[] { x });
}
}
[Theory]
[MemberData(nameof(CodeFixProviderTypeData))]
public void TestExportCodeFixProviderAttribute(Type codeFixProvider)
{
var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault();
Assert.NotNull(exportCodeFixProviderAttribute);
Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name);
Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length);
Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]);
}
}
} | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using StyleCop.Analyzers.ReadabilityRules;
using Xunit;
public class ExportCodeFixProviderAttributeNameTest
{
public static IEnumerable<object[]> CodeFixProviderTypeData
{
get
{
var codeFixProviders = typeof(SA1110OpeningParenthesisMustBeOnDeclarationLine)
.Assembly
.GetTypes()
.Where(t => typeof(CodeFixProvider).IsAssignableFrom(t));
return codeFixProviders.Select(x => new[] { x });
}
}
[Theory]
[MemberData(nameof(CodeFixProviderTypeData))]
public void TestExportCodeFixProviderAttribute(Type codeFixProvider)
{
var exportCodeFixProviderAttribute = codeFixProvider.GetCustomAttributes<ExportCodeFixProviderAttribute>(false).FirstOrDefault();
Assert.NotNull(exportCodeFixProviderAttribute);
Assert.Equal(codeFixProvider.Name, exportCodeFixProviderAttribute.Name);
Assert.Equal(1, exportCodeFixProviderAttribute.Languages.Length);
Assert.Equal(LanguageNames.CSharp, exportCodeFixProviderAttribute.Languages[0]);
}
}
} | mit | C# |
89ea9b73d62e94fb4cabb4e2d584e49aba7deb8a | Make the rectangle a member and centre it. | pleroy/Principia,eggrobin/Principia,pleroy/Principia,eggrobin/Principia,mockingbirdnest/Principia,pleroy/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,mockingbirdnest/Principia,eggrobin/Principia,pleroy/Principia | ksp_plugin_adapter/dialog.cs | ksp_plugin_adapter/dialog.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace principia {
namespace ksp_plugin_adapter {
internal class Dialog : IConfigNode {
public void Show(String message) {
UnityEngine.GUI.skin = null;
rectangle_ = UnityEngine.GUILayout.Window(
id : this.GetHashCode(),
screenRect : rectangle_,
func : (int id) => {
using (new VerticalLayout())
{
UnityEngine.GUILayout.TextArea(message);
}
UnityEngine.GUI.DragWindow();
},
text : "Principia");
WindowUtilities.EnsureOnScreen(ref rectangle_);
}
void IConfigNode.Load(ConfigNode node) {
String x_value = node.GetAtMostOneValue("x");
if (x_value != null) {
rectangle_.x = System.Convert.ToSingle(x_value);
}
String y_value = node.GetAtMostOneValue("y");
if (y_value != null) {
rectangle_.y = System.Convert.ToSingle(y_value);
}
}
void IConfigNode.Save(ConfigNode node) {
node.SetValue("x", rectangle_.x, createIfNotFound: true);
node.SetValue("y", rectangle_.y, createIfNotFound: true);
}
private static readonly float min_width_ = 500;
private UnityEngine.Rect rectangle_ =
new UnityEngine.Rect(x : (UnityEngine.Screen.width - min_width_) / 2,
y : UnityEngine.Screen.height / 3,
width : min_width_,
height :0);
}
} // namespace ksp_plugin_adapter
} // namespace principia
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace principia {
namespace ksp_plugin_adapter {
internal class Dialog : IConfigNode {
public void Show(String message) {
UnityEngine.Rect dialog_window_rectangle = UnityEngine.Rect.zero;
UnityEngine.GUI.skin = null;
dialog_window_rectangle.xMin = x_;
dialog_window_rectangle.yMin = y_;
dialog_window_rectangle = UnityEngine.GUILayout.Window(
id : this.GetHashCode(),
screenRect : dialog_window_rectangle,
func : (int id) => {
using (new VerticalLayout())
{
UnityEngine.GUILayout.TextArea(message);
}
UnityEngine.GUI.DragWindow(
position: new UnityEngine.Rect(x : 0f,
y : 0f,
width : 10000f,
height : 10000f));
},
text: "Principia",
options: UnityEngine.GUILayout.MinWidth(500));
WindowUtilities.EnsureOnScreen(ref dialog_window_rectangle);
x_ = dialog_window_rectangle.xMin;
y_ = dialog_window_rectangle.yMin;
}
void IConfigNode.Load(ConfigNode node) {
String x_value = node.GetAtMostOneValue("x");
if (x_value != null) {
x_ = System.Convert.ToSingle(x_value);
}
String y_value = node.GetAtMostOneValue("y");
if (y_value != null) {
y_ = System.Convert.ToSingle(y_value);
}
}
void IConfigNode.Save(ConfigNode node) {
node.SetValue("x", x_, createIfNotFound: true);
node.SetValue("y", y_, createIfNotFound: true);
}
private Single x_ = UnityEngine.Screen.width / 2;
private Single y_ = UnityEngine.Screen.height / 3;
}
} // namespace ksp_plugin_adapter
} // namespace principia
| mit | C# |
74e9bc8c2c2fe345634b2b0ad9c0f3f4d19dece8 | Increase timeout for Timer tests | noobot/SlackConnector | tests/SlackConnector.Tests.Unit/Connections/Monitoring/TimerTests.cs | tests/SlackConnector.Tests.Unit/Connections/Monitoring/TimerTests.cs | using System;
using System.Threading;
using Xunit;
using Should;
using Timer = SlackConnector.Connections.Monitoring.Timer;
namespace SlackConnector.Tests.Unit.Connections.Monitoring
{
public class TimerTests
{
[Fact]
public void should_run_task_at_least_5_times()
{
// given
var timer = new Timer();
int calls = 0;
DateTime timeout = DateTime.Now.AddSeconds(20);
// when
timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1));
while (calls < 5 && DateTime.Now < timeout)
{
Thread.Sleep(TimeSpan.FromMilliseconds(5));
}
// then
calls.ShouldBeGreaterThanOrEqualTo(5);
}
[Fact]
public void should_throw_exception_if_a_second_timer_is_created()
{
// given
var timer = new Timer();
timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1));
// when + then
Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1)));
}
}
} | using System;
using System.Threading;
using Xunit;
using Should;
using Timer = SlackConnector.Connections.Monitoring.Timer;
namespace SlackConnector.Tests.Unit.Connections.Monitoring
{
public class TimerTests
{
[Fact]
public void should_run_task_at_least_5_times()
{
// given
var timer = new Timer();
int calls = 0;
DateTime timeout = DateTime.Now.AddSeconds(4);
// when
timer.RunEvery(() => calls++, TimeSpan.FromMilliseconds(1));
while (calls < 5 && DateTime.Now < timeout)
{
Thread.Sleep(TimeSpan.FromMilliseconds(5));
}
// then
calls.ShouldBeGreaterThanOrEqualTo(5);
}
[Fact]
public void should_throw_exception_if_a_second_timer_is_created()
{
// given
var timer = new Timer();
timer.RunEvery(() => { }, TimeSpan.FromMilliseconds(1));
// when + then
Assert.Throws<Timer.TimerAlreadyInitialisedException>(() => timer.RunEvery(() => { }, TimeSpan.FromMinutes(1)));
}
}
} | mit | C# |
3187094f54c0413c15135bda9cd04b803bef9deb | Add try catch for GetTextFromAllPages and write error message to text file. | McFunston/PDFDump | PDFDump/Program.cs | PDFDump/Program.cs | using System;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace PDFDump
{
class Program
{
static void Main(string[] args)
{
ProcessPDFs(GetPDFList());
//string fileName;
//fileName = @"Resume_MicaFunston.pdf";
//var results = GetTextFromAllPages(fileName);
//WriteText(fileName, results);
}
public static List<string> GetPDFList()
{
List<String> PDFs = new List<string>();
var folder = new DirectoryInfo(System.IO.Directory.GetCurrentDirectory());
foreach (var fi in folder.EnumerateFiles("*.pdf"))
{
PDFs.Add(fi.Name);
}
return PDFs;
}
public static void ProcessPDFs(List<string> PDFList)
{
foreach(var pdf in PDFList)
{
var txt = GetTextFromAllPages(pdf);
WriteText(pdf, txt);
}
}
public static void WriteText(string fileName, string textToWrite)
{
string txtFile = fileName.Remove(fileName.Length - 4);
txtFile = txtFile + ".txt";
var file = System.IO.File.CreateText(@txtFile);
file.Write(textToWrite);
file.Dispose();
}
public static string GetTextFromAllPages(String pdfPath)
{
PdfReader reader = new PdfReader(pdfPath);
StringWriter output = new StringWriter();
try
{
for (int i = 1; i <= reader.NumberOfPages; i++)
output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
return output.ToString();
}
catch (Exception e)
{
output.Write($"{pdfPath} was not able to be processed. Here is the error {e.Message}");
return output.ToString();
}
}
}
}
| using System;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System.Text;
using System.IO;
using System.Collections.Generic;
namespace PDFDump
{
class Program
{
static void Main(string[] args)
{
ProcessPDFs(GetPDFList());
//string fileName;
//fileName = @"Resume_MicaFunston.pdf";
//var results = GetTextFromAllPages(fileName);
//WriteText(fileName, results);
}
public static List<string> GetPDFList()
{
List<String> PDFs = new List<string>();
var folder = new DirectoryInfo(System.IO.Directory.GetCurrentDirectory());
foreach (var fi in folder.EnumerateFiles("*.pdf"))
{
PDFs.Add(fi.Name);
}
return PDFs;
}
public static void ProcessPDFs(List<string> PDFList)
{
foreach(var pdf in PDFList)
{
var txt = GetTextFromAllPages(pdf);
WriteText(pdf, txt);
}
}
public static void WriteText(string fileName, string textToWrite)
{
string txtFile = fileName.Remove(fileName.Length - 4);
txtFile = txtFile + ".txt";
var file = System.IO.File.CreateText(@txtFile);
file.Write(textToWrite);
file.Dispose();
}
public static string GetTextFromAllPages(String pdfPath)
{
PdfReader reader = new PdfReader(pdfPath);
StringWriter output = new StringWriter();
for (int i = 1; i <= reader.NumberOfPages; i++)
output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
return output.ToString();
}
}
}
| mit | C# |
aa27466f7f827dc91d4ae21beb1c41673c4388d5 | use NRT | shyamnamboodiripad/roslyn,physhi/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,wvdd007/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,KevinRansom/roslyn,physhi/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,diryboy/roslyn,diryboy/roslyn,weltkante/roslyn,weltkante/roslyn,AmadeusW/roslyn,diryboy/roslyn,dotnet/roslyn,KevinRansom/roslyn,dotnet/roslyn,mavasani/roslyn,sharwell/roslyn,wvdd007/roslyn,eriawan/roslyn,eriawan/roslyn,weltkante/roslyn,mavasani/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn | src/Features/Core/Portable/CodeCleanup/ICodeCleanupService.cs | src/Features/Core/Portable/CodeCleanup/ICodeCleanupService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
internal interface ICodeCleanupService : ILanguageService
{
Task<Document> CleanupAsync(Document document, EnabledDiagnosticOptions enabledDiagnostics, IProgressTracker progressTracker, CancellationToken cancellationToken);
EnabledDiagnosticOptions GetAllDiagnostics();
}
}
| // 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.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.CodeCleanup
{
internal interface ICodeCleanupService : ILanguageService
{
Task<Document> CleanupAsync(Document document, EnabledDiagnosticOptions enabledDiagnostics, IProgressTracker progressTracker, CancellationToken cancellationToken);
EnabledDiagnosticOptions GetAllDiagnostics();
}
}
| mit | C# |
ce006661bbe551aecef6151deda82aad47a6fc77 | Allow replacing an existing TTimestampParser | MikaelGRA/InfluxDB.Client | src/Vibrant.InfluxDB.Client/DefaultTimestampParserRegistry.cs | src/Vibrant.InfluxDB.Client/DefaultTimestampParserRegistry.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vibrant.InfluxDB.Client.Resources;
namespace Vibrant.InfluxDB.Client
{
internal class DefaultTimestampParserRegistry : ITimestampParserRegistry
{
private readonly Dictionary<Type, object> _timestampParsers;
public DefaultTimestampParserRegistry()
{
_timestampParsers = new Dictionary<Type, object>();
AddOrReplace<DateTime, UtcDateTimeParser>( new UtcDateTimeParser() );
AddOrReplace<DateTime?, NullableUtcDateTimeParser>( new NullableUtcDateTimeParser() );
AddOrReplace<DateTimeOffset, LocalDateTimeOffsetParser>( new LocalDateTimeOffsetParser() );
AddOrReplace<DateTimeOffset?, NullableLocalDateTimeOffsetParser>( new NullableLocalDateTimeOffsetParser() );
}
public void AddOrReplace<TTimestamp, TTimestampParser>( TTimestampParser timestampParser ) where TTimestampParser : ITimestampParser<TTimestamp>
{
_timestampParsers[ typeof( TTimestamp ) ] = timestampParser;
}
public bool Contains<TTimestamp>()
{
return _timestampParsers.ContainsKey( typeof( TTimestamp ) );
}
public ITimestampParser<TTimestamp> FindTimestampParser<TTimestamp>()
{
object obj;
if( _timestampParsers.TryGetValue( typeof( TTimestamp ), out obj ) && obj is ITimestampParser<TTimestamp> )
{
var timestampParser = (ITimestampParser<TTimestamp>)obj;
return timestampParser;
}
throw new InfluxException( string.Format( Errors.CouldNotFindTimestampParser, typeof( TTimestamp ).FullName ) );
}
public void Remove<TTimestamp>()
{
_timestampParsers.Remove( typeof( TTimestamp ) );
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vibrant.InfluxDB.Client.Resources;
namespace Vibrant.InfluxDB.Client
{
internal class DefaultTimestampParserRegistry : ITimestampParserRegistry
{
private readonly Dictionary<Type, object> _timestampParsers;
public DefaultTimestampParserRegistry()
{
_timestampParsers = new Dictionary<Type, object>();
AddOrReplace<DateTime, UtcDateTimeParser>( new UtcDateTimeParser() );
AddOrReplace<DateTime?, NullableUtcDateTimeParser>( new NullableUtcDateTimeParser() );
AddOrReplace<DateTimeOffset, LocalDateTimeOffsetParser>( new LocalDateTimeOffsetParser() );
AddOrReplace<DateTimeOffset?, NullableLocalDateTimeOffsetParser>( new NullableLocalDateTimeOffsetParser() );
}
public void AddOrReplace<TTimestamp, TTimestampParser>( TTimestampParser timestampParser ) where TTimestampParser : ITimestampParser<TTimestamp>
{
_timestampParsers.Add( typeof( TTimestamp ), timestampParser );
}
public bool Contains<TTimestamp>()
{
return _timestampParsers.ContainsKey( typeof( TTimestamp ) );
}
public ITimestampParser<TTimestamp> FindTimestampParser<TTimestamp>()
{
object obj;
if( _timestampParsers.TryGetValue( typeof( TTimestamp ), out obj ) && obj is ITimestampParser<TTimestamp> )
{
var timestampParser = (ITimestampParser<TTimestamp>)obj;
return timestampParser;
}
throw new InfluxException( string.Format( Errors.CouldNotFindTimestampParser, typeof( TTimestamp ).FullName ) );
}
public void Remove<TTimestamp>()
{
_timestampParsers.Remove( typeof( TTimestamp ) );
}
}
}
| mit | C# |
1da4b6c765c0ea29b87a609fce0e8bfe0627bb32 | Fix build post test framework merge | adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,elastic/elasticsearch-net,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net | src/Tests/Cluster/ClusterAllocationExplain/ClusterAllocationExplainApiTests.cs | src/Tests/Cluster/ClusterAllocationExplain/ClusterAllocationExplainApiTests.cs | using System;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using Xunit;
namespace Tests.Cluster.ClusterAllocationExplain
{
[Collection(TypeOfCluster.ReadOnly)]
public class ClusterAllocationExplainApiTests : ApiIntegrationTestBase<IClusterAllocationExplainResponse, IClusterAllocationExplainRequest, ClusterAllocationExplainDescriptor, ClusterAllocationExplainRequest>
{
public ClusterAllocationExplainApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override LazyResponses ClientUsage() => Calls(
fluent: (client, f) => client.ClusterAllocationExplain(f),
fluentAsync: (client, f) => client.ClusterAllocationExplainAsync(f),
request: (client, r) => client.ClusterAllocationExplain(r),
requestAsync: (client, r) => client.ClusterAllocationExplainAsync(r)
);
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override HttpMethod HttpMethod => HttpMethod.POST;
protected override string UrlPath => "/_cluster/allocation/explain?include_yes_decisions=true";
protected override object ExpectJson =>
new
{
index = "project",
shard = 0,
primary = true
};
protected override Func<ClusterAllocationExplainDescriptor, IClusterAllocationExplainRequest> Fluent => s => s
.Index<Project>()
.Shard(0)
.Primary()
.IncludeYesDecisions();
protected override ClusterAllocationExplainRequest Initializer =>
new ClusterAllocationExplainRequest
{
Index = typeof(Project),
Shard = 0,
Primary = true,
IncludeYesDecisions = true
};
protected override void ExpectResponse(IClusterAllocationExplainResponse response)
{
response.Shard.Primary.Should().BeTrue();
response.Shard.Id.Should().Be(0);
response.Shard.IndexUniqueId.Should().NotBeNullOrEmpty();
response.Assigned.Should().BeTrue();
foreach (var node in response.Nodes)
{
var explanation = node.Value;
explanation.NodeName.Should().NotBeNullOrEmpty();
explanation.Weight.Should().BeGreaterOrEqualTo(0);
explanation.NodeAttributes.Should().NotBeEmpty();
explanation.FinalDecision.Should().NotBeNullOrEmpty();
explanation.Decisions.Should().NotBeNullOrEmpty();
}
}
}
}
| using System;
using Elasticsearch.Net;
using FluentAssertions;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using Xunit;
namespace Tests.Cluster.ClusterAllocationExplain
{
[Collection(IntegrationContext.ReadOnly)]
public class ClusterAllocationExplainApiTests : ApiIntegrationTestBase<IClusterAllocationExplainResponse, IClusterAllocationExplainRequest, ClusterAllocationExplainDescriptor, ClusterAllocationExplainRequest>
{
public ClusterAllocationExplainApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }
protected override LazyResponses ClientUsage() => Calls(
fluent: (client, f) => client.ClusterAllocationExplain(f),
fluentAsync: (client, f) => client.ClusterAllocationExplainAsync(f),
request: (client, r) => client.ClusterAllocationExplain(r),
requestAsync: (client, r) => client.ClusterAllocationExplainAsync(r)
);
protected override bool ExpectIsValid => true;
protected override int ExpectStatusCode => 200;
protected override HttpMethod HttpMethod => HttpMethod.POST;
protected override string UrlPath => "/_cluster/allocation/explain?include_yes_decisions=true";
protected override object ExpectJson =>
new
{
index = "project",
shard = 0,
primary = true
};
protected override Func<ClusterAllocationExplainDescriptor, IClusterAllocationExplainRequest> Fluent => s => s
.Index<Project>()
.Shard(0)
.Primary()
.IncludeYesDecisions();
protected override ClusterAllocationExplainRequest Initializer =>
new ClusterAllocationExplainRequest
{
Index = typeof(Project),
Shard = 0,
Primary = true,
IncludeYesDecisions = true
};
protected override void ExpectResponse(IClusterAllocationExplainResponse response)
{
response.Shard.Primary.Should().BeTrue();
response.Shard.Id.Should().Be(0);
response.Shard.IndexUniqueId.Should().NotBeNullOrEmpty();
response.Assigned.Should().BeTrue();
foreach (var node in response.Nodes)
{
var explanation = node.Value;
explanation.NodeName.Should().NotBeNullOrEmpty();
explanation.Weight.Should().BeGreaterOrEqualTo(0);
explanation.NodeAttributes.Should().NotBeEmpty();
explanation.FinalDecision.Should().NotBeNullOrEmpty();
explanation.Decisions.Should().NotBeNullOrEmpty();
}
}
}
}
| apache-2.0 | C# |
8099de0f7a31c9674e6c061af54558afd3478409 | Remove test code | rockfordlhotka/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla | Samples/RazorPagesExample/RazorPagesExample/Program.cs | Samples/RazorPagesExample/RazorPagesExample/Program.cs | using Csla.Configuration;
using Csla.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages().AddMvcOptions(options =>
{
options.ModelBinderProviders.Insert(0, new CslaModelBinderProvider());
});
builder.Services.AddHttpContextAccessor();
builder.Services.AddCsla(options => options.AddAspNetCore());
builder.Services.AddTransient(typeof(DataAccess.IPersonDal), typeof(DataAccess.PersonDal));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
| using Csla.Configuration;
using Csla.Web.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorPages().AddMvcOptions(options =>
{
options.ModelBinderProviders.Insert(0, new CslaModelBinderProvider());
});
builder.Services.AddHttpContextAccessor();
//builder.Services.AddTransient(typeof(Csla.DataPortalClient.IDataPortalProxy), typeof(Csla.Channels.Test.TestProxy));
builder.Services.AddCsla(options => options.AddAspNetCore());
builder.Services.AddTransient(typeof(DataAccess.IPersonDal), typeof(DataAccess.PersonDal));
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapRazorPages();
app.Run();
| mit | C# |
24b81339b46db2cdcdbe15d6051e7ccfc979d002 | add color pulse on blade when active | thestonefox/SteamVR_Unity_Toolkit,phr00t/SteamVR_Unity_Toolkit,Fulby/VRTK,Innoactive/IA-unity-VR-toolkit-VRTK,gomez-addams/SteamVR_Unity_Toolkit,mbbmbbmm/SteamVR_Unity_Toolkit,jcrombez/SteamVR_Unity_Toolkit,pargee/SteamVR_Unity_Toolkit,nmccarty/htvr,TMaloteaux/SteamVR_Unity_Toolkit,gpvigano/VRTK,adamjweaver/VRTK,Blueteak/SteamVR_Unity_Toolkit,virror/VRTK,thacio/SteamVR_Unity_Toolkit,mimminito/SteamVR_Unity_Toolkit,gpvigano/SteamVR_Unity_Toolkit,red-horizon/VRTK,bengolds/SteamVR_Unity_Toolkit,mattboy64/SteamVR_Unity_Toolkit,thestonefox/VRTK | Assets/SteamVR_Unity_Toolkit/Examples/Resources/Scripts/LightSaber.cs | Assets/SteamVR_Unity_Toolkit/Examples/Resources/Scripts/LightSaber.cs | using UnityEngine;
using System.Collections;
using VRTK;
public class LightSaber : VRTK_InteractableObject
{
private bool beamActive = false;
private Vector2 beamLimits = new Vector2(0f, 1.2f);
private float currentBeamSize;
private float beamExtendSpeed = 0;
private GameObject blade;
private Color activeColor;
private Color targetColor;
private Color[] bladePhaseColors;
public override void StartUsing(GameObject usingObject)
{
base.StartUsing(usingObject);
beamExtendSpeed = 5f;
bladePhaseColors = new Color[2] { Color.blue, Color.cyan };
activeColor = bladePhaseColors[0];
targetColor = bladePhaseColors[1];
}
public override void StopUsing(GameObject usingObject)
{
base.StopUsing(usingObject);
beamExtendSpeed = -5f;
}
protected override void Start()
{
base.Start();
blade = this.transform.Find("Blade").gameObject;
currentBeamSize = beamLimits.x;
SetBeamSize();
}
protected override void Update()
{
currentBeamSize = Mathf.Clamp(blade.transform.localScale.y + (beamExtendSpeed * Time.deltaTime), beamLimits.x, beamLimits.y);
SetBeamSize();
PulseBeam();
}
private void SetBeamSize()
{
blade.transform.localScale = new Vector3(1f, currentBeamSize, 1f);
beamActive = (currentBeamSize >= beamLimits.y ? true : false);
}
private void PulseBeam()
{
if (beamActive)
{
Color bladeColor = Color.Lerp(activeColor, targetColor, Mathf.PingPong(Time.time, 1));
blade.transform.FindChild("Beam").GetComponent<MeshRenderer>().material.color = bladeColor;
if (bladeColor == targetColor)
{
var previouslyActiveColor = activeColor;
activeColor = targetColor;
targetColor = previouslyActiveColor;
}
}
}
}
| using UnityEngine;
using System.Collections;
using VRTK;
public class LightSaber : VRTK_InteractableObject
{
private bool beamActive = false;
private Vector2 beamLimits = new Vector2(0f, 1.2f);
private float currentBeamSize;
private float beamExtendSpeed = 0;
private GameObject blade;
public override void StartUsing(GameObject usingObject)
{
base.StartUsing(usingObject);
beamExtendSpeed = 5f;
}
public override void StopUsing(GameObject usingObject)
{
base.StopUsing(usingObject);
beamExtendSpeed = -5f;
}
protected override void Start()
{
base.Start();
blade = this.transform.Find("Blade").gameObject;
currentBeamSize = beamLimits.x;
SetBeamSize();
}
private void SetBeamSize()
{
blade.transform.localScale = new Vector3(1f, currentBeamSize, 1f);
beamActive = (currentBeamSize >= beamLimits.y ? true : false);
}
protected override void Update()
{
currentBeamSize = Mathf.Clamp(blade.transform.localScale.y + (beamExtendSpeed * Time.deltaTime), beamLimits.x, beamLimits.y);
SetBeamSize();
}
}
| mit | C# |
66497a32051e16f679734fe866d584462c8fa3f4 | Update the pointer test | jonathanvdc/ecsc | tests/cs/dereference/Dereference.cs | tests/cs/dereference/Dereference.cs | using System;
public static class Program
{
public static unsafe void Main()
{
int local = 10;
int* localPtr = &local;
*localPtr = 42;
Console.WriteLine(*localPtr);
void* voidPtr = localPtr;
localPtr = (int*)voidPtr;
Console.WriteLine(*localPtr);
}
} | using System;
public static class Program
{
public static unsafe void Main()
{
int local = 10;
int* localPtr = &local;
*localPtr = 42;
Console.WriteLine(*localPtr);
}
} | mit | C# |
89f02a9db67eb5ddebf4bbb184ea084610c2fb9e | Fix REST API url in documentation | TimeLog/TimeLogApiSdk,TimeLog/TimeLogApiSdk,TimeLog/TimeLogApiSdk | TimeLog.Api.Core.Documentation/Models/RestDocumentationHelpers/RestMethodDoc.cs | TimeLog.Api.Core.Documentation/Models/RestDocumentationHelpers/RestMethodDoc.cs | using System.Collections.Generic;
using System.Linq;
using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core;
namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers
{
public class RestMethodDoc
{
#region Variables
public IReadOnlyList<RestResponse> Responses { get; }
public IReadOnlyList<RestMethodParam> Params { get; }
public string MethodType { get; }
public RestTypeDoc Parent { get; }
public string OperationId { get; }
public string FullName { get; }
public string Summary { get; }
public string Name { get; }
#endregion
#region Constructor
public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action)
{
OperationId = action.OperationId;
FullName = $"https://app[x].timelog.com/[account name]/api{action.Name}";
Name = action.OperationId.Replace($"{action.Tags[0]}_", "");
Summary = action.Summary;
MethodType = action.MethodType.ToUpper();
Parent = restTypeDoc;
Params = MapToMethodParam(action.Parameters);
Responses = action.Responses.OrderBy(x => x.Code).ToList();
}
#endregion
#region Internal and Private Implementations
private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters)
{
return parameters
.Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef))
.ToList();
}
#endregion
}
} | using System.Collections.Generic;
using System.Linq;
using TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers.Core;
namespace TimeLog.Api.Core.Documentation.Models.RestDocumentationHelpers
{
public class RestMethodDoc
{
#region Variables
public IReadOnlyList<RestResponse> Responses { get; }
public IReadOnlyList<RestMethodParam> Params { get; }
public string MethodType { get; }
public RestTypeDoc Parent { get; }
public string OperationId { get; }
public string FullName { get; }
public string Summary { get; }
public string Name { get; }
#endregion
#region Constructor
public RestMethodDoc(RestTypeDoc restTypeDoc, RestAction action)
{
OperationId = action.OperationId;
FullName = $"http://app[x].timelog.com/[account name]{action.Name}";
Name = action.OperationId.Replace($"{action.Tags[0]}_", "");
Summary = action.Summary;
MethodType = action.MethodType.ToUpper();
Parent = restTypeDoc;
Params = MapToMethodParam(action.Parameters);
Responses = action.Responses.OrderBy(x => x.Code).ToList();
}
#endregion
#region Internal and Private Implementations
private IReadOnlyList<RestMethodParam> MapToMethodParam(IReadOnlyList<RestParameter> parameters)
{
return parameters
.Select(x => new RestMethodParam(x.Name, x.Description, x.Type, x.SchemaRestRef))
.ToList();
}
#endregion
}
} | mit | C# |
92376b30aa9d9330510e612d06137fdbdc4edaf7 | Add files via upload | ryan27968/expert_system | expert_system/Program.cs | expert_system/Program.cs | using System;
using System.IO;
namespace expert_system
{
class Program
{
static void Main(string[] args)
{
if (args.Length == 1)
{
string line, condition, result;
StreamReader file = new StreamReader(args[0]);
Rules rule_obj = new Rules();
while ((line = file.ReadLine()) != null)
{
condition = line.Substring(0, line.IndexOf("=>"));
result = line.Substring(line.IndexOf("=>"));
rule_obj.add(condition, result);
}
}
}
}
}
| using System;
namespace expert_system
{
class Program
{
static void Main(string[] args)
{
foreach(var str in args)
Console.WriteLine(str);
}
}
}
| mit | C# |
73bd78e4180b144787703190ab660b2318bdd8a6 | add tests for HealthCheckExtensions | lvermeulen/Nanophone | test/Nanophone.RegistryHost.ConsulRegistry.Tests/HealthCheckExtensionsShould.cs | test/Nanophone.RegistryHost.ConsulRegistry.Tests/HealthCheckExtensionsShould.cs | using Consul;
using Xunit;
namespace Nanophone.RegistryHost.ConsulRegistry.Tests
{
public class HealthCheckExtensionsShould
{
[Fact]
public void IgnoreNullHealthCheck()
{
Assert.False(HealthCheckExtensions.NeedsStatusCheck(null));
}
[Fact]
public void IgnoreConsul()
{
var healthCheck = new HealthCheck { ServiceName = "consul" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreServicesWithoutServiceId()
{
var healthCheck = new HealthCheck { ServiceID = "" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreSystemHealthChecks()
{
var healthCheck = new HealthCheck { CheckID = "serfHealth" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreServicesInNodeMaintenance()
{
var healthCheck = new HealthCheck { CheckID = "_node_maintenance" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreServicesInMaintenance()
{
var healthCheck = new HealthCheck { CheckID = "_service_maintenance:" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void NotIgnoreNormalService()
{
var healthCheck = new HealthCheck
{
ServiceName = nameof(NotIgnoreNormalService),
ServiceID = nameof(NotIgnoreNormalService),
CheckID = nameof(NotIgnoreNormalService)
};
Assert.True(healthCheck.NeedsStatusCheck());
}
}
}
| using Consul;
using Xunit;
namespace Nanophone.RegistryHost.ConsulRegistry.Tests
{
public class HealthCheckExtensionsShould
{
[Fact]
public void IgnoreServicesWithoutServiceId()
{
var healthCheck = new HealthCheck { ServiceID = "" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreSystemHealthChecks()
{
var healthCheck = new HealthCheck { CheckID = "serfHealth" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreServicesInNodeMaintenance()
{
var healthCheck = new HealthCheck { CheckID = "_node_maintenance" };
Assert.False(healthCheck.NeedsStatusCheck());
}
[Fact]
public void IgnoreServicesInMaintenance()
{
var healthCheck = new HealthCheck { CheckID = "_service_maintenance:" };
Assert.False(healthCheck.NeedsStatusCheck());
}
}
}
| mit | C# |
bc3b2af39d5d391e3bf0c95a5514193e6853faf2 | Add rounded corners to timeline ticks display | smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu | osu.Game/Screens/Edit/Components/Timelines/Summary/Visualisations/PointVisualisation.cs | osu.Game/Screens/Edit/Components/Timelines/Summary/Visualisations/PointVisualisation.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. 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.Shapes;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations
{
/// <summary>
/// Represents a singular point on a timeline part.
/// </summary>
public class PointVisualisation : Circle
{
public const float MAX_WIDTH = 4;
public PointVisualisation(double startTime)
: this()
{
X = (float)startTime;
}
public PointVisualisation()
{
Origin = Anchor.TopCentre;
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.Y;
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
Width = MAX_WIDTH;
Height = 0.75f;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. 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.Shapes;
namespace osu.Game.Screens.Edit.Components.Timelines.Summary.Visualisations
{
/// <summary>
/// Represents a singular point on a timeline part.
/// </summary>
public class PointVisualisation : Box
{
public const float MAX_WIDTH = 4;
public PointVisualisation(double startTime)
: this()
{
X = (float)startTime;
}
public PointVisualisation()
{
Origin = Anchor.TopCentre;
RelativePositionAxes = Axes.X;
RelativeSizeAxes = Axes.Y;
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
Width = MAX_WIDTH;
Height = 0.75f;
}
}
}
| mit | C# |
3495d13efcfecf3e968a65f9c38b4812d94b6f00 | Mark the eight-byte-boundaries when dumping a message | Tragetaschen/DbusCore | src/Dbus/ExtensionMethods.cs | src/Dbus/ExtensionMethods.cs | using System;
using System.Buffers;
namespace Dbus
{
internal static class ExtensionMethods
{
public static void Dump(this ReadOnlySequence<byte> buffers)
{
var counter = 0;
foreach (var segment in buffers)
{
var buffer = segment.Span;
dump(buffer, ref counter);
}
Console.WriteLine();
}
public static void Dump(this Span<byte> memory)
{
var counter = 0;
dump(memory, ref counter);
Console.WriteLine();
}
private static void dump(this ReadOnlySpan<byte> buffer, ref int counter)
{
for (var i = 0; i < buffer.Length; ++i)
{
var isDigitOrAsciiLetter = false;
isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57;
isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90;
isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122;
if (isDigitOrAsciiLetter)
Console.Write($"{(char)buffer[i]} ");
else
Console.Write($"x{buffer[i]:X} ");
counter += 1;
if ((counter & 7) == 0)
Console.Write("| ");
}
}
}
}
| using System;
using System.Buffers;
namespace Dbus
{
internal static class ExtensionMethods
{
public static void Dump(this ReadOnlySequence<byte> buffers)
{
foreach (var segment in buffers)
{
var buffer = segment.Span;
dump(buffer);
}
Console.WriteLine();
}
public static void Dump(this Span<byte> memory)
{
dump(memory);
Console.WriteLine();
}
private static void dump(this ReadOnlySpan<byte> buffer)
{
for (var i = 0; i < buffer.Length; ++i)
{
var isDigitOrAsciiLetter = false;
isDigitOrAsciiLetter |= 48 <= buffer[i] && buffer[i] <= 57;
isDigitOrAsciiLetter |= 65 <= buffer[i] && buffer[i] <= 90;
isDigitOrAsciiLetter |= 97 <= buffer[i] && buffer[i] <= 122;
if (isDigitOrAsciiLetter)
Console.Write($"{(char)buffer[i]} ");
else
Console.Write($"x{buffer[i]:X} ");
}
}
}
}
| mit | C# |
c62b3668d081bdf8cff004f8f255991d0f7e0f5e | add byte[] extension ToDosString() tests | martinlindhe/Punku | PunkuTests/Extensions/ByteArrayExtensions.cs | PunkuTests/Extensions/ByteArrayExtensions.cs | using System;
using System.Text;
using NUnit.Framework;
using Punku;
[TestFixture]
[Category ("Extensions")]
public class Extensions_ByteArray
{
[Test]
public void DosString01 ()
{
byte[] x = { (byte)'a', (byte)'b', (byte)'c', (byte)'$' };
Assert.AreEqual (
x.ToDosString (),
"abc"
);
}
[Test]
public void DosString02 ()
{
byte[] x = { (byte)'$' };
Assert.AreEqual (
x.ToDosString (),
""
);
}
[Test]
public void DosString03 ()
{
byte[] x = { 0 };
Assert.AreEqual (
x.ToDosString (),
"\u0000"
);
}
[Test]
public void CString01 ()
{
byte[] x = { (byte)'a', (byte)'b', (byte)'c' };
Assert.AreEqual (
x.ToCString (),
"abc"
);
}
[Test]
public void CString02 ()
{
byte[] x = { (byte)'a', (byte)'b', (byte)'c', 0, (byte)'d' };
Assert.AreEqual (
x.ToCString (),
"abc"
);
}
[Test]
public void HexString01 ()
{
byte[] x = { 1, 2, 3 };
Assert.AreEqual (
x.ToHexString (),
"010203"
);
}
[Test]
public void HexString02 ()
{
byte[] x = { 1, 2, 3, 0, 4 };
Assert.AreEqual (
x.ToHexString (),
"0102030004"
);
}
}
| using System;
using System.Text;
using NUnit.Framework;
using Punku;
[TestFixture]
[Category ("Extensions")]
public class Extensions_ByteArray
{
[Test]
public void CString01 ()
{
byte[] x = { (byte)'a', (byte)'b', (byte)'c' };
Assert.AreEqual (
x.ToCString (),
"abc"
);
}
[Test]
public void CString02 ()
{
byte[] x = { (byte)'a', (byte)'b', (byte)'c', 0, (byte)'d' };
Assert.AreEqual (
x.ToCString (),
"abc"
);
}
[Test]
public void HexString01 ()
{
byte[] x = { 1, 2, 3 };
Assert.AreEqual (
x.ToHexString (),
"010203"
);
}
[Test]
public void HexString02 ()
{
byte[] x = { 1, 2, 3, 0, 4 };
Assert.AreEqual (
x.ToHexString (),
"0102030004"
);
}
}
| mit | C# |
1177220a1f90394e799f4f5258b168c2d3b3d67f | Fix GenFloat to have a range generator | Weingartner/SolidworksAddinFramework | SolidworksAddinFramework.FSCheck/GenFloat.cs | SolidworksAddinFramework.FSCheck/GenFloat.cs | using System;
using FsCheck;
using static LanguageExt.Prelude;
namespace WeinCadSW.Spec.FsCheck
{
/// <summary>
/// Different float generators
/// </summary>
public static class GenFloat
{
private static double fraction(int a, int b, int c) =>a + (double) b/ c;
public static Gen<double> Normal =>
Arb.Default.DoNotSizeInt32()
.Generator
.Three()
.Where(v=>v.Item3.Item!=0)
.Select(t=>fraction(t.Item1.Item, t.Item2.Item, t.Item3.Item));
private static Gen<double> _Range(double lower, double upper) =>
Normal
.Select(f => lower + (upper - lower)*Math.Abs(f)%1.0);
public static Gen<double> Range(double lower, double upper) =>
Gen.Frequency
(Tuple(1, Gen.Constant(lower)),
Tuple(1, Gen.Constant(lower + double.Epsilon)),
Tuple(1, Gen.Constant(upper - double.Epsilon)),
Tuple(1, Gen.Constant(upper)),
Tuple(20, GenFloat._Range(lower, upper))
);
}
} | using FsCheck;
namespace WeinCadSW.Spec.FsCheck
{
/// <summary>
/// Different float generators
/// </summary>
public static class GenFloat
{
public static Gen<double> Normal =>
Arb.Default.NormalFloat().Generator.Select(f=>f.Item);
}
} | mit | C# |
7406501f584f3f5c9ea8341e9102181a8330a7d1 | Update CurrencyHelper.cs | tiksn/TIKSN-Framework | TIKSN.Core/Finance/Helpers/CurrencyHelper.cs | TIKSN.Core/Finance/Helpers/CurrencyHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance.Helpers
{
internal static class CurrencyHelper
{
public static async Task<IEnumerable<ICurrencyConverter>> FilterConvertersAsync(
IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn,
CancellationToken cancellationToken) => await FilterConvertersAsync(converters, pair.BaseCurrency,
pair.CounterCurrency, asOn, cancellationToken).ConfigureAwait(false);
public static async Task<IEnumerable<ICurrencyConverter>> FilterConvertersAsync(
IEnumerable<ICurrencyConverter> converters, CurrencyInfo baseCurrency, CurrencyInfo counterCurrency,
DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = new List<ICurrencyConverter>();
foreach (var converter in converters)
{
var pairs = await converter.GetCurrencyPairsAsync(asOn, cancellationToken).ConfigureAwait(false);
if (pairs.Any(item => item.BaseCurrency == baseCurrency && item.CounterCurrency == counterCurrency))
{
filteredConverters.Add(converter);
}
}
return filteredConverters;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace TIKSN.Finance.Helpers
{
internal static class CurrencyHelper
{
public static async Task<IEnumerable<ICurrencyConverter>> FilterConverters(
IEnumerable<ICurrencyConverter> converters, CurrencyPair pair, DateTimeOffset asOn,
CancellationToken cancellationToken) => await FilterConverters(converters, pair.BaseCurrency,
pair.CounterCurrency, asOn, cancellationToken);
public static async Task<IEnumerable<ICurrencyConverter>> FilterConverters(
IEnumerable<ICurrencyConverter> converters, CurrencyInfo baseCurrency, CurrencyInfo counterCurrency,
DateTimeOffset asOn, CancellationToken cancellationToken)
{
var filteredConverters = new List<ICurrencyConverter>();
foreach (var converter in converters)
{
var pairs = await converter.GetCurrencyPairsAsync(asOn, cancellationToken);
if (pairs.Any(item => item.BaseCurrency == baseCurrency && item.CounterCurrency == counterCurrency))
{
filteredConverters.Add(converter);
}
}
return filteredConverters;
}
}
}
| mit | C# |
6e3379ae69a3bcc7466b1be5f9b8d2ad48d7d092 | Update GroupingRowsAndColumns.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET | Examples/CSharp/RowsColumns/Grouping/GroupingRowsAndColumns.cs | Examples/CSharp/RowsColumns/Grouping/GroupingRowsAndColumns.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.Grouping
{
public class GroupingRowsAndColumns
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Grouping first six rows (from 0 to 5) and making them hidden by passing true
worksheet.Cells.GroupRows(0, 5, true);
//Grouping first three columns (from 0 to 2) and making them hidden by passing true
worksheet.Cells.GroupColumns(0, 2, true);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.Grouping
{
public class GroupingRowsAndColumns
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Grouping first six rows (from 0 to 5) and making them hidden by passing true
worksheet.Cells.GroupRows(0, 5, true);
//Grouping first three columns (from 0 to 2) and making them hidden by passing true
worksheet.Cells.GroupColumns(0, 2, true);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
}
}
} | mit | C# |
77f6497d5c3062e6097d9578c9314bc2a60588a7 | Update to GroundOverlay size. | nuitsjp/Xamarin.Forms.GoogleMaps.Bindings | Sample/GoogleMaps.Bindings/GoogleMaps.Bindings/ViewModels/GroundOverlaysPageViewModel.cs | Sample/GoogleMaps.Bindings/GoogleMaps.Bindings/ViewModels/GroundOverlaysPageViewModel.cs | using System.Collections.ObjectModel;
using Xamarin.Forms;
using Xamarin.Forms.GoogleMaps;
namespace GoogleMaps.Bindings.ViewModels
{
public class GroundOverlaysPageViewModel : ViewModelBase
{
public ObservableCollection<GroundOverlay> GroundOverlays { get; set; }
public Command<MapClickedEventArgs> MapClickedCommand => new Command<MapClickedEventArgs>(
args =>
{
var icon = BitmapDescriptorFactory.FromBundle("image01.png");
var overlay = new GroundOverlay()
{
Bounds = new Bounds(args.Point, new Position(args.Point.Latitude + 0.01d, args.Point.Longitude + 0.01d)),
Icon = icon,
Transparency = 0.5f,
Tag = "THE GROUNDOVERLAY"
};
GroundOverlays.Add(overlay);
});
}
}
| using System.Collections.ObjectModel;
using Xamarin.Forms;
using Xamarin.Forms.GoogleMaps;
namespace GoogleMaps.Bindings.ViewModels
{
public class GroundOverlaysPageViewModel : ViewModelBase
{
public ObservableCollection<GroundOverlay> GroundOverlays { get; set; }
public Command<MapClickedEventArgs> MapClickedCommand => new Command<MapClickedEventArgs>(
args =>
{
var icon = BitmapDescriptorFactory.FromBundle("image01.png");
var overlay = new GroundOverlay()
{
Bounds = new Bounds(args.Point, new Position(args.Point.Latitude + 0.001d, args.Point.Longitude + 0.001d)),
Icon = icon,
Transparency = 0.5f,
Tag = "THE GROUNDOVERLAY"
};
GroundOverlays.Add(overlay);
});
}
}
| mit | C# |
1e6fe95987052dfb16eb38a294c39a7fb573229c | Add access tests for all nullable types. | Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet | Tests/IntegrationTests.Shared/AccessTests.cs | Tests/IntegrationTests.Shared/AccessTests.cs | /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System.IO;
using NUnit.Framework;
using Realms;
namespace IntegrationTests.Shared
{
[TestFixture]
public class AccessTests
{
protected string _databasePath;
protected Realm _realm;
[SetUp]
public void Setup()
{
_databasePath = Path.GetTempFileName();
_realm = Realm.GetInstance(_databasePath);
}
[TearDown]
public void TearDown()
{
_realm.Dispose();
}
[TestCase("NullableCharProperty", '0')]
[TestCase("NullableByteProperty", (byte)100)]
[TestCase("NullableInt16Property", (short)100)]
[TestCase("NullableInt32Property", 100)]
[TestCase("NullableInt64Property", 100L)]
[TestCase("NullableSingleProperty", 123.123f)]
[TestCase("NullableDoubleProperty", 123.123)]
[TestCase("NullableBooleanProperty", true)]
public void SetValueAndReplaceWithNull(string propertyName, object propertyValue)
{
AllTypesObject ato;
using (var transaction = _realm.BeginWrite())
{
ato = _realm.CreateObject<AllTypesObject>();
TestHelpers.SetPropertyValue(ato, propertyName, propertyValue);
transaction.Commit();
}
Assert.That(TestHelpers.GetPropertyValue(ato, propertyName), Is.EqualTo(propertyValue));
using (var transaction = _realm.BeginWrite())
{
TestHelpers.SetPropertyValue(ato, propertyName, null);
transaction.Commit();
}
Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null));
}
}
}
| /* Copyright 2015 Realm Inc - All Rights Reserved
* Proprietary and Confidential
*/
using System.IO;
using NUnit.Framework;
using Realms;
namespace IntegrationTests.Shared
{
[TestFixture]
public class AccessTests
{
protected string _databasePath;
protected Realm _realm;
[SetUp]
public void Setup()
{
_databasePath = Path.GetTempFileName();
_realm = Realm.GetInstance(_databasePath);
}
[TearDown]
public void TearDown()
{
_realm.Dispose();
}
[Test]
public void SetValueAndReplaceWithNull()
{
AllTypesObject ato;
using (var transaction = _realm.BeginWrite())
{
ato = _realm.CreateObject<AllTypesObject>();
TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", true);
transaction.Commit();
}
Assert.That(ato.NullableBooleanProperty, Is.EqualTo(true));
using (var transaction = _realm.BeginWrite())
{
TestHelpers.SetPropertyValue(ato, "NullableBooleanProperty", null);
transaction.Commit();
}
Assert.That(ato.NullableBooleanProperty, Is.EqualTo(null));
}
}
}
| apache-2.0 | C# |
a80df4cc9cd90ad3819707e35552abc3fe5d5ed1 | Remove unneeded locks | residuum/xwt,lytico/xwt,akrisiun/xwt,mono/xwt,directhex/xwt,sevoku/xwt,steffenWi/xwt,hamekoz/xwt,cra0zy/xwt,TheBrainTech/xwt,antmicro/xwt,mminns/xwt,mminns/xwt,hwthomas/xwt,iainx/xwt | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <[email protected]>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
System.Timers.Timer timer = new System.Timers.Timer (100);
public ProgressBarBackend ()
{
}
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
progressBar.Pulse ();
timer.Elapsed += Pulse;
Widget.Show ();
timer.Start ();
}
private void Pulse (object sender, System.Timers.ElapsedEventArgs args)
{
Application.Invoke (() => Widget.Pulse ());
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetFraction (double? fraction)
{
if (fraction == null)
{
timer.Start ();
Widget.Fraction = 0.1;
} else {
timer.Stop ();
Widget.Fraction = fraction.Value;
}
}
}
}
| //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <[email protected]>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
System.Timers.Timer timer = new System.Timers.Timer (100);
public ProgressBarBackend ()
{
}
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
progressBar.Pulse ();
lock(timer)
timer.Elapsed += Pulse;
Widget.Show ();
lock (timer)
timer.Start ();
}
private void Pulse (object sender, System.Timers.ElapsedEventArgs args)
{
Application.Invoke (() => Widget.Pulse ());
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetFraction (double? fraction)
{
if (fraction == null)
{
lock (timer)
timer.Start ();
Widget.Fraction = 0.1;
} else {
lock (timer)
timer.Stop ();
Widget.Fraction = fraction.Value;
}
}
}
}
| mit | C# |
4c634118e8d94d2674a05cdc6381c6e5dba42366 | Add Color custom display option for star ratings | davek17/SurveyMonkeyApi-v3,bcemmett/SurveyMonkeyApi-v3 | SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs | SurveyMonkey/Containers/QuestionDisplayOptionsCustomOptions.cs | using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; }
public int StepSize { get; set; }
public string Color { get; set; }
}
} | using Newtonsoft.Json;
using System.Collections.Generic;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class QuestionDisplayOptionsCustomOptions
{
public List<string> OptionSet { get; set; }
public int StartingPosition { get; set; }
public int StepSize { get; set; }
}
} | mit | C# |
32207b72fe872e82d545f065cfce1a52e5ffb0dd | Remove redundant case from switch statement | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices/Language/PesterDocumentSymbolProvider.cs | src/PowerShellEditorServices/Language/PesterDocumentSymbolProvider.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.PowerShell.EditorServices
{
internal class PesterDocumentSymbolProvider : DocumentSymbolProvider
{
protected override bool CanProvideFor(ScriptFile scriptFile)
{
return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase);
}
protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion)
{
var commandAsts = scriptFile.ScriptAst.FindAll(ast =>
{
switch ((ast as CommandAst)?.GetCommandName().ToLower())
{
case "describe":
case "context":
case "it":
return true;
default:
return false;
}
},
true);
return commandAsts.Select(ast => new SymbolReference(
SymbolType.Function,
ast.Extent,
scriptFile.FilePath,
scriptFile.GetLine(ast.Extent.StartLineNumber)));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.PowerShell.EditorServices
{
internal class PesterDocumentSymbolProvider : DocumentSymbolProvider
{
protected override bool CanProvideFor(ScriptFile scriptFile)
{
return scriptFile.FilePath.EndsWith("tests.ps1", StringComparison.OrdinalIgnoreCase);
}
protected override IEnumerable<SymbolReference> GetSymbolsImpl(ScriptFile scriptFile, Version psVersion)
{
var commandAsts = scriptFile.ScriptAst.FindAll(ast =>
{
switch ((ast as CommandAst)?.GetCommandName().ToLower())
{
case "describe":
case "context":
case "it":
return true;
case null:
default:
return false;
}
},
true);
return commandAsts.Select(ast => new SymbolReference(
SymbolType.Function,
ast.Extent,
scriptFile.FilePath,
scriptFile.GetLine(ast.Extent.StartLineNumber)));
}
}
}
| mit | C# |
103c916e219994ee3231946054332faed7dbe8da | Use timed observations 2 VM. | escape-llc/yet-another-chart-component | YetAnotherChartComponent/eScape.Yacc.Demo/Pages/Chart3.xaml.cs | YetAnotherChartComponent/eScape.Yacc.Demo/Pages/Chart3.xaml.cs | using eScape.Core.Page;
using System.Collections.Generic;
using System.Threading;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Yacc.Demo.VM;
using System;
namespace Yacc.Demo.Pages {
public sealed partial class Chart3 : BasicPage {
public override string PageTitle => "Recycling";
public int CurrentChildCount { get; private set; }
Timer cctimer;
public Chart3() {
this.InitializeComponent();
cctimer = new Timer(Timer_Callback, this, 1000, 1000);
}
/// <summary>
/// Update the child count so the viewer can see how recycling levels out.
/// </summary>
/// <param name="ox"></param>
async void Timer_Callback(object ox) {
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
// the chart has one child, which is a Canvas
var child = VisualTreeHelper.GetChild(chart, 0);
// everything lives in the canvas on one level
CurrentChildCount = VisualTreeHelper.GetChildrenCount(child);
// tell x:Bind
Bindings.Update();
});
}
protected override object InitializeDataContext(NavigationEventArgs e) {
// start out with placeholders so chart "appears" empty and "scrolls" to the left
var list = new List<Observation2>();
for (int ix = 0; ix < 30; ix++) list.Add(Observation2.PLACEHOLDER);
var vm = new TimedObservations2VM(Dispatcher, list);
vm.ResetCounter();
return vm;
}
protected override void DataContextReleased(NavigatingCancelEventArgs ncea) {
base.DataContextReleased(ncea);
if (cctimer != null) {
try {
cctimer.Change(Timeout.Infinite, Timeout.Infinite);
cctimer.Dispose();
} finally {
cctimer = null;
}
}
}
}
}
| using eScape.Core.Page;
using System.Collections.Generic;
using System.Threading;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Yacc.Demo.VM;
using System;
namespace Yacc.Demo.Pages {
public sealed partial class Chart3 : BasicPage {
public override string PageTitle => "Recycling";
public int CurrentChildCount { get; private set; }
Timer cctimer;
public Chart3() {
this.InitializeComponent();
cctimer = new Timer(Timer_Callback, this, 1000, 1000);
}
/// <summary>
/// Update the child count so the viewer can see how recycling levels out.
/// </summary>
/// <param name="ox"></param>
async void Timer_Callback(object ox) {
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => {
// the chart has one child, which is a Canvas
var child = VisualTreeHelper.GetChild(chart, 0);
// everything lives in the canvas on one level
CurrentChildCount = VisualTreeHelper.GetChildrenCount(child);
// tell x:Bind
Bindings.Update();
});
}
protected override object InitializeDataContext(NavigationEventArgs e) {
// start out with placeholders so chart "appears" empty and "scrolls" to the left
var list = new List<Observation2>();
for (int ix = 0; ix < 30; ix++) list.Add(Observation2.PLACEHOLDER);
var vm = new TimedObservationsVM(Dispatcher, list);
vm.ResetCounter();
return vm;
}
protected override void DataContextReleased(NavigatingCancelEventArgs ncea) {
base.DataContextReleased(ncea);
if (cctimer != null) {
try {
cctimer.Change(Timeout.Infinite, Timeout.Infinite);
cctimer.Dispose();
} finally {
cctimer = null;
}
}
}
}
}
| apache-2.0 | C# |
8a54dab5d0e28d4aaa372c1f62a8a655629c5a4e | Tidy up code | ppy/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,ZLima12/osu,peppy/osu-new,ZLima12/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu | osu.iOS/AppDelegate.cs | osu.iOS/AppDelegate.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using Foundation;
using osu.Framework.iOS;
using osu.Game;
using UIKit;
namespace osu.iOS
{
[Register("AppDelegate")]
public class AppDelegate : GameAppDelegate
{
private OsuGameIOS game;
protected override Framework.Game CreateGame() => game = new OsuGameIOS();
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
Task.Run(() => game.Import(url.Path));
return true;
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Threading.Tasks;
using Foundation;
using osu.Framework.iOS;
using osu.Game;
using UIKit;
namespace osu.iOS
{
[Register("AppDelegate")]
public class AppDelegate : GameAppDelegate
{
private OsuGameIOS IOSGame;
protected override Framework.Game CreateGame()
{
//Save OsuGameIOS for Import
IOSGame = new OsuGameIOS();
return IOSGame;
}
public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
{
//Open in Application
Task.Run(() => IOSGame.Import(url.Path));
return true;
}
}
}
| mit | C# |
48830c782f8fb90715d36849c5df32a3e0d8dc6a | Remove extra empty line in Util | frederickrogan/RiotSharp | RiotSharp/Misc/Util.cs | RiotSharp/Misc/Util.cs | using System;
using System.Collections.Generic;
using System.Linq;
using RiotSharp.MatchEndpoint.Enums;
namespace RiotSharp.Misc
{
static class Util
{
public static DateTime BaseDateTime = new DateTime(1970, 1, 1);
public static DateTime ToDateTimeFromMilliSeconds(this long millis)
{
return BaseDateTime.AddMilliseconds(millis);
}
public static long ToLong(this DateTime dateTime)
{
var span = dateTime - BaseDateTime;
return (long)span.TotalMilliseconds;
}
public static string BuildIdsString(List<int> ids)
{
return string.Join(",", ids);
}
public static string BuildIdsString(List<long> ids)
{
return string.Join(",", ids);
}
public static string BuildNamesString(List<string> names)
{
return string.Join(",", names.Select(Uri.EscapeDataString));
}
public static string BuildQueuesString(List<string> queues)
{
return string.Join(",", queues);
}
public static string BuildSeasonString(List<Season> seasons)
{
return string.Join(",", seasons.Select(s => s.ToCustomString()));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using RiotSharp.MatchEndpoint.Enums;
namespace RiotSharp.Misc
{
static class Util
{
public static DateTime BaseDateTime = new DateTime(1970, 1, 1);
public static DateTime ToDateTimeFromMilliSeconds(this long millis)
{
return BaseDateTime.AddMilliseconds(millis);
}
public static long ToLong(this DateTime dateTime)
{
var span = dateTime - BaseDateTime;
return (long)span.TotalMilliseconds;
}
public static string BuildIdsString(List<int> ids)
{
return string.Join(",", ids);
}
public static string BuildIdsString(List<long> ids)
{
return string.Join(",", ids);
}
public static string BuildNamesString(List<string> names)
{
return string.Join(",", names.Select(Uri.EscapeDataString));
}
public static string BuildQueuesString(List<string> queues)
{
return string.Join(",", queues);
}
public static string BuildSeasonString(List<Season> seasons)
{
return string.Join(",", seasons.Select(s => s.ToCustomString()));
}
}
}
| mit | C# |
e9b97d10d5910bf9cb63db6b7838417fa28a765e | Remove unnecessary field | Priya91/corefx-1,marksmeltzer/corefx,DnlHarvey/corefx,richlander/corefx,MaggieTsang/corefx,Petermarcu/corefx,parjong/corefx,gkhanna79/corefx,parjong/corefx,ravimeda/corefx,the-dwyer/corefx,nchikanov/corefx,elijah6/corefx,axelheer/corefx,billwert/corefx,dhoehna/corefx,nbarbettini/corefx,yizhang82/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,weltkante/corefx,dhoehna/corefx,DnlHarvey/corefx,stone-li/corefx,twsouthwick/corefx,axelheer/corefx,dotnet-bot/corefx,Ermiar/corefx,alexperovich/corefx,ericstj/corefx,billwert/corefx,weltkante/corefx,lggomez/corefx,seanshpark/corefx,elijah6/corefx,shmao/corefx,rubo/corefx,ravimeda/corefx,YoupHulsebos/corefx,ravimeda/corefx,dhoehna/corefx,manu-silicon/corefx,stone-li/corefx,nchikanov/corefx,manu-silicon/corefx,nchikanov/corefx,krytarowski/corefx,ericstj/corefx,dhoehna/corefx,YoupHulsebos/corefx,tijoytom/corefx,manu-silicon/corefx,weltkante/corefx,parjong/corefx,iamjasonp/corefx,cydhaselton/corefx,yizhang82/corefx,elijah6/corefx,Chrisboh/corefx,ericstj/corefx,Priya91/corefx-1,stone-li/corefx,zhenlan/corefx,Ermiar/corefx,mmitche/corefx,wtgodbe/corefx,jhendrixMSFT/corefx,jhendrixMSFT/corefx,alphonsekurian/corefx,shimingsg/corefx,richlander/corefx,the-dwyer/corefx,cydhaselton/corefx,rubo/corefx,weltkante/corefx,billwert/corefx,ericstj/corefx,rubo/corefx,Petermarcu/corefx,jlin177/corefx,Ermiar/corefx,mmitche/corefx,jlin177/corefx,DnlHarvey/corefx,iamjasonp/corefx,Jiayili1/corefx,jhendrixMSFT/corefx,shmao/corefx,lggomez/corefx,ellismg/corefx,MaggieTsang/corefx,fgreinacher/corefx,cydhaselton/corefx,adamralph/corefx,tijoytom/corefx,the-dwyer/corefx,fgreinacher/corefx,seanshpark/corefx,ptoonen/corefx,mazong1123/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,tijoytom/corefx,elijah6/corefx,gkhanna79/corefx,dotnet-bot/corefx,rahku/corefx,adamralph/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,rahku/corefx,shimingsg/corefx,yizhang82/corefx,elijah6/corefx,stephenmichaelf/corefx,mmitche/corefx,richlander/corefx,Jiayili1/corefx,stone-li/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,ericstj/corefx,seanshpark/corefx,krk/corefx,cydhaselton/corefx,axelheer/corefx,twsouthwick/corefx,zhenlan/corefx,Chrisboh/corefx,mmitche/corefx,lggomez/corefx,alexperovich/corefx,weltkante/corefx,alexperovich/corefx,DnlHarvey/corefx,seanshpark/corefx,billwert/corefx,ravimeda/corefx,stephenmichaelf/corefx,manu-silicon/corefx,krk/corefx,DnlHarvey/corefx,Ermiar/corefx,ericstj/corefx,stone-li/corefx,ellismg/corefx,shmao/corefx,mazong1123/corefx,ptoonen/corefx,alphonsekurian/corefx,ravimeda/corefx,nbarbettini/corefx,wtgodbe/corefx,alexperovich/corefx,Jiayili1/corefx,Ermiar/corefx,dotnet-bot/corefx,gkhanna79/corefx,MaggieTsang/corefx,zhenlan/corefx,YoupHulsebos/corefx,shmao/corefx,jhendrixMSFT/corefx,stephenmichaelf/corefx,BrennanConroy/corefx,dsplaisted/corefx,ViktorHofer/corefx,krytarowski/corefx,Jiayili1/corefx,BrennanConroy/corefx,axelheer/corefx,dsplaisted/corefx,ravimeda/corefx,Petermarcu/corefx,Petermarcu/corefx,ViktorHofer/corefx,DnlHarvey/corefx,Priya91/corefx-1,jlin177/corefx,ViktorHofer/corefx,fgreinacher/corefx,MaggieTsang/corefx,marksmeltzer/corefx,tijoytom/corefx,JosephTremoulet/corefx,lggomez/corefx,YoupHulsebos/corefx,yizhang82/corefx,alphonsekurian/corefx,jhendrixMSFT/corefx,marksmeltzer/corefx,shimingsg/corefx,krk/corefx,iamjasonp/corefx,Priya91/corefx-1,cydhaselton/corefx,billwert/corefx,manu-silicon/corefx,Ermiar/corefx,alphonsekurian/corefx,ptoonen/corefx,JosephTremoulet/corefx,weltkante/corefx,seanshpark/corefx,marksmeltzer/corefx,krk/corefx,alexperovich/corefx,rjxby/corefx,rjxby/corefx,stephenmichaelf/corefx,shimingsg/corefx,jhendrixMSFT/corefx,ellismg/corefx,YoupHulsebos/corefx,Chrisboh/corefx,nbarbettini/corefx,rahku/corefx,Priya91/corefx-1,nchikanov/corefx,jlin177/corefx,stephenmichaelf/corefx,wtgodbe/corefx,ViktorHofer/corefx,jlin177/corefx,Petermarcu/corefx,zhenlan/corefx,ravimeda/corefx,twsouthwick/corefx,JosephTremoulet/corefx,krk/corefx,nchikanov/corefx,ptoonen/corefx,yizhang82/corefx,Chrisboh/corefx,dhoehna/corefx,mazong1123/corefx,ellismg/corefx,iamjasonp/corefx,alexperovich/corefx,rjxby/corefx,shimingsg/corefx,gkhanna79/corefx,mazong1123/corefx,stone-li/corefx,jlin177/corefx,krytarowski/corefx,parjong/corefx,Petermarcu/corefx,fgreinacher/corefx,alphonsekurian/corefx,dhoehna/corefx,nbarbettini/corefx,twsouthwick/corefx,rahku/corefx,wtgodbe/corefx,iamjasonp/corefx,ellismg/corefx,MaggieTsang/corefx,lggomez/corefx,yizhang82/corefx,Jiayili1/corefx,lggomez/corefx,Jiayili1/corefx,rubo/corefx,Ermiar/corefx,lggomez/corefx,twsouthwick/corefx,MaggieTsang/corefx,dotnet-bot/corefx,rahku/corefx,nchikanov/corefx,seanshpark/corefx,parjong/corefx,krytarowski/corefx,nbarbettini/corefx,Chrisboh/corefx,nbarbettini/corefx,shmao/corefx,tijoytom/corefx,alphonsekurian/corefx,ptoonen/corefx,axelheer/corefx,rjxby/corefx,tijoytom/corefx,tijoytom/corefx,zhenlan/corefx,gkhanna79/corefx,mmitche/corefx,nchikanov/corefx,parjong/corefx,shimingsg/corefx,rahku/corefx,ellismg/corefx,krk/corefx,jhendrixMSFT/corefx,rjxby/corefx,ViktorHofer/corefx,cydhaselton/corefx,MaggieTsang/corefx,rahku/corefx,elijah6/corefx,adamralph/corefx,manu-silicon/corefx,manu-silicon/corefx,richlander/corefx,ptoonen/corefx,stephenmichaelf/corefx,twsouthwick/corefx,mmitche/corefx,wtgodbe/corefx,marksmeltzer/corefx,richlander/corefx,krytarowski/corefx,parjong/corefx,YoupHulsebos/corefx,shmao/corefx,the-dwyer/corefx,billwert/corefx,nbarbettini/corefx,dotnet-bot/corefx,alphonsekurian/corefx,Jiayili1/corefx,mazong1123/corefx,mmitche/corefx,axelheer/corefx,gkhanna79/corefx,dsplaisted/corefx,weltkante/corefx,DnlHarvey/corefx,zhenlan/corefx,krytarowski/corefx,zhenlan/corefx,rjxby/corefx,shmao/corefx,iamjasonp/corefx,ptoonen/corefx,richlander/corefx,dhoehna/corefx,the-dwyer/corefx,mazong1123/corefx,gkhanna79/corefx,rubo/corefx,Priya91/corefx-1,wtgodbe/corefx,Petermarcu/corefx,mazong1123/corefx,cydhaselton/corefx,twsouthwick/corefx,seanshpark/corefx,Chrisboh/corefx,ViktorHofer/corefx,marksmeltzer/corefx,alexperovich/corefx,elijah6/corefx,billwert/corefx,richlander/corefx,iamjasonp/corefx,stone-li/corefx,the-dwyer/corefx,YoupHulsebos/corefx,rjxby/corefx,ericstj/corefx,the-dwyer/corefx,yizhang82/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,jlin177/corefx,marksmeltzer/corefx,krytarowski/corefx,krk/corefx | src/System.ComponentModel.TypeConverter/src/System/ComponentModel/HandledEventArgs.cs | src/System.ComponentModel.TypeConverter/src/System/ComponentModel/HandledEventArgs.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.ComponentModel
{
/// <summary>
/// <para>
/// Provides data for the <see cref='System.ComponentModel.HandledEventArgs.Handled'/>
/// event.
/// </para>
/// </summary>
public class HandledEventArgs : EventArgs
{
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.HandledEventArgs'/> class with
/// handled set to <see langword='false'/>.
/// </para>
/// </summary>
public HandledEventArgs() : this(false)
{
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.HandledEventArgs'/> class with
/// handled set to the given value.
/// </para>
/// </summary>
public HandledEventArgs(bool defaultHandledValue)
: base()
{
Handled = defaultHandledValue;
}
/// <summary>
/// <para>
/// Gets or sets a value indicating whether the event was handled in the application's event handler.
/// </para>
/// </summary>
public bool Handled { get; set; }
}
}
| // 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 System.ComponentModel
{
/// <summary>
/// <para>
/// Provides data for the <see cref='System.ComponentModel.HandledEventArgs.Handled'/>
/// event.
/// </para>
/// </summary>
public class HandledEventArgs : EventArgs
{
/// <summary>
/// Indicates, on return, whether or not the event was handled in the application's event handler.
/// 'true' means the application handled the event, 'false' means it didn't.
/// </summary>
private bool _handled;
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.HandledEventArgs'/> class with
/// handled set to <see langword='false'/>.
/// </para>
/// </summary>
public HandledEventArgs() : this(false)
{
}
/// <summary>
/// <para>
/// Initializes a new instance of the <see cref='System.ComponentModel.HandledEventArgs'/> class with
/// handled set to the given value.
/// </para>
/// </summary>
public HandledEventArgs(bool defaultHandledValue)
: base()
{
_handled = defaultHandledValue;
}
/// <summary>
/// <para>
/// Gets or sets a value
/// indicating whether the event is handled.
/// </para>
/// </summary>
public bool Handled
{
get
{
return _handled;
}
set
{
_handled = value;
}
}
}
}
| mit | C# |
6bec2a91c138399a2c1ea0b01d696a2eff172c86 | Update BryceMcDonald.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/BryceMcDonald.cs | src/Firehose.Web/Authors/BryceMcDonald.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BryceMcDonald : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Bryce";
public string LastName => "McDonald";
public string ShortBioOrTagLine => "KC based PowerShell and Automation guru";
public string StateOrRegion => "Kansas City, Missouri";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "_brycemcdonald";
public string GravatarHash => "e6600de53eef91dd803a6386c20a40bf";
public string GitHubHandle => "mcdonaldbm";
public GeoPosition Position => new GeoPosition(39.0997, -94.5786);
public bool Filter(SyndicationItem item)
public Uri WebSite => new Uri("https://www.brycematthew.net");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://www.brycematthew.net/feed.xml"); }
}
public bool Filter(SyndicationItem item)
{
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class BryceMcDonald : IAmACommunityMember, IFilterMyBlogPosts
{
public string FirstName => "Bryce";
public string LastName => "McDonald";
public string ShortBioOrTagLine => "KC based PowerShell and Automation guru";
public string StateOrRegion => "Kansas City, Missouri";
public string EmailAddress => "[email protected]";
public string TwitterHandle => "_brycemcdonald";
public string GravatarHash => "e6600de53eef91dd803a6386c20a40bf";
public string GitHubHandle => "mcdonaldbm";
public GeoPosition Position => new GeoPosition(39.0997, -94.5786);
public bool Filter(SyndicationItem item)
public Uri WebSite => new Uri("https://www.brycematthew.net");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://www.brycematthew.net/feed.xml"); }
}
{
return item.Title.Text.ToLowerInvariant().Contains("powershell");
}
}
}
| mit | C# |
b920ecd7fdbd9ed7fa3cba950fdc336978eee56e | Fix mono bug in the FontHelper class | gmartin7/libpalaso,gmartin7/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,ddaspit/libpalaso,marksvc/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,hatton/libpalaso,sillsdev/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,darcywong00/libpalaso,hatton/libpalaso,marksvc/libpalaso,marksvc/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,glasseyes/libpalaso,hatton/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,tombogle/libpalaso | PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs | PalasoUIWindowsForms.Tests/FontTests/FontHelperTests.cs | using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
Assert.IsTrue(true);
}
}
}
| using System;
using System.Drawing;
using System.Linq;
using NUnit.Framework;
using Palaso.UI.WindowsForms;
namespace PalasoUIWindowsForms.Tests.FontTests
{
[TestFixture]
public class FontHelperTests
{
[SetUp]
public void SetUp()
{
// setup code goes here
}
[TearDown]
public void TearDown()
{
// tear down code goes here
}
[Test]
public void MakeFont_FontName_ValidFont()
{
Font sourceFont = SystemFonts.DefaultFont;
Font returnFont = FontHelper.MakeFont(sourceFont.FontFamily.Name);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
}
[Test]
public void MakeFont_FontNameAndStyle_ValidFont()
{
// use Times New Roman
foreach (var family in FontFamily.Families.Where(family => family.Name == "Times New Roman"))
{
Font sourceFont = new Font(family, 10f, FontStyle.Regular);
Font returnFont = FontHelper.MakeFont(sourceFont, FontStyle.Bold);
Assert.AreEqual(sourceFont.FontFamily.Name, returnFont.FontFamily.Name);
Assert.AreEqual(FontStyle.Bold, returnFont.Style & FontStyle.Bold);
break;
}
}
}
}
| mit | C# |
796883e229f48464bdce1813555a7fadb66b1be9 | Update version number | miniter/SSH.NET,Bloomcredit/SSH.NET,sshnet/SSH.NET,GenericHero/SSH.NET | Renci.SshClient/Renci.SshNet/Properties/AssemblyInfo.cs | Renci.SshClient/Renci.SshNet/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System;
// 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("SshNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Renci")]
[assembly: AssemblyProduct("SSH.NET")]
[assembly: AssemblyCopyright("Copyright © Renci 2013")]
[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("ad816c5e-6f13-4589-9f3e-59523f8b77a4")]
// 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("2013.4.7")]
[assembly: AssemblyFileVersion("2013.4.7")]
[assembly: AssemblyInformationalVersion("2013.4.7")]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Renci.SshNet.Tests")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif | using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System;
// 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("SshNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyCompany("Renci")]
[assembly: AssemblyProduct("SSH.NET")]
[assembly: AssemblyCopyright("Copyright © Renci 2013")]
[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("ad816c5e-6f13-4589-9f3e-59523f8b77a4")]
// 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("2013.1.27")]
[assembly: AssemblyFileVersion("2013.1.27")]
[assembly: AssemblyInformationalVersion("2013.1.27")]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Renci.SshNet.Tests")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif | mit | C# |
8c5674dc72ef759b37ee918467607cecaecb7f68 | Make RequestKey agnostic from ASP.NET types. | tiesmaster/DCC,tiesmaster/DCC | Dcc/RequestKey.cs | Dcc/RequestKey.cs | using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Tiesmaster.Dcc
{
// ReSharper disable once UseNameofExpression
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public struct RequestKey
{
private readonly string _method;
private readonly string _path;
public RequestKey(HttpRequest request)
{
_method = request.Method;
_path = request.Path;
}
public async Task<TapedResponse> CreateTapeFromAsync(HttpResponseMessage httpResponseMessage)
{
var body = await httpResponseMessage.Content.ReadAsByteArrayAsync();
return new HttpClientTapedResponse(this, httpResponseMessage, body);
}
private string DebuggerDisplay => $"{_method}: {_path}";
}
} | using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
namespace Tiesmaster.Dcc
{
// ReSharper disable once UseNameofExpression
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public struct RequestKey
{
private readonly string _method;
private readonly PathString _path;
public RequestKey(HttpRequest request)
{
_method = request.Method;
_path = request.Path;
}
public async Task<TapedResponse> CreateTapeFromAsync(HttpResponseMessage httpResponseMessage)
{
var body = await httpResponseMessage.Content.ReadAsByteArrayAsync();
return new HttpClientTapedResponse(this, httpResponseMessage, body);
}
private string DebuggerDisplay => $"{_method}: {_path}";
}
} | mit | C# |
1ddaf8687e00de73a75ac6f174bf865ef23c28d0 | Stop using ForRelational. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/MusicStore.Spa/Models/MusicStoreContext.cs | src/MusicStore.Spa/Models/MusicStoreContext.cs | using System;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Framework.OptionsModel;
namespace MusicStore.Models
{
public class ApplicationUser : IdentityUser { }
public class MusicStoreContext : IdentityDbContext<ApplicationUser>
{
public MusicStoreContext()
{
}
public DbSet<Album> Albums { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
// Configure pluralization
builder.Entity<Album>().Table("Albums");
builder.Entity<Artist>().Table("Artists");
builder.Entity<Order>().Table("Orders");
builder.Entity<Genre>().Table("Genres");
builder.Entity<CartItem>().Table("CartItems");
builder.Entity<OrderDetail>().Table("OrderDetails");
// TODO: Remove this when we start using auto generated values
builder.Entity<Artist>().Property(a => a.ArtistId).GenerateValueOnAdd(generateValue: false);
builder.Entity<Album>().Property(a => a.ArtistId).GenerateValueOnAdd(generateValue: false);
builder.Entity<Genre>().Property(g => g.GenreId).GenerateValueOnAdd(generateValue: false);
base.OnModelCreating(builder);
}
}
} | using System;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using Microsoft.Framework.OptionsModel;
namespace MusicStore.Models
{
public class ApplicationUser : IdentityUser { }
public class MusicStoreContext : IdentityDbContext<ApplicationUser>
{
public MusicStoreContext()
{
}
public DbSet<Album> Albums { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<CartItem> CartItems { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
// Configure pluralization
builder.Entity<Album>().ForRelational().Table("Albums");
builder.Entity<Artist>().ForRelational().Table("Artists");
builder.Entity<Order>().ForRelational().Table("Orders");
builder.Entity<Genre>().ForRelational().Table("Genres");
builder.Entity<CartItem>().ForRelational().Table("CartItems");
builder.Entity<OrderDetail>().ForRelational().Table("OrderDetails");
// TODO: Remove this when we start using auto generated values
builder.Entity<Artist>().Property(a => a.ArtistId).GenerateValueOnAdd(generateValue: false);
builder.Entity<Album>().Property(a => a.ArtistId).GenerateValueOnAdd(generateValue: false);
builder.Entity<Genre>().Property(g => g.GenreId).GenerateValueOnAdd(generateValue: false);
base.OnModelCreating(builder);
}
}
} | apache-2.0 | C# |
457ade0b771697ff6f99f8138098e223e56326d6 | Update ApiControllerAttribute with link to more info (#29292) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs | src/Mvc/Mvc.Core/src/ApiControllerAttribute.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Indicates that a type and all derived types are used to serve HTTP API responses.
/// <para>
/// Controllers decorated with this attribute are configured with features and behavior targeted at improving the
/// developer experience for building APIs.
/// </para>
/// <para>
/// When decorated on an assembly, all controllers in the assembly will be treated as controllers with API behavior.
/// For more information, see <see href="https://docs.microsoft.com/aspnet/core/web-api/#apicontroller-attribute">ApiController attribute</see>.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata
{
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNetCore.Mvc.Infrastructure;
namespace Microsoft.AspNetCore.Mvc
{
/// <summary>
/// Indicates that a type and all derived types are used to serve HTTP API responses.
/// <para>
/// Controllers decorated with this attribute are configured with features and behavior targeted at improving the
/// developer experience for building APIs.
/// </para>
/// <para>
/// When decorated on an assembly, all controllers in the assembly will be treated as controllers with API behavior.
/// </para>
/// </summary>
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class ApiControllerAttribute : ControllerAttribute, IApiBehaviorMetadata
{
}
}
| apache-2.0 | C# |
4e4c3cc52f95d2cdd18a04065bd2b1f29097f470 | Replace the existing ProblemDetailsFactory from MVC | khellang/Middleware,khellang/Middleware | src/ProblemDetails/Mvc/MvcBuilderExtensions.cs | src/ProblemDetails/Mvc/MvcBuilderExtensions.cs | using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.Replace(
ServiceDescriptor.Singleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>()));
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using MvcProblemDetailsFactory = Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory;
namespace Hellang.Middleware.ProblemDetails.Mvc
{
public static class MvcBuilderExtensions
{
/// <summary>
/// Adds conventions to turn off MVC's built-in <see cref="ApiBehaviorOptions.ClientErrorMapping"/>,
/// adds a <see cref="ProducesErrorResponseTypeAttribute"/> to all actions with in controllers with an
/// <see cref="ApiControllerAttribute"/> and a result filter that transforms <see cref="ObjectResult"/>
/// containing a <see cref="string"/> to <see cref="ProblemDetails"/> responses.
/// </summary>
/// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
/// <returns>The <see cref="IMvcBuilder"/>.</returns>
public static IMvcBuilder AddProblemDetailsConventions(this IMvcBuilder builder)
{
// Forward the MVC problem details factory registration to the factory used by the middleware.
builder.Services.TryAddSingleton<MvcProblemDetailsFactory>(p => p.GetRequiredService<ProblemDetailsFactory>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IConfigureOptions<ApiBehaviorOptions>, ProblemDetailsApiBehaviorOptionsSetup>());
builder.Services.TryAddEnumerable(
ServiceDescriptor.Transient<IApplicationModelProvider, ProblemDetailsApplicationModelProvider>());
return builder;
}
}
}
| mit | C# |
7cadcd3ebbe205043f5528182c6a5d8781e8505b | Add missing $ in Label.ToString() | 0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced,0xd4d/iced | src/csharp/Intel/Iced/Intel/Assembler/Label.cs | src/csharp/Intel/Iced/Intel/Assembler/Label.cs | /*
Copyright (C) 2018-2019 [email protected]
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if !NO_ENCODER
using System;
namespace Iced.Intel {
/// <summary>
/// A label that can be created by <see cref="Assembler.CreateLabel"/>.
/// </summary>
public struct Label : IEquatable<Label> {
internal Label(string? name, ulong id) {
Name = name ?? "___label";
Id = id;
InstructionIndex = -1;
}
/// <summary>
/// Name of this label.
/// </summary>
public readonly string Name;
/// <summary>
/// Id of this label.
/// </summary>
public readonly ulong Id;
/// <summary>
/// Gets the instruction index associated with this label. This is setup after calling <see cref="Assembler.Label"/>.
/// </summary>
public int InstructionIndex { get; internal set; }
/// <summary>
/// <c>true</c> if this label is empty and was not created by <see cref="Assembler.CreateLabel"/>.
/// </summary>
public bool IsEmpty => Id == 0;
/// <inheritdoc />
public override string ToString() => $"{Name}@{Id}";
/// <inheritdoc />
public bool Equals(Label other) => Name == other.Name && Id == other.Id;
/// <inheritdoc />
public override bool Equals(object? obj) => obj is Label other && Equals(other);
/// <inheritdoc />
public override int GetHashCode() {
unchecked {
return (Name.GetHashCode() * 397) ^ Id.GetHashCode();
}
}
/// <summary>
/// Equality operator for <see cref="Label"/>
/// </summary>
/// <param name="left">Label</param>
/// <param name="right">Label</param>
/// <returns></returns>
public static bool operator ==(Label left, Label right) => left.Equals(right);
/// <summary>
/// Inequality operator for <see cref="Label"/>
/// </summary>
/// <param name="left">Label</param>
/// <param name="right">Label</param>
/// <returns></returns>
public static bool operator !=(Label left, Label right) => !left.Equals(right);
}
}
#endif
| /*
Copyright (C) 2018-2019 [email protected]
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#if !NO_ENCODER
using System;
namespace Iced.Intel {
/// <summary>
/// A label that can be created by <see cref="Assembler.CreateLabel"/>.
/// </summary>
public struct Label : IEquatable<Label> {
internal Label(string? name, ulong id) {
Name = name ?? "___label";
Id = id;
InstructionIndex = -1;
}
/// <summary>
/// Name of this label.
/// </summary>
public readonly string Name;
/// <summary>
/// Id of this label.
/// </summary>
public readonly ulong Id;
/// <summary>
/// Gets the instruction index associated with this label. This is setup after calling <see cref="Assembler.Label"/>.
/// </summary>
public int InstructionIndex { get; internal set; }
/// <summary>
/// <c>true</c> if this label is empty and was not created by <see cref="Assembler.CreateLabel"/>.
/// </summary>
public bool IsEmpty => Id == 0;
/// <inheritdoc />
public override string ToString() => "{Name}@{Id}";
/// <inheritdoc />
public bool Equals(Label other) => Name == other.Name && Id == other.Id;
/// <inheritdoc />
public override bool Equals(object? obj) => obj is Label other && Equals(other);
/// <inheritdoc />
public override int GetHashCode() {
unchecked {
return (Name.GetHashCode() * 397) ^ Id.GetHashCode();
}
}
/// <summary>
/// Equality operator for <see cref="Label"/>
/// </summary>
/// <param name="left">Label</param>
/// <param name="right">Label</param>
/// <returns></returns>
public static bool operator ==(Label left, Label right) => left.Equals(right);
/// <summary>
/// Inequality operator for <see cref="Label"/>
/// </summary>
/// <param name="left">Label</param>
/// <param name="right">Label</param>
/// <returns></returns>
public static bool operator !=(Label left, Label right) => !left.Equals(right);
}
}
#endif
| mit | C# |
9037afddb5ccfa68a2fc7b6397e6760599eb6a91 | Update cake script | PluginsForXamarin/vibrate | CI/build.cake | CI/build.cake | #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
var libraries = new Dictionary<string, string> {
{ "./../Vibrate.sln", "Any" },
};
var samples = new Dictionary<string, string> {
{ "./../Sample/VibrateSample.sln", "Win" },
};
var BuildAction = new Action<Dictionary<string, string>> (solutions =>
{
foreach (var sln in solutions)
{
// If the platform is Any build regardless
// If the platform is Win and we are running on windows build
// If the platform is Mac and we are running on Mac, build
if ((sln.Value == "Any")
|| (sln.Value == "Win" && IsRunningOnWindows ())
|| (sln.Value == "Mac" && IsRunningOnUnix ()))
{
// Bit of a hack to use nuget3 to restore packages for project.json
if (IsRunningOnWindows ())
{
Information ("RunningOn: {0}", "Windows");
NuGetRestore (sln.Key, new NuGetRestoreSettings
{
ToolPath = "./tools/nuget3.exe"
});
// Windows Phone / Universal projects require not using the amd64 msbuild
MSBuild (sln.Key, c =>
{
c.Configuration = "Release";
c.MSBuildPlatform = Cake.Common.Tools.MSBuild.MSBuildPlatform.x86;
});
}
else
{
// Mac is easy ;)
NuGetRestore (sln.Key);
DotNetBuild (sln.Key, c => c.Configuration = "Release");
}
}
}
});
Task("Libraries").Does(()=>
{
BuildAction(libraries);
});
Task("Samples")
.IsDependentOn("Libraries")
.Does(()=>
{
BuildAction(samples);
});
Task ("NuGet")
.IsDependentOn ("Samples")
.Does (() =>
{
if(!DirectoryExists("./../Build/nuget/"))
CreateDirectory("./../Build/nuget");
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./../",
BasePath = "./../",
});
});
Task("Component")
.IsDependentOn("Samples")
.IsDependentOn("NuGet")
.Does(()=>
{
// Clear out xml files from build (they interfere with the component packaging)
DeleteFiles ("./../Build/**/*.xml");
// Generate component.yaml files from templates
CopyFile ("./../Component/component.template.yaml", "./../Component/component.yaml");
// Replace version in template files
ReplaceTextInFiles ("./../**/component.yaml", "{VERSION}", version);
var xamCompSettings = new XamarinComponentSettings { ToolPath = "./tools/xamarin-component.exe" };
// Package both components
PackageComponent ("./../Component/", xamCompSettings);
});
Task ("Default").IsDependentOn("Component")
Task ("Clean").Does (() =>
{
CleanDirectory ("./../Component/tools/");
CleanDirectories ("./../Build/");
CleanDirectories ("./../**/bin");
CleanDirectories ("./../**/obj");
});
RunTarget (TARGET);
| #addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Default"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Default").Does (() =>
{
const string sln = "./../Vibrate.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Default")
.Does (() =>
{
NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./../",
BasePath = "./../",
});
});
RunTarget (TARGET);
| mit | C# |
45b1aaea04340e835e396ddbcd881897ebbb35b4 | Update CurrentCommandContext.cs | tiksn/TIKSN-Framework | TIKSN.Core/PowerShell/CurrentCommandContext.cs | TIKSN.Core/PowerShell/CurrentCommandContext.cs | using System;
namespace TIKSN.PowerShell
{
public class CurrentCommandContext : ICurrentCommandStore, ICurrentCommandProvider
{
private CommandBase _command;
public CommandBase GetCurrentCommand()
{
if (this._command == null)
{
throw new NullReferenceException("Command is not set yet.");
}
return this._command;
}
public void SetCurrentCommand(CommandBase command) => this._command = command ?? throw new ArgumentNullException(nameof(command));
}
}
| using System;
namespace TIKSN.PowerShell
{
public class CurrentCommandContext : ICurrentCommandStore, ICurrentCommandProvider
{
private CommandBase _command;
public CommandBase GetCurrentCommand()
{
if (this._command == null)
{
throw new NullReferenceException("Command is not set yet.");
}
return this._command;
}
public void SetCurrentCommand(CommandBase command)
{
if (command == null)
{
throw new ArgumentNullException(nameof(command));
}
this._command = command;
}
}
}
| mit | C# |
3bf538d4159c781adfdb76abf738d73b0af282e0 | Fix iOS nullref on orientation change (#2701) | EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework.iOS/GameViewController.cs | osu.Framework.iOS/GameViewController.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using CoreGraphics;
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
internal class GameViewController : UIViewController
{
private readonly IOSGameView gameView;
private readonly GameHost gameHost;
public override bool PrefersStatusBarHidden() => true;
public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;
public GameViewController(IOSGameView view, GameHost host)
{
View = view;
gameView = view;
gameHost = host;
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
gameHost.Collect();
}
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
UIView.AnimationsEnabled = false;
base.ViewWillTransitionToSize(toSize, coordinator);
gameView.RequestResizeFrameBuffer();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using CoreGraphics;
using osu.Framework.Platform;
using UIKit;
namespace osu.Framework.iOS
{
internal class GameViewController : UIViewController
{
private readonly IOSGameView view;
private readonly GameHost host;
public override bool PrefersStatusBarHidden() => true;
public override UIRectEdge PreferredScreenEdgesDeferringSystemGestures => UIRectEdge.All;
public GameViewController(IOSGameView view, GameHost host)
{
View = view;
this.host = host;
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
host.Collect();
}
public override void ViewWillTransitionToSize(CGSize toSize, IUIViewControllerTransitionCoordinator coordinator)
{
coordinator.AnimateAlongsideTransition(_ => { }, _ => UIView.AnimationsEnabled = true);
UIView.AnimationsEnabled = false;
base.ViewWillTransitionToSize(toSize, coordinator);
view.RequestResizeFrameBuffer();
}
}
}
| mit | C# |
e00179f3c92dd16e3e2ad2b9c7281fd19f90d3f6 | Remove dead private and comments | mono/dbus-sharp-glib,mono/dbus-sharp-glib | glib/GLib.cs | glib/GLib.cs | // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
static Connection connection;
public static Connection Connection
{
get {
return connection;
}
}
public static void Init ()
{
connection = new Connection ();
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
| // Copyright 2006 Alp Toker <[email protected]>
// This software is made available under the MIT License
// See COPYING for details
using System;
//using GLib;
//using Gtk;
using NDesk.DBus;
using NDesk.GLib;
using org.freedesktop.DBus;
namespace NDesk.DBus
{
//FIXME: this API needs review and de-unixification
public static class DApplication
{
public static bool Dispatch (IOChannel source, IOCondition condition, IntPtr data)
{
//Console.Error.WriteLine ("Dispatch " + source.UnixFd + " " + condition);
connection.Iterate ();
//Console.Error.WriteLine ("Dispatch done");
return true;
}
public static Connection Connection
{
get {
return connection;
}
}
static Connection connection;
static Bus bus;
public static void Init ()
{
connection = new Connection ();
//ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus");
//string name = "org.freedesktop.DBus";
/*
bus = connection.GetObject<Bus> (name, opath);
bus.NameAcquired += delegate (string acquired_name) {
Console.Error.WriteLine ("NameAcquired: " + acquired_name);
};
string myName = bus.Hello ();
Console.Error.WriteLine ("myName: " + myName);
*/
IOChannel channel = new IOChannel ((int)connection.sock.Handle);
IO.AddWatch (channel, IOCondition.In, Dispatch);
}
}
}
| mit | C# |
ec727cd63d092e36b20664e27372ee595df0d53c | Fix the parameters | phaetto/serviceable-objects | Serviceable.Objects.Instrumentation/CommonParameters/CommonInstrumentationParameters.cs | Serviceable.Objects.Instrumentation/CommonParameters/CommonInstrumentationParameters.cs | namespace Serviceable.Objects.Instrumentation.CommonParameters
{
using System.Management.Automation;
public sealed class CommonInstrumentationParameters
{
public const string ContainerParameterSet = "Container";
public const string ServiceParameterSet = "Service";
public const string NodeParameterSet = "Node";
public const string CustomPipeParameterSet = "Custom Pipe";
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The container that you want to connect to", ParameterSetName = ContainerParameterSet)]
[Parameter(Mandatory = true, HelpMessage = "The container that you want to connect to", ParameterSetName = ServiceParameterSet)]
[Parameter(Mandatory = true, HelpMessage = "The container that you want to connect to", ParameterSetName = NodeParameterSet)]
public string ServiceContainerName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The service that you want to connect to", ParameterSetName = ServiceParameterSet)]
[Parameter(Mandatory = true, HelpMessage = "The service that you want to connect to", ParameterSetName = NodeParameterSet)]
public string ServiceName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The custom pipe that will transfer the command", ParameterSetName = CustomPipeParameterSet)]
public string PipeName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The node id that you want to connect to", ParameterSetName = NodeParameterSet)]
public string NodeId { get; set; }
[ValidateRange(100, int.MaxValue)]
[Parameter(Mandatory = false, HelpMessage = "The timeout that the connection will fail")]
public int TimeoutInMilliseconds { get; set; } = 1000;
}
} | namespace Serviceable.Objects.Instrumentation.CommonParameters
{
using System.Management.Automation;
public sealed class CommonInstrumentationParameters
{
public const string ContainerParameterSet = "Container";
public const string ServiceParameterSet = "Service";
public const string NodeParameterSet = "Node";
public const string CustomPipeParameterSet = "Custom Pipe";
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The container that you want to connect to", ParameterSetName = ContainerParameterSet)]
public string ServiceContainerName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The service that you want to connect to", ParameterSetName = ServiceParameterSet)]
[Parameter(Mandatory = true, HelpMessage = "The service that you want to connect to", ParameterSetName = NodeParameterSet)]
public string ServiceName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The custom pipe that will transfer the command", ParameterSetName = CustomPipeParameterSet)]
public string PipeName { get; set; }
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, HelpMessage = "The node id that you want to connect to", ParameterSetName = NodeParameterSet)]
[Parameter(Mandatory = true, HelpMessage = "The node id that you want to connect to", ParameterSetName = CustomPipeParameterSet)]
public string NodeId { get; set; }
[ValidateRange(100, int.MaxValue)]
[Parameter(Mandatory = false, HelpMessage = "The timeout that the connection will fail")]
public int TimeoutInMilliseconds { get; set; } = 1000;
}
} | mit | C# |
470446b02b685f2b2678bb314a6c97aaa800c1a7 | Add OAuth flow to extended splash screen | tjcsl/ionapp-w10,tjcsl/ionapp-w10 | Ion10/App.xaml.cs | Ion10/App.xaml.cs | using Windows.UI.Xaml;
using System.Threading.Tasks;
using Ion10.Services.SettingsServices;
using Windows.ApplicationModel.Activation;
using Template10.Controls;
using Template10.Common;
using System;
using System.Linq;
using Windows.UI.Popups;
using Windows.UI.Xaml.Data;
using Windows.Web.Http;
using Ion10.Services;
namespace Ion10 {
/// Documentation on APIs used in this page:
/// https://github.com/Windows-XAML/Template10/wiki
[Bindable]
sealed partial class App : Template10.Common.BootStrapper {
public App() {
InitializeComponent();
SplashFactory = (e) => new Views.Splash(e);
#region App settings
var _settings = SettingsService.Instance;
RequestedTheme = _settings.AppTheme;
CacheMaxDuration = _settings.CacheMaxDuration;
ShowShellBackButton = _settings.UseShellBackButton;
#endregion
}
public static HttpClient HttpClient { get; set; } = new HttpClient();
public override async Task OnInitializeAsync(IActivatedEventArgs args) {
await SettingsService.Instance.InitializeAsync();
if(Window.Current.Content as ModalDialog == null) {
// create a new frame
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
// create modal root
Window.Current.Content = new ModalDialog {
DisableBackButtonWhenModal = true,
Content = new Views.Shell(nav),
ModalContent = new Views.Busy(),
};
}
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) {
var settings = SettingsService.Instance;
var code = await OAuthService.Instance.GetOAuthCodeAsync(
settings.BaseUri,
settings.OAuthId,
settings.OAuthCallbackUri);
var token = await OAuthService.Instance.GetOAuthTokenAsync(
settings.BaseUri,
settings.OAuthId,
settings.OAuthSecret,
code,
settings.OAuthCallbackUri);
await OAuthService.Instance.RefreshOAuthTokenAsync(
settings.BaseUri,
settings.OAuthId,
settings.OAuthSecret,
token.RefreshToken,
settings.OAuthCallbackUri);
NavigationService.Navigate(typeof(Views.MainPage));
}
}
}
| using Windows.UI.Xaml;
using System.Threading.Tasks;
using Ion10.Services.SettingsServices;
using Windows.ApplicationModel.Activation;
using Template10.Controls;
using Template10.Common;
using System;
using System.Linq;
using Windows.UI.Xaml.Data;
namespace Ion10 {
/// Documentation on APIs used in this page:
/// https://github.com/Windows-XAML/Template10/wiki
[Bindable]
sealed partial class App : Template10.Common.BootStrapper {
public App() {
InitializeComponent();
SplashFactory = (e) => new Views.Splash(e);
#region App settings
var _settings = SettingsService.Instance;
RequestedTheme = _settings.AppTheme;
CacheMaxDuration = _settings.CacheMaxDuration;
ShowShellBackButton = _settings.UseShellBackButton;
#endregion
}
public override async Task OnInitializeAsync(IActivatedEventArgs args) {
if(Window.Current.Content as ModalDialog == null) {
// create a new frame
var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
// create modal root
Window.Current.Content = new ModalDialog {
DisableBackButtonWhenModal = true,
Content = new Views.Shell(nav),
ModalContent = new Views.Busy(),
};
}
await Task.CompletedTask;
}
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) {
// long-running startup tasks go here
await Task.Delay(5000);
NavigationService.Navigate(typeof(Views.MainPage));
await Task.CompletedTask;
}
}
}
| mit | C# |
80bd4b04f9ee2644f0ba6b1f4b816f2c78e20036 | Make CodeFactor happy at the cost of my own happiness (code unfolding) | HoLLy-HaCKeR/osu-database-reader | osu-database-reader/Components/HitObjects/HitObjectSlider.cs | osu-database-reader/Components/HitObjects/HitObjectSlider.cs | using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L':
CurveType = CurveType.Linear;
break;
case 'C':
CurveType = CurveType.Catmull;
break;
case 'P':
CurveType = CurveType.Perfect;
break;
case 'B':
CurveType = CurveType.Bezier;
break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
| using System.Collections.Generic;
using System.Diagnostics;
namespace osu_database_reader.Components.HitObjects
{
public class HitObjectSlider : HitObject
{
public CurveType CurveType;
public List<Vector2> Points = new List<Vector2>(); //does not include initial point!
public int RepeatCount;
public double Length; //seems to be length in o!p, so it doesn't have to be calculated?
public void ParseSliderSegments(string sliderString)
{
string[] split = sliderString.Split('|');
foreach (var s in split) {
if (s.Length == 1) { //curve type
switch (s[0]) {
case 'L': CurveType = CurveType.Linear; break;
case 'C': CurveType = CurveType.Catmull; break;
case 'P': CurveType = CurveType.Perfect; break;
case 'B': CurveType = CurveType.Bezier; break;
}
continue;
}
string[] split2 = s.Split(':');
Debug.Assert(split2.Length == 2);
Points.Add(new Vector2(
int.Parse(split2[0]),
int.Parse(split2[1])));
}
}
}
}
| mit | C# |
0347fc4b1c6c90fdfa1da56e942fd17dd97f3f3b | implement arraylist | aloisdg/edx-csharp | edX/Module7/Program.cs | edX/Module7/Program.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module7
{
//Create a Stack object inside the Student object, called Grades, to store test scores.
//Create 3 student objects.
//Add 5 grades to the the Stack in the each Student object. (this does not have to be inside the constructor because you may not have grades for a student when you create a new student.)
//Add the three Student objects to the Students ArrayList inside the Course object.
//Using a foreach loop, iterate over the Students in the ArrayList and output their first and last names to the console window. (For this exercise you MUST cast the returned object from the ArrayList to a Student object. Also, place each student name on its own line)
//Create a method inside the Course object called ListStudents() that contains the foreach loop.
//Call the ListStudents() method from Main().
class Program
{
#region enum
public enum SchoolStatus
{
Student,
Teacher,
Other
}
#endregion
#region interface
public interface INameable
{
string Name { get; }
}
#endregion
#region abstract
public abstract class ANameable : INameable
{
public string Name { get; private set; }
protected ANameable(string name)
{
Name = name;
}
}
public abstract class APerson : INameable
{
public string Name { get; private set; }
public string FirstName { get; protected set; }
public string LastName { get; protected set; }
public DateTime Birthdate { get; set; }
public abstract SchoolStatus SchoolStatus { get; }
protected APerson(string firstName, string lastName, DateTime birthdate)
{
Name = firstName + " " + lastName;
FirstName = firstName;
LastName = lastName;
Birthdate = birthdate;
}
}
#endregion
#region class
public class UProgram : ANameable
{
public Degree Degree { get; set; }
public UProgram(string name) : base(name) { }
public override string ToString()
{
return "The " + Name
+ " program contains the "
+ Degree.Name + " degree";
}
}
public class Degree : ANameable
{
public Course Course { get; set; }
public Degree(string name) : base(name) { }
public override string ToString()
{
return "The " + Name
+ " degree contains the course "
+ Course.Name;
}
}
//Modify your code to use the ArrayList collection as the replacement to the array.
public class Students : ArrayList
{
//In other words, when you add a Student to the Course object, you will add it to the ArrayList and not an array.
public override int Add(object value)
{
if (value is Student)
return base.Add(value);
throw new InvalidOperationException();
}
}
public class Course : ANameable
{
//Delete the Student array in your Course object that you created in Module 5.
//Create an ArrayList to replace the array and to hold students, inside the Course object.
public Students Students { get; set; }
private IEnumerable<Teacher> _teachers;
public IEnumerable<Teacher> Teachers
{
get { return _teachers; }
set
{
if (!value.Any())
throw new Exception("Instantiate at least one Teacher object.");
_teachers = value;
}
}
public Course(string name) : base(name) { }
public override string ToString()
{
return "The " + Name
+ " course contains " + Students.Count
+ " student<s>";
}
}
public class Student : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Student; } }
public Student(string firstName, string lastName, DateTime birthdate)
: base(firstName, lastName, birthdate) { }
public void TakeTest()
{
Console.WriteLine("Student takes the test.");
}
}
public class Teacher : APerson
{
public override SchoolStatus SchoolStatus { get { return SchoolStatus.Teacher; } }
public Teacher(string firstName, string lastName, DateTime birthdate)
: base(firstName, lastName, birthdate) { }
public void GradeTest()
{
Console.WriteLine("Teacher grades the test.");
}
}
#endregion
private static void Main()
{
var uProgram = new UProgram("Information Technology")
{
Degree = new Degree("Bachelor")
{
Course = new Course("Programming with C#")
{
Students = new Collection<Student>
{
new Student("Harry", "Potter", new DateTime(1980, 7, 31)),
new Student("Ron", "Weasley", new DateTime(1980, 3, 1)),
new Student("Hermione", "Granger", new DateTime(1979, 9, 19))
},
Teachers = new Collection<Teacher> { new Teacher("Remus", "Lupin", new DateTime(1960, 3, 10)) }
}
}
};
try
{
Console.WriteLine(uProgram + Environment.NewLine);
Console.WriteLine(uProgram.Degree + Environment.NewLine);
Console.WriteLine(uProgram.Degree.Course.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.WriteLine("Press any key to continue ...");
Console.ReadLine();
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Module7
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
48c46efdd72ea4a8a34243ebbe3f3f56d37d3b05 | Remove rogue newline | NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu | osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs | osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(TeamScore),
typeof(TeamScoreDisplay),
typeof(TeamDisplay),
typeof(MatchHeader),
typeof(MatchScoreDisplay),
typeof(BeatmapInfoScreen),
typeof(SongBar),
};
[BackgroundDependencyLoader]
private void load()
{
Add(new GameplayScreen());
Add(chat);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(TeamScore),
typeof(TeamScoreDisplay),
typeof(TeamDisplay),
typeof(MatchHeader),
typeof(MatchScoreDisplay),
typeof(BeatmapInfoScreen),
typeof(SongBar),
};
[BackgroundDependencyLoader]
private void load()
{
Add(new GameplayScreen());
Add(chat);
}
}
}
| mit | C# |
6d3d906e604d530c5f1e03d2c8dc191f8b6f45e7 | add example of custom error message to sample | AntiTcb/Discord.Net,RogueException/Discord.Net | samples/02_commands_framework/Modules/PublicModule.cs | samples/02_commands_framework/Modules/PublicModule.cs | using System.IO;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using _02_commands_framework.Services;
namespace _02_commands_framework.Modules
{
// Modules must be public and inherit from an IModuleBase
public class PublicModule : ModuleBase<SocketCommandContext>
{
// Dependency Injection will fill this value in for us
public PictureService PictureService { get; set; }
[Command("ping")]
[Alias("pong", "hello")]
public Task PingAsync()
=> ReplyAsync("pong!");
[Command("cat")]
public async Task CatAsync()
{
// Get a stream containing an image of a cat
var stream = await PictureService.GetCatPictureAsync();
// Streams must be seeked to their beginning before being uploaded!
stream.Seek(0, SeekOrigin.Begin);
await Context.Channel.SendFileAsync(stream, "cat.png");
}
// Get info on a user, or the user who invoked the command if one is not specified
[Command("userinfo")]
public async Task UserInfoAsync(IUser user = null)
{
user = user ?? Context.User;
await ReplyAsync(user.ToString());
}
// Ban a user
[Command("ban")]
[RequireContext(ContextType.Guild)]
// make sure the user invoking the command can ban
[RequireUserPermission(GuildPermission.BanMembers)]
// make sure the bot itself can ban
[RequireBotPermission(GuildPermission.BanMembers)]
public async Task BanUserAsync(IGuildUser user, [Remainder] string reason = null)
{
await user.Guild.AddBanAsync(user, reason: reason);
await ReplyAsync("ok!");
}
// [Remainder] takes the rest of the command's arguments as one argument, rather than splitting every space
[Command("echo")]
public Task EchoAsync([Remainder] string text)
// Insert a ZWSP before the text to prevent triggering other bots!
=> ReplyAsync('\u200B' + text);
// 'params' will parse space-separated elements into a list
[Command("list")]
public Task ListAsync(params string[] objects)
=> ReplyAsync("You listed: " + string.Join("; ", objects));
[Command("guild_only")]
[RequireContext(ContextType.Guild, ErrorMessage = "Sorry, this command must be ran from within a server, not a DM!")]
public Task GuildOnlyCommand()
=> ReplyAsync("Nothing to see here!");
}
}
| using System.IO;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using _02_commands_framework.Services;
namespace _02_commands_framework.Modules
{
// Modules must be public and inherit from an IModuleBase
public class PublicModule : ModuleBase<SocketCommandContext>
{
// Dependency Injection will fill this value in for us
public PictureService PictureService { get; set; }
[Command("ping")]
[Alias("pong", "hello")]
public Task PingAsync()
=> ReplyAsync("pong!");
[Command("cat")]
public async Task CatAsync()
{
// Get a stream containing an image of a cat
var stream = await PictureService.GetCatPictureAsync();
// Streams must be seeked to their beginning before being uploaded!
stream.Seek(0, SeekOrigin.Begin);
await Context.Channel.SendFileAsync(stream, "cat.png");
}
// Get info on a user, or the user who invoked the command if one is not specified
[Command("userinfo")]
public async Task UserInfoAsync(IUser user = null)
{
user = user ?? Context.User;
await ReplyAsync(user.ToString());
}
// Ban a user
[Command("ban")]
[RequireContext(ContextType.Guild)]
// make sure the user invoking the command can ban
[RequireUserPermission(GuildPermission.BanMembers)]
// make sure the bot itself can ban
[RequireBotPermission(GuildPermission.BanMembers)]
public async Task BanUserAsync(IGuildUser user, [Remainder] string reason = null)
{
await user.Guild.AddBanAsync(user, reason: reason);
await ReplyAsync("ok!");
}
// [Remainder] takes the rest of the command's arguments as one argument, rather than splitting every space
[Command("echo")]
public Task EchoAsync([Remainder] string text)
// Insert a ZWSP before the text to prevent triggering other bots!
=> ReplyAsync('\u200B' + text);
// 'params' will parse space-separated elements into a list
[Command("list")]
public Task ListAsync(params string[] objects)
=> ReplyAsync("You listed: " + string.Join("; ", objects));
}
}
| mit | C# |
84bc84d17977983ee387c2c5e906122112132f7c | Extend class User with RingId property #67 | JetBrains/YouTrackSharp,JetBrains/YouTrackSharp | src/YouTrackSharp/Management/User.cs | src/YouTrackSharp/Management/User.cs | using Newtonsoft.Json;
namespace YouTrackSharp.Management
{
/// <summary>
/// A class that represents YouTrack user information.
/// </summary>
public class User
{
/// <summary>
/// Ring ID of the user.
/// </summary>
[JsonProperty("ringId")]
public string RingId { get; set; }
/// <summary>
/// Username of the user.
/// </summary>
[JsonProperty("login")]
public string Username { get; set; }
/// <summary>
/// Full name of the user.
/// </summary>
[JsonProperty("fullName")]
public string FullName { get; set; }
/// <summary>
/// Email address of the user.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Jabber of the user.
/// </summary>
[JsonProperty("jabber")]
public string Jabber { get; set; }
}
} | using Newtonsoft.Json;
namespace YouTrackSharp.Management
{
/// <summary>
/// A class that represents YouTrack user information.
/// </summary>
public class User
{
/// <summary>
/// Username of the user.
/// </summary>
[JsonProperty("login")]
public string Username { get; set; }
/// <summary>
/// Full name of the user.
/// </summary>
[JsonProperty("fullName")]
public string FullName { get; set; }
/// <summary>
/// Email address of the user.
/// </summary>
[JsonProperty("email")]
public string Email { get; set; }
/// <summary>
/// Jabber of the user.
/// </summary>
[JsonProperty("jabber")]
public string Jabber { get; set; }
}
} | apache-2.0 | C# |
b80acbf059ab4ba69b9e8dbd4444c0735b5c310c | Use separate output directories for debug and release builds | Thealexbarney/VGAudio,Thealexbarney/VGAudio,Thealexbarney/LibDspAdpcm,Thealexbarney/LibDspAdpcm | build/Lifetime.cs | build/Lifetime.cs | using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine($"bin/{(context.IsReleaseBuild ? "release" : "debug")}");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
} | using Cake.Common;
using Cake.Frosting;
namespace Build
{
public sealed class Lifetime : FrostingLifetime<Context>
{
public override void Setup(Context context)
{
context.Configuration = context.Argument("configuration", "Release");
context.BaseDir = context.Environment.WorkingDirectory;
context.SourceDir = context.BaseDir.Combine("src");
context.BuildDir = context.BaseDir.Combine("build");
context.CakeToolsDir = context.BaseDir.Combine("tools/cake");
context.LibraryDir = context.SourceDir.Combine("VGAudio");
context.CliDir = context.SourceDir.Combine("VGAudio.Cli");
context.TestsDir = context.SourceDir.Combine("VGAudio.Tests");
context.BenchmarkDir = context.SourceDir.Combine("VGAudio.Benchmark");
context.UwpDir = context.SourceDir.Combine("VGAudio.Uwp");
context.SlnFile = context.SourceDir.CombineWithFilePath("VGAudio.sln");
context.TestsCsproj = context.TestsDir.CombineWithFilePath("VGAudio.Tests.csproj");
context.PublishDir = context.BaseDir.Combine("Publish");
context.LibraryPublishDir = context.PublishDir.Combine("NuGet");
context.CliPublishDir = context.PublishDir.Combine("cli");
context.UwpPublishDir = context.PublishDir.Combine("uwp");
context.ReleaseCertThumbprint = "2043012AE523F7FA0F77A537387633BEB7A9F4DD";
}
}
} | mit | C# |
05e21ca49ffe542d234a41612c1b94ccca5924ca | Move ProxyActivator to Abstractions | AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/AspectCore-Framework | src/AspectCore.Lite/Internal/ProxyActivator.cs | src/AspectCore.Lite/Internal/ProxyActivator.cs | using AspectCore.Lite.Abstractions;
using AspectCore.Lite.Generators;
using System;
using Microsoft.Extensions.DependencyInjection;
namespace AspectCore.Lite.Abstractions
{
public class ProxyActivator : IProxyActivator
{
private readonly IServiceProvider serviceProvider;
public ProxyActivator(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
this.serviceProvider = serviceProvider;
}
public object CreateClassProxy(Type serviceType , object instance , Type[] interfaceTypes)
{
var proxyGenerator = new ClassProxyGenerator(serviceProvider , serviceType , interfaceTypes);
var proxyType = proxyGenerator.GenerateProxyType();
return ActivatorUtilities.CreateInstance(serviceProvider , proxyType , new object[] { serviceProvider , instance });
}
public object CreateInterfaceProxy(Type serviceType , object instance , Type[] interfaceTypes)
{
var proxyGenerator = new InterfaceProxyGenerator(serviceProvider , serviceType , interfaceTypes);
var proxyType = proxyGenerator.GenerateProxyType();
return ActivatorUtilities.CreateInstance(serviceProvider , proxyType , new object[] { serviceProvider , instance });
}
}
}
| using AspectCore.Lite.Abstractions;
using AspectCore.Lite.Generators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
namespace AspectCore.Lite.Internal
{
public class ProxyActivator : IProxyActivator
{
private readonly IServiceProvider serviceProvider;
public ProxyActivator(IServiceProvider serviceProvider)
{
if (serviceProvider == null)
{
throw new ArgumentNullException(nameof(serviceProvider));
}
this.serviceProvider = serviceProvider;
}
public object CreateClassProxy(Type serviceType , object instance , Type[] interfaceTypes)
{
var proxyGenerator = new ClassProxyGenerator(serviceProvider , serviceType , interfaceTypes);
var proxyType = proxyGenerator.GenerateProxyType();
return ActivatorUtilities.CreateInstance(serviceProvider , proxyType , new object[] { serviceProvider , instance });
}
public object CreateInterfaceProxy(Type serviceType , object instance , Type[] interfaceTypes)
{
var proxyGenerator = new InterfaceProxyGenerator(serviceProvider , serviceType , interfaceTypes);
var proxyType = proxyGenerator.GenerateProxyType();
return ActivatorUtilities.CreateInstance(serviceProvider , proxyType , new object[] { serviceProvider , instance });
}
}
}
| mit | C# |
0abc2ff83eb994b43ac762e632198039632f392b | Optimize polymorphic serializer check | FreecraftCore/FreecraftCore.Serializer,FreecraftCore/FreecraftCore.Serializer | src/FreecraftCore.Serializer/Serializer/SerializerService.cs | src/FreecraftCore.Serializer/Serializer/SerializerService.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace FreecraftCore.Serializer
{
//So it's abit confusing but these are legacy interface types that used to exist and implement
//the logic for serialization.
public sealed class SerializerService : ISerializerService, ISerializationPolymorphicRegister
{
public readonly object SyncObj = new object();
//WARNING: Do not change this strange implementation, 10-15% faster than mapping Type via dictionary and then casting.
//This is a clever hack for performance that avoids slow Dictionary key lookups
//and casting
//Realistically it should have this contraint but not required: where TWireType : IWireMessage<TWireType>
private class GenericPolymorphicSerializerContainer<TWireType>
{
public static ITypeSerializerReadingStrategy<TWireType> Instance { get; set; }
}
//Do not remove!
static SerializerService()
{
}
/// <inheritdoc />
public T Read<T>(Span<byte> buffer, ref int offset)
where T : ITypeSerializerReadingStrategy<T>
{
//To support polymorphic serialization this hack was invented, requiring polymorphic
//serializers be registered with the serializer service at application startup
//These type checks were slow in hotpath. It's actually cheaper to check
//generic nullness.
//Doing the above null check instead is about 10% speedup.
//Proven by profiling
//if (typeof(T).IsValueType || !typeof(T).IsAbstract)
if (GenericPolymorphicSerializerContainer<T>.Instance == null)
{
return Activator.CreateInstance<T>()
.Read(buffer, ref offset);
}
else
{
//HOT PATH: This is a clever hack to avoid costly lookup and casting.
//This is the case where we have a non-newable abstract type
//that actually cannot be construted and read as a WireMessage type
return GenericPolymorphicSerializerContainer<T>.Instance
.Read(buffer, ref offset);
}
}
/// <inheritdoc />
public void Write<T>(T value, Span<byte> buffer, ref int offset)
where T : ITypeSerializerWritingStrategy<T>
{
value.Write(value, buffer, ref offset);
}
public void RegisterPolymorphicSerializer<TWireType, TSerializerType>()
where TSerializerType : ITypeSerializerReadingStrategy<TWireType>, new()
where TWireType : IWireMessage<TWireType>
{
lock (SyncObj)
{
//WARNING: Do not change this strange implementation, 10-15% faster than mapping Type via dictionary and then casting.
TSerializerType serializer = new TSerializerType();
GenericPolymorphicSerializerContainer<TWireType>.Instance = serializer;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace FreecraftCore.Serializer
{
//So it's abit confusing but these are legacy interface types that used to exist and implement
//the logic for serialization.
public sealed class SerializerService : ISerializerService, ISerializationPolymorphicRegister
{
public readonly object SyncObj = new object();
//WARNING: Do not change this strange implementation, 10-15% faster than mapping Type via dictionary and then casting.
//This is a clever hack for performance that avoids slow Dictionary key lookups
//and casting
//Realistically it should have this contraint but not required: where TWireType : IWireMessage<TWireType>
private class GenericPolymorphicSerializerContainer<TWireType>
{
public static ITypeSerializerReadingStrategy<TWireType> Instance { get; set; }
}
//Do not remove!
static SerializerService()
{
}
/// <inheritdoc />
public T Read<T>(Span<byte> buffer, ref int offset)
where T : ITypeSerializerReadingStrategy<T>
{
//To support polymorphic serialization this hack was invented, requiring polymorphic
//serializers be registered with the serializer service at application startup
if (typeof(T).IsValueType || !typeof(T).IsAbstract)
{
return Activator.CreateInstance<T>()
.Read(buffer, ref offset);
}
else
{
//HOT PATH: This is a clever hack to avoid costly lookup and casting.
//This is the case where we have a non-newable abstract type
//that actually cannot be construted and read as a WireMessage type
return GenericPolymorphicSerializerContainer<T>.Instance
.Read(buffer, ref offset);
}
}
/// <inheritdoc />
public void Write<T>(T value, Span<byte> buffer, ref int offset)
where T : ITypeSerializerWritingStrategy<T>
{
value.Write(value, buffer, ref offset);
}
public void RegisterPolymorphicSerializer<TWireType, TSerializerType>()
where TSerializerType : ITypeSerializerReadingStrategy<TWireType>, new()
where TWireType : IWireMessage<TWireType>
{
lock (SyncObj)
{
//WARNING: Do not change this strange implementation, 10-15% faster than mapping Type via dictionary and then casting.
TSerializerType serializer = new TSerializerType();
GenericPolymorphicSerializerContainer<TWireType>.Instance = serializer;
}
}
}
}
| agpl-3.0 | C# |
8faab9175c8d0b92bf3010ea04d935455792ff5b | Fix SampleBass potentially adding invalid memory pressure | peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework | osu.Framework/Audio/Sample/SampleBass.cs | osu.Framework/Audio/Sample/SampleBass.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using ManagedBass;
using osu.Framework.Allocation;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using osu.Framework.Platform;
namespace osu.Framework.Audio.Sample
{
internal sealed class SampleBass : Sample, IBassAudio
{
private volatile int sampleId;
public override bool IsLoaded => sampleId != 0;
private NativeMemoryTracker.NativeMemoryLease memoryLease;
internal SampleBass(byte[] data, ConcurrentQueue<Task> customPendingActions = null, int concurrency = DEFAULT_CONCURRENCY)
: base(concurrency)
{
if (customPendingActions != null)
PendingActions = customPendingActions;
if (data.Length > 0)
{
EnqueueAction(() =>
{
sampleId = loadSample(data);
memoryLease = NativeMemoryTracker.AddMemory(this, data.Length);
});
}
}
protected override void Dispose(bool disposing)
{
if (IsLoaded)
{
Bass.SampleFree(sampleId);
memoryLease?.Dispose();
}
base.Dispose(disposing);
}
void IBassAudio.UpdateDevice(int deviceIndex)
{
if (IsLoaded)
// counter-intuitively, this is the correct API to use to migrate a sample to a new device.
Bass.ChannelSetDevice(sampleId, deviceIndex);
}
public int CreateChannel() => Bass.SampleGetChannel(sampleId);
private int loadSample(byte[] data)
{
const BassFlags flags = BassFlags.Default | BassFlags.SampleOverrideLongestPlaying;
if (RuntimeInfo.SupportsJIT)
return Bass.SampleLoad(data, 0, data.Length, PlaybackConcurrency, flags);
using (var handle = new ObjectHandle<byte[]>(data, GCHandleType.Pinned))
return Bass.SampleLoad(handle.Address, 0, data.Length, PlaybackConcurrency, flags);
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using ManagedBass;
using osu.Framework.Allocation;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using osu.Framework.Platform;
namespace osu.Framework.Audio.Sample
{
internal sealed class SampleBass : Sample, IBassAudio
{
private volatile int sampleId;
public override bool IsLoaded => sampleId != 0;
private NativeMemoryTracker.NativeMemoryLease memoryLease;
internal SampleBass(byte[] data, ConcurrentQueue<Task> customPendingActions = null, int concurrency = DEFAULT_CONCURRENCY)
: base(concurrency)
{
if (customPendingActions != null)
PendingActions = customPendingActions;
EnqueueAction(() =>
{
sampleId = loadSample(data);
memoryLease = NativeMemoryTracker.AddMemory(this, data.Length);
});
}
protected override void Dispose(bool disposing)
{
if (IsLoaded)
{
Bass.SampleFree(sampleId);
memoryLease?.Dispose();
}
base.Dispose(disposing);
}
void IBassAudio.UpdateDevice(int deviceIndex)
{
if (IsLoaded)
// counter-intuitively, this is the correct API to use to migrate a sample to a new device.
Bass.ChannelSetDevice(sampleId, deviceIndex);
}
public int CreateChannel() => Bass.SampleGetChannel(sampleId);
private int loadSample(byte[] data)
{
const BassFlags flags = BassFlags.Default | BassFlags.SampleOverrideLongestPlaying;
if (RuntimeInfo.SupportsJIT)
return Bass.SampleLoad(data, 0, data.Length, PlaybackConcurrency, flags);
using (var handle = new ObjectHandle<byte[]>(data, GCHandleType.Pinned))
return Bass.SampleLoad(handle.Address, 0, data.Length, PlaybackConcurrency, flags);
}
}
}
| mit | C# |
7a4944d83f313de6aa1577e4dcd8ac986802f99b | Add check for new embedded portable PDB data | 0xd4d/dnlib | src/DotNet/Pdb/Portable/SymbolReaderCreator.cs | src/DotNet/Pdb/Portable/SymbolReaderCreator.cs | // dnlib: See LICENSE.txt for more info
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb.Symbols;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Pdb.Portable {
static class SymbolReaderCreator {
public static SymbolReader TryCreate(IImageStream pdbStream, bool isEmbeddedPortablePdb) {
try {
if (pdbStream != null) {
pdbStream.Position = 0;
if (pdbStream.ReadUInt32() == 0x424A5342) {
pdbStream.Position = 0;
return new PortablePdbReader(pdbStream, isEmbeddedPortablePdb ? PdbFileKind.EmbeddedPortablePDB : PdbFileKind.PortablePDB);
}
}
}
catch (IOException) {
}
if (pdbStream != null)
pdbStream.Dispose();
return null;
}
public static SymbolReader TryCreate(IMetaData metaData) {
if (metaData == null)
return null;
try {
var peImage = metaData.PEImage;
if (peImage == null)
return null;
var embeddedDir = TryGetEmbeddedDebugDirectory(peImage);
if (embeddedDir == null)
return null;
using (var reader = peImage.CreateStream(embeddedDir.PointerToRawData, embeddedDir.SizeOfData)) {
// "MPDB" = 0x4244504D
if (reader.ReadUInt32() != 0x4244504D)
return null;
uint uncompressedSize = reader.ReadUInt32();
// If this fails, see the (hopefully) updated spec:
// https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/PE-COFF.md#embedded-portable-pdb-debug-directory-entry-type-17
bool newVersion = (uncompressedSize & 0x80000000) != 0;
Debug.Assert(!newVersion);
if (newVersion)
return null;
var decompressedBytes = new byte[uncompressedSize];
using (var deflateStream = new DeflateStream(new MemoryStream(reader.ReadRemainingBytes()), CompressionMode.Decompress)) {
int pos = 0;
while (pos < decompressedBytes.Length) {
int read = deflateStream.Read(decompressedBytes, pos, decompressedBytes.Length - pos);
if (read == 0)
break;
pos += read;
}
if (pos != decompressedBytes.Length)
return null;
var stream = MemoryImageStream.Create(decompressedBytes);
return TryCreate(stream, true);
}
}
}
catch (IOException) {
}
return null;
}
static ImageDebugDirectory TryGetEmbeddedDebugDirectory(IPEImage peImage) {
foreach (var idd in peImage.ImageDebugDirectories) {
if (idd.Type == ImageDebugType.EmbeddedPortablePdb)
return idd;
}
return null;
}
}
}
| // dnlib: See LICENSE.txt for more info
using System.IO;
using System.IO.Compression;
using dnlib.DotNet.MD;
using dnlib.DotNet.Pdb.Symbols;
using dnlib.IO;
using dnlib.PE;
namespace dnlib.DotNet.Pdb.Portable {
static class SymbolReaderCreator {
public static SymbolReader TryCreate(IImageStream pdbStream, bool isEmbeddedPortablePdb) {
try {
if (pdbStream != null) {
pdbStream.Position = 0;
if (pdbStream.ReadUInt32() == 0x424A5342) {
pdbStream.Position = 0;
return new PortablePdbReader(pdbStream, isEmbeddedPortablePdb ? PdbFileKind.EmbeddedPortablePDB : PdbFileKind.PortablePDB);
}
}
}
catch (IOException) {
}
if (pdbStream != null)
pdbStream.Dispose();
return null;
}
public static SymbolReader TryCreate(IMetaData metaData) {
if (metaData == null)
return null;
try {
var peImage = metaData.PEImage;
if (peImage == null)
return null;
var embeddedDir = TryGetEmbeddedDebugDirectory(peImage);
if (embeddedDir == null)
return null;
using (var reader = peImage.CreateStream(embeddedDir.PointerToRawData, embeddedDir.SizeOfData)) {
// "MPDB" = 0x4244504D
if (reader.ReadUInt32() != 0x4244504D)
return null;
uint uncompressedSize = reader.ReadUInt32();
if (uncompressedSize > int.MaxValue)
return null;
var decompressedBytes = new byte[uncompressedSize];
using (var deflateStream = new DeflateStream(new MemoryStream(reader.ReadRemainingBytes()), CompressionMode.Decompress)) {
int pos = 0;
while (pos < decompressedBytes.Length) {
int read = deflateStream.Read(decompressedBytes, pos, decompressedBytes.Length - pos);
if (read == 0)
break;
pos += read;
}
if (pos != decompressedBytes.Length)
return null;
var stream = MemoryImageStream.Create(decompressedBytes);
return TryCreate(stream, true);
}
}
}
catch (IOException) {
}
return null;
}
static ImageDebugDirectory TryGetEmbeddedDebugDirectory(IPEImage peImage) {
foreach (var idd in peImage.ImageDebugDirectories) {
if (idd.Type == ImageDebugType.EmbeddedPortablePdb)
return idd;
}
return null;
}
}
}
| mit | C# |
6fa4efdd422d80373e2de91fb3712fc311616160 | Fix the default virtual path | mrahhal/ExternalTemplates | src/ExternalTemplates.AspNet/IGeneratorOptions.Default.cs | src/ExternalTemplates.AspNet/IGeneratorOptions.Default.cs | using System;
namespace ExternalTemplates
{
/// <summary>
/// Default generator options.
/// </summary>
public class GeneratorOptions : IGeneratorOptions
{
/// <summary>
/// Gets the path relative to the web root where the templates are stored.
/// Default is "Content/templates".
/// </summary>
public string VirtualPath { get; set; } = "Content/templates";
/// <summary>
/// Gets the extension of the templates.
/// Default is ".tmpl.html".
/// </summary>
public string Extension { get; set; } = ".tmpl.html";
/// <summary>
/// Gets the post string to add to the end of the script tag's id following its name.
/// Default is "-tmpl".
/// </summary>
public string PostString { get; set; } = "-tmpl";
}
} | using System;
namespace ExternalTemplates
{
/// <summary>
/// Default generator options.
/// </summary>
public class GeneratorOptions : IGeneratorOptions
{
/// <summary>
/// Gets the path relative to the web root where the templates are stored.
/// Default is "/Content/templates".
/// </summary>
public string VirtualPath { get; set; } = "/Content/templates";
/// <summary>
/// Gets the extension of the templates.
/// Default is ".tmpl.html".
/// </summary>
public string Extension { get; set; } = ".tmpl.html";
/// <summary>
/// Gets the post string to add to the end of the script tag's id following its name.
/// Default is "-tmpl".
/// </summary>
public string PostString { get; set; } = "-tmpl";
}
} | mit | C# |
c29d19ab7150409d3c4bfad1d8321c7eb582dd29 | remove the loop and use first item in FileNames | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.VisualStudio/Helpers/ActiveDocumentSnapshot.cs | src/GitHub.VisualStudio/Helpers/ActiveDocumentSnapshot.cs | using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TextManager.Interop;
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
namespace GitHub.VisualStudio
{
[Export(typeof(IActiveDocumentSnapshot))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ActiveDocumentSnapshot : IActiveDocumentSnapshot
{
public string Name { get; private set; }
public int StartLine { get; private set; }
public int EndLine { get; private set; }
[ImportingConstructor]
public ActiveDocumentSnapshot([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
{
StartLine = EndLine = -1;
Name = Services.Dte2?.ActiveDocument?.FullName;
var projectItem = Services.Dte2?.ActiveDocument?.ProjectItem;
if ((String.Compare(Name, projectItem.FileNames[1], StringComparison.Ordinal) != 0) && (String.Compare(Name, projectItem.FileNames[1], StringComparison.OrdinalIgnoreCase) == 0))
{
Name = projectItem.FileNames[1];
}
var textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
Debug.Assert(textManager != null, "No SVsTextManager service available");
if (textManager == null)
return;
IVsTextView view;
int anchorLine, anchorCol, endLine, endCol;
if (ErrorHandler.Succeeded(textManager.GetActiveView(0, null, out view)) &&
ErrorHandler.Succeeded(view.GetSelection(out anchorLine, out anchorCol, out endLine, out endCol)))
{
StartLine = anchorLine + 1;
EndLine = endLine + 1;
}
}
}
}
| using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TextManager.Interop;
using System;
using System.ComponentModel.Composition;
using System.Diagnostics;
namespace GitHub.VisualStudio
{
[Export(typeof(IActiveDocumentSnapshot))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ActiveDocumentSnapshot : IActiveDocumentSnapshot
{
public string Name { get; private set; }
public int StartLine { get; private set; }
public int EndLine { get; private set; }
[ImportingConstructor]
public ActiveDocumentSnapshot([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider)
{
StartLine = EndLine = -1;
Name = Services.Dte2?.ActiveDocument?.FullName;
var projectItem = Services.Dte2?.ActiveDocument?.ProjectItem;
for (short i = 0; i < 20; i++)
{
if (!Name.Equals(projectItem.FileNames[i]) && Name.Equals(projectItem.FileNames[i].ToLower(System.Globalization.CultureInfo.CurrentCulture)))
{
Name = projectItem.FileNames[i];
return;
}
}
var textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
Debug.Assert(textManager != null, "No SVsTextManager service available");
if (textManager == null)
return;
IVsTextView view;
int anchorLine, anchorCol, endLine, endCol;
if (ErrorHandler.Succeeded(textManager.GetActiveView(0, null, out view)) &&
ErrorHandler.Succeeded(view.GetSelection(out anchorLine, out anchorCol, out endLine, out endCol)))
{
StartLine = anchorLine + 1;
EndLine = endLine + 1;
}
}
}
}
| mit | C# |
456e18cdcb50ddb64bded8ef5a0820a5b848f7f2 | Fix test in the testproj | JetBrains/teamcity-dotmemory,JetBrains/teamcity-dotmemory | testproj/UnitTest1.cs | testproj/UnitTest1.cs | namespace testproj
{
using System;
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
var str1 = "1";
var str2 = "2";
var str3 = "3";
Assert.LessOrEqual(2, memory.ObjectsCount);
Console.WriteLine(str1 + str2 + str3);
});
}
}
}
| namespace testproj
{
using JetBrains.dotMemoryUnit;
using NUnit.Framework;
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
dotMemory.Check(
memory =>
{
Assert.AreEqual(10, memory.ObjectsCount);
});
}
}
}
| apache-2.0 | C# |
1982396c31833fbec2190a193142d35bb9010912 | Add basic formatting support to GlobalStatisticsDisplay (#2616) | ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Statistics/GlobalStatistic.cs | osu.Framework/Statistics/GlobalStatistic.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
namespace osu.Framework.Statistics
{
public class GlobalStatistic<T> : IGlobalStatistic
{
public string Group { get; }
public string Name { get; }
public IBindable<string> DisplayValue => displayValue;
private readonly Bindable<string> displayValue = new Bindable<string>();
public Bindable<T> Bindable { get; } = new Bindable<T>();
public T Value
{
get => Bindable.Value;
set => Bindable.Value = value;
}
public GlobalStatistic(string group, string name)
{
Group = group;
Name = name;
Bindable.BindValueChanged(val =>
{
switch (val.NewValue)
{
case double d:
displayValue.Value = d.ToString("#,0.##");
break;
case int i:
displayValue.Value = i.ToString("#,0");
break;
case long l:
displayValue.Value = l.ToString("#,0");
break;
default:
displayValue.Value = val.NewValue.ToString();
break;
}
}, true);
}
public virtual void Clear() => Bindable.SetDefault();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
namespace osu.Framework.Statistics
{
public class GlobalStatistic<T> : IGlobalStatistic
{
public string Group { get; }
public string Name { get; }
public IBindable<string> DisplayValue => displayValue;
private readonly Bindable<string> displayValue = new Bindable<string>();
public Bindable<T> Bindable { get; } = new Bindable<T>();
public T Value
{
get => Bindable.Value;
set => Bindable.Value = value;
}
public GlobalStatistic(string group, string name)
{
Group = group;
Name = name;
Bindable.BindValueChanged(val => displayValue.Value = val.NewValue.ToString(), true);
}
public virtual void Clear() => Bindable.SetDefault();
}
}
| mit | C# |
72f30a2b5ed6eaa8d669b25f331e7fa0073485d4 | Package Update | cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack,cetusfinance/qwack | src/Qwack.Providers/Json/CurrenciesFromJson.cs | src/Qwack.Providers/Json/CurrenciesFromJson.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Qwack.Core.Basic;
using Qwack.Dates;
using Qwack.Serialization;
namespace Qwack.Providers.Json
{
public class CurrenciesFromJson : ICurrencyProvider
{
[SkipSerialization]
private readonly JsonSerializerSettings _jsonSettings;
private readonly ICalendarProvider _calendarProvider;
private readonly List<Currency> _allCurrencies;
private readonly Dictionary<string, Currency> _currenciesByName;
private readonly ILogger _logger;
public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILoggerFactory loggerFactory)
:this(calendarProvider, fileName, loggerFactory.CreateLogger<CurrenciesFromJson>())
{
}
public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILogger<CurrenciesFromJson> logger)
{
_logger = logger;
_calendarProvider = calendarProvider;
_jsonSettings = new JsonSerializerSettings()
{
Converters = new JsonConverter[]
{
new CurrencyConverter(_calendarProvider),
},
};
try
{
_allCurrencies = JsonConvert.DeserializeObject<List<Currency>>(System.IO.File.ReadAllText(fileName), _jsonSettings);
_currenciesByName = _allCurrencies.ToDictionary(c => c.Ccy, c => c, StringComparer.OrdinalIgnoreCase);
}
catch(Exception ex)
{
_logger.LogError(ex, "Failed to load currencies from Json");
}
}
public Currency this[string ccy] => _currenciesByName[ccy];
public Currency GetCurrency(string ccy) => TryGetCurrency(ccy, out var C) ? C : throw new Exception($"Currency {ccy} not found in cache");
public bool TryGetCurrency(string ccy, out Currency output) => _currenciesByName.TryGetValue(ccy, out output);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Qwack.Core.Basic;
using Qwack.Dates;
using Qwack.Serialization;
namespace Qwack.Providers.Json
{
public class CurrenciesFromJson : ICurrencyProvider
{
[SkipSerialization]
private readonly JsonSerializerSettings _jsonSettings;
private readonly ICalendarProvider _calendarProvider;
private readonly List<Currency> _allCurrencies;
private readonly Dictionary<string, Currency> _currenciesByName;
private readonly ILogger _logger;
public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILoggerFactory loggerFactory)
:this(calendarProvider, fileName, loggerFactory.CreateLogger<CurrenciesFromJson>())
{
}
public CurrenciesFromJson(ICalendarProvider calendarProvider, string fileName, ILogger<CurrenciesFromJson> logger)
{
_logger = logger;
_calendarProvider = calendarProvider;
_jsonSettings = new JsonSerializerSettings()
{
Converters = new JsonConverter[]
{
new CurrencyConverter(_calendarProvider),
},
};
try
{
_allCurrencies = JsonConvert.DeserializeObject<List<Currency>>(System.IO.File.ReadAllText(fileName), _jsonSettings);
_currenciesByName = _allCurrencies.ToDictionary(c => c.Ccy, c => c, StringComparer.OrdinalIgnoreCase);
}
catch(Exception ex)
{
_logger.LogError(ex, "Failed to load currencies from Json");
}
}
public Currency this[string ccy] => _currenciesByName[ccy];
public Currency GetCurrency(string ccy) => TryGetCurrency(ccy, out var C) ? C : throw new Exception($"Currency {ccy} not found in cache");
public bool TryGetCurrency(string ccy, out Currency output) => _currenciesByName.TryGetValue(ccy, out output);
}
}
| mit | C# |
a6d99737e8b8907f0b429e87d49b27f38da3bd13 | Install service with "delayed auto start". | PeteGoo/graphite-client,peschuster/graphite-client | source/Graphite.System/ServiceInstaller.designer.cs | source/Graphite.System/ServiceInstaller.designer.cs | using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
this.serviceInstaller.DelayedAutoStart = true;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
} | using System.ComponentModel;
using System.ServiceProcess;
using System.Configuration.Install;
namespace Graphite.System
{
public partial class ServiceInstaller
{
private IContainer components = null;
private global::System.ServiceProcess.ServiceInstaller serviceInstaller;
private ServiceProcessInstaller serviceProcessInstaller;
protected override void Dispose(bool disposing)
{
if (disposing && (this.components != null))
{
this.components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.serviceInstaller = new global::System.ServiceProcess.ServiceInstaller();
this.serviceProcessInstaller = new ServiceProcessInstaller();
//
// serviceInstaller
//
this.serviceInstaller.Description = "Graphite System Monitoring";
this.serviceInstaller.DisplayName = "Graphite System Monitoring";
this.serviceInstaller.ServiceName = "GraphiteSystemMonitoring";
this.serviceInstaller.StartType = ServiceStartMode.Automatic;
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = ServiceAccount.LocalSystem;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// ServiceInstaller
//
this.Installers.AddRange(new Installer[]
{
this.serviceInstaller,
this.serviceProcessInstaller
});
}
}
} | mit | C# |
526c5bf58a002c4ecf4b064d7dfcabe61e4c6ed4 | Add tests for SA1018 with nullable tuple types | DotNetAnalyzers/StyleCopAnalyzers | StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/SpacingRules/SA1018CSharp7UnitTests.cs | StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/SpacingRules/SA1018CSharp7UnitTests.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules
{
using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using StyleCop.Analyzers.Test.SpacingRules;
using TestHelper;
using Xunit;
public class SA1018CSharp7UnitTests : SA1018UnitTests
{
/// <summary>
/// Verifies that nullable tuple types with different kinds of spacing will report.
/// </summary>
/// <returns>A <see cref="Task"/> representing the asynchronous unit test.</returns>
[Fact]
public async Task TestNullableTupleTypeSpacingAsync()
{
var testCode = @"namespace TestNamespace
{
public class TestClass
{
public void TestMethod()
{
(int, int) ? v1;
(int, int) /* test */ ? v2;
(int, int)
? v3;
(int, int)
/* test */
? v4;
(int, int)
// test
? v5;
(int, int)
#if TEST
? v6a;
#else
? v6b;
#endif
}
}
}
";
var fixedTestCode = @"namespace TestNamespace
{
public class TestClass
{
public void TestMethod()
{
(int, int)? v1;
(int, int)/* test */? v2;
(int, int)? v3;
(int, int)/* test */? v4;
(int, int)
// test
? v5;
(int, int)
#if TEST
? v6a;
#else
? v6b;
#endif
}
}
}
";
DiagnosticResult[] expectedResults =
{
// v1
this.CSharpDiagnostic().WithLocation(7, 24),
// v2
this.CSharpDiagnostic().WithLocation(8, 35),
// v3
this.CSharpDiagnostic().WithLocation(10, 1),
// v4
this.CSharpDiagnostic().WithLocation(13, 1),
// v5
this.CSharpDiagnostic().WithLocation(16, 1),
// v6
this.CSharpDiagnostic().WithLocation(22, 1),
};
// The fixed test code will have diagnostics, because not all cases can be code fixed automatically.
DiagnosticResult[] fixedExpectedResults =
{
this.CSharpDiagnostic().WithLocation(13, 1),
this.CSharpDiagnostic().WithLocation(19, 1),
};
await this.VerifyCSharpDiagnosticAsync(testCode, expectedResults, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpDiagnosticAsync(fixedTestCode, fixedExpectedResults, CancellationToken.None).ConfigureAwait(false);
await this.VerifyCSharpFixAsync(testCode, fixedTestCode, numberOfFixAllIterations: 2, cancellationToken: CancellationToken.None).ConfigureAwait(false);
}
protected override Solution CreateSolution(ProjectId projectId, string language)
{
Solution solution = base.CreateSolution(projectId, language);
Assembly systemRuntime = AppDomain.CurrentDomain.GetAssemblies().Single(x => x.GetName().Name == "System.Runtime");
return solution
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(systemRuntime.Location))
.AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ValueTuple).Assembly.Location));
}
}
}
| // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
namespace StyleCop.Analyzers.Test.CSharp7.SpacingRules
{
using Test.SpacingRules;
public class SA1018CSharp7UnitTests : SA1018UnitTests
{
}
}
| mit | C# |
fee21072edbe5b4d12b663d96a5e809614dab5ef | Support gist direct link. | congdanhqx/BlogEngine.Gist | GistExtension.cs | GistExtension.cs | using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlogEngine.Gist
{
[Extension("This extension enables Github Gist support for BlogEngine.NET.", "1.0", "Cong Danh")]
public class GistExtension
{
public GistExtension()
{
Post.Serving += Post_Serving;
}
void Post_Serving(object sender, ServingEventArgs e)
{
// [gist id=1234]
e.Body = Regex.Replace(e.Body, "\\[gist\\s[^\\]]*id=(\\d+)[^\\]]*\\]","<script src=\"https://gist.github.com/$1.js\"></script>");
// [gist]1234[/gist]
e.Body = Regex.Replace(e.Body, "\\[gist\\](\\d+)\\[\\/gist\\]", "<script src=\"https://gist.github.com/$1.js\"></script>");
e.Body = Regex.Replace(e.Body, "(\\n|<(br|p)\\s*/?>)\\s*https://gist\\.github\\.com/(\\w+/)?(\\d+)/?\\s*(\\n|<(br|p)\\s*/?>|</p>|</li>)", "<script src=\"https://gist.github.com/$4.js\"></script>");
e.Body = Regex.Replace(e.Body, "\\[gist\\s+https://gist\\.github\\.com/(\\w+/)?(\\d+)/?\\s*\\]", "<script src=\"https://gist.github.com/$2.js\"></script>");
}
}
}
| using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace BlogEngine.Gist
{
[Extension("This extension enables Github Gist support for BlogEngine.NET.", "1.0", "Cong Danh")]
public class GistExtension
{
public GistExtension()
{
Post.Serving += Post_Serving;
}
void Post_Serving(object sender, ServingEventArgs e)
{
// [gist id=1234]
e.Body = Regex.Replace(e.Body, "\\[gist\\s[^\\]]*id=(\\d+)[^\\]]*\\]","<script src=\"https://gist.github.com/$1.js\"></script>");
// [gist]1234[/gist]
e.Body = Regex.Replace(e.Body, "\\[gist\\](\\d+)\\[\\/gist\\]", "<script src=\"https://gist.github.com/$1.js\"></script>");
}
}
}
| apache-2.0 | C# |
243048ecdbe82b6f2fa98ceeec2fdfca75a09e35 | Update ShapeStateTypeConverter.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | src/Serializer.Xaml/Converters/ShapeStateTypeConverter.cs | src/Serializer.Xaml/Converters/ShapeStateTypeConverter.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
#if NETSTANDARD1_3
using System.ComponentModel;
#else
using Portable.Xaml.ComponentModel;
#endif
using Core2D.Shape;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ShapeState"/> type converter.
/// </summary>
internal class ShapeStateTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ShapeState.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var state = value as ShapeState;
if (state != null)
{
return state.ToString();
}
throw new NotSupportedException();
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Globalization;
#if NETSTANDARD
using System.ComponentModel;
#else
using Portable.Xaml.ComponentModel;
#endif
using Core2D.Shape;
namespace Serializer.Xaml.Converters
{
/// <summary>
/// Defines <see cref="ShapeState"/> type converter.
/// </summary>
internal class ShapeStateTypeConverter : TypeConverter
{
/// <inheritdoc/>
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
/// <inheritdoc/>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string);
}
/// <inheritdoc/>
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
return ShapeState.Parse((string)value);
}
/// <inheritdoc/>
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
var state = value as ShapeState;
if (state != null)
{
return state.ToString();
}
throw new NotSupportedException();
}
}
}
| mit | C# |
6c2dee76e68deee4aa8a392b79a876f42da01171 | Add filter to prune away outdated VCS branches | amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre | src/TeamCityTheatre.Core/DataServices/BuildDataService.cs | src/TeamCityTheatre.Core/DataServices/BuildDataService.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using TeamCityTheatre.Core.Client;
using TeamCityTheatre.Core.Client.Mappers;
using TeamCityTheatre.Core.Client.Responses;
using TeamCityTheatre.Core.Models;
namespace TeamCityTheatre.Core.DataServices {
public class BuildDataService : IBuildDataService {
readonly ITeamCityClient _teamCityClient;
readonly IBuildMapper _buildMapper;
public BuildDataService(ITeamCityClient teamCityClient, IBuildMapper buildMapper) {
_teamCityClient = teamCityClient ?? throw new ArgumentNullException(nameof(teamCityClient));
_buildMapper = buildMapper ?? throw new ArgumentNullException(nameof(buildMapper));
}
public async Task<IEnumerable<IDetailedBuild>> GetBuildsOfBuildConfigurationAsync(string buildConfigurationId, int count = 100) {
var request = new RestRequest("builds/?locator=branch:(default:any,policy:active_history_and_active_vcs_branches),running:any,count:{count},buildType:(id:{buildConfigurationId})" +
"&fields=count,build(id,buildTypeId,number,status,state,percentageComplete,branchName,defaultBranch,href,webUrl," +
"running-info(percentageComplete,elapsedSeconds,estimatedTotalSeconds,currentStageText),queuedDate,startDate,finishDate)");
request.AddUrlSegment("count", Convert.ToString(count));
request.AddUrlSegment("buildConfigurationId", buildConfigurationId);
var response = await _teamCityClient.ExecuteRequestAsync<BuildsResponse>(request);
return _buildMapper.Map(response);
}
public async Task<IDetailedBuild> GetBuildDetailsAsync(int buildId) {
var request = new RestRequest("builds/id:{buildId}");
request.AddUrlSegment("buildId", Convert.ToString(buildId));
var response = await _teamCityClient.ExecuteRequestAsync<BuildResponse>(request);
return _buildMapper.Map(response);
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using TeamCityTheatre.Core.Client;
using TeamCityTheatre.Core.Client.Mappers;
using TeamCityTheatre.Core.Client.Responses;
using TeamCityTheatre.Core.Models;
namespace TeamCityTheatre.Core.DataServices {
public class BuildDataService : IBuildDataService {
readonly ITeamCityClient _teamCityClient;
readonly IBuildMapper _buildMapper;
public BuildDataService(ITeamCityClient teamCityClient, IBuildMapper buildMapper) {
_teamCityClient = teamCityClient ?? throw new ArgumentNullException(nameof(teamCityClient));
_buildMapper = buildMapper ?? throw new ArgumentNullException(nameof(buildMapper));
}
public async Task<IEnumerable<IDetailedBuild>> GetBuildsOfBuildConfigurationAsync(string buildConfigurationId, int count = 100) {
var request = new RestRequest("builds/?locator=branch:(default:any),running:any,count:{count},buildType:(id:{buildConfigurationId})" +
"&fields=count,build(id,buildTypeId,number,status,state,percentageComplete,branchName,defaultBranch,href,webUrl," +
"running-info(percentageComplete,elapsedSeconds,estimatedTotalSeconds,currentStageText),queuedDate,startDate,finishDate)");
request.AddUrlSegment("count", Convert.ToString(count));
request.AddUrlSegment("buildConfigurationId", buildConfigurationId);
var response = await _teamCityClient.ExecuteRequestAsync<BuildsResponse>(request);
return _buildMapper.Map(response);
}
public async Task<IDetailedBuild> GetBuildDetailsAsync(int buildId) {
var request = new RestRequest("builds/id:{buildId}");
request.AddUrlSegment("buildId", Convert.ToString(buildId));
var response = await _teamCityClient.ExecuteRequestAsync<BuildResponse>(request);
return _buildMapper.Map(response);
}
}
} | mit | C# |
21104ec1ee26d2f89affaa76a737ec23fb185e61 | remove BOM | jboeuf/grpc,vjpai/grpc,muxi/grpc,vjpai/grpc,grpc/grpc,grpc/grpc,ejona86/grpc,donnadionne/grpc,firebase/grpc,pszemus/grpc,ctiller/grpc,ctiller/grpc,vjpai/grpc,pszemus/grpc,jtattermusch/grpc,ctiller/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,ejona86/grpc,jtattermusch/grpc,firebase/grpc,firebase/grpc,muxi/grpc,grpc/grpc,firebase/grpc,nicolasnoble/grpc,jtattermusch/grpc,firebase/grpc,grpc/grpc,donnadionne/grpc,nicolasnoble/grpc,nicolasnoble/grpc,jboeuf/grpc,vjpai/grpc,muxi/grpc,nicolasnoble/grpc,muxi/grpc,muxi/grpc,muxi/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,pszemus/grpc,jtattermusch/grpc,vjpai/grpc,stanley-cheung/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jboeuf/grpc,grpc/grpc,firebase/grpc,ctiller/grpc,stanley-cheung/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,muxi/grpc,pszemus/grpc,ejona86/grpc,pszemus/grpc,nicolasnoble/grpc,stanley-cheung/grpc,ejona86/grpc,firebase/grpc,ctiller/grpc,ejona86/grpc,firebase/grpc,donnadionne/grpc,jboeuf/grpc,pszemus/grpc,nicolasnoble/grpc,ctiller/grpc,stanley-cheung/grpc,pszemus/grpc,ctiller/grpc,jtattermusch/grpc,donnadionne/grpc,grpc/grpc,ctiller/grpc,jtattermusch/grpc,firebase/grpc,ctiller/grpc,donnadionne/grpc,jtattermusch/grpc,vjpai/grpc,grpc/grpc,muxi/grpc,ejona86/grpc,vjpai/grpc,stanley-cheung/grpc,nicolasnoble/grpc,ejona86/grpc,jtattermusch/grpc,jboeuf/grpc,jboeuf/grpc,stanley-cheung/grpc,jboeuf/grpc,donnadionne/grpc,vjpai/grpc,pszemus/grpc,ejona86/grpc,muxi/grpc,ejona86/grpc,muxi/grpc,jtattermusch/grpc,grpc/grpc,donnadionne/grpc,pszemus/grpc,nicolasnoble/grpc,ctiller/grpc,grpc/grpc,ejona86/grpc,muxi/grpc,vjpai/grpc,stanley-cheung/grpc,pszemus/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,jtattermusch/grpc,jtattermusch/grpc,firebase/grpc,firebase/grpc,pszemus/grpc,vjpai/grpc,donnadionne/grpc,ctiller/grpc,grpc/grpc,jboeuf/grpc,nicolasnoble/grpc,vjpai/grpc,ejona86/grpc,nicolasnoble/grpc,ctiller/grpc,pszemus/grpc,grpc/grpc,donnadionne/grpc,muxi/grpc,jboeuf/grpc,firebase/grpc,jtattermusch/grpc,jboeuf/grpc | test/distrib/csharp/DistribTest/Program.cs | test/distrib/csharp/DistribTest/Program.cs | #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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.
#endregion
using System;
using Grpc.Core;
namespace TestGrpcPackage
{
class MainClass
{
public static void Main(string[] args)
{
// test codegen works
var reply = new Testcodegen.HelloReply();
// This code doesn't do much but makes sure the native extension is loaded
// which is what we are testing here.
Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure);
c.ShutdownAsync().Wait();
Console.WriteLine("Success!");
}
}
}
| #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// 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.
#endregion
using System;
using Grpc.Core;
namespace TestGrpcPackage
{
class MainClass
{
public static void Main(string[] args)
{
// test codegen works
var reply = new Testcodegen.HelloReply();
// This code doesn't do much but makes sure the native extension is loaded
// which is what we are testing here.
Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure);
c.ShutdownAsync().Wait();
Console.WriteLine("Success!");
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.