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 |
|---|---|---|---|---|---|---|---|---|
f324072d44d70ec439fe8ef17e95f7dff2d426a2 | Make map pool layout more correct | johnneijzen/osu,EVAST9919/osu,2yangk23/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu | osu.Game.Tournament.Tests/TestCaseMapPool.cs | osu.Game.Tournament.Tests/TestCaseMapPool.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Screens;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
using OpenTK;
namespace osu.Game.Tournament.Tests
{
public class TestCaseMapPool : LadderTestCase
{
[BackgroundDependencyLoader]
private void load()
{
var round = Ladder.Groupings.First(g => g.Name == "Finals");
Add(new MapPoolScreen(round));
}
}
public class MapPoolScreen : OsuScreen
{
public MapPoolScreen(TournamentGrouping round)
{
FillFlowContainer maps;
InternalChildren = new Drawable[]
{
maps = new FillFlowContainer
{
Spacing = new Vector2(20),
Padding = new MarginPadding(50),
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.Both,
},
};
foreach (var b in round.Beatmaps)
maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
});
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Ladder.Components;
namespace osu.Game.Tournament.Tests
{
public class TestCaseMapPool : LadderTestCase
{
[BackgroundDependencyLoader]
private void load()
{
var round = Ladder.Groupings.First(g => g.Name == "Finals");
Add(new MapPoolScreen(round));
}
}
public class MapPoolScreen : CompositeDrawable
{
public MapPoolScreen(TournamentGrouping round)
{
FillFlowContainer maps;
InternalChildren = new Drawable[]
{
maps = new FillFlowContainer
{
Direction = FillDirection.Full,
RelativeSizeAxes = Axes.Both,
},
};
foreach (var b in round.Beatmaps)
maps.Add(new TournamentBeatmapPanel(b.BeatmapInfo));
}
}
}
| mit | C# |
47d6b3da8b1d6c6b685030830801c7004deb0034 | Bump version | programcsharp/griddly,programcsharp/griddly,programcsharp/griddly | Build/CommonAssemblyInfo.cs | Build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Griddly")]
[assembly: AssemblyCopyright("Copyright © 2013-2022 Chris Hynes, Joel Potter, and Data Research Group")]
[assembly: ComVisible(false)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("3.6.21")]
[assembly: AssemblyFileVersion("3.6.21")]
//[assembly: AssemblyInformationalVersion("2.5-filters")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Griddly")]
[assembly: AssemblyCopyright("Copyright © 2013-2022 Chris Hynes, Joel Potter, and Data Research Group")]
[assembly: ComVisible(false)]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("3.6.20")]
[assembly: AssemblyFileVersion("3.6.20")]
//[assembly: AssemblyInformationalVersion("2.5-filters")]
| mit | C# |
4a6add483f69fc88d4a9909bcde5c7de57f27f98 | Modify Thief and Perspective modification | Guityyo/minerparty,Guityyo/minerparty | Assets/_Scripts/Sensors/Senses/Perspective.cs | Assets/_Scripts/Sensors/Senses/Perspective.cs | using UnityEngine;
using System.Collections;
public class Perspective : Sense
{
public int FieldOfView = 45;
public int ViewDistance = 100;
private Transform playerTrans;
private Vector3 rayDirection;
protected override void Initialise()
{
playerTrans = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
protected override void UpdateSense()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= detectionRate)
DetectAspect();
}
//Detect perspective field of view for the AI Character
void DetectAspect()
{
RaycastHit hit;
rayDirection = playerTrans.position - transform.position;
if ((Vector3.Angle(rayDirection, transform.forward)) < FieldOfView)
{
// Detect if player is within the field of view
if (Physics.Raycast(transform.position, rayDirection, out hit, ViewDistance))
{
Aspect aspect = hit.collider.GetComponent<Aspect>();
if (aspect != null)
{
//Check the aspect
if (aspect.aspectName == aspectName)
{
// enemy = true;
Debug.Log("Enemy Detected!!");
}
}
}
}
}
//Detect perspective field of view for the AI Character
public bool IsWithinViewfield(GameObject obj) {
RaycastHit hit;
rayDirection = obj.transform.position - transform.position;
if ((Vector3.Angle(rayDirection, transform.forward)) < FieldOfView) {
// Detect if mine is within the field of view
if (Physics.Raycast(transform.position, rayDirection, out hit, ViewDistance)) {
//Debug.Log ("Mine visible!");
return true;
}
}
//Debug.Log ("Mine not visible :(");
return false;
}
/// <summary>
/// Show Debug Grids and obstacles inside the editor
/// </summary>
void OnDrawGizmos()
{
if ( playerTrans == null)
return;
Debug.DrawLine(transform.position, playerTrans.position, Color.red);
Vector3 frontRayPoint = transform.position + (transform.forward * ViewDistance);
//Approximate perspective visualization
Vector3 leftRayPoint = frontRayPoint;
leftRayPoint.x += FieldOfView * 0.5f;
Vector3 rightRayPoint = frontRayPoint;
rightRayPoint.x -= FieldOfView * 0.5f;
Debug.DrawLine(transform.position, frontRayPoint, Color.green);
Debug.DrawLine(transform.position, leftRayPoint, Color.green);
Debug.DrawLine(transform.position, rightRayPoint, Color.green);
}
}
| using UnityEngine;
using System.Collections;
public class Perspective : Sense
{
public int FieldOfView = 45;
public int ViewDistance = 100;
private Transform playerTrans;
private Vector3 rayDirection;
protected override void Initialise()
{
playerTrans = GameObject.FindGameObjectWithTag("Player").transform;
}
// Update is called once per frame
protected override void UpdateSense()
{
elapsedTime += Time.deltaTime;
if (elapsedTime >= detectionRate)
DetectAspect();
}
//Detect perspective field of view for the AI Character
void DetectAspect()
{
RaycastHit hit;
rayDirection = playerTrans.position - transform.position;
if ((Vector3.Angle(rayDirection, transform.forward)) < FieldOfView)
{
// Detect if player is within the field of view
if (Physics.Raycast(transform.position, rayDirection, out hit, ViewDistance))
{
Aspect aspect = hit.collider.GetComponent<Aspect>();
if (aspect != null)
{
//Check the aspect
if (aspect.aspectName == aspectName)
{
// enemy = true;
Debug.Log("Enemy Detected!!");
}
}
}
}
}
//Detect perspective field of view for the AI Character
public bool IsWithinViewfield(GameObject obj) {
RaycastHit hit;
rayDirection = obj.transform.position - transform.position;
if ((Vector3.Angle(rayDirection, transform.forward)) < FieldOfView) {
// Detect if mine is within the field of view
if (Physics.Raycast(transform.position, rayDirection, out hit, ViewDistance)) {
Debug.Log ("Mine visible!");
return true;
}
}
Debug.Log ("Mine not visible :(");
return false;
}
/// <summary>
/// Show Debug Grids and obstacles inside the editor
/// </summary>
void OnDrawGizmos()
{
if ( playerTrans == null)
return;
Debug.DrawLine(transform.position, playerTrans.position, Color.red);
Vector3 frontRayPoint = transform.position + (transform.forward * ViewDistance);
//Approximate perspective visualization
Vector3 leftRayPoint = frontRayPoint;
leftRayPoint.x += FieldOfView * 0.5f;
Vector3 rightRayPoint = frontRayPoint;
rightRayPoint.x -= FieldOfView * 0.5f;
Debug.DrawLine(transform.position, frontRayPoint, Color.green);
Debug.DrawLine(transform.position, leftRayPoint, Color.green);
Debug.DrawLine(transform.position, rightRayPoint, Color.green);
}
}
| apache-2.0 | C# |
30a5a4abed9fb2519b6e72308977f624484b5b57 | Add support for named argument parsing. | alastairs/BobTheBuilder,fffej/BobTheBuilder | BobTheBuilder/NamedArgumentsDynamicBuilder.cs | BobTheBuilder/NamedArgumentsDynamicBuilder.cs | using System;
using System.Dynamic;
using System.Linq;
namespace BobTheBuilder
{
public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
private readonly IDynamicBuilder<T> wrappedBuilder;
private readonly IArgumentStore argumentStore;
internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore)
{
if (wrappedBuilder == null)
{
throw new ArgumentNullException("wrappedBuilder");
}
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.wrappedBuilder = wrappedBuilder;
this.argumentStore = argumentStore;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (binder.Name == "With")
{
ParseNamedArgumentValues(binder.CallInfo, args);
}
return wrappedBuilder.TryInvokeMember(binder, args, out result);
}
private void ParseNamedArgumentValues(CallInfo callInfo, object[] args)
{
var argumentName = callInfo.ArgumentNames.First();
argumentName = argumentName.First().ToString().ToUpper() + argumentName.Substring(1);
argumentStore.SetMemberNameAndValue(argumentName, args.First());
}
public T Build()
{
return wrappedBuilder.Build();
}
}
} | using System;
using System.Dynamic;
namespace BobTheBuilder
{
public class NamedArgumentsDynamicBuilder<T> : DynamicObject, IDynamicBuilder<T> where T : class
{
private readonly IDynamicBuilder<T> wrappedBuilder;
private readonly IArgumentStore argumentStore;
internal NamedArgumentsDynamicBuilder(IDynamicBuilder<T> wrappedBuilder, IArgumentStore argumentStore)
{
if (wrappedBuilder == null)
{
throw new ArgumentNullException("wrappedBuilder");
}
if (argumentStore == null)
{
throw new ArgumentNullException("argumentStore");
}
this.wrappedBuilder = wrappedBuilder;
this.argumentStore = argumentStore;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
return wrappedBuilder.TryInvokeMember(binder, args, out result);
}
public T Build()
{
return wrappedBuilder.Build();
}
}
} | apache-2.0 | C# |
0a5951b03955ecc02b083a874209a33518a687af | Remove IDisposable from NaturalSortComparer | BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop | src/BloomExe/Collection/NaturalSortComparer.cs | src/BloomExe/Collection/NaturalSortComparer.cs | using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Bloom.Collection
{
/// <summary>
/// From James McCormack, http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html
/// </summary>
/// <typeparam name="T"></typeparam>
public class NaturalSortComparer<T> : IComparer<string>
{
private bool isAscending;
public NaturalSortComparer(bool inAscendingOrder = true)
{
this.isAscending = inAscendingOrder;
}
#region IComparer<string> Members
public int Compare(string x, string y)
{
throw new NotImplementedException();
}
#endregion
#region IComparer<string> Members
int IComparer<string>.Compare(string x, string y)
{
if (x == y)
return 0;
string[] x1, y1;
if (!table.TryGetValue(x, out x1))
{
x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
table.Add(x, x1);
}
if (!table.TryGetValue(y, out y1))
{
y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
table.Add(y, y1);
}
int returnVal;
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
returnVal = PartCompare(x1[i], y1[i]);
return isAscending ? returnVal : -returnVal;
}
}
if (y1.Length > x1.Length)
{
returnVal = 1;
}
else if (x1.Length > y1.Length)
{
returnVal = -1;
}
else
{
returnVal = 0;
}
return isAscending ? returnVal : -returnVal;
}
private static int PartCompare(string left, string right)
{
int x, y;
if (!int.TryParse(left, out x))
return left.CompareTo(right);
if (!int.TryParse(right, out y))
return left.CompareTo(right);
return x.CompareTo(y);
}
#endregion
private Dictionary<string, string[]> table = new Dictionary<string, string[]>();
}
}
| using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace Bloom.Collection
{
/// <summary>
/// From James McCormack, http://zootfroot.blogspot.com/2009/09/natural-sort-compare-with-linq-orderby.html
/// </summary>
/// <typeparam name="T"></typeparam>
public class NaturalSortComparer<T> : IComparer<string>, IDisposable
{
private bool isAscending;
public NaturalSortComparer(bool inAscendingOrder = true)
{
this.isAscending = inAscendingOrder;
}
#region IComparer<string> Members
public int Compare(string x, string y)
{
throw new NotImplementedException();
}
#endregion
#region IComparer<string> Members
int IComparer<string>.Compare(string x, string y)
{
if (x == y)
return 0;
string[] x1, y1;
if (!table.TryGetValue(x, out x1))
{
x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
table.Add(x, x1);
}
if (!table.TryGetValue(y, out y1))
{
y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
table.Add(y, y1);
}
int returnVal;
for (int i = 0; i < x1.Length && i < y1.Length; i++)
{
if (x1[i] != y1[i])
{
returnVal = PartCompare(x1[i], y1[i]);
return isAscending ? returnVal : -returnVal;
}
}
if (y1.Length > x1.Length)
{
returnVal = 1;
}
else if (x1.Length > y1.Length)
{
returnVal = -1;
}
else
{
returnVal = 0;
}
return isAscending ? returnVal : -returnVal;
}
private static int PartCompare(string left, string right)
{
int x, y;
if (!int.TryParse(left, out x))
return left.CompareTo(right);
if (!int.TryParse(right, out y))
return left.CompareTo(right);
return x.CompareTo(y);
}
#endregion
private Dictionary<string, string[]> table = new Dictionary<string, string[]>();
public void Dispose()
{
table.Clear();
table = null;
GC.SuppressFinalize(this);
}
}
}
| mit | C# |
f5aa6b09edc9338111114e4e8ea425be37f99cce | Enable stopwatch extension methods for .NET Core | malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,jskeet/nodatime,nodatime/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime | src/NodaTime/Extensions/StopwatchExtensions.cs | src/NodaTime/Extensions/StopwatchExtensions.cs | // Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Diagnostics;
using JetBrains.Annotations;
using NodaTime.Utility;
namespace NodaTime.Extensions
{
/// <summary>
/// Extension methods for <see cref="Stopwatch"/>.
/// </summary>
public static class StopwatchExtensions
{
/// <summary>
/// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>.
/// </summary>
/// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param>
/// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns>
public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch)
{
Preconditions.CheckNotNull(stopwatch, nameof(stopwatch));
return stopwatch.Elapsed.ToDuration();
}
}
}
| // Copyright 2014 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
#if !PCL
using System.Diagnostics;
using JetBrains.Annotations;
using NodaTime.Utility;
namespace NodaTime.Extensions
{
/// <summary>
/// Extension methods for <see cref="Stopwatch"/>.
/// </summary>
public static class StopwatchExtensions
{
/// <summary>
/// Returns the elapsed time of <paramref name="stopwatch"/> as a <see cref="Duration"/>.
/// </summary>
/// <param name="stopwatch">The <c>Stopwatch</c> to obtain the elapsed time from.</param>
/// <returns>The elapsed time of <paramref name="stopwatch"/> as a <c>Duration</c>.</returns>
public static Duration ElapsedDuration([NotNull] this Stopwatch stopwatch)
{
Preconditions.CheckNotNull(stopwatch, nameof(stopwatch));
return stopwatch.Elapsed.ToDuration();
}
}
}
#endif | apache-2.0 | C# |
e466e3d15f8522d4db37575a6665d943d8c6e1e6 | Add group by yellow cards count | mglodack/RedCard.API,mglodack/RedCard.API | src/RedCard.API/Controllers/StatsController.cs | src/RedCard.API/Controllers/StatsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RedCard.API.Contexts;
using RedCard.API.Models;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace RedCard.API.Controllers
{
[Route("api/[controller]")]
public class StatsController : Controller
{
public StatsController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
readonly ApplicationDbContext _dbContext;
[Route("redcards")]
[HttpGet]
public IActionResult RedCardCountForCountry()
{
Func<IGrouping<string, Player>, object> getRedCardsForCountry =
(grouping) => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) };
var redCardCount = _CardsForCountry(getRedCardsForCountry);
return new ObjectResult(new { redCardCountForCountry = redCardCount });
}
[Route("yellowcards")]
[HttpGet]
public IActionResult YellowCardCountForCountry()
{
Func<IGrouping<string, Player>, object> getYellowCardsForCountry =
(grouping) => new { country = grouping.Key, yellowCardCount = grouping.Sum(player => player.YellowCards) };
var yellowCardCount = _CardsForCountry(getYellowCardsForCountry);
return new ObjectResult(new { yellowCardCountForCountry = yellowCardCount });
}
IEnumerable<object> _CardsForCountry(Func<IGrouping<string, Player>, object> getInfo)
{
return _dbContext.Players
.GroupBy(player => player.Country)
.Select(getInfo)
.ToArray();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using RedCard.API.Contexts;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace RedCard.API.Controllers
{
[Route("api/[controller]")]
public class StatsController : Controller
{
public StatsController(ApplicationDbContext dbContext)
{
_dbContext = dbContext;
}
readonly ApplicationDbContext _dbContext;
[HttpGet]
public IActionResult RedCardCountForCountry()
{
var redCardCount = _dbContext.Players
.GroupBy(player => player.Country)
.Select(grouping => new { country = grouping.Key, redCardCount = grouping.Sum(player => player.RedCards) })
.ToArray();
return new ObjectResult(new { redCardCountForCountry = redCardCount });
}
}
}
| mit | C# |
f0cf94f283aaca7981561800cc250eea11742d42 | Allow coroutines of 0 sec delay | gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Utilities/CoroutineUtil.cs | Client/Utilities/CoroutineUtil.cs | using System;
using System.Collections;
using UnityEngine;
namespace LunaClient.Utilities
{
public class CoroutineUtil
{
public static void StartDelayedRoutine(string routineName, Action action, float delayInSec)
{
Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec));
}
private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec)
{
if (delayInSec > 0)
yield return new WaitForSeconds(delayInSec);
try
{
action();
}
catch (Exception e)
{
LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}");
}
}
}
}
| using System;
using System.Collections;
using UnityEngine;
namespace LunaClient.Utilities
{
public class CoroutineUtil
{
public static void StartDelayedRoutine(string routineName, Action action, float delayInSec)
{
Client.Singleton.StartCoroutine(DelaySeconds(routineName, action, delayInSec));
}
private static IEnumerator DelaySeconds(string routineName, Action action, float delayInSec)
{
yield return new WaitForSeconds(delayInSec);
try
{
action();
}
catch (Exception e)
{
LunaLog.LogError($"Error in delayed coroutine: {routineName}. Details {e}");
}
}
}
}
| mit | C# |
a2e4d250d2c5127a8ae99a8dd99fbcb93844c309 | Add perf tests | rmandvikar/csharp-extensions,rmandvikar/csharp-extensions | tests/rm.ExtensionsTest/Base64ExtensionTest.cs | tests/rm.ExtensionsTest/Base64ExtensionTest.cs | using System;
using System.Diagnostics;
using NUnit.Framework;
using rm.Extensions;
namespace rm.ExtensionsTest
{
[TestFixture]
public class Base64ExtensionTest
{
private const int iterations = 1_000_000;
[Test]
[TestCase("Man", "TWFu")]
[TestCase("Woman", "V29tYW4=")]
[TestCase("light work.", "bGlnaHQgd29yay4=")]
[TestCase("light work", "bGlnaHQgd29yaw==")]
public void Base64Encode_01(string s, string base64)
{
Assert.AreEqual(base64, s.ToUtf8Bytes().Base64Encode());
}
[Test]
[TestCase("TWFu", "Man")]
[TestCase("V29tYW4=", "Woman")]
[TestCase("bGlnaHQgd29yay4=", "light work.")]
[TestCase("bGlnaHQgd29yaw==", "light work")]
public void Base64Decode_01(string base64, string s)
{
Assert.AreEqual(s, base64.Base64Decode().ToUtf8String());
}
[Test]
[TestCase("Man", "TWFu")]
[TestCase("Woman", "V29tYW4")]
[TestCase("light work.", "bGlnaHQgd29yay4")]
[TestCase("light work", "bGlnaHQgd29yaw")]
public void Base64UrlEncode_01(string s, string base64Url)
{
Assert.AreEqual(base64Url, s.ToUtf8Bytes().Base64UrlEncode());
}
[Test]
[TestCase("TWFu", "Man")]
[TestCase("V29tYW4", "Woman")]
[TestCase("bGlnaHQgd29yay4", "light work.")]
[TestCase("bGlnaHQgd29yaw", "light work")]
public void Base64UrlDecode_01(string base64Url, string s)
{
Assert.AreEqual(s, base64Url.Base64UrlDecode().ToUtf8String());
}
[Explicit]
[Test]
[Category("slow")]
public void Perf_Base64Encode()
{
var bytes = "The quick brown fox jumps over the lazy dog.".ToUtf8Bytes();
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
var base64 = bytes.Base64Encode();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
[Explicit]
[Test]
[Category("slow")]
public void Perf_Base64Decode()
{
var base64 = "ahm6a83henmp6ts0c9s6yxve41k6yy10d9tptw3k41qqcsbj41t6gs90dhgqmy90chqpebg=";
var sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
var bytes = base64.Base64Decode();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
}
}
}
| using NUnit.Framework;
using rm.Extensions;
namespace rm.ExtensionsTest
{
[TestFixture]
public class Base64ExtensionTest
{
[Test]
[TestCase("Man", "TWFu")]
[TestCase("Woman", "V29tYW4=")]
[TestCase("light work.", "bGlnaHQgd29yay4=")]
[TestCase("light work", "bGlnaHQgd29yaw==")]
public void Base64Encode_01(string s, string base64)
{
Assert.AreEqual(base64, s.ToUtf8Bytes().Base64Encode());
}
[Test]
[TestCase("TWFu", "Man")]
[TestCase("V29tYW4=", "Woman")]
[TestCase("bGlnaHQgd29yay4=", "light work.")]
[TestCase("bGlnaHQgd29yaw==", "light work")]
public void Base64Decode_01(string base64, string s)
{
Assert.AreEqual(s, base64.Base64Decode().ToUtf8String());
}
[Test]
[TestCase("Man", "TWFu")]
[TestCase("Woman", "V29tYW4")]
[TestCase("light work.", "bGlnaHQgd29yay4")]
[TestCase("light work", "bGlnaHQgd29yaw")]
public void Base64UrlEncode_01(string s, string base64Url)
{
Assert.AreEqual(base64Url, s.ToUtf8Bytes().Base64UrlEncode());
}
[Test]
[TestCase("TWFu", "Man")]
[TestCase("V29tYW4", "Woman")]
[TestCase("bGlnaHQgd29yay4", "light work.")]
[TestCase("bGlnaHQgd29yaw", "light work")]
public void Base64UrlDecode_01(string base64Url, string s)
{
Assert.AreEqual(s, base64Url.Base64UrlDecode().ToUtf8String());
}
}
}
| mit | C# |
2364b0539d6672482b90a5a005b690b86204e2b6 | Fix README to reflect recent name changes | rlugojr/octokit.net,hahmed/octokit.net,Sarmad93/octokit.net,ChrisMissal/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shiftkey-tester/octokit.net,mminns/octokit.net,Sarmad93/octokit.net,ivandrofly/octokit.net,hahmed/octokit.net,hitesh97/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,kolbasov/octokit.net,devkhan/octokit.net,takumikub/octokit.net,fffej/octokit.net,editor-tools/octokit.net,mminns/octokit.net,forki/octokit.net,octokit/octokit.net,khellang/octokit.net,rlugojr/octokit.net,magoswiat/octokit.net,chunkychode/octokit.net,SLdragon1989/octokit.net,M-Zuber/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,khellang/octokit.net,ivandrofly/octokit.net,adamralph/octokit.net,gdziadkiewicz/octokit.net,octokit-net-test/octokit.net,thedillonb/octokit.net,SamTheDev/octokit.net,Red-Folder/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,fake-organization/octokit.net,eriawan/octokit.net,octokit-net-test-org/octokit.net,michaKFromParis/octokit.net,TattsGroup/octokit.net,shana/octokit.net,devkhan/octokit.net,daukantas/octokit.net,editor-tools/octokit.net,darrelmiller/octokit.net,brramos/octokit.net,alfhenrik/octokit.net,SmithAndr/octokit.net,nsrnnnnn/octokit.net,SamTheDev/octokit.net,gabrielweyer/octokit.net,thedillonb/octokit.net,nsnnnnrn/octokit.net,shiftkey/octokit.net,bslliw/octokit.net,yonglehou/octokit.net,eriawan/octokit.net,shiftkey-tester/octokit.net,shiftkey/octokit.net,octokit-net-test-org/octokit.net,gabrielweyer/octokit.net,yonglehou/octokit.net,kdolan/octokit.net,naveensrinivasan/octokit.net,shana/octokit.net,alfhenrik/octokit.net,octokit/octokit.net,dampir/octokit.net,cH40z-Lord/octokit.net,gdziadkiewicz/octokit.net,dlsteuer/octokit.net,chunkychode/octokit.net,geek0r/octokit.net | Nocto.Tests.Integration/Readme.cs | Nocto.Tests.Integration/Readme.cs | using System.Threading.Tasks;
namespace Nocto.Tests
{
public class Readme
{
public Readme()
{
// create an anonymous client
var client = new GitHubClient();
// create a client with basic auth
client = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// create a client with an oauth token
client = new GitHubClient { Token = "oauthtoken" };
}
public async Task UserApi()
{
var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// Get the authenticated user
var user = await github.User.Current();
// Get a user by username
user = await github.User.Get("tclem");
// Update a user
user = await github.User.Update(new UserUpdate { Name = "octolish" });
}
public async Task AuthorizationsApi()
{
var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// create a new auth
var auth = await github.Authorization.CreateAsync(new AuthorizationUpdate { Note = "integration test", NoteUrl = "http://example.com", Scopes = new[] { "public_repo" } });
// list all authorizations for the authenticated user
var auths = await github.Authorization.GetAllAsync();
// get a specific auth
auth = await github.Authorization.GetAsync(auth.Id);
// update an auth
auth = await github.Authorization.UpdateAsync(auth.Id, new AuthorizationUpdate { Note = "integration test update" });
// delete a specific auth
await github.Authorization.DeleteAsync(auth.Id);
}
public async Task ReposApi()
{
var github = new GitHubClient { Token = "945c6aa4194a6916c9eb1d845d2ff9f357dfe43e" };
// list all repos for the authenticated user
var repos = await github.Repository.GetAll();
// list repos for a user
//github.Repositories.GetAllAsync(new RepositoryQuery { Login = "tclem" });
// list repos for an org
//github.Repositories.GetAllAsync(new RepositoryQuery { Login = "github" });
}
}
}
| using System.Threading.Tasks;
namespace Nocto.Tests
{
public class Readme
{
public Readme()
{
// create an anonymous client
var client = new GitHubClient();
// create a client with basic auth
client = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// create a client with an oauth token
client = new GitHubClient { Token = "oauthtoken" };
}
public async Task UserApi()
{
var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// Get the authenticated user
var user = await github.User.Current();
// Get a user by username
user = await github.User.Get("tclem");
// Update a user
user = await github.User.Update(new UserUpdate { Name = "octolish" });
}
public async Task AuthorizationsApi()
{
var github = new GitHubClient { Login = "xapitestaccountx", Password = "octocat11" };
// create a new auth
var auth = await github.Authorization.CreateAsync(new AuthorizationUpdate { Note = "integration test", NoteUrl = "http://example.com", Scopes = new[] { "public_repo" } });
// list all authorizations for the authenticated user
var auths = await github.Authorization.GetAllAsync();
// get a specific auth
auth = await github.Authorization.GetAsync(auth.Id);
// update an auth
auth = await github.Authorization.UpdateAsync(auth.Id, new AuthorizationUpdate { Note = "integration test update" });
// delete a specific auth
await github.Authorization.DeleteAsync(auth.Id);
}
public async Task ReposApi()
{
var github = new GitHubClient { Token = "945c6aa4194a6916c9eb1d845d2ff9f357dfe43e" };
// list all repos for the authenticated user
var repos = await github.Repository.GetAllAsync();
// list repos for a user
//github.Repositories.GetAllAsync(new RepositoryQuery { Login = "tclem" });
// list repos for an org
//github.Repositories.GetAllAsync(new RepositoryQuery { Login = "github" });
}
}
}
| mit | C# |
6bcfe067e9399b01d576cd6c685e4427f02d6dec | Correct Exception Message | Luke-Wolf/krystal-voicecontrol | Krystal.Core/FileCommand.cs | Krystal.Core/FileCommand.cs | //
// Copyright 2014 Luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
namespace Krystal.Core
{
public abstract class FileCommand
{
#region Constructors
#endregion
#region Methods
#region Public
protected void Execute(String path)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
Process.Start(path);
else if (Environment.OSVersion.Platform == PlatformID.Unix)
Process.Start("xdg-open", path);
}
protected void CheckFileExists(String path)
{
if (File.Exists(path))
PlayPath = path;
else
throw new FileNotFoundException();
}
protected void ExecuteRandomFile(List<String> files)
{
if (files.Count == 0)
throw new InvalidDataException("No Valid Files in this directory");
int rand = randGen.Next(files.Count);
Execute(files[rand]);
}
#endregion
#region Private
#endregion
#region Abstract
public abstract void Execute();
#endregion
#endregion
#region Properties
#region Abstract
#endregion
#endregion
#region Variables
protected String PlayPath;
readonly Random randGen = new Random();
#endregion
}
}
| //
// Copyright 2014 Luke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
namespace Krystal.Core
{
public abstract class FileCommand
{
#region Constructors
#endregion
#region Methods
#region Public
protected void Execute(String path)
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
Process.Start(path);
else if (Environment.OSVersion.Platform == PlatformID.Unix)
Process.Start("xdg-open", path);
}
protected void CheckFileExists(String path)
{
if (File.Exists(path))
PlayPath = path;
else
throw new FileNotFoundException();
}
protected void ExecuteRandomFile(List<String> files)
{
if (files.Count == 0)
throw new InvalidDataException("No Powerpoint Files in this directory");
int rand = randGen.Next(files.Count);
Execute(files[rand]);
}
#endregion
#region Private
#endregion
#region Abstract
public abstract void Execute();
#endregion
#endregion
#region Properties
#region Abstract
#endregion
#endregion
#region Variables
protected String PlayPath;
readonly Random randGen = new Random();
#endregion
}
}
| apache-2.0 | C# |
deb74f5c7ade2ff476ca13e88b659e51b27168fb | Update DataReader.cs | Fody/Obsolete | Obsolete.Fody/DataReader.cs | Obsolete.Fody/DataReader.cs | using Mono.Cecil;
public static class DataReader
{
public static AttributeData ReadAttributeData(CustomAttribute attribute, bool throwsNotImplemented)
{
return new AttributeData
{
Message = attribute.GetValue("Message"),
Replacement = attribute.GetValue("ReplacementTypeOrMember"),
TreatAsErrorFromVersion = attribute.GetValue("TreatAsErrorFromVersion"),
RemoveInVersion = attribute.GetValue("RemoveInVersion"),
ThrowsNotImplemented = throwsNotImplemented
};
}
} | using Mono.Cecil;
public static class DataReader
{
public static AttributeData ReadAttributeData(CustomAttribute obsoleteExAttribute, bool throwsNotImplemented)
{
var treatAsErrorFromVersionString = obsoleteExAttribute.GetValue("TreatAsErrorFromVersion");
var removeInVersionString = obsoleteExAttribute.GetValue("RemoveInVersion");
return new AttributeData
{
Message = obsoleteExAttribute.GetValue("Message"),
Replacement = obsoleteExAttribute.GetValue("ReplacementTypeOrMember"),
TreatAsErrorFromVersion = treatAsErrorFromVersionString,
RemoveInVersion = removeInVersionString,
ThrowsNotImplemented = throwsNotImplemented
};
}
} | mit | C# |
369064dfc8bb2c20e25ba9c5aeeae1b42088e78d | Refactor GetBgpMessage | mstrother/BmpListener | BMPClient/BGP/BgpMessage.cs | BMPClient/BGP/BgpMessage.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected BgpMessage(BgpHeader bgpHeader)
{
Length = bgpHeader.Length;
Type = bgpHeader.Type;
}
[JsonIgnore]
public uint Length { get; }
[JsonConverter(typeof(StringEnumConverter))]
public MessageType Type { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
data = new ArraySegment<byte>(data.Array, 0, 19);
var bgpHeader = new BgpHeader(data);
var msgLength = (int) bgpHeader.Length - 19;
data = new ArraySegment<byte>(data.Array, 19, msgLength);
switch (bgpHeader.Type)
{
case MessageType.Open:
return new BgpOpenMessage(bgpHeader, data);
case MessageType.Update:
return new BgpUpdateMessage(bgpHeader, data);
case MessageType.Notification:
return new BgpNotification(bgpHeader, data);
//case MessageType.Keepalive:
// return new BgpKeepAliveMessage(bgpHeader, msgData);
//case MessageType.RouteRefresh:
// return new BgpRouteMessage(data);
default:
throw new NotImplementedException();
}
}
}
} | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace BmpListener.Bgp
{
public abstract class BgpMessage
{
protected BgpMessage(BgpHeader bgpHeader)
{
Length = bgpHeader.Length;
Type = bgpHeader.Type;
}
[JsonIgnore]
public uint Length { get; }
[JsonConverter(typeof(StringEnumConverter))]
public MessageType Type { get; }
public abstract void DecodeFromBytes(ArraySegment<byte> data);
public static BgpMessage GetBgpMessage(ArraySegment<byte> data)
{
var headerData = new ArraySegment<byte>(data.Array, 0, 19);
var bgpHeader = new BgpHeader(headerData);
var msgLength = (int) bgpHeader.Length - 19;
var msgData = new ArraySegment<byte>(data.Array, 19, msgLength);
switch (bgpHeader.Type)
{
case MessageType.Open:
return new BgpOpenMessage(bgpHeader, msgData);
case MessageType.Update:
return new BgpUpdateMessage(bgpHeader, msgData);
case MessageType.Notification:
return new BgpNotification(bgpHeader, msgData);
//case MessageType.Keepalive:
// return new BgpKeepAliveMessage(bgpHeader, msgData);
//case MessageType.RouteRefresh:
// return new BgpRouteMessage(data);
default:
throw new NotImplementedException();
}
}
}
} | mit | C# |
6b17d8bab2977129f97f3960307e2728d0ef74c4 | Add blank package migration (to get into the list) | KevinJump/uSync,KevinJump/uSync,KevinJump/uSync | uSync/uSync.cs | uSync/uSync.cs | using System;
using Umbraco.Cms.Core.IO;
using Umbraco.Cms.Core.Packaging;
using Umbraco.Cms.Core.PropertyEditors;
using Umbraco.Cms.Core.Services;
using Umbraco.Cms.Core.Strings;
using Umbraco.Cms.Infrastructure.Migrations;
using Umbraco.Cms.Infrastructure.Packaging;
namespace uSync
{
/// <summary>
/// we only have this class, so there is a dll in the root
/// uSync package.
///
/// With a root dll, the package can be stopped from installing
/// on .netframework sites.
/// </summary>
public static class uSync
{
public static string PackageName = "uSync";
// private static string Welcome = "uSync all the things";
}
/// <summary>
/// A package migration plan, allows us to put uSync in the list
/// of installed packages. we don't actually need a migration
/// for uSync (doesn't add anything to the db). but by doing
/// this people can see that it is insalled.
/// </summary>
public class uSyncMigrationPlan : PackageMigrationPlan
{
public uSyncMigrationPlan() :
base(uSync.PackageName)
{ }
protected override void DefinePlan()
{
To<SetupuSync>(new Guid("65735030-E8F2-4F34-B28A-2201AF9792BE"));
}
}
public class SetupuSync : PackageMigrationBase
{
public SetupuSync(
IPackagingService packagingService,
IMediaService mediaService,
MediaFileManager mediaFileManager,
MediaUrlGeneratorCollection mediaUrlGenerators,
IShortStringHelper shortStringHelper,
IContentTypeBaseServiceProvider contentTypeBaseServiceProvider,
IMigrationContext context)
: base(packagingService, mediaService, mediaFileManager, mediaUrlGenerators, shortStringHelper, contentTypeBaseServiceProvider, context)
{
}
protected override void Migrate()
{
// we don't actually need to do anything, but this means we end up
// on the list of installed packages.
}
}
}
| namespace uSync
{
/// <summary>
/// we only have this class, so there is a dll in the root
/// uSync package.
///
/// With a root dll, the package can be stopped from installing
/// on .netframework sites.
/// </summary>
public static class uSync
{
// private static string Welcome = "uSync all the things";
}
}
| mpl-2.0 | C# |
21cfb943bf38a1fcaaeea0227cabf8b151db5915 | bump version | raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2 | source/Raml.Parser/Properties/AssemblyInfo.cs | source/Raml.Parser/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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.1")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")] | apache-2.0 | C# |
1ead34fde2360df97a290b062a24ca5b94b85797 | bump version | raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2 | source/Raml.Parser/Properties/AssemblyInfo.cs | source/Raml.Parser/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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.8")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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.7")] | apache-2.0 | C# |
263b2e6f8078a90113b1bd7da2bf5c8ade1d5199 | Fix comment | CyrusNajmabadi/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,heejaechang/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,gafter/roslyn,AlekseyTs/roslyn,aelij/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,weltkante/roslyn,wvdd007/roslyn,weltkante/roslyn,wvdd007/roslyn,heejaechang/roslyn,wvdd007/roslyn,gafter/roslyn,brettfo/roslyn,mavasani/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,mavasani/roslyn,aelij/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,physhi/roslyn,physhi/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,sharwell/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,dotnet/roslyn,KevinRansom/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,physhi/roslyn,dotnet/roslyn,weltkante/roslyn,diryboy/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,jmarolf/roslyn,genlu/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,brettfo/roslyn,aelij/roslyn,eriawan/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,tmat/roslyn,gafter/roslyn,tmat/roslyn,genlu/roslyn | src/Compilers/Core/Portable/SourceGeneration/ISourceGenerator.cs | src/Compilers/Core/Portable/SourceGeneration/ISourceGenerator.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;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
#nullable enable
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The base interface required to implement a source generator
/// </summary>
/// <remarks>
/// The lifetime of a generator is controlled by the compiler.
/// State should not be stored directly on the generator, as there
/// is no guarantee that the same instance will be used on a
/// subsequent generation pass.
/// </remarks>
public interface ISourceGenerator
{
/// <summary>
/// Called before generation occurs. A generator can use the <paramref name="context"/>
/// to register callbacks required to perform generation.
/// </summary>
/// <param name="context">The <see cref="GeneratorInitializationContext"/> to register callbacks on</param>
void Initialize(GeneratorInitializationContext context);
/// <summary>
/// Called to perform source generation. A generator can use the <paramref name="context"/>
/// to add source files via the <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>
/// method.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> to add source to</param>
/// <remarks>
/// This call represents the main generation step. It is called after a <see cref="Compilation"/> is
/// created that contains the user written code.
///
/// A generator can use the <see cref="GeneratorExecutionContext.Compilation"/> property to
/// discover information about the users compilation and make decisions on what source to
/// provide.
/// </remarks>
void Execute(GeneratorExecutionContext context);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
#nullable enable
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// The base interface required to implement a source generator
/// </summary>
/// <remarks>
/// The lifetime of a generator is controlled by the compiler.
/// State should not be stored directly on the generator, as there
/// is no guarantee that the same instance will be used on a
/// subsequent generation pass.
/// </remarks>
public interface ISourceGenerator
{
/// <summary>
/// Called before generation occurs. A generator can use the <paramref name="context"/>
/// to register callbacks required to perform generation.
/// </summary>
/// <param name="context">The <see cref="InitializationContext"/> to register callbacks on</param>
void Initialize(GeneratorInitializationContext context);
/// <summary>
/// Called to perform source generation. A generator can use the <paramref name="context"/>
/// to add source files via the <see cref="GeneratorExecutionContext.AddSource(string, SourceText)"/>
/// method.
/// </summary>
/// <param name="context">The <see cref="GeneratorExecutionContext"/> to add source to</param>
/// <remarks>
/// This call represents the main generation step. It is called after a <see cref="Compilation"/> is
/// created that contains the user written code.
///
/// A generator can use the <see cref="GeneratorExecutionContext.Compilation"/> property to
/// discover information about the users compilation and make decisions on what source to
/// provide.
/// </remarks>
void Execute(GeneratorExecutionContext context);
}
}
| mit | C# |
c638b00103c9c4852c667baa9f313ebe1ed0b3e6 | Update ObsCollection.cs | ADAPT/ADAPT | source/ADAPT/Documents/ObsCollection.cs | source/ADAPT/Documents/ObsCollection.cs | /*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
* 20210119 R. Andres Ferreyra: Adding code components by value, removing by reference *
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class ObsCollection
{
public ObsCollection()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponents = new List<ObsCodeComponent>(); // List of code components by value to allow parameters, semantic refinement
TimeScopes = new List<TimeScope>(); // List of TimeScopes that apply to all child Obs in the collection
ContextItems = new List<ContextItem>();
ObsCollectionIds = new List<int>(); // Note: these are references to ObsCollections in Documents
ObsIds = new List<int>(); // Note: these are references to Obs in Documents
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces child Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces child Obs to (mostly) key,value pair when installation data is not needed
public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code).
public List<ObsCodeComponent> CodeComponents { get; set; } // List of code components (by value) to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public List<int> ObsCollectionIds { get; set; } // Recursive!
public List<int> ObsIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| /*******************************************************************************
* Copyright (C) 2019 AgGateway; PAIL and ADAPT Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors: 20190430 R. Andres Ferreyra: Translate from PAIL Part 2 Schema
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Documents
{
public class ObsCollection
{
public ObsCollection()
{
Id = CompoundIdentifierFactory.Instance.Create();
CodeComponentIds = new List<int>(); // List of code components that apply to all child Obs in the collection
TimeScopes = new List<TimeScope>(); // List of TimeScopes that apply to all child Obs in the collection
ContextItems = new List<ContextItem>();
ObsCollectionIds = new List<int>(); // Note: these are references to ObsCollections in Documents
ObsIds = new List<int>(); // Note: these are references to Obs in Documents
}
public CompoundIdentifier Id { get; private set; }
public int? OMSourceId { get; set; } // OMSource reduces child Obs to (mostly) key,value pair even with sensors, installation
public int? OMCodeId { get; set; } // OMCode reduces child Obs to (mostly) key,value pair when installation data is not needed
public string OMCode { get; set; } // The string value provides the simplest form of meaning, by referring a pre-existing semantic resource by name (code).
public List<int> CodeComponentIds { get; set; } // List of code components refs to allow parameters, semantic refinement
public List<TimeScope> TimeScopes { get; set; }
public int? GrowerId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a grower
public int? PlaceId { get; set; } // Optional, provides ability to put an ObsCollection in the context of a Place
public Shape SpatialExtent { get; set; } // Optional, includes Point, Polyline, and Polygon features of interest
// Note: PlaceId provides a feature of interest by reference; SpatialExtent does so by value. They are not necessarily
// mutually exclusive.
public List<int> ObsCollectionIds { get; set; } // Recursive!
public List<int> ObsIds { get; set; }
public List<ContextItem> ContextItems { get; set; }
}
}
| epl-1.0 | C# |
96b0804f4e44b1d1d8d0c093df16c7eb2c5556c0 | remove empty statement | Liwoj/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET | Src/Metrics/Sampling/SlidingWindowReservoir.cs | Src/Metrics/Sampling/SlidingWindowReservoir.cs | using System;
using System.Linq;
using Metrics.ConcurrencyUtilities;
namespace Metrics.Sampling
{
public sealed class SlidingWindowReservoir : Reservoir
{
private const int DefaultSize = 1028;
private readonly UserValueWrapper[] values;
private AtomicLong count = new AtomicLong();
public SlidingWindowReservoir()
: this(DefaultSize) { }
public SlidingWindowReservoir(int size)
{
this.values = new UserValueWrapper[size];
}
public void Update(long value, string userValue = null)
{
var newCount = this.count.Increment();
this.values[(int)((newCount - 1) % this.values.Length)] = new UserValueWrapper(value, userValue);
}
public void Reset()
{
Array.Clear(this.values, 0, this.values.Length);
this.count.SetValue(0L);
}
public Snapshot GetSnapshot(bool resetReservoir = false)
{
var size = Math.Min((int)this.count.GetValue(), this.values.Length);
if (size == 0)
{
return new UniformSnapshot(0, Enumerable.Empty<long>());
}
var snapshotValues = new UserValueWrapper[size];
Array.Copy(this.values, snapshotValues, size);
if (resetReservoir)
{
Array.Clear(this.values, 0, snapshotValues.Length);
this.count.SetValue(0L);
}
Array.Sort(snapshotValues, UserValueWrapper.Comparer);
var minValue = snapshotValues[0].UserValue;
var maxValue = snapshotValues[size - 1].UserValue;
return new UniformSnapshot(this.count.GetValue(), snapshotValues.Select(v => v.Value), valuesAreSorted: true, minUserValue: minValue, maxUserValue: maxValue);
}
}
}
| using System;
using System.Linq;
using Metrics.ConcurrencyUtilities;
namespace Metrics.Sampling
{
public sealed class SlidingWindowReservoir : Reservoir
{
private const int DefaultSize = 1028;
private readonly UserValueWrapper[] values;
private AtomicLong count = new AtomicLong();
public SlidingWindowReservoir()
: this(DefaultSize) { }
public SlidingWindowReservoir(int size)
{
this.values = new UserValueWrapper[size];
}
public void Update(long value, string userValue = null)
{
var newCount = this.count.Increment();
this.values[(int)((newCount - 1) % this.values.Length)] = new UserValueWrapper(value, userValue);
}
public void Reset()
{
Array.Clear(this.values, 0, this.values.Length);
this.count.SetValue(0L);
}
public Snapshot GetSnapshot(bool resetReservoir = false)
{
var size = Math.Min((int)this.count.GetValue(), this.values.Length); ;
if (size == 0)
{
return new UniformSnapshot(0, Enumerable.Empty<long>());
}
var snapshotValues = new UserValueWrapper[size];
Array.Copy(this.values, snapshotValues, size);
if (resetReservoir)
{
Array.Clear(this.values, 0, snapshotValues.Length);
this.count.SetValue(0L);
}
Array.Sort(snapshotValues, UserValueWrapper.Comparer);
var minValue = snapshotValues[0].UserValue;
var maxValue = snapshotValues[size - 1].UserValue;
return new UniformSnapshot(this.count.GetValue(), snapshotValues.Select(v => v.Value), valuesAreSorted: true, minUserValue: minValue, maxUserValue: maxValue);
}
}
}
| apache-2.0 | C# |
d841fadc260ec4f87b2f424823ad24a68e2858cf | patch in updating | dev-zzo/Spritesse,dev-zzo/Spritesse | ThreeSheeps.Spritesse/Physics/PhysicalShape.cs | ThreeSheeps.Spritesse/Physics/PhysicalShape.cs | using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace ThreeSheeps.Spritesse.Physics
{
public abstract class PhysicalShape
{
public class CreationInfo
{
public bool SendCollisions;
public bool ReceiveCollisions;
public Vector2 Position;
}
protected PhysicalShape(CreationInfo info)
{
this.canSendCollisions = info.SendCollisions;
this.canReceiveCollisions = info.ReceiveCollisions;
this.position = info.Position;
if (this.canReceiveCollisions)
{
this.collisions = new List<CollisionInformation>();
}
}
public bool CanSendCollisions
{
get { return this.canSendCollisions; }
}
public bool CanReceiveCollisions
{
get { return this.canReceiveCollisions; }
}
public Vector2 Position
{
get { return this.position; }
set { this.UpdatePosition(value); }
}
public abstract Vector2 HalfDimensions { get; }
public IList<CollisionInformation> CollisionList
{
get { return this.collisions; }
}
private void UpdatePosition(Vector2 newValue)
{
if (this.position == newValue)
return;
this.position = newValue;
if (!this.CanSendCollisions)
return;
this.resolver.Update(this);
}
protected ICollisionResolverService resolver;
private bool canSendCollisions;
private bool canReceiveCollisions;
private Vector2 position;
private IList<CollisionInformation> collisions;
}
}
| using System.Collections.Generic;
using Microsoft.Xna.Framework;
namespace ThreeSheeps.Spritesse.Physics
{
public abstract class PhysicalShape
{
public class CreationInfo
{
public bool SendCollisions;
public bool ReceiveCollisions;
public Vector2 Position;
}
protected PhysicalShape(CreationInfo info)
{
this.canSendCollisions = info.SendCollisions;
this.canReceiveCollisions = info.ReceiveCollisions;
this.position = info.Position;
if (this.canReceiveCollisions)
{
this.collisions = new List<CollisionInformation>();
}
}
public bool CanSendCollisions
{
get { return this.canSendCollisions; }
}
public bool CanReceiveCollisions
{
get { return this.canReceiveCollisions; }
}
public Vector2 Position
{
get { return this.position; }
set { this.UpdatePosition(value); }
}
public abstract Vector2 HalfDimensions { get; }
public IList<CollisionInformation> CollisionList
{
get { return this.collisions; }
}
private void UpdatePosition(Vector2 newValue)
{
if (this.position == newValue)
return;
this.position = newValue;
if (!this.CanSendCollisions)
return;
// TODO
}
protected ICollisionResolverService resolver;
private bool canSendCollisions;
private bool canReceiveCollisions;
private Vector2 position;
private IList<CollisionInformation> collisions;
}
}
| unlicense | C# |
73a78470a14e55e8a476582c0f081b04d108f979 | Remove console.log | octoblu/meshblu-connector-skype,octoblu/meshblu-connector-skype | src/csharp/stop-meetings.cs | src/csharp/stop-meetings.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
private async Task stopConversation(Conversation conversation) {
var tcs = new TaskCompletionSource<bool>();
conversation.StateChanged += (sender, e) => {
if (e.NewState != ConversationState.Terminated) return;
tcs.TrySetResult(true);
};
conversation.End();
await tcs.Task;
return;
}
public async Task<object> Invoke(string ignored)
{
foreach(Conversation conversation in LyncClient.GetClient().ConversationManager.Conversations) {
await stopConversation(conversation);
}
return null;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Lync.Model;
using Microsoft.Lync.Model.Conversation;
using Microsoft.Lync.Model.Conversation.AudioVideo;
using Microsoft.Lync.Model.Extensibility;
public class Startup
{
private async Task stopConversation(Conversation conversation) {
// var window = automation.GetConversationWindow(conversation);
// window.Close();
var tcs = new TaskCompletionSource<bool>();
conversation.StateChanged += (sender, e) => {
System.Console.WriteLine("StateChanged: " + e.NewState);
if (e.NewState != ConversationState.Terminated) return;
tcs.TrySetResult(true);
};
conversation.End();
await tcs.Task;
return;
}
public async Task<object> Invoke(string ignored)
{
foreach(Conversation conversation in LyncClient.GetClient().ConversationManager.Conversations) {
await stopConversation(conversation);
}
return null;
}
}
| mit | C# |
a1cedd02c9ed37931a10f872e42be5bf4e7c4909 | improve Paragraph test case names | icarus-consulting/Yaapii.Atoms | tests/Yaapii.Atoms.Tests/Text/ParagraphTest.cs | tests/Yaapii.Atoms.Tests/Text/ParagraphTest.cs | using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Yaapii.Atoms.Enumerable;
namespace Yaapii.Atoms.Texts.Tests
{
public sealed class ParagraphTest
{
[Fact]
public void BuildsWithParamsString()
{
var p = new Paragraph("a", "b", "c");
Assert.Equal("a\nb\nc".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void BuildsWithITextEnumerable()
{
var p = new Paragraph(
new Many.Live<IText>(
new Text.Live("a"),
new Text.Live("b"),
new Text.Live("c")
));
Assert.Equal("a\nb\nc".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void HeadArrayTailStrings()
{
var p = new Paragraph(
"Hello", "World",
new string[] { "I", "was", "here" },
"foo", "bar"
);
Assert.Equal("Hello\nWorld\nI\nwas\nhere\nfoo\nbar".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void HeadsAndTailsMixedITextStrings()
{
var p = new Paragraph(
new Text.Live("Hello"), new Text.Live("World"),
new string[] { "I", "was", "here" },
new Text.Live("foo"), new Text.Live("bar")
);
Assert.Equal("Hello\nWorld\nI\nwas\nhere\nfoo\nbar".Replace("\n", Environment.NewLine), p.AsString());
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using Yaapii.Atoms.Enumerable;
namespace Yaapii.Atoms.Texts.Tests
{
public sealed class ParagraphTest
{
[Fact]
public void ParamsStringWorks()
{
var p = new Paragraph("a", "b", "c");
Assert.Equal("a\nb\nc".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void IEnumITextWorks()
{
var p = new Paragraph(
new Many.Live<IText>(
new Text.Live("a"),
new Text.Live("b"),
new Text.Live("c")
));
Assert.Equal("a\nb\nc".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void HeadArrayTailStrings()
{
var p = new Paragraph(
"Hello", "World",
new string[] { "I", "was", "here" },
"foo", "bar"
);
Assert.Equal("Hello\nWorld\nI\nwas\nhere\nfoo\nbar".Replace("\n", Environment.NewLine), p.AsString());
}
[Fact]
public void HeadsAndTailsMixedITextStrings()
{
var p = new Paragraph(
new Text.Live("Hello"), new Text.Live("World"),
new string[] { "I", "was", "here" },
new Text.Live("foo"), new Text.Live("bar")
);
Assert.Equal("Hello\nWorld\nI\nwas\nhere\nfoo\nbar".Replace("\n", Environment.NewLine), p.AsString());
}
}
}
| mit | C# |
4e84e5fd389c65e2e000aa4702bc8aff2f09a86a | Revert "test port changed" | Softlr/Selenium.WebDriver.Extensions,RaYell/selenium-webdriver-extensions,Softlr/selenium-webdriver-extensions,Softlr/selenium-webdriver-extensions | test/Selenium.WebDriver.Extensions.IntegrationTests/TestsBase.cs | test/Selenium.WebDriver.Extensions.IntegrationTests/TestsBase.cs | namespace Selenium.WebDriver.Extensions.IntegrationTests
{
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Nancy.Hosting.Self;
using OpenQA.Selenium;
using PostSharp.Patterns.Model;
[Disposable]
[PublicAPI]
[ExcludeFromCodeCoverage]
public abstract class TestsBase
{
protected TestsBase(IWebDriver browser, string path)
{
var config = new HostConfiguration { UrlReservations = { CreateAutomatically = true } };
const string serverUrl = "http://localhost:50502";
Host = new NancyHost(config, new Uri(serverUrl));
Host.Start();
Browser = browser;
Browser.Navigate().GoToUrl(new Uri($"{serverUrl}{path}"));
}
[Child]
protected NancyHost Host { get; }
[Reference]
protected IWebDriver Browser { get; }
}
} | namespace Selenium.WebDriver.Extensions.IntegrationTests
{
using System;
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
using Nancy.Hosting.Self;
using OpenQA.Selenium;
using PostSharp.Patterns.Model;
[Disposable]
[PublicAPI]
[ExcludeFromCodeCoverage]
public abstract class TestsBase
{
protected TestsBase(IWebDriver browser, string path)
{
var config = new HostConfiguration { UrlReservations = { CreateAutomatically = true } };
const string serverUrl = "http://localhost:54321";
Host = new NancyHost(config, new Uri(serverUrl));
Host.Start();
Browser = browser;
Browser.Navigate().GoToUrl(new Uri($"{serverUrl}{path}"));
}
[Child]
protected NancyHost Host { get; }
[Reference]
protected IWebDriver Browser { get; }
}
} | apache-2.0 | C# |
4acb077538a8769345de48615b930430e2a253d4 | Resolve #170 - Fix query to get label detail | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.Domain.Impl/Labels/ExistingLabelReader.cs | Agiil.Domain.Impl/Labels/ExistingLabelReader.cs | using System;
using System.Linq;
using CSF.Data.Entities;
using CSF.Data.NHibernate;
namespace Agiil.Domain.Labels
{
public class ExistingLabelReader : IGetsExistingLabel
{
readonly IEntityData data;
public Label GetLabel(string name)
{
if(String.IsNullOrEmpty(name)) return null;
return data.Query<Label>()
.Where(x => x.Name == name)
.FetchMany(x => x.Tickets)
.AsEnumerable()
.FirstOrDefault();
}
public ExistingLabelReader(IEntityData data)
{
if(data == null)
throw new ArgumentNullException(nameof(data));
this.data = data;
}
}
}
| using System;
using System.Linq;
using CSF.Data.Entities;
using CSF.Data.NHibernate;
namespace Agiil.Domain.Labels
{
public class ExistingLabelReader : IGetsExistingLabel
{
readonly IEntityData data;
public Label GetLabel(string name)
{
if(String.IsNullOrEmpty(name)) return null;
return data.Query<Label>()
.Where(x => x.Name == name)
.FetchMany(x => x.Tickets)
.FirstOrDefault();
}
public ExistingLabelReader(IEntityData data)
{
if(data == null)
throw new ArgumentNullException(nameof(data));
this.data = data;
}
}
}
| mit | C# |
0ded40800b7f6395fb5a18278a58a379ececb763 | Add check for content type when parsing in client. Fallback to Json if Protobuf is not available | Hypnobrew/StockMonitor | Web/Controllers/HomeController.cs | Web/Controllers/HomeController.cs | using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace Web.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public async Task<string> Index()
{
var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("api/home");
if (response.IsSuccessStatusCode)
{
using(var stream = await response.Content.ReadAsStreamAsync())
{
ProtobufModelDto model = null;
if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf")
{
model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream);
return $"{model.Name}, {model.StringValue}, {model.Id}";
}
var content = await response.Content.ReadAsStringAsync();
model = JsonConvert.DeserializeObject<ProtobufModelDto>(content);
return $"{model.Name}, {model.StringValue}, {model.Id}";
}
}
return "Failed";
}
}
} | using System;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Infrastructure.Model;
using Microsoft.AspNetCore.Mvc;
namespace Web.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public async Task<string> Index()
{
var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf"));
var response = await client.GetAsync("api/home");
if (response.IsSuccessStatusCode)
{
using(var stream = await response.Content.ReadAsStreamAsync())
{
var model = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream);
return $"{model.Name}, {model.StringValue}, {model.Id}";
}
}
return "Failed";
}
}
} | mit | C# |
d32cf85d64067ea24ddbfd5888927d215f3bf647 | Update NavItemGroup.cs according to code guidelines | YOTOV-LIMITED/monotouch-samples,iFreedive/monotouch-samples,sakthivelnagarajan/monotouch-samples,kingyond/monotouch-samples,andypaul/monotouch-samples,a9upam/monotouch-samples,xamarin/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,W3SS/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,davidrynn/monotouch-samples,haithemaraissia/monotouch-samples,a9upam/monotouch-samples,nelzomal/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,albertoms/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples,markradacz/monotouch-samples,a9upam/monotouch-samples,YOTOV-LIMITED/monotouch-samples,robinlaide/monotouch-samples,nelzomal/monotouch-samples,YOTOV-LIMITED/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,hongnguyenpro/monotouch-samples,iFreedive/monotouch-samples,nelzomal/monotouch-samples,albertoms/monotouch-samples,xamarin/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,peteryule/monotouch-samples,andypaul/monotouch-samples,nelzomal/monotouch-samples,xamarin/monotouch-samples,andypaul/monotouch-samples,kingyond/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,andypaul/monotouch-samples,labdogg1003/monotouch-samples,W3SS/monotouch-samples,nervevau2/monotouch-samples,sakthivelnagarajan/monotouch-samples,a9upam/monotouch-samples,nervevau2/monotouch-samples,labdogg1003/monotouch-samples,YOTOV-LIMITED/monotouch-samples,kingyond/monotouch-samples,davidrynn/monotouch-samples,albertoms/monotouch-samples,hongnguyenpro/monotouch-samples,iFreedive/monotouch-samples,nervevau2/monotouch-samples,robinlaide/monotouch-samples,peteryule/monotouch-samples,W3SS/monotouch-samples,labdogg1003/monotouch-samples,haithemaraissia/monotouch-samples,markradacz/monotouch-samples | CoreAnimation/Code/NavigationTable/NavItemGroup.cs | CoreAnimation/Code/NavigationTable/NavItemGroup.cs | using System;
using System.Collections.Generic;
namespace Example_CoreAnimation.Code.NavigationTable
{
/// <summary>
/// A group that contains table items
/// </summary>
public class NavItemGroup
{
public string Name { get; set; }
public string Footer { get; set; }
public List<NavItem> Items {
get { return items; }
set { items = value; }
}
protected List<NavItem> items = new List<NavItem> ();
public NavItemGroup ()
{
}
public NavItemGroup (string name)
{
Name = name;
}
}
}
| using System;
using System.Collections.Generic;
namespace Example_CoreAnimation.Code.NavigationTable
{
/// <summary>
/// A group that contains table items
/// </summary>
public class NavItemGroup
{
public string Name { get; set; }
public string Footer { get; set; }
public List<NavItem> Items
{
get { return items; }
set { items = value; }
}
protected List<NavItem> items = new List<NavItem> ();
public NavItemGroup ()
{
}
public NavItemGroup (string name)
{
this.Name = name;
}
}
}
| mit | C# |
57d29fed40cf13c86806557838b57621c06a2bc7 | add footer links | kreeben/resin,kreeben/resin | src/Sir.HttpServer/Views/_Layout.cshtml | src/Sir.HttpServer/Views/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<style>
a {
text-decoration: none;
color: orangered;
}
a.result-link {
color: mediumblue;
}
a.result-link:visited {
color: purple;
}
input[type=text] {
width: 300px;
}
textarea {
width: 300px;
height: 150px;
}
footer {
border-top: 1px solid black;
}
footer span{
padding-top: 10px;
}
footer a {
text-decoration: none;
color: gray;
}
</style>
<a href="/"><h1>Did you go go?</h1></a>
<p>No tracking. Just web search.</p>
<div>
@RenderBody()
</div>
<footer>
<div>
@if (ViewData["doc_count"] != null)
{
<p>Index size: @ViewData["doc_count"] documents</p>
}
@if (ViewData["last_processed_url"] != null)
{
<p>Last crawled: <a href="@ViewData["last_processed_url"]">@ViewData["last_processed_title"]</a></p>
}
<p>Powered by <a href="https://github.com/kreeben/resin">Resin</a>.</p>
<p>Report issues <a href="https://github.com/kreeben/resin/issues">here</a>.</p>
<p><a href="https://docs.google.com/document/d/1Rv307YVEXVqebvKJNJaRKvRFwV7eGkPrSTzSoRLvVgc/edit?usp=sharing">About</a></p>
</div>
</footer>
</body>
</html> | <!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>@ViewBag.Title</title>
</head>
<body>
<style>
a {
text-decoration: none;
color: orangered;
}
a.result-link {
color: mediumblue;
}
a.result-link:visited {
color: purple;
}
input[type=text] {
width: 300px;
}
textarea {
width: 300px;
height: 150px;
}
footer {
border-top: 1px solid black;
}
footer span{
padding-top: 10px;
}
footer a {
text-decoration: none;
color: gray;
}
</style>
<a href="/"><h1>Did you go go?</h1></a>
<p>No tracking. Just web search.</p>
<div>
@RenderBody()
</div>
<footer>
<div>
@if (ViewData["doc_count"] != null)
{
<p>Index size: @ViewData["doc_count"] documents</p>
}
@if (ViewData["last_processed_url"] != null)
{
<p>Last crawled: <a href="@ViewData["last_processed_url"]">@ViewData["last_processed_title"]</a></p>
}
<p>Powered by <a href="https://github.com/kreeben/resin">Resin</a>.</p>
</div>
</footer>
</body>
</html> | mit | C# |
5c958ebeb8e847fd47a7fc383b82e42a4beea1a1 | Disable warnings about obsoletion since the point is testing the obsolete stuff still works | EamonNerbonne/ExpressionToCode | ExpressionToCodeTest/ExceptionsSerialization.cs | ExpressionToCodeTest/ExceptionsSerialization.cs | using System;
using System.IO;
using System.Runtime.CompilerServices;
using ExpressionToCodeLib;
using Xunit;
//requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core
namespace ExpressionToCodeTest
{
public class ExceptionsSerialization
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void IntentionallyFailingMethod()
=> PAssert.That(() => false);
[Fact]
public void PAssertExceptionIsSerializable()
=> AssertMethodFailsWithSerializableException(IntentionallyFailingMethod);
#pragma warning disable SYSLIB0011 // BinaryFormatter is Obsolete
static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod)
{
var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod);
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var ms = new MemoryStream();
formatter.Serialize(ms, original);
var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray()));
Assert.Equal(original.ToString(), deserialized.ToString());
}
#pragma warning restore SYSLIB0011
}
}
| using System;
using System.IO;
using System.Runtime.CompilerServices;
using ExpressionToCodeLib;
using Xunit;
//requires binary serialization, which is omitted in older .net cores - but those are out of support: https://docs.microsoft.com/en-us/lifecycle/products/microsoft-net-and-net-core
namespace ExpressionToCodeTest
{
public class ExceptionsSerialization
{
[MethodImpl(MethodImplOptions.NoInlining)]
static void IntentionallyFailingMethod()
=> PAssert.That(() => false);
[Fact]
public void PAssertExceptionIsSerializable()
=> AssertMethodFailsWithSerializableException(IntentionallyFailingMethod);
static void AssertMethodFailsWithSerializableException(Action intentionallyFailingMethod)
{
var original = Assert.ThrowsAny<Exception>(intentionallyFailingMethod);
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
var ms = new MemoryStream();
formatter.Serialize(ms, original);
var deserialized = formatter.Deserialize(new MemoryStream(ms.ToArray()));
Assert.Equal(original.ToString(), deserialized.ToString());
}
}
}
| apache-2.0 | C# |
9f734cca43ceb042e00f5c151e11f472e56b0b05 | Fix a warning about m_log due to change in SimulationBase. | TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim,TechplexEngineer/Aurora-Sim | Aurora/Server/ServerBase.cs | Aurora/Server/ServerBase.cs | /*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using Aurora.Framework;
using Aurora.Simulation.Base;
namespace Aurora.Server
{
public class AuroraBase : SimulationBase
{
public override void SetUpConsole()
{
base.SetUpConsole();
//Fix the default prompt
if(m_console != null)
m_console.DefaultPrompt = "Aurora.Server ";
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public override void Startup()
{
base.Startup();
m_log.Info("[AURORASTARTUP]: Startup completed in " + (DateTime.Now - this.StartupTime).TotalSeconds);
}
public override ISimulationBase Copy()
{
return new AuroraBase();
}
}
}
| /*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using Aurora.Framework;
using Aurora.Simulation.Base;
namespace Aurora.Server
{
public class AuroraBase : SimulationBase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override void SetUpConsole()
{
base.SetUpConsole();
//Fix the default prompt
if(m_console != null)
m_console.DefaultPrompt = "Aurora.Server ";
}
/// <summary>
/// Performs initialisation of the scene, such as loading configuration from disk.
/// </summary>
public override void Startup()
{
base.Startup();
m_log.Info("[AURORASTARTUP]: Startup completed in " + (DateTime.Now - this.StartupTime).TotalSeconds);
}
public override ISimulationBase Copy()
{
return new AuroraBase();
}
}
}
| bsd-3-clause | C# |
b3fb8ca44996f7f3e21005e1761f7257820612a6 | fix warnings | stanac/LiteApi,stanac/LiteApi,stanac/LiteApi | LiteApi/LiteApi.Tests/Fakes/FakeHttpResponse.cs | LiteApi/LiteApi.Tests/Fakes/FakeHttpResponse.cs | using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace LiteApi.Tests.Fakes
{
public class FakeHttpResponse : HttpResponse, IDisposable
{
internal IResponseCookies cookies = null;
internal IHeaderDictionary headers = null;
internal HttpContext httpContext = null;
internal bool hasStarted = false;
public override Stream Body { get; set; } = new MemoryStream();
public override long? ContentLength { get; set; }
public override string ContentType { get; set; }
public override IResponseCookies Cookies => cookies;
public override bool HasStarted => hasStarted;
public override IHeaderDictionary Headers => headers;
public override HttpContext HttpContext => httpContext;
public override int StatusCode { get; set; }
public override void OnCompleted(Func<object, Task> callback, object state)
{
}
public override void OnStarting(Func<object, Task> callback, object state)
{
}
public override void Redirect(string location, bool permanent)
{
}
public void Dispose()
{
if (Body != null)
{
Body.Dispose();
}
}
}
}
| using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace LiteApi.Tests.Fakes
{
public class FakeHttpResponse : HttpResponse, IDisposable
{
internal IResponseCookies cookies;
internal IHeaderDictionary headers;
internal HttpContext httpContext;
internal bool hasStarted;
public override Stream Body { get; set; } = new MemoryStream();
public override long? ContentLength { get; set; }
public override string ContentType { get; set; }
public override IResponseCookies Cookies => cookies;
public override bool HasStarted => hasStarted;
public override IHeaderDictionary Headers => headers;
public override HttpContext HttpContext => httpContext;
public override int StatusCode { get; set; }
public override void OnCompleted(Func<object, Task> callback, object state)
{
}
public override void OnStarting(Func<object, Task> callback, object state)
{
}
public override void Redirect(string location, bool permanent)
{
}
public void Dispose()
{
if (Body != null)
{
Body.Dispose();
}
}
}
}
| mit | C# |
27b3f23ff3c7b040885784b46a90e9523e633e93 | Remove some usings that stopped compilation | RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Services/Interfaces/IAttachmentsService.cs | OpenSim/Services/Interfaces/IAttachmentsService.cs | ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
namespace OpenSim.Services.Interfaces
{
public interface IAttachmentsService
{
string Get(string id);
void Store(string id, string data);
}
}
| ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Server.Base;
using OpenSim.Services.Base;
using OpenSim.Services.Interfaces;
using Nini.Config;
using log4net;
using Careminster;
using OpenMetaverse;
namespace Careminster
{
public interface IAttachmentsService
{
string Get(string id);
void Store(string id, string data);
}
}
| bsd-3-clause | C# |
28bd86e720ffdb3dbb2440484fd5b0bdf92a6f3a | Add intermediate comments to help explain what to do | tompaana/intermediator-bot-sample,tompaana/intermediator-bot-sample | IntermediatorBotSample/Controllers/Api/ConversationsController.cs | IntermediatorBotSample/Controllers/Api/ConversationsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using IntermediatorBotSample.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
namespace IntermediatorBotSample.Controllers.Api
{
[Route("api/[controller]")]
public class ConversationsController : Controller
{
[HttpGet]
public IEnumerable<Conversation> Get(int convId, int top)
{
var channels = new[] { "facebook", "skype", "skype for business", "directline" };
var random = new RandomGenerator();
return Builder<Conversation>.CreateListOfSize(5)
.All()
.With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew()
.With(ci => ci.MessagesCount = random.Next(2, 30))
.With(ci => ci.SentimentScore = random.Next(0.0d, 1.0d))
.Build())
.With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew()
.With(cr => cr.ChannelId = channels[random.Next(0, channels.Count())])
.Build())
.With(o => o.UserInformation = Builder<UserInformation>.CreateNew()
.Build())
.Build()
.ToList();
}
//TODO: Retrieve ALL the conversation
//TOOD: Forward conersation
//TODO: DELETE Conversation = immediate kill by conversationId
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using FizzWare.NBuilder;
using IntermediatorBotSample.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
namespace IntermediatorBotSample.Controllers.Api
{
[Route("api/[controller]")]
public class ConversationsController : Controller
{
[HttpGet]
public IEnumerable<Conversation> Get()
{
return Builder<Conversation>.CreateListOfSize(2)
.All()
.With(o => o.ConversationInformation = Builder<ConversationInformation>.CreateNew().Build())
.With(o => o.ConversationReference = Builder<ConversationReference>.CreateNew().Build())
.With(o => o.UserInformation = Builder<UserInformation>.CreateNew().Build())
.Build()
.ToList();
}
}
} | mit | C# |
48cd23cfc0c415e8950f08624209cd6c71815cbe | Add GetChebyshevDistance method | rvhuang/heuristic-suite | AlgorithmForce.HeuristicSuite/DistanceHelper.cs | AlgorithmForce.HeuristicSuite/DistanceHelper.cs | using System;
namespace AlgorithmForce.HeuristicSuite
{
public static class DistanceHelper
{
public static long GetManhattanDistance(long x1, long y1, long x2, long y2)
{
return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
}
public static long GetChebyshevDistance(long x1, long y1, long x2, long y2)
{
return Math.Max(Math.Abs(x1 - x2), Math.Abs(y1 - y2));
}
}
}
| using System;
namespace AlgorithmForce.HeuristicSuite
{
public static class DistanceHelper
{
public static long GetManhattanDistance(long x1, long y1, long x2, long y2)
{
return Math.Abs(x1 - x2) + Math.Abs(y1 - y2);
}
}
}
| mit | C# |
a5cfc060d903486786102726db324ae8b9b2d82e | Use different sounds for minigun's missed enemy effect. | fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game,fr1tz/rotc-ethernet-game | game/server/weapons/minigun.projectile.sfx.cs | game/server/weapons/minigun.projectile.sfx.cs | //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
datablock AudioProfile(MinigunProjectileImpactSound)
{
filename = "share/sounds/rotc/impact1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileFlybySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioCloseLooping3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/ricochet1-1.wav";
alternate[0] = "share/sounds/rotc/ricochet1-1.wav";
alternate[1] = "share/sounds/rotc/ricochet1-2.wav";
alternate[2] = "share/sounds/rotc/ricochet1-3.wav";
alternate[3] = "share/sounds/rotc/ricochet1-4.wav";
alternate[4] = "share/sounds/rotc/ricochet1-5.wav";
alternate[5] = "share/sounds/rotc/ricochet1-6.wav";
description = AudioClose3D;
preload = true;
};
| //------------------------------------------------------------------------------
// Revenge Of The Cats: Ethernet
// Copyright (C) 2008, mEthLab Interactive
//------------------------------------------------------------------------------
datablock AudioProfile(MinigunProjectileImpactSound)
{
filename = "share/sounds/rotc/impact1.wav";
description = AudioDefault3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileFlybySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioCloseLooping3D;
preload = true;
};
datablock AudioProfile(MinigunProjectileMissedEnemySound)
{
filename = "share/sounds/rotc/flyby1.wav";
description = AudioClose3D;
preload = true;
};
| lgpl-2.1 | C# |
59b37bc3455616cf02d1886d1d904737b670e54c | add indexer support | jjnguy/LRU.Net | LRU.Net/LRU.Net/LruCache.cs | LRU.Net/LRU.Net/LruCache.cs | using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRU.Net
{
public class LruCache<TKey, TValue>
{
private readonly int _maxObjects;
private OrderedDictionary _data;
public LruCache(int maxObjects = 1000)
{
_maxObjects = maxObjects;
_data = new OrderedDictionary();
}
public void Add(TKey key, TValue value)
{
if (_data.Count >= _maxObjects)
{
_data.RemoveAt(0);
}
_data.Add(key, value);
}
public TValue Get(TKey key)
{
if (!_data.Contains(key)) throw new Exception();
var result = _data[key];
if (result == null) throw new Exception();
_data.Remove(key);
_data.Add(key, result);
return (TValue)result;
}
public bool Contains(TKey key)
{
return _data.Contains(key);
}
public TValue this[TKey key]
{
get { return Get(key); }
set { Add(key, value); }
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LRU.Net
{
public class LruCache<TKey, TValue>
{
private readonly int _maxObjects;
private OrderedDictionary _data;
public LruCache(int maxObjects = 1000)
{
_maxObjects = maxObjects;
_data = new OrderedDictionary();
}
public void Add(TKey key, TValue value)
{
if (_data.Count >= _maxObjects)
{
_data.RemoveAt(0);
}
_data.Add(key, value);
}
public TValue Get(TKey key)
{
if (!_data.Contains(key)) throw new Exception();
var result = _data[key];
if (result == null) throw new Exception();
_data.Remove(key);
_data.Add(key, result);
return (TValue)result;
}
public bool Contains(TKey key)
{
return _data.Contains(key);
}
}
}
| mit | C# |
dded58fed8f177d82807dc7738dc08cce5ba16cf | implement TableRowWrapper with IamVisualElement | mvbalaw/FluentBrowserAutomation | src/FluentBrowserAutomation/Controls/TableRowWrapper.cs | src/FluentBrowserAutomation/Controls/TableRowWrapper.cs | using System;
using System.Linq;
using OpenQA.Selenium;
namespace FluentBrowserAutomation.Controls
{
public class TableRowWrapper : BasicInfoWrapper, IAmVisualElement
{
public TableRowWrapper(IWebElement tableRow, string howFound, IBrowserContext browserContext)
: base(tableRow, howFound, browserContext)
{
}
public string[] CellValues()
{
var elements = Element.FindElements(By.TagName("td"));
return elements.Select((cell, index) => new TableCellWrapper(cell, String.Format("{0}, table cell with index {1}", HowFound, index), BrowserContext))
.Select(x => (string)x.Text())
.ToArray();
}
public TableCellWrapper CellWithIndex(int zeroBasedIndex)
{
var elements = Element.FindElements(By.TagName("td"));
var cell = elements.Count > zeroBasedIndex ? elements[zeroBasedIndex] : null;
var tableCellWrapper = new TableCellWrapper(cell, String.Format("{0}, table cell with index {1}", HowFound, zeroBasedIndex), BrowserContext);
tableCellWrapper.Exists().ShouldBeTrue();
return tableCellWrapper;
}
}
public class TableHeaderRowWrapper : BasicInfoWrapper
{
public TableHeaderRowWrapper(IWebElement tableRow, string howFound, IBrowserContext browserContext)
: base(tableRow, howFound, browserContext)
{
}
public string[] CellValues()
{
var elements = Element.FindElements(By.TagName("th"));
return elements.Select((cell, index) => new TableHeaderCellWrapper(cell, String.Format("{0}, table header cell with index {1}", HowFound, index), BrowserContext))
.Select(x => (string)x.Text())
.ToArray();
}
public TableHeaderCellWrapper CellWithIndex(int zeroBasedIndex)
{
var elements = Element.FindElements(By.TagName("th"));
var cell = elements.Count > zeroBasedIndex ? elements[zeroBasedIndex] : null;
return new TableHeaderCellWrapper(cell, String.Format("{0}, table header cell with index {1}", HowFound, zeroBasedIndex), BrowserContext);
}
}
} | using System;
using System.Linq;
using OpenQA.Selenium;
namespace FluentBrowserAutomation.Controls
{
public class TableRowWrapper : BasicInfoWrapper
{
public TableRowWrapper(IWebElement tableRow, string howFound, IBrowserContext browserContext)
: base(tableRow, howFound, browserContext)
{
}
public string[] CellValues()
{
var elements = Element.FindElements(By.TagName("td"));
return elements.Select((cell, index) => new TableCellWrapper(cell, String.Format("{0}, table cell with index {1}", HowFound, index), BrowserContext))
.Select(x => (string)x.Text())
.ToArray();
}
public TableCellWrapper CellWithIndex(int zeroBasedIndex)
{
var elements = Element.FindElements(By.TagName("td"));
var cell = elements.Count > zeroBasedIndex ? elements[zeroBasedIndex] : null;
var tableCellWrapper = new TableCellWrapper(cell, String.Format("{0}, table cell with index {1}", HowFound, zeroBasedIndex), BrowserContext);
tableCellWrapper.Exists().ShouldBeTrue();
return tableCellWrapper;
}
}
public class TableHeaderRowWrapper : BasicInfoWrapper
{
public TableHeaderRowWrapper(IWebElement tableRow, string howFound, IBrowserContext browserContext)
: base(tableRow, howFound, browserContext)
{
}
public string[] CellValues()
{
var elements = Element.FindElements(By.TagName("th"));
return elements.Select((cell, index) => new TableHeaderCellWrapper(cell, String.Format("{0}, table header cell with index {1}", HowFound, index), BrowserContext))
.Select(x => (string)x.Text())
.ToArray();
}
public TableHeaderCellWrapper CellWithIndex(int zeroBasedIndex)
{
var elements = Element.FindElements(By.TagName("th"));
var cell = elements.Count > zeroBasedIndex ? elements[zeroBasedIndex] : null;
return new TableHeaderCellWrapper(cell, String.Format("{0}, table header cell with index {1}", HowFound, zeroBasedIndex), BrowserContext);
}
}
} | mit | C# |
326c3520b04da7633df76cc7911f3c95e38f6d83 | Add a comment in MathUtil.Wrap tests for floats to point out that precision cannot be guaranteed and safely tested | RobyDX/SharpDX,wyrover/SharpDX,jwollen/SharpDX,dazerdude/SharpDX,RobyDX/SharpDX,weltkante/SharpDX,sharpdx/SharpDX,TechPriest/SharpDX,manu-silicon/SharpDX,wyrover/SharpDX,jwollen/SharpDX,dazerdude/SharpDX,fmarrabal/SharpDX,TigerKO/SharpDX,Ixonos-USA/SharpDX,waltdestler/SharpDX,wyrover/SharpDX,RobyDX/SharpDX,TechPriest/SharpDX,Ixonos-USA/SharpDX,wyrover/SharpDX,VirusFree/SharpDX,Ixonos-USA/SharpDX,davidlee80/SharpDX-1,Ixonos-USA/SharpDX,TigerKO/SharpDX,waltdestler/SharpDX,VirusFree/SharpDX,waltdestler/SharpDX,PavelBrokhman/SharpDX,RobyDX/SharpDX,TechPriest/SharpDX,dazerdude/SharpDX,PavelBrokhman/SharpDX,VirusFree/SharpDX,davidlee80/SharpDX-1,andrewst/SharpDX,andrewst/SharpDX,PavelBrokhman/SharpDX,mrvux/SharpDX,davidlee80/SharpDX-1,weltkante/SharpDX,andrewst/SharpDX,TigerKO/SharpDX,mrvux/SharpDX,VirusFree/SharpDX,TechPriest/SharpDX,davidlee80/SharpDX-1,mrvux/SharpDX,sharpdx/SharpDX,TigerKO/SharpDX,dazerdude/SharpDX,fmarrabal/SharpDX,fmarrabal/SharpDX,jwollen/SharpDX,jwollen/SharpDX,manu-silicon/SharpDX,PavelBrokhman/SharpDX,sharpdx/SharpDX,weltkante/SharpDX,weltkante/SharpDX,fmarrabal/SharpDX,waltdestler/SharpDX,manu-silicon/SharpDX,manu-silicon/SharpDX | Source/Tests/SharpDX.Tests/MathUtilWrapTests.cs | Source/Tests/SharpDX.Tests/MathUtilWrapTests.cs | using System;
namespace SharpDX.Tests
{
using NUnit.Framework;
[TestFixture]
public class MathUtilWrapTests
{
[TestCase(0, 10, 2, 2)]
[TestCase(0, 10, 15, 4)]
[TestCase(0, 10, -15, 7)]
[TestCase(0, 10, 0, 0)]
[TestCase(0, 10, 10, 10)]
[TestCase(0, 0, 10, 0)]
[TestCase(10, 0, 15, 4)]
[TestCase(-10, -1, -15, -5)]
[TestCase(-1, -10, -15, -5)]
[TestCase(-10, 0, 15, -7)]
public void WrapsInt(int min, int max, int valueToWrap, int expectedResult)
{
var result = MathUtil.Wrap(valueToWrap, min, max);
Assert.AreEqual(expectedResult, result);
}
[TestCase(0.0f, 10.0f, 2.0f, 2.0f)]
[TestCase(0.0f, 10.0f, 15.0f, 5.0f)]
[TestCase(0.0f, 10.0f, -15.0f, 5.0f)]
[TestCase(0.0f, 10.0f, 0.0f, 0.0f)]
[TestCase(0.0f, 10.0f, 10.0f, 0.0f)]
[TestCase(0.0f, 0.0f, 10.0f, 0.0f)]
[TestCase(10.0f, 0.0f, 15.0f, 5.0f)]
[TestCase(-10.0f, -1.0f, -15.0f, -6.0f)]
[TestCase(-1.0f, -10.0f, -15.0f, -6.0f)]
[TestCase(-10.0f, 0.0f, 15.0f, -5.0f)]
[TestCase(0.0f, 0.1f, 10.0f, 0.0f)]
public void WrapsFloat(float min, float max, float valueToWrap, float expectedResult)
{
var result = MathUtil.Wrap(valueToWrap, min, max);
Assert.True(Math.Abs(expectedResult - result) < 0.00001f ||
Math.Abs(max - result) < 0.00001f , "Expected [{0}] : Result [{1}]", expectedResult, result);
}
}
} | using System;
namespace SharpDX.Tests
{
using NUnit.Framework;
[TestFixture]
public class MathUtilWrapTests
{
[TestCase(0, 10, 2, 2)]
[TestCase(0, 10, 15, 4)]
[TestCase(0, 10, -15, 7)]
[TestCase(0, 10, 0, 0)]
[TestCase(0, 10, 10, 10)]
[TestCase(0, 0, 10, 0)]
[TestCase(10, 0, 15, 4)]
[TestCase(-10, -1, -15, -5)]
[TestCase(-1, -10, -15, -5)]
[TestCase(-10, 0, 15, -7)]
public void WrapsInt(int min, int max, int valueToWrap, int expectedResult)
{
var result = MathUtil.Wrap(valueToWrap, min, max);
Assert.AreEqual(expectedResult, result);
}
[TestCase(0.0f, 10.0f, 2.0f, 2.0f)]
[TestCase(0.0f, 10.0f, 15.0f, 5.0f)]
[TestCase(0.0f, 10.0f, -15.0f, 5.0f)]
[TestCase(0.0f, 10.0f, 0.0f, 0.0f)]
[TestCase(0.0f, 10.0f, 10.0f, 0.0f)]
[TestCase(0.0f, 0.0f, 10.0f, 0.0f)]
[TestCase(10.0f, 0.0f, 15.0f, 5.0f)]
[TestCase(-10.0f, -1.0f, -15.0f, -6.0f)]
[TestCase(-1.0f, -10.0f, -15.0f, -6.0f)]
[TestCase(-10.0f, 0.0f, 15.0f, -5.0f)]
public void WrapsFloat(float min, float max, float valueToWrap, float expectedResult)
{
var result = MathUtil.Wrap(valueToWrap, min, max);
Assert.True(MathUtil.WithinEpsilon(expectedResult, result), "Expected [{0}] : Result [{1}]", expectedResult, result);
}
}
} | mit | C# |
2aa441c70d61afaa06711293b412f3412e15cafa | Use assembly version for file version | danielchalmers/SteamAccountSwitcher | SteamAccountSwitcher/Properties/AssemblyInfo.cs | SteamAccountSwitcher/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Steam Account Switcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Chalmers Software")]
[assembly: AssemblyProduct("Steam Account Switcher")]
[assembly: AssemblyCopyright("© Daniel Chalmers 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("2.2.0.1")] | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 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("Steam Account Switcher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Daniel Chalmers Software")]
[assembly: AssemblyProduct("Steam Account Switcher")]
[assembly: AssemblyCopyright("© Daniel Chalmers 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")]
// 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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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("2.2.0.1")]
[assembly: AssemblyFileVersion("2.2.0.1")] | mit | C# |
52e613967747fa061cea87226d0771fdf97d69ee | Update AssemblyInfo.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Properties/AssemblyInfo.cs | TIKSN.Framework.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following set of attributes.
// Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle("TIKSN.Framework.Core")]
[assembly: AssemblyTrademark("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ed598e91-6d8e-4132-a73d-a1a9a402f395")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following set of attributes.
// Change these attribute values to modify the information associated with an assembly.
[assembly: AssemblyTitle("TIKSN.Framework.Core")]
[assembly: AssemblyTrademark("")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ed598e91-6d8e-4132-a73d-a1a9a402f395")] | mit | C# |
5ac41384f2a70b11844e493b622317050ce00641 | bump version | raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2 | source/Raml.Parser/Properties/AssemblyInfo.cs | source/Raml.Parser/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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.4")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RAML.Parser")]
[assembly: AssemblyDescription("A RAML Parser implementation in .NET for all CLR languages. RESTful API Modeling Language (RAML) is a simple and succinct way of describing practically-RESTful APIs. It encourages reuse, enables discovery and pattern-sharing, and aims for merit-based emergence of best practices.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mulesoft Inc")]
[assembly: AssemblyProduct("Raml.Parser")]
[assembly: AssemblyCopyright("Copyright © 2015 MuleSoft")]
[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("d5f8e5f6-634a-4487-be70-591c4d8546f2")]
// 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")] | apache-2.0 | C# |
b7f425adacb65a037c2969e5622308785260a856 | add FossilDeltaTest | gamestdio/colyseus-unity3d,gamestdio/colyseus-unity3d | Assets/Editor/ColyseusTests/FossilDeltaTest.cs | Assets/Editor/ColyseusTests/FossilDeltaTest.cs | using NUnit.Framework;
using UnityEngine;
using Colyseus;
public class FossilDeltaTest
{
FossilDeltaSerializer serializer = new FossilDeltaSerializer();
[SetUp]
public void Init()
{
}
[TearDown]
public void Dispose()
{
}
[Test]
public void ApplyPatchTest()
{
Assert.DoesNotThrow(() =>
{
byte[] initialState = { (byte)Protocol.ROOM_STATE, 133, 165, 97, 114, 114, 97, 121, 144, 168, 101, 110, 116, 105, 116, 105, 101, 115, 128, 163, 105, 110, 116, 1, 164, 98, 111, 111, 108, 195, 166, 115, 116, 114, 105, 110, 103, 166, 115, 116, 114, 105, 110, 103 };
serializer.SetState(initialState, 1);
Assert.IsTrue(serializer.GetState().ContainsKey("array"));
Assert.IsTrue(serializer.GetState().ContainsKey("entities"));
Assert.IsTrue(serializer.GetState().ContainsKey("int"));
Assert.IsTrue(serializer.GetState().ContainsKey("bool"));
Assert.IsTrue(serializer.GetState().ContainsKey("string"));
byte[] patchState = { (byte)Protocol.ROOM_STATE_PATCH, 49, 71, 10, 49, 71, 58, 133, 165, 97, 114, 114, 97, 121, 145, 1, 168, 101, 110, 116, 105, 116, 105, 101, 115, 129, 169, 83, 78, 52, 98, 89, 65, 83, 107, 87, 131, 161, 120, 10, 161, 121, 10, 164, 110, 97, 109, 101, 173, 74, 97, 107, 101, 32, 66, 97, 100, 108, 97, 110, 100, 115, 163, 105, 110, 116, 1, 164, 98, 111, 111, 108, 195, 166, 115, 116, 114, 105, 110, 103, 166, 115, 116, 114, 105, 110, 103, 51, 108, 100, 76, 100, 73, 59 };
serializer.Patch(patchState, 1);
});
}
} | using System;
namespace Application
{
public class NewClass
{
public NewClass()
{
}
}
}
| mit | C# |
2f978a9e54b33753d672a869e7a934302d811e91 | Revert "Adding Request-Id to ShopifyException message. When exception are logged, it is very useful to be able to see the Request-Id for Shopify support to investigate." | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Infrastructure/ShopifyException.cs | ShopifySharp/Infrastructure/ShopifyException.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
namespace ShopifySharp
{
public class ShopifyException : Exception
{
public HttpResponseMessage HttpResponse { get; }
public HttpStatusCode HttpStatusCode { get; }
/// <summary>
/// The XRequestId header returned by Shopify. Can be used when working with the Shopify support team to identify the failed request.
/// </summary>
public string RequestId { get; }
/// <remarks>
/// List is always initialized to ensure null reference errors won't be thrown when trying to check error messages.
/// </remarks>
public IEnumerable<string> Errors { get; } = Enumerable.Empty<string>();
/// <summary>
/// The raw JSON string returned by Shopify.
/// </summary>
public string RawBody { get; }
public ShopifyException() { }
public ShopifyException(string message) : base(message) { }
public ShopifyException(HttpResponseMessage response, HttpStatusCode httpStatusCode, IEnumerable<string> errors, string message, string rawBody, string requestId) : base(message)
{
HttpResponse = response;
HttpStatusCode = httpStatusCode;
Errors = (errors ?? Enumerable.Empty<string>()).ToArray();
RawBody = rawBody;
RequestId = requestId;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
namespace ShopifySharp
{
public class ShopifyException : Exception
{
public HttpResponseMessage HttpResponse { get; }
public HttpStatusCode HttpStatusCode { get; }
/// <summary>
/// The XRequestId header returned by Shopify. Can be used when working with the Shopify support team to identify the failed request.
/// </summary>
public string RequestId { get; }
/// <remarks>
/// List is always initialized to ensure null reference errors won't be thrown when trying to check error messages.
/// </remarks>
public IEnumerable<string> Errors { get; } = Enumerable.Empty<string>();
/// <summary>
/// The raw JSON string returned by Shopify.
/// </summary>
public string RawBody { get; }
public ShopifyException() { }
public ShopifyException(string message) : base(message) { }
public ShopifyException(HttpResponseMessage response, HttpStatusCode httpStatusCode, IEnumerable<string> errors, string message, string rawBody, string requestId) :
base($"Request-Id: {requestId ?? "None"}\r\n{message}")
{
HttpResponse = response;
HttpStatusCode = httpStatusCode;
Errors = (errors ?? Enumerable.Empty<string>()).ToArray();
RawBody = rawBody;
RequestId = requestId;
}
}
}
| mit | C# |
6f97aeab90939df17c5befa8c18507ca3d16a4c6 | update test date time string | yasokada/unity-150908-udpTimeGraph | Assets/Test_weekly.cs | Assets/Test_weekly.cs | using UnityEngine;
using System.Collections;
public class Test_weekly : MonoBehaviour {
void Test_addWeeklyData() {
string [] dts = new string[]{
"2015/09/07 12:30",
"2015/09/08 09:30",
"2015/09/10 11:30",
"2015/09/11 13:30",
"2015/09/12 13:30",
};
System.DateTime curDt;
float yval;
int idx = 0;
timeGraphScript.SetXType ((int)timeGraphScript.XType.Weekly);
foreach(var dt in dts) {
curDt = System.DateTime.Parse(dt);
// yval = vals[idx];
yval = Random.Range(-1.0f, 1.0f);
timeGraphScript.SetXYVal(curDt, yval);
idx++;
}
}
void Start () {
Test_addWeeklyData ();
}
void Update () {
}
}
| using UnityEngine;
using System.Collections;
public class Test_weekly : MonoBehaviour {
void Test_addWeeklyData() {
string [] dts = new string[]{
"2015/09/07 12:30",
"2015/09/08 09:30",
"2015/09/10 11:30",
"2015/09/11 13:30"
};
System.DateTime curDt;
float yval;
int idx = 0;
timeGraphScript.SetXType ((int)timeGraphScript.XType.Weekly);
foreach(var dt in dts) {
curDt = System.DateTime.Parse(dt);
// yval = vals[idx];
yval = Random.Range(-1.0f, 1.0f);
timeGraphScript.SetXYVal(curDt, yval);
idx++;
}
}
void Start () {
Test_addWeeklyData ();
}
void Update () {
}
}
| mit | C# |
37324c63719a3816fece44625e2d4e2e3ba83957 | Update TurkeyProvider.cs | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Src/Nager.Date/PublicHolidays/TurkeyProvider.cs | Src/Nager.Date/PublicHolidays/TurkeyProvider.cs | using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class TurkeyProvider : IPublicHolidayProvider
{
public IEnumerable<PublicHoliday> Get(int year)
{
//Turkey
//https://en.wikipedia.org/wiki/Public_holidays_in_Turkey
var countryCode = CountryCode.TR;
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Yılbaşı", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 23, "Ulusal Egemenlik ve Çocuk Bayramı", "National Independence & Children's Day", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "İşçi Bayramı", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 5, 19, "Atatürk'ü Anma, Gençlik ve Spor Bayramı", "Atatürk Commemoration & Youth Day", countryCode));
items.Add(new PublicHoliday(year, 7, 15, "Demokrasi Bayramı", "Democracy Day", countryCode));
items.Add(new PublicHoliday(year, 8, 30, "Zafer Bayramı", "Victory Day", countryCode));
items.Add(new PublicHoliday(year, 10, 29, "Cumhuriyet Bayramı", "Republic Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Contract;
using Nager.Date.Model;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class TurkeyProvider : IPublicHolidayProvider
{
public IEnumerable<PublicHoliday> Get(int year)
{
//Turkey
//https://en.wikipedia.org/wiki/Public_holidays_in_Turkey
var countryCode = CountryCode.TR;
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(year, 1, 1, "Yılbaşı", "New Year's Day", countryCode));
items.Add(new PublicHoliday(year, 4, 23, "Ulusal Egemenlik ve Çocuk Bayramı", "National Independence & Children's Day", countryCode));
items.Add(new PublicHoliday(year, 5, 1, "İşçi Bayramı", "Labour Day", countryCode));
items.Add(new PublicHoliday(year, 5, 19, "Atatürk'ü Anma, Gençlik ve Spor Bayramı", "Atatürk Commemoration & Youth Day", countryCode));
items.Add(new PublicHoliday(year, 8, 30, "Zafer Bayramı", "Victory Day", countryCode));
items.Add(new PublicHoliday(year, 10, 29, "Cumhuriyet Bayramı", "Republic Day", countryCode));
return items.OrderBy(o => o.Date);
}
}
}
| mit | C# |
ebb2290abf8ec652db505451292c93bdd275b52b | Implement IList.IsFixedSize | jbevain/cecil,cgourlay/cecil,xen2/cecil,kzu/cecil,ttRevan/cecil,mono/cecil,sailro/cecil,saynomoo/cecil,SiliconStudio/Mono.Cecil,gluck/cecil,furesoft/cecil,fnajera-rac-de/cecil,joj/cecil | Mono.Collections.Generic/ReadOnlyCollection.cs | Mono.Collections.Generic/ReadOnlyCollection.cs | //
// ReadOnlyCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// 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 System.Collections;
using System .Collections.Generic;
namespace Mono.Collections.Generic {
public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {
static ReadOnlyCollection<T> empty;
public static ReadOnlyCollection<T> Empty {
get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
bool IList.IsFixedSize {
get { return true; }
}
bool IList.IsReadOnly {
get { return true; }
}
private ReadOnlyCollection ()
{
}
public ReadOnlyCollection (T [] array)
{
if (array == null)
throw new ArgumentNullException ();
Initialize (array, array.Length);
}
public ReadOnlyCollection (Collection<T> collection)
{
if (collection == null)
throw new ArgumentNullException ();
Initialize (collection.items, collection.size);
}
void Initialize (T [] items, int size)
{
this.items = new T [size];
Array.Copy (items, 0, this.items, 0, size);
this.size = size;
}
internal override void Grow (int desired)
{
throw new InvalidOperationException ();
}
protected override void OnAdd (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnClear ()
{
throw new InvalidOperationException ();
}
protected override void OnInsert (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnRemove (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnSet (T item, int index)
{
throw new InvalidOperationException ();
}
}
}
| //
// ReadOnlyCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2010 Jb Evain
//
// 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 System.Collections;
using System .Collections.Generic;
namespace Mono.Collections.Generic {
public sealed class ReadOnlyCollection<T> : Collection<T>, ICollection<T>, IList {
static ReadOnlyCollection<T> empty;
public static ReadOnlyCollection<T> Empty {
get { return empty ?? (empty = new ReadOnlyCollection<T> ()); }
}
bool ICollection<T>.IsReadOnly {
get { return true; }
}
bool IList.IsReadOnly {
get { return true; }
}
private ReadOnlyCollection ()
{
}
public ReadOnlyCollection (T [] array)
{
if (array == null)
throw new ArgumentNullException ();
Initialize (array, array.Length);
}
public ReadOnlyCollection (Collection<T> collection)
{
if (collection == null)
throw new ArgumentNullException ();
Initialize (collection.items, collection.size);
}
void Initialize (T [] items, int size)
{
this.items = new T [size];
Array.Copy (items, 0, this.items, 0, size);
this.size = size;
}
internal override void Grow (int desired)
{
throw new InvalidOperationException ();
}
protected override void OnAdd (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnClear ()
{
throw new InvalidOperationException ();
}
protected override void OnInsert (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnRemove (T item, int index)
{
throw new InvalidOperationException ();
}
protected override void OnSet (T item, int index)
{
throw new InvalidOperationException ();
}
}
}
| mit | C# |
87d653aa42b0309980b79654b8ef744c8350ee07 | Update addin description | mhutch/MonoDevelop.AddinMaker,mhutch/MonoDevelop.AddinMaker | MonoDevelop.AddinMaker/Properties/AddinInfo.cs | MonoDevelop.AddinMaker/Properties/AddinInfo.cs | using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly:Addin (
"AddinMaker",
Namespace = "MonoDevelop",
Version = "1.3.6",
Url = "http://github.com/mhutch/MonoDevelop.AddinMaker"
)]
[assembly:AddinName ("Addin Maker")]
[assembly:AddinCategory ("Extension Development")]
[assembly:AddinDescription ("Makes it easy to create and edit IDE extensions")]
[assembly:AddinAuthor ("Mikayla Hutchinson")]
| using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly:Addin (
"AddinMaker",
Namespace = "MonoDevelop",
Version = "1.3.6",
Url = "http://github.com/mhutch/MonoDevelop.AddinMaker"
)]
[assembly:AddinName ("Addin Maker")]
[assembly:AddinCategory ("Addin Development")]
[assembly:AddinDescription ("Makes it easy to create and edit addins")]
[assembly:AddinAuthor ("Mikayla Hutchinson")]
| mit | C# |
2fa82c82dcaf200e418255431a615c07e7a13afd | bump version | Fody/PropertyChanged,0x53A/PropertyChanged,user1568891/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyVersion("1.32.2.0")]
[assembly: AssemblyFileVersion("1.32.2.0")]
| using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyVersion("1.32.1.0")]
[assembly: AssemblyFileVersion("1.32.1.0")]
| mit | C# |
ce07a82040d6d06e1a6fea4ea19225433542e49a | fix name and version | GeertvanHorrik/MethodTimer,Fody/MethodTimer | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("MethodTimer")]
[assembly: AssemblyProduct("MethodTimer")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Obsolete")]
[assembly: AssemblyProduct("Obsolete")]
[assembly: AssemblyVersion("0.9.0.0")]
[assembly: AssemblyFileVersion("0.9.0.0")]
| mit | C# |
8f9964230a1f8355979f3c4303c79ee2b6ddf033 | Change data in script | conekta/conekta-xamarin | ConektaSDK/Conekta.cs | ConektaSDK/Conekta.cs | using System;
using System.Drawing;
using System.Diagnostics;
#if __IOS__
using Foundation;
using ObjectiveC;
using ObjCRuntime;
using UIKit;
#endif
#if __ANDROID__
using Android;
#endif
namespace ConektaSDK {
public abstract class Conekta {
public static string ApiVersion { get; set; }
public const string BaseUri = "https://api.conekta.io";
public static string PublicKey { get; set; }
#if __IOS__
public static UIViewController _delegate { get; set; }
#endif
public static void collectDevice() {
string SessionId = Conekta.DeviceFingerPrint ();
string PublicKey = Conekta.PublicKey;
string html = "<html style=\"background: blue;\"><head></head><body>";
html += "<script type=\"text/javascript\" src=\"https://conektaapi.s3.amazonaws.com/v0.5.0/js/conekta.js\" data-conekta-public-key=\"" + PublicKey + "\" data-conekta-session-id=\"" + SessionId + "\"></script>";
html += "</body></html>";
string contentPath = Environment.CurrentDirectory;
#if __IOS__
UIWebView web = new UIWebView(new RectangleF(new PointF(0,0), new SizeF(0, 0)));
web.LoadHtmlString(html, new NSUrl(contentPath, true));
web.ScalesPageToFit = true;
Conekta._delegate.View.AddSubview(web);
#endif
#if __ANDROID__
#endif
}
public static string DeviceFingerPrint() {
string uuidString = "";
#if __IOS__
//NSUuid uuid = new NSUuid();
//uuidString = uuid.AsString();
uuidString = UIKit.UIDevice.CurrentDevice.IdentifierForVendor.AsString();
uuidString = uuidString.Replace("-", "");
#elif __ANDROID__
uuidString = Android.OS.Build.Serial;
#elif WINDOWS_PHONE
uuidString = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
#endif
return uuidString;
}
}
}
| using System;
using System.Drawing;
using System.Diagnostics;
#if __IOS__
using Foundation;
using ObjectiveC;
using ObjCRuntime;
using UIKit;
#endif
#if __ANDROID__
using Android;
#endif
namespace ConektaSDK {
public abstract class Conekta {
public static string ApiVersion { get; set; }
public const string BaseUri = "https://api.conekta.io";
public static string PublicKey { get; set; }
#if __IOS__
public static UIViewController _delegate { get; set; }
#endif
public static void collectDevice() {
string SessionId = Conekta.DeviceFingerPrint ();
string PublicKey = Conekta.PublicKey;
string html = "<html style=\"background: blue;\"><head></head><body>";
html += "<script type=\"text/javascript\" src=\"https://conektaapi.s3.amazonaws.com/v0.5.0/js/conekta.js\" data-public-key=\"" + PublicKey + "\" data-session-id=\"" + SessionId + "\"></script>";
html += "</body></html>";
string contentPath = Environment.CurrentDirectory;
#if __IOS__
UIWebView web = new UIWebView(new RectangleF(new PointF(0,0), new SizeF(0, 0)));
web.LoadHtmlString(html, new NSUrl(contentPath, true));
web.ScalesPageToFit = true;
Conekta._delegate.View.AddSubview(web);
#endif
#if __ANDROID__
#endif
}
public static string DeviceFingerPrint() {
string uuidString = "";
#if __IOS__
//NSUuid uuid = new NSUuid();
//uuidString = uuid.AsString();
uuidString = UIKit.UIDevice.CurrentDevice.IdentifierForVendor.AsString();
uuidString = uuidString.Replace("-", "");
#elif __ANDROID__
uuidString = Android.OS.Build.Serial;
#elif WINDOWS_PHONE
uuidString = Windows.Phone.System.Analytics.HostInformation.PublisherHostId;
#endif
return uuidString;
}
}
}
| mit | C# |
a8537d3b6ba4675a1bae21c91d45b72c233c86dc | create commands each time | jbtule/keyczar-dotnet | Keyczar/KeyczarTool/Program.cs | Keyczar/KeyczarTool/Program.cs | // Copyright 2012 James Tuley (jay+code@tuley.name)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KeyczarTool.Commands;
using ManyConsole.CommandLineUtils;
namespace KeyczarTool
{
public class Program
{
internal static ConsoleCommand[] Commands =>
new ConsoleCommand[] {
new Create(),
new AddKey(),
new PubKey(),
new Promote(),
new Demote(),
new Revoke(),
new ImportKey(),
new Export(),
new UseKey(),
new Password(),
new KeyTypes(),
};
public static int Main(string[] args)
{
// run the command for the console input
return ConsoleCommandDispatcher.DispatchCommand(Commands, args, Console.Out);
}
}
}
| // Copyright 2012 James Tuley (jay+code@tuley.name)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using KeyczarTool.Commands;
using ManyConsole.CommandLineUtils;
namespace KeyczarTool
{
public class Program
{
internal readonly static ConsoleCommand[] Commands =
{
new Create(),
new AddKey(),
new PubKey(),
new Promote(),
new Demote(),
new Revoke(),
new ImportKey(),
new Export(),
new UseKey(),
new Password(),
new KeyTypes(),
};
public static int Main(string[] args)
{
// run the command for the console input
return ConsoleCommandDispatcher.DispatchCommand(Commands, args, Console.Out);
}
}
}
| apache-2.0 | C# |
c8655ae990a4988342814f94add9b2edf8141a1d | Fix height limit. | PlanetLotus/TetrisClone2D | Assets/GridManager.cs | Assets/GridManager.cs | using UnityEngine;
public class GridManager : MonoBehaviour
{
public const int MinX = 0;
public const int MaxX = 9;
public const int MinY = 0;
public bool IsValidPosition(Transform transform)
{
// Check out of bounds
if (transform.position.x > MaxX || transform.position.x < MinX ||
transform.position.y < MinY)
{
return false;
}
// If spot is full or if spot is occupied by another shape, it's invalid
// This may be naive, but we assume that the shape won't try to collide with itself
if (grid[(int)transform.position.x, (int)transform.position.y] != null &&
grid[(int)transform.position.x, (int)transform.position.y].parent == transform.parent)
{
return false;
}
return true;
}
private void Start()
{
}
private void Update()
{
// Check for completed rows and clear them
}
private const int Width = 10;
private const int Height = 24;
// Each transform is a block, not the entire shape
// Instead of just setting a flag here, having the actual object helps
// us determine how it relates to the objects around it, like
// whether they're attached to the same shape.
private Transform[,] grid = new Transform[Width, Height];
}
| using UnityEngine;
public class GridManager : MonoBehaviour
{
public const int MinX = 0;
public const int MaxX = 9;
public const int MinY = 0;
public bool IsValidPosition(Transform transform)
{
// Check out of bounds
if (transform.position.x > MaxX || transform.position.x < MinX ||
transform.position.y < MinY)
{
return false;
}
// If spot is full or if spot is occupied by another shape, it's invalid
// This may be naive, but we assume that the shape won't try to collide with itself
if (grid[(int)transform.position.x, (int)transform.position.y] != null &&
grid[(int)transform.position.x, (int)transform.position.y].parent == transform.parent)
{
return false;
}
return true;
}
private void Start()
{
}
private void Update()
{
// Check for completed rows and clear them
}
private const int Width = 10;
private const int Height = 20;
// Each transform is a block, not the entire shape
// Instead of just setting a flag here, having the actual object helps
// us determine how it relates to the objects around it, like
// whether they're attached to the same shape.
private Transform[,] grid = new Transform[Width, Height];
}
| mit | C# |
f607a04b74d525bb10ec75f98813a4f2d46420ca | Move template paths into static array. | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.App/Services/PullRequestService.cs | src/GitHub.App/Services/PullRequestService.cs | using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using GitHub.Models;
namespace GitHub.Services
{
[NullGuard.NullGuard(NullGuard.ValidationFlags.None)]
[Export(typeof(IPullRequestService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class PullRequestService : IPullRequestService
{
static readonly string[] TemplatePaths = new[]
{
"PULL_REQUEST_TEMPLATE.md",
"PULL_REQUEST_TEMPLATE",
".github\\PULL_REQUEST_TEMPLATE.md",
".github\\PULL_REQUEST_TEMPLATE",
};
public IObservable<IPullRequestModel> CreatePullRequest(IRepositoryHost host, ISimpleRepositoryModel repository, string title, string body, IBranch source, IBranch target)
{
Extensions.Guard.ArgumentNotNull(host, nameof(host));
Extensions.Guard.ArgumentNotNull(repository, nameof(repository));
Extensions.Guard.ArgumentNotNull(title, nameof(title));
Extensions.Guard.ArgumentNotNull(body, nameof(body));
Extensions.Guard.ArgumentNotNull(source, nameof(source));
Extensions.Guard.ArgumentNotNull(target, nameof(target));
return host.ModelService.CreatePullRequest(repository, title, body, source, target);
}
public string GetPullRequestTemplate(ISimpleRepositoryModel repository)
{
Extensions.Guard.ArgumentNotNull(repository, nameof(repository));
var paths = TemplatePaths.Select(x => Path.Combine(repository.LocalPath, x));
foreach (var path in paths)
{
if (File.Exists(path))
{
try { return File.ReadAllText(path); } catch { }
}
}
return null;
}
}
} | using System;
using System.ComponentModel.Composition;
using System.IO;
using GitHub.Models;
namespace GitHub.Services
{
[NullGuard.NullGuard(NullGuard.ValidationFlags.None)]
[Export(typeof(IPullRequestService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class PullRequestService : IPullRequestService
{
public IObservable<IPullRequestModel> CreatePullRequest(IRepositoryHost host, ISimpleRepositoryModel repository, string title, string body, IBranch source, IBranch target)
{
Extensions.Guard.ArgumentNotNull(host, nameof(host));
Extensions.Guard.ArgumentNotNull(repository, nameof(repository));
Extensions.Guard.ArgumentNotNull(title, nameof(title));
Extensions.Guard.ArgumentNotNull(body, nameof(body));
Extensions.Guard.ArgumentNotNull(source, nameof(source));
Extensions.Guard.ArgumentNotNull(target, nameof(target));
return host.ModelService.CreatePullRequest(repository, title, body, source, target);
}
public string GetPullRequestTemplate(ISimpleRepositoryModel repository)
{
Extensions.Guard.ArgumentNotNull(repository, nameof(repository));
var paths = new[]
{
Path.Combine(repository.LocalPath, "PULL_REQUEST_TEMPLATE"),
Path.Combine(repository.LocalPath, "PULL_REQUEST_TEMPLATE.md"),
Path.Combine(repository.LocalPath, ".github", "PULL_REQUEST_TEMPLATE"),
Path.Combine(repository.LocalPath, ".github", "PULL_REQUEST_TEMPLATE.md"),
};
foreach (var path in paths)
{
if (File.Exists(path))
{
try { return File.ReadAllText(path); } catch { }
}
}
return null;
}
}
} | mit | C# |
e87452fc6af58701db40b4dbf0efc2b82ce63f81 | Add composition overloads | StanJav/language-ext,louthy/language-ext,StefanBertels/language-ext | LanguageExt.Core/Compose.cs | LanguageExt.Core/Compose.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LanguageExt
{
public static class __ComposeExt
{
/// <summary>
/// Function composition
/// </summary>
/// <returns>v => b(a(v))</returns>
[Pure]
public static Func<T1, T3> Compose<T1, T2, T3>(this Func<T2, T3> b, Func<T1, T2> a) =>
v => b(a(v));
/// <summary>
/// Function composition
/// </summary>
/// <returns>() => b(a())</returns>
[Pure]
public static Func<T2> Compose<T1, T2>(this Func<T1, T2> b, Func<T1> a) =>
() => b(a());
/// <summary>
/// Function composition
/// </summary>
/// <returns>v => b(a(v))</returns>
[Pure]
public static Func<T1, Unit> Compose<T1, T2>(this Action<T2> b, Func<T1, T2> a)
=> v => { b(a(v)); return Unit.Default; };
/// <summary>
/// Function composition
/// </summary>
/// <returns>() => b(a())</returns>
[Pure]
public static Func<Unit> Compose<T>(this Action<T> b, Func<T> a)
=> () => { b(a()); return Unit.Default; };
/// <summary>
/// Function back composition
/// </summary>
/// <returns>b(a(v))</returns>
[Pure]
public static Func<T1, T3> BackCompose<T1, T2, T3>(this Func<T1, T2> a, Func<T2, T3> b) =>
v => b(a(v));
/// <summary>
/// Function back composition
/// </summary>
/// <returns>b(a())</returns>
[Pure]
public static Func<T2> BackCompose<T1, T2>(this Func<T1> a, Func<T1, T2> b) =>
() => b(a());
/// <summary>
/// Function back composition
/// </summary>
/// <returns>v => b(a(v))</returns>
[Pure]
public static Func<T1, Unit> BackCompose<T1, T2>(this Func<T1, T2> a, Action<T2> b)
=> v => { b(a(v)); return Unit.Default; };
/// <summary>
/// Function back composition
/// </summary>
/// <returns>() => b(a())</returns>
[Pure]
public static Func<Unit> BackCompose<T>(this Func<T> a, Action<T> b)
=> () => { b(a()); return Unit.Default; };
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LanguageExt
{
public static class __ComposeExt
{
/// <summary>
/// Function composition
/// </summary>
/// <returns>b(a(v))</returns>
[Pure]
public static Func<T1, T3> Compose<T1, T2, T3>(this Func<T2, T3> b, Func<T1, T2> a) =>
v => b(a(v));
/// <summary>
/// Function back composition
/// </summary>
/// <returns>b(a(v))</returns>
[Pure]
public static Func<T1, T3> BackCompose<T1, T2, T3>(this Func<T1, T2> a, Func<T2, T3> b) =>
v => b(a(v));
}
}
| mit | C# |
9773beed0dcb14b94a819ad060a49ca492f4e753 | Handle empty aggregate fact source. #146 | NRules/NRules | src/NRules/NRules/Rete/AggregateFactSource.cs | src/NRules/NRules/Rete/AggregateFactSource.cs | using System.Collections.Generic;
using NRules.RuleModel;
namespace NRules.Rete
{
internal class AggregateFactSource : IFactSource
{
private static readonly IEnumerable<IFact> Empty = new IFact[0];
public AggregateFactSource(IEnumerable<IFact> facts)
{
Facts = facts ?? Empty;
}
public FactSourceType SourceType => FactSourceType.Aggregate;
public IEnumerable<IFact> Facts { get; }
}
} | using System.Collections.Generic;
using NRules.RuleModel;
namespace NRules.Rete
{
internal class AggregateFactSource : IFactSource
{
public AggregateFactSource(IEnumerable<IFact> facts)
{
Facts = facts;
}
public FactSourceType SourceType => FactSourceType.Aggregate;
public IEnumerable<IFact> Facts { get; }
}
} | mit | C# |
816241e1a9d75510e9bfd5c2d2a96eefde7ec8fe | fix coreclr build | UdiBen/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,azubanov/elasticsearch-net,elastic/elasticsearch-net | src/Nest/Cat/CatHelp/ElasticClient-CatHelp.cs | src/Nest/Cat/CatHelp/ElasticClient-CatHelp.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
namespace Nest
{
public partial interface IElasticClient
{
/// <inheritdoc/>
ICatResponse<CatHelpRecord> CatHelp(Func<CatHelpDescriptor, ICatHelpRequest> selector = null);
/// <inheritdoc/>
ICatResponse<CatHelpRecord> CatHelp(ICatHelpRequest request);
/// <inheritdoc/>
Task<ICatResponse<CatHelpRecord>> CatHelpAsync(Func<CatHelpDescriptor, ICatHelpRequest> selector = null);
/// <inheritdoc/>
Task<ICatResponse<CatHelpRecord>> CatHelpAsync(ICatHelpRequest request);
}
public partial class ElasticClient
{
private CatResponse<CatHelpRecord> DeserializeCatHelpResponse(IApiCallDetails response, Stream stream)
{
using (stream)
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
var body = ms.ToArray().Utf8String();
return new CatResponse<CatHelpRecord>
{
Records = body.Split('\n').Skip(1)
.Select(f => new CatHelpRecord { Endpoint = f.Trim() })
.ToList()
};
}
}
/// <inheritdoc/>
public ICatResponse<CatHelpRecord> CatHelp(Func<CatHelpDescriptor, ICatHelpRequest> selector = null) =>
this.CatHelp(selector.InvokeOrDefault(new CatHelpDescriptor()));
/// <inheritdoc/>
public ICatResponse<CatHelpRecord> CatHelp(ICatHelpRequest request) =>
this.Dispatcher.Dispatch<ICatHelpRequest, CatHelpRequestParameters, CatResponse<CatHelpRecord>>(
request,
new Func<IApiCallDetails, Stream, CatResponse<CatHelpRecord>>(this.DeserializeCatHelpResponse),
(p, d) => this.LowLevelDispatch.CatHelpDispatch<CatResponse<CatHelpRecord>>(p)
);
/// <inheritdoc/>
public Task<ICatResponse<CatHelpRecord>> CatHelpAsync(Func<CatHelpDescriptor, ICatHelpRequest> selector = null) =>
this.CatHelpAsync(selector.InvokeOrDefault(new CatHelpDescriptor()));
/// <inheritdoc/>
public Task<ICatResponse<CatHelpRecord>> CatHelpAsync(ICatHelpRequest request) =>
this.Dispatcher.DispatchAsync<ICatHelpRequest, CatHelpRequestParameters, CatResponse<CatHelpRecord>, ICatResponse<CatHelpRecord>>(
request,
new Func<IApiCallDetails, Stream, CatResponse<CatHelpRecord>>(this.DeserializeCatHelpResponse),
(p, d) => this.LowLevelDispatch.CatHelpDispatchAsync<CatResponse<CatHelpRecord>>(p)
);
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Elasticsearch.Net;
namespace Nest
{
public partial interface IElasticClient
{
/// <inheritdoc/>
ICatResponse<CatHelpRecord> CatHelp(Func<CatHelpDescriptor, ICatHelpRequest> selector = null);
/// <inheritdoc/>
ICatResponse<CatHelpRecord> CatHelp(ICatHelpRequest request);
/// <inheritdoc/>
Task<ICatResponse<CatHelpRecord>> CatHelpAsync(Func<CatHelpDescriptor, ICatHelpRequest> selector = null);
/// <inheritdoc/>
Task<ICatResponse<CatHelpRecord>> CatHelpAsync(ICatHelpRequest request);
}
public partial class ElasticClient
{
private CatResponse<CatHelpRecord> DeserializeCatHelpResponse(IApiCallDetails response, Stream stream)
{
using (stream)
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
var body = Encoding.UTF8.GetString(ms.ToArray());
return new CatResponse<CatHelpRecord>
{
Records = body.Split('\n').Skip(1)
.Select(f => new CatHelpRecord { Endpoint = f.Trim() })
.ToList()
};
}
}
/// <inheritdoc/>
public ICatResponse<CatHelpRecord> CatHelp(Func<CatHelpDescriptor, ICatHelpRequest> selector = null) =>
this.CatHelp(selector.InvokeOrDefault(new CatHelpDescriptor()));
/// <inheritdoc/>
public ICatResponse<CatHelpRecord> CatHelp(ICatHelpRequest request) =>
this.Dispatcher.Dispatch<ICatHelpRequest, CatHelpRequestParameters, CatResponse<CatHelpRecord>>(
request,
new Func<IApiCallDetails, Stream, CatResponse<CatHelpRecord>>(this.DeserializeCatHelpResponse),
(p, d) => this.LowLevelDispatch.CatHelpDispatch<CatResponse<CatHelpRecord>>(p)
);
/// <inheritdoc/>
public Task<ICatResponse<CatHelpRecord>> CatHelpAsync(Func<CatHelpDescriptor, ICatHelpRequest> selector = null) =>
this.CatHelpAsync(selector.InvokeOrDefault(new CatHelpDescriptor()));
/// <inheritdoc/>
public Task<ICatResponse<CatHelpRecord>> CatHelpAsync(ICatHelpRequest request) =>
this.Dispatcher.DispatchAsync<ICatHelpRequest, CatHelpRequestParameters, CatResponse<CatHelpRecord>, ICatResponse<CatHelpRecord>>(
request,
new Func<IApiCallDetails, Stream, CatResponse<CatHelpRecord>>(this.DeserializeCatHelpResponse),
(p, d) => this.LowLevelDispatch.CatHelpDispatchAsync<CatResponse<CatHelpRecord>>(p)
);
}
}
| apache-2.0 | C# |
8072cf75408b76aa55d6dc85f3a901034d69b207 | Remove lag | CSharpForLife/PoE-TradeUI | PoE-TradeUI/MainWindow.xaml.cs | PoE-TradeUI/MainWindow.xaml.cs | using System;
using System.Windows;
using System.Windows.Threading;
using PoE_TradeUI.poe;
namespace PoE_TradeUI {
public partial class MainWindow {
public MainWindow() {
InitializeComponent();
var game = new Game();
game.WindowStateChanged += GameOnWindowStateChanged;
}
private void GameOnWindowStateChanged(object sender, Native.Rect rect) {
var width = rect.Right - rect.Left;
var height = rect.Bottom - rect.Top;
Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => {
var x = rect.Left + SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left;
var y = rect.Top + SystemParameters.CaptionHeight + SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left;
var w = width - (SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left) * 2;
var h = height - (SystemParameters.CaptionHeight + SystemParameters.WindowResizeBorderThickness.Left +
SystemParameters.WindowNonClientFrameThickness.Left) - (SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left);
if (Left != x) Left = x;
if (Top != y) Top = y;
if (Width != w) Width = w;
if (Height != h) Height = h;
}));
}
}
}
| using System;
using System.Windows;
using System.Windows.Threading;
using PoE_TradeUI.poe;
namespace PoE_TradeUI {
public partial class MainWindow {
public MainWindow() {
InitializeComponent();
var game = new Game();
game.WindowStateChanged += GameOnWindowStateChanged;
}
private void GameOnWindowStateChanged(object sender, Native.Rect rect) {
var width = rect.Right - rect.Left;
var height = rect.Bottom - rect.Top;
Dispatcher.Invoke(DispatcherPriority.Send, new Action(() => {
Left = rect.Left + SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left;
Top = rect.Top + SystemParameters.CaptionHeight + SystemParameters.WindowResizeBorderThickness.Left +
SystemParameters.WindowNonClientFrameThickness.Left;
Width = width - (SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left) * 2;
Height = height - (SystemParameters.CaptionHeight + SystemParameters.WindowResizeBorderThickness.Left +
SystemParameters.WindowNonClientFrameThickness.Left) - (SystemParameters.WindowResizeBorderThickness.Left + SystemParameters.WindowNonClientFrameThickness.Left);
}));
}
}
}
| mit | C# |
d0bfd06c5f3995df6c38a4f08c218eebb247b4a9 | remove Dispose() from test | MiniProfiler/dotnet,MiniProfiler/dotnet | tests/MiniProfiler.Tests/Storage/MongoDbStorageTests.cs | tests/MiniProfiler.Tests/Storage/MongoDbStorageTests.cs | using System;
using Xunit;
using Xunit.Abstractions;
namespace StackExchange.Profiling.Tests.Storage
{
public class MongoDbStorageTests : StorageBaseTest, IClassFixture<MongoDbStorageFixture>
{
public MongoDbStorageTests(MongoDbStorageFixture fixture, ITestOutputHelper output) : base(fixture, output)
{
}
}
public class MongoDbStorageFixture : StorageFixtureBase<MongoDbStorage>, IDisposable
{
public MongoDbStorageFixture()
{
Skip.IfNoConfig(nameof(TestConfig.Current.MongoDbConnectionString), TestConfig.Current.MongoDbConnectionString);
try
{
Storage = new MongoDbStorage(TestConfig.Current.MongoDbConnectionString).WithIndexCreation();
Storage.GetUnviewedIds("");
}
catch (Exception e)
{
ShouldSkip = true;
SkipReason = e.Message;
}
}
public void Dispose()
{
if (!ShouldSkip)
{
Storage.DropDatabase();
}
}
}
public static class MongoDbStorageExtensions
{
/// <summary>
/// Drop database for MongoDb storage.
/// </summary>
/// <param name="storage">The storage to drop schema for.</param>
public static void DropDatabase(this MongoDbStorage storage)
{
storage.GetClient().DropDatabase("MiniProfiler");
}
}
}
| using System;
using Xunit;
using Xunit.Abstractions;
namespace StackExchange.Profiling.Tests.Storage
{
public class MongoDbStorageTests : StorageBaseTest, IClassFixture<MongoDbStorageFixture>
{
public MongoDbStorageTests(MongoDbStorageFixture fixture, ITestOutputHelper output) : base(fixture, output)
{
}
}
public class MongoDbStorageFixture : StorageFixtureBase<MongoDbStorage>, IDisposable
{
public MongoDbStorageFixture()
{
Skip.IfNoConfig(nameof(TestConfig.Current.MongoDbConnectionString), TestConfig.Current.MongoDbConnectionString);
try
{
Storage = new MongoDbStorage(TestConfig.Current.MongoDbConnectionString).WithIndexCreation();
Storage.GetUnviewedIds("");
}
catch (Exception e)
{
ShouldSkip = true;
SkipReason = e.Message;
}
}
public void Dispose()
{
if (!ShouldSkip)
{
Storage.DropDatabase();
Storage.Dispose();
}
}
}
public static class MongoDbStorageExtensions
{
/// <summary>
/// Drop database for MongoDb storage.
/// </summary>
/// <param name="storage">The storage to drop schema for.</param>
public static void DropDatabase(this MongoDbStorage storage)
{
storage.GetClient().DropDatabase("MiniProfiler");
}
}
}
| mit | C# |
cd56b49e34486d1733a97a5c6dd593abacee9993 | Move client handling into a separate method. | darkriszty/NetworkCardsGame | EchoServer/Program.cs | EchoServer/Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EchoServer
{
class Program
{
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
Console.WriteLine("Starting server");
TcpListener server = new TcpListener(IPAddress.IPv6Loopback, 8080);
Console.WriteLine("Starting listener");
server.Start();
while (true)
{
TcpClient client = await server.AcceptTcpClientAsync();
Task.Factory.StartNew(() => HandleConnection(client));
}
server.Stop();
}
static async Task HandleConnection(TcpClient client)
{
Console.WriteLine($"New connection from {client.Client.RemoteEndPoint}");
client.ReceiveTimeout = 30;
client.SendTimeout = 30;
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
StreamReader reader = new StreamReader(stream, Encoding.ASCII);
string line = await reader.ReadLineAsync();
Console.WriteLine($"Received {line}");
await writer.WriteLineAsync(line);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EchoServer
{
class Program
{
static void Main(string[] args)
{
Task main = MainAsync(args);
main.Wait();
}
static async Task MainAsync(string[] args)
{
Console.WriteLine("Starting server");
CancellationToken cancellationToken = new CancellationTokenSource().Token;
TcpListener listener = new TcpListener(IPAddress.IPv6Loopback, 8080);
listener.Start();
TcpClient client = await listener.AcceptTcpClientAsync();
client.ReceiveTimeout = 30;
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream, Encoding.ASCII) { AutoFlush = true };
StreamReader reader = new StreamReader(stream, Encoding.ASCII);
while (true)
{
string line = await reader.ReadLineAsync();
Console.WriteLine($"Received {line}");
await writer.WriteLineAsync(line);
if (cancellationToken.IsCancellationRequested)
break;
}
listener.Stop();
}
}
}
| mit | C# |
66a2a54aebcc6197c1bacf84b0aa5105b86e3f27 | Clean up the diagnostic in FieldToProperty pass. | mono/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,zillemarco/CppSharp,u255436/CppSharp,mono/CppSharp,mono/CppSharp,inordertotest/CppSharp,ddobrev/CppSharp,inordertotest/CppSharp,mono/CppSharp,ktopouzi/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,inordertotest/CppSharp,ktopouzi/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,mohtamohit/CppSharp,mohtamohit/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,zillemarco/CppSharp,ddobrev/CppSharp,ddobrev/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,u255436/CppSharp,ktopouzi/CppSharp,inordertotest/CppSharp | src/Generator/Passes/FieldToPropertyPass.cs | src/Generator/Passes/FieldToPropertyPass.cs | using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;
namespace CppSharp.Passes
{
public class FieldToPropertyPass : TranslationUnitPass
{
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
return base.VisitClassDecl(@class);
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
var @class = field.Namespace as Class;
if (@class == null)
return false;
if (ASTUtils.CheckIgnoreField(field))
return false;
// Check if we already have a synthetized property.
var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field);
if (existingProp != null)
return false;
field.GenerationKind = GenerationKind.Internal;
var prop = new Property
{
Name = field.Name,
Namespace = field.Namespace,
QualifiedType = field.QualifiedType,
Access = field.Access,
Field = field
};
// do not rename value-class fields because they would be
// generated as fields later on even though they are wrapped by properties;
// that is, in turn, because it's cleaner to write
// the struct marshalling logic just for properties
if (!prop.IsInRefTypeAndBackedByValueClassField())
field.Name = Generator.GeneratedIdentifier(field.Name);
@class.Properties.Add(prop);
Diagnostics.Debug($"Property created from field: {field.QualifiedName}");
return false;
}
}
}
| using System.Linq;
using CppSharp.AST;
using CppSharp.Generators;
namespace CppSharp.Passes
{
public class FieldToPropertyPass : TranslationUnitPass
{
public override bool VisitClassDecl(Class @class)
{
if (@class.CompleteDeclaration != null)
return VisitClassDecl(@class.CompleteDeclaration as Class);
return base.VisitClassDecl(@class);
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
var @class = field.Namespace as Class;
if (@class == null)
return false;
if (ASTUtils.CheckIgnoreField(field))
return false;
// Check if we already have a synthetized property.
var existingProp = @class.Properties.FirstOrDefault(property => property.Field == field);
if (existingProp != null)
return false;
field.GenerationKind = GenerationKind.Internal;
var prop = new Property
{
Name = field.Name,
Namespace = field.Namespace,
QualifiedType = field.QualifiedType,
Access = field.Access,
Field = field
};
// do not rename value-class fields because they would be
// generated as fields later on even though they are wrapped by properties;
// that is, in turn, because it's cleaner to write
// the struct marshalling logic just for properties
if (!prop.IsInRefTypeAndBackedByValueClassField())
field.Name = Generator.GeneratedIdentifier(field.Name);
@class.Properties.Add(prop);
Diagnostics.Debug("Property created from field: {0}::{1}", @class.Name,
field.Name);
return false;
}
}
}
| mit | C# |
f761049c342a401950ea20d305737294bfbfff96 | Remove extra space | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/Acknowledgement.cshtml | src/SFA.DAS.EmployerApprenticeshipsService.Web/Views/EmployerCommitments/Acknowledgement.cshtml | <div class="grid-row">
<div class="column-two-thirds">
<div class="govuk-box-highlight">
<h1 class="heading-xlarge" id="changeHeadline">
Sent to provider
</h1>
<p id="changeRefNumber">
Your reference number is <br>
<strong class="heading-medium">EE98HGS3F</strong>
</p>
</div>
<h2 class="heading-medium">What happens next?</h2>
<p id="changeMainCopy">The employer will log on to their account and see the changes you’ve made. They’ll then either approve them or send the cohort back to you to make changes.</p>
<a class="button" href="@Url.Action("Index")">Continue</a>
</div>
<div class="column-one-third">
</div>
</div> | <div class="grid-row">
<div class="column-two-thirds">
<div class="govuk-box-highlight">
<h1 class="heading-xlarge" id="changeHeadline">
Sent to provider
</h1>
<p id="changeRefNumber">
Your reference number is <br>
<strong class="heading-medium">EE98HGS3F</strong>
</p>
</div>
<h2 class="heading-medium">What happens next?</h2>
<p id="changeMainCopy">The employer will log on to their account and see the changes you’ve made. They’ll then either approve them or send the cohort back to you to make changes.</p>
<a class="button" href="@Url.Action(" Index")">Continue</a>
</div>
<div class="column-one-third">
</div>
</div> | mit | C# |
23e4e8afd376ede7e3b0aa97099443305f557ceb | Add additional languages | f0xy/forecast.io-csharp | forecast.io/Entities/Constants.cs | forecast.io/Entities/Constants.cs | using System.ComponentModel;
namespace ForecastIO
{
public enum Unit
{
us,
si,
ca,
uk,
auto
}
public enum Exclude
{
currently,
minutely,
hourly,
daily,
alerts,
flags
}
// Keeping this an enum for now to since only hourly is supported (not sure if the devs will allow the other types to be extended).
public enum Extend
{
hourly
}
public enum Language
{
ar,
az,
be,
bs,
cs,
de,
el,
en,
es,
fr,
hr,
hu,
id,
it,
@is,
kw,
nb,
nl,
pl,
pt,
ru,
sk,
sr,
sv,
tet,
tr,
uk,
[Description("x-pig-latin")]
xpiglatin,
zh,
[Description("zh-tw")]
zhtw
}
} | using System.ComponentModel;
namespace ForecastIO
{
public enum Unit
{
us,
si,
ca,
uk,
auto
}
public enum Exclude
{
currently,
minutely,
hourly,
daily,
alerts,
flags
}
// Keeping this an enum for now to since only hourly is supported (not sure if the devs will allow the other types to be extended).
public enum Extend
{
hourly
}
public enum Language
{
ar,
be,
cs,
el,
es,
fr,
hr,
hu,
id,
it,
@is,
kw,
nb,
nl,
pl,
pt,
ru,
sk,
sr,
sv,
tet,
tr,
uk,
[Description("x-pig-latin")]
xpiglatin,
zh,
[Description("zh-tw")]
zhtw,
bs,
de,
en
}
} | mit | C# |
9a89c1721f0767da2ee7fc8863e02ce3b80c27bc | Mark evil test as ignore, again | mattolenik/HttpMock,hibri/HttpMock,oschwald/HttpMock,zhdusurfin/HttpMock | src/HttpMock.Unit.Tests/HttpFactoryTests.cs | src/HttpMock.Unit.Tests/HttpFactoryTests.cs |
using System;
using NUnit.Framework;
namespace HttpMock.Unit.Tests
{
[TestFixture]
public class HttpFactoryTests
{
[Test]
[Ignore ("Makes the test suite flaky (???)")]
public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed()
{
var serverFactory = new HttpServerFactory();
var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting()));
IHttpServer server1, server2 = null;
server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
try
{
server1.Start();
server1.Dispose();
server1 = null;
server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
Assert.DoesNotThrow(server2.Start);
}
finally
{
if (server1 != null)
{
server1.Dispose();
}
if (server2 != null)
{
server2.Dispose();
}
}
}
}
}
|
using System;
using NUnit.Framework;
namespace HttpMock.Unit.Tests
{
[TestFixture]
public class HttpFactoryTests
{
[Test]
public void ShouldBeAbleToHostAtSameAddressIfPreviousWasDisposed()
{
var serverFactory = new HttpServerFactory();
var uri = new Uri(String.Format("http://localhost:{0}", PortHelper.FindLocalAvailablePortForTesting()));
IHttpServer server1, server2 = null;
server1 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
try
{
server1.Start();
server1.Dispose();
server1 = null;
server2 = serverFactory.Get(uri).WithNewContext(uri.AbsoluteUri);
Assert.DoesNotThrow(server2.Start);
}
finally
{
if (server1 != null)
{
server1.Dispose();
}
if (server2 != null)
{
server2.Dispose();
}
}
}
}
}
| mit | C# |
2544c314b8c124d5184188e4785ff850cad092c4 | Update AssemblyInfo.cs | Brillio/appium-dotnet-driver,rajfidel/appium-dotnet-driver,suryarend/appium-dotnet-driver,rajfidel/appium-dotnet-driver,Astro03/appium-dotnet-driver,appium/appium-dotnet-driver | appium-dotnet-driver/Properties/AssemblyInfo.cs | appium-dotnet-driver/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("appium-dotnet-driver")]
[assembly: AssemblyDescription ("Appium Dotnet Driver")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Appium Contributors")]
[assembly: AssemblyProduct ("Appium-Dotnet-Driver")]
[assembly: AssemblyCopyright ("Copyright © 2014")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.2.0.4")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("appium-dotnet-driver")]
[assembly: AssemblyDescription ("Appium Dotnet Driver")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("Appium Contributors")]
[assembly: AssemblyProduct ("Appium-Dotnet-Driver")]
[assembly: AssemblyCopyright ("Copyright © 2014")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.2.0.3")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| apache-2.0 | C# |
95acc457aad5f08df2b7a7a4bc37af4a241ffc2d | Fix stupid mistake | peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,smoogipooo/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game/Online/Rooms/BeatmapAvailability.cs | osu.Game/Online/Rooms/BeatmapAvailability.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly double? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, double? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(double progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly double? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, double? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(double progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Downloaded);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
| mit | C# |
368bd5021918e524fd64475aba6c214e27717300 | Update assembly version | DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit,DevExpress/AjaxControlToolkit | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2016")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("16.1.2.0")]
[assembly: AssemblyFileVersion("16.1.2.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
| using System.Reflection;
using System.Resources;
// WARNING this file is shared accross multiple projects
[assembly: AssemblyProduct("ASP.NET AJAX Control Toolkit")]
[assembly: AssemblyCopyright("Copyright © CodePlex Foundation 2012-2016")]
[assembly: AssemblyCompany("CodePlex Foundation")]
[assembly: AssemblyVersion("16.1.1.0")]
[assembly: AssemblyFileVersion("16.1.1.0")]
[assembly: NeutralResourcesLanguage("en-US")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif | bsd-3-clause | C# |
a95bdcf8ab928c29c9ac93be8c5f6fe3dccc84c5 | Fix assembly product name | xt0rted/Nancy.Validation.DataAnnotations.Extensions | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Brian Surowiec")]
[assembly: AssemblyProduct("Nancy.Validation.DataAnnotations.Extensions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyInformationalVersion("0.4.0")]
[assembly: AssemblyVersion("0.4.0")]
[assembly: AssemblyFileVersion("0.4.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Brian Surowiec")]
[assembly: AssemblyProduct("Nancy.Validation.DataAnnotations.Extensions.Tests")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyInformationalVersion("0.4.0")]
[assembly: AssemblyVersion("0.4.0")]
[assembly: AssemblyFileVersion("0.4.0")] | mit | C# |
04b587c61475b5ab383c27b426bf4c522185df83 | Bump to version 0.1.1 | Kryptos-FR/markdig-wpf,Kryptos-FR/markdig.wpf | src/Markdig.Xaml/Properties/AssemblyInfo.cs | src/Markdig.Xaml/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// 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("Markdig.Xaml")]
[assembly: AssemblyDescription("a XAML port to CommonMark compliant Markdig.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Markdig.Xaml")]
[assembly: AssemblyCopyright("Copyright © Nicolas Musset 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion(Markdig.Xaml.Markdown.Version)]
[assembly: AssemblyFileVersion(Markdig.Xaml.Markdown.Version)]
namespace Markdig.Xaml
{
public static partial class Markdown
{
public const string Version = "0.1.1";
}
}
| using System.Reflection;
using System.Resources;
// 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("Markdig.Xaml")]
[assembly: AssemblyDescription("a XAML port to CommonMark compliant Markdig.")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Markdig.Xaml")]
[assembly: AssemblyCopyright("Copyright © Nicolas Musset 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
[assembly: AssemblyVersion(Markdig.Xaml.Markdown.Version)]
[assembly: AssemblyFileVersion(Markdig.Xaml.Markdown.Version)]
namespace Markdig.Xaml
{
public static partial class Markdown
{
public const string Version = "0.1.0";
}
}
| mit | C# |
f62f20e1b9d723cdec45edf52482f03a6f89fb9c | Update ReferenceCacheManager.cs | PowerMogli/Rabbit.Db | src/Micro+/Caching/ReferenceCacheManager.cs | src/Micro+/Caching/ReferenceCacheManager.cs | using MicroORM.Entity;
namespace MicroORM.Caching
{
internal static class ReferenceCacheManager
{
private static readonly object _lock = new object();
private static EntityInfoReferenceCache<object> _referenceCache = new EntityInfoReferenceCache<object>();
internal static EntityInfo GetEntityInfo<TEntity>(TEntity entity)
{
EntityInfo entityInfo;
lock (_lock)
{
entityInfo = _referenceCache.Get(entity);
}
if (entityInfo != null)
return entityInfo;
return SetObjectInfo<TEntity>(entity, new EntityInfo());
}
private static EntityInfo SetEntityInfo<TEntity>(TEntity entity, EntityInfo entityInfo)
{
lock (_lock)
{
if (_referenceCache.Get(entity) == null)
_referenceCache.Add(entity, entityInfo);
else
_referenceCache.Update(entity, entityInfo);
}
return entityInfo;
}
}
}
| using MicroORM.Entity;
namespace MicroORM.Caching
{
internal static class ReferenceCacheManager
{
private static readonly object _lock = new object();
private static EntityInfoReferenceCache<object> _referenceCache = new EntityInfoReferenceCache<object>();
internal static EntityInfo GetEntityInfo<TEntity>(TEntity entity)
{
EntityInfo entityInfo;
lock (_lock)
{
entityInfo = _referenceCache.Get(entity);
}
if (entityInfo != null)
return entityInfo;
return SetObjectInfo<TEntity>(entity, new EntityInfo());
}
private static EntityInfo SetObjectInfo<TEntity>(TEntity entity, EntityInfo entityInfo)
{
lock (_lock)
{
if (_referenceCache.Get(entity) == null)
_referenceCache.Add(entity, entityInfo);
else
_referenceCache.Update(entity, entityInfo);
}
return entityInfo;
}
}
}
| apache-2.0 | C# |
b6953e379573db2a6c71a35ec69b6b45826d6d58 | Use CreateDelegate for method without parameter and return value | KodamaSakuno/Sakuno.Base | src/Sakuno.Base/Reflection/MethodInvoker.cs | src/Sakuno.Base/Reflection/MethodInvoker.cs | using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Sakuno.Reflection
{
public class MethodInvoker
{
public MethodInfo Method { get; }
Func<object, object[], object> _invoker;
public MethodInvoker(MethodInfo method)
{
Method = method ?? throw new ArgumentNullException(nameof(method));
_invoker = CreateInvokerCore(method);
}
public object Invoke(object instance, params object[] args) =>
_invoker(instance, args);
static Func<object, object[], object> CreateInvokerCore(MethodInfo method)
{
if (method.ReturnType == typeof(void) && method.GetParameters().Length == 0)
{
var action = (Action)Delegate.CreateDelegate(typeof(Action), method);
return delegate
{
action();
return null;
};
}
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var argsParameter = Expression.Parameter(typeof(object[]), "args");
var arguments = method.GetParameters().Select((r, i) =>
{
var parameterValue = Expression.ArrayIndex(argsParameter, Expression.Constant(i));
return Expression.Convert(parameterValue, r.ParameterType);
}).ToArray();
var castInstance = !method.IsStatic ? Expression.Convert(instanceParameter, method.ReflectedType) : null;
var call = Expression.Call(castInstance, method, arguments);
if (call.Type == typeof(void))
{
var func = Expression.Lambda<Action<object, object[]>>(call, instanceParameter, argsParameter).Compile();
return (instance, args) =>
{
func(instance, args);
return null;
};
}
else
{
var castReturnValue = Expression.Convert(call, typeof(object));
return Expression.Lambda<Func<object, object[], object>>(castReturnValue, instanceParameter, argsParameter).Compile();
}
}
}
}
| using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Sakuno.Reflection
{
public class MethodInvoker
{
public MethodInfo Method { get; }
Func<object, object[], object> _invoker;
public MethodInvoker(MethodInfo method)
{
Method = method ?? throw new ArgumentNullException(nameof(method));
_invoker = CreateInvokerCore(method);
}
public object Invoke(object instance, params object[] args) =>
_invoker(instance, args);
static Func<object, object[], object> CreateInvokerCore(MethodInfo method)
{
var instanceParameter = Expression.Parameter(typeof(object), "instance");
var argsParameter = Expression.Parameter(typeof(object[]), "args");
var arguments = method.GetParameters().Select((r, i) =>
{
var parameterValue = Expression.ArrayIndex(argsParameter, Expression.Constant(i));
return Expression.Convert(parameterValue, r.ParameterType);
}).ToArray();
var castInstance = !method.IsStatic ? Expression.Convert(instanceParameter, method.ReflectedType) : null;
var call = Expression.Call(castInstance, method, arguments);
if (call.Type == typeof(void))
{
var func = Expression.Lambda<Action<object, object[]>>(call, instanceParameter, argsParameter).Compile();
return (instance, args) =>
{
func(instance, args);
return null;
};
}
else
{
var castReturnValue = Expression.Convert(call, typeof(object));
return Expression.Lambda<Func<object, object[], object>>(castReturnValue, instanceParameter, argsParameter).Compile();
}
}
}
}
| mit | C# |
aabe4a7ede2134f5bdca8637a5285efa7bf31c75 | Remove unused variable | another-guy/CSharpToTypeScript,another-guy/CSharpToTypeScript | TsModelGen/Program.cs | TsModelGen/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using TsModelGen.Core;
using TsModelGen.Core.TypeTranslationContext;
namespace TsModelGen
{
public class Program
{
public static void Main(string[] args)
{
// TODO Move this to input parameters
// TODO Translate into a list of namespaces, types, rules on types (such as
var targetNameSpace = "TsModelGen.TargetNamespace";
var targetNamespaces = new[] { targetNameSpace }; // TODO Make a parameter
var rootTranslationTargetTypes = RootTargetTypes.LocateFrom(targetNamespaces).ToList();
var translationContext = new TranslationContextBuilder().Build(rootTranslationTargetTypes);
var generatedCode = rootTranslationTargetTypes
.Union(
translationContext
.OfType<RegularTypeTranslationContext>()
.Select(typeTranslationContext => typeTranslationContext.TypeInfo)
)
.Select(targetType =>
translationContext
.First(typeTranslationContext => typeTranslationContext.CanProcess(targetType.AsType()))
.Process(targetType.AsType())
.Definition
)
.Where(definition => string.IsNullOrWhiteSpace(definition) == false)
.Aggregate((accumulated, typeDefinition) => accumulated + "\n\n" + typeDefinition);
Console.WriteLine(generatedCode);
Console.ReadKey();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using TsModelGen.Core;
using TsModelGen.Core.TypeTranslationContext;
namespace TsModelGen
{
public class Program
{
public static void Main(string[] args)
{
// TODO Move this to input parameters
// TODO Translate into a list of namespaces, types, rules on types (such as
var targetNameSpace = "TsModelGen.TargetNamespace";
var targetNamespaces = new[] { targetNameSpace }; // TODO Make a parameter
var rootTranslationTargetTypes = RootTargetTypes.LocateFrom(targetNamespaces).ToList();
var translationContext = new TranslationContextBuilder().Build(rootTranslationTargetTypes);
// TODO Remove this dictionary
var dictionary = rootTranslationTargetTypes
.Union(
translationContext
.OfType<RegularTypeTranslationContext>()
.Select(typeTranslationContext => typeTranslationContext.TypeInfo)
)
.ToDictionary(
targetType => targetType.FullName,
targetType => translationContext
.First(typeTranslationContext => typeTranslationContext.CanProcess(targetType.AsType())));
var generatedCode = rootTranslationTargetTypes
.Union(
translationContext
.OfType<RegularTypeTranslationContext>()
.Select(typeTranslationContext => typeTranslationContext.TypeInfo)
)
.Select(targetType =>
translationContext
.First(typeTranslationContext => typeTranslationContext.CanProcess(targetType.AsType()))
.Process(targetType.AsType())
.Definition
)
.Where(definition => string.IsNullOrWhiteSpace(definition) == false)
.Aggregate((accumulated, typeDefinition) => accumulated + "\n\n" + typeDefinition);
Console.WriteLine(generatedCode);
Console.ReadKey();
}
}
} | mit | C# |
747cd0f76321c26285b4492f0afa49c934963290 | Update Item.cs | mihov/J.D.Salinger | Waits/TheGame/Item.cs | Waits/TheGame/Item.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Waits
{
public abstract class Item
{
private int price;
public Item(int price)
{
this.Price = price;
}
public int Price
{
get { return this.price; }
set { this.price = value; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Waits
{
abstract class Item
{
private int price;
public Item(int price)
{
this.Price = price;
}
public int Price
{
get { return this.price; }
set { this.Price = price; }
}
}
}
| unlicense | C# |
2d6a960b281ae4a900e8b3801dc06a0438edfe42 | Clean up Startup.cs | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/AtomicChessPuzzles/Startup.cs | src/AtomicChessPuzzles/Startup.cs | using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace AtomicChessPuzzles
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
using Microsoft.Extensions.DependencyInjection;
namespace AtomicChessPuzzles
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.UseIISPlatformHandler();
app.UseStaticFiles();
app.UseMvc();
}
// Entry point for the application.
public static void Main(string[] args) => WebApplication.Run<Startup>(args);
}
}
| agpl-3.0 | C# |
e907394d50a53c6ac5287113b7b1da9ec22c4768 | Add missing variable field to support Update Variable | opinum/opisense-sample-dotnet-console | opisense-sample-dotnet-console/Model/Variable.cs | opisense-sample-dotnet-console/Model/Variable.cs | namespace opisense_sample_dotnet_console.Model
{
public class Variable
{
public int Id { get; set; }
public string Name { get; set; }
public int SourceId { get; set; }
public int VariableTypeId { get; set; }
public int UnitId { get; set; }
public double Granularity { get; set; }
public TimePeriod GranularityTimeBase { get; set; }
public string MappingConfig { get; set; }
public QuantityType QuantityType { get; set; }
}
public enum QuantityType
{
Instantaneous = 1,
Integrated = 2,
Cumulative = 3,
Minimum = 4,
Maximum = 5,
Averaged = 6
}
} | namespace opisense_sample_dotnet_console.Model
{
public class Variable
{
public int Id { get; set; }
public string Name { get; set; }
public int SourceId { get; set; }
public int VariableTypeId { get; set; }
public int UnitId { get; set; }
public double Granularity { get; set; }
public TimePeriod GranularityTimeBase { get; set; }
public string MappingConfig { get; set; }
}
} | mit | C# |
b2ae012598085ed86961105e461cac59f19d53a8 | Add GitHubAccessToken support to the tests | tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server | tests/Tgstation.Server.Tests/TestingServer.cs | tests/Tgstation.Server.Tests/TestingServer.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
sealed class TestingServer : IServer
{
public Uri Url { get; }
public string Directory { get; }
public bool RestartRequested => realServer.RestartRequested;
readonly IServer realServer;
public TestingServer()
{
Directory = Path.GetTempFileName();
File.Delete(Directory);
System.IO.Directory.CreateDirectory(Directory);
Url = new Uri("http://localhost:5001");
//so we need a db
//we have to rely on env vars
var databaseType = Environment.GetEnvironmentVariable("TGS4_TEST_DATABASE_TYPE");
var connectionString = Environment.GetEnvironmentVariable("TGS4_TEST_CONNECTION_STRING");
var gitHubAccessToken = Environment.GetEnvironmentVariable("TGS4_TEST_GITHUB_TOKEN");
if (String.IsNullOrEmpty(databaseType))
Assert.Fail("No database type configured in env var TGS4_TEST_DATABASE_TYPE!");
if (String.IsNullOrEmpty(connectionString))
Assert.Fail("No connection string configured in env var TGS4_TEST_CONNECTION_STRING!");
var args = new List<string>()
{
"--urls",
Url.ToString(),
String.Format(CultureInfo.InvariantCulture, "Database:DatabaseType={0}", databaseType),
String.Format(CultureInfo.InvariantCulture, "Database:ConnectionString={0}", connectionString),
"Database:DropDatabase=true"
};
if (!String.IsNullOrEmpty(gitHubAccessToken))
args.Add(String.Format(CultureInfo.InvariantCulture, "General:GitHubAccessToken={0}", gitHubAccessToken));
realServer = new ServerFactory().CreateServer(args.ToArray(), null);
}
public void Dispose()
{
realServer.Dispose();
System.IO.Directory.Delete(Directory, true);
}
public Task RunAsync(CancellationToken cancellationToken) => realServer.RunAsync(cancellationToken);
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
sealed class TestingServer : IServer
{
public Uri Url { get; }
public string Directory { get; }
public bool RestartRequested => realServer.RestartRequested;
readonly IServer realServer;
public TestingServer()
{
Directory = Path.GetTempFileName();
File.Delete(Directory);
System.IO.Directory.CreateDirectory(Directory);
Url = new Uri("http://localhost:5001");
//so we need a db
//we have to rely on env vars
var databaseType = Environment.GetEnvironmentVariable("TGS4_TEST_DATABASE_TYPE");
var connectionString = Environment.GetEnvironmentVariable("TGS4_TEST_CONNECTION_STRING");
if (String.IsNullOrEmpty(databaseType))
Assert.Fail("No database type configured in env var TGS4_TEST_DATABASE_TYPE!");
if (String.IsNullOrEmpty(connectionString))
Assert.Fail("No connection string configured in env var TGS4_TEST_CONNECTION_STRING!");
realServer = new ServerFactory().CreateServer(new string[]
{
"--urls",
Url.ToString(),
String.Format(CultureInfo.InvariantCulture, "Database:DatabaseType={0}", databaseType),
String.Format(CultureInfo.InvariantCulture, "Database:ConnectionString={0}", connectionString),
"Database:DropDatabase=true"
}, null);
}
public void Dispose()
{
realServer.Dispose();
System.IO.Directory.Delete(Directory, true);
}
public Task RunAsync(CancellationToken cancellationToken) => realServer.RunAsync(cancellationToken);
}
}
| agpl-3.0 | C# |
3acab01ae313553f85beaddcdfe9aa8922aa1acf | Align output and remove needless padding format spec | smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Logging/LoadingComponentsLogger.cs | osu.Framework/Logging/LoadingComponentsLogger.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Development;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Lists;
namespace osu.Framework.Logging
{
internal static class LoadingComponentsLogger
{
private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>();
public static void Add(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Add(component);
}
public static void Remove(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Remove(component);
}
public static void LogAndFlush()
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
{
Logger.Log($"⏳ Currently loading components ({loading_components.Count()})");
foreach (var c in loading_components.OrderBy(c => c.LoadThread?.Name).ThenBy(c => c.LoadState))
{
Logger.Log($"{c.GetType().ReadableName()}");
Logger.Log($"- thread: {c.LoadThread?.Name ?? "none"}");
Logger.Log($"- state: {c.LoadState}");
}
loading_components.Clear();
Logger.Log("🧵 Task schedulers");
Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString());
Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString());
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using osu.Framework.Development;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Lists;
namespace osu.Framework.Logging
{
internal static class LoadingComponentsLogger
{
private static readonly WeakList<Drawable> loading_components = new WeakList<Drawable>();
public static void Add(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Add(component);
}
public static void Remove(Drawable component)
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
loading_components.Remove(component);
}
public static void LogAndFlush()
{
if (!DebugUtils.IsDebugBuild) return;
lock (loading_components)
{
Logger.Log($"⏳ Currently loading components ({loading_components.Count()})");
foreach (var c in loading_components.OrderBy(c => c.LoadThread?.Name).ThenBy(c => c.LoadState))
{
Logger.Log($"{c.GetType().ReadableName(),-16}");
Logger.Log($"- thread:{c.LoadThread?.Name ?? "none"}");
Logger.Log($"- state:{c.LoadState,-5}");
}
loading_components.Clear();
Logger.Log("🧵 Task schedulers");
Logger.Log(CompositeDrawable.SCHEDULER_STANDARD.GetStatusString());
Logger.Log(CompositeDrawable.SCHEDULER_LONG_LOAD.GetStatusString());
}
}
}
}
| mit | C# |
00a4d60e8910869457d3e70ec04b6727b705d15f | Make sure distance is clamped to sane values | johnneijzen/osu,EVAST9919/osu,2yangk23/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,naoey/osu,ZLima12/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,UselessToucan/osu,NeoAdonis/osu,naoey/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | osu.Game.Rulesets.Osu/Difficulty/Skills/Speed.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = Math.Min(SINGLE_SPACING_THRESHOLD, current.TravelDistance + current.JumpDistance);
return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Rulesets.Osu.Difficulty.Preprocessing;
namespace osu.Game.Rulesets.Osu.Difficulty.Skills
{
/// <summary>
/// Represents the skill required to press keys with regards to keeping up with the speed at which objects need to be hit.
/// </summary>
public class Speed : Skill
{
protected override double SkillMultiplier => 1400;
protected override double StrainDecayBase => 0.3;
protected override double StrainValueOf(OsuDifficultyHitObject current)
{
double distance = current.TravelDistance + current.JumpDistance;
return (0.95 + Math.Pow(distance / SINGLE_SPACING_THRESHOLD, 4)) / current.StrainTime;
}
}
}
| mit | C# |
b5834044e0d405ec4acbfa9629271d4dc77fa729 | Update `GetScoreRequest` to support requests with interface types | peppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu | osu.Game/Online/API/Requests/GetScoresRequest.cs | osu.Game/Online/API/Requests/GetScoresRequest.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Screens.Select.Leaderboards;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets.Mods;
using System.Text;
using System.Collections.Generic;
namespace osu.Game.Online.API.Requests
{
public class GetScoresRequest : APIRequest<APIScoresCollection>
{
private readonly IBeatmapInfo beatmapInfo;
private readonly BeatmapLeaderboardScope scope;
private readonly IRulesetInfo ruleset;
private readonly IEnumerable<IMod> mods;
public GetScoresRequest(IBeatmapInfo beatmapInfo, IRulesetInfo ruleset, BeatmapLeaderboardScope scope = BeatmapLeaderboardScope.Global, IEnumerable<IMod> mods = null)
{
if (beatmapInfo.OnlineID <= 0)
throw new InvalidOperationException($"Cannot lookup a beatmap's scores without having a populated {nameof(IBeatmapInfo.OnlineID)}.");
if (scope == BeatmapLeaderboardScope.Local)
throw new InvalidOperationException("Should not attempt to request online scores for a local scoped leaderboard");
this.beatmapInfo = beatmapInfo;
this.scope = scope;
this.ruleset = ruleset ?? throw new ArgumentNullException(nameof(ruleset));
this.mods = mods ?? Array.Empty<IMod>();
}
protected override string Target => $@"beatmaps/{beatmapInfo.OnlineID}/scores{createQueryParameters()}";
private string createQueryParameters()
{
StringBuilder query = new StringBuilder(@"?");
query.Append($@"type={scope.ToString().ToLowerInvariant()}");
query.Append($@"&mode={ruleset.ShortName}");
foreach (var mod in mods)
query.Append($@"&mods[]={mod.Acronym}");
return query.ToString();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Screens.Select.Leaderboards;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Rulesets.Mods;
using System.Text;
using System.Collections.Generic;
namespace osu.Game.Online.API.Requests
{
public class GetScoresRequest : APIRequest<APIScoresCollection>
{
private readonly BeatmapInfo beatmapInfo;
private readonly BeatmapLeaderboardScope scope;
private readonly RulesetInfo ruleset;
private readonly IEnumerable<IMod> mods;
public GetScoresRequest(BeatmapInfo beatmapInfo, RulesetInfo ruleset, BeatmapLeaderboardScope scope = BeatmapLeaderboardScope.Global, IEnumerable<IMod> mods = null)
{
if (!beatmapInfo.OnlineBeatmapID.HasValue)
throw new InvalidOperationException($"Cannot lookup a beatmap's scores without having a populated {nameof(BeatmapInfo.OnlineBeatmapID)}.");
if (scope == BeatmapLeaderboardScope.Local)
throw new InvalidOperationException("Should not attempt to request online scores for a local scoped leaderboard");
this.beatmapInfo = beatmapInfo;
this.scope = scope;
this.ruleset = ruleset ?? throw new ArgumentNullException(nameof(ruleset));
this.mods = mods ?? Array.Empty<IMod>();
}
protected override string Target => $@"beatmaps/{beatmapInfo.OnlineBeatmapID}/scores{createQueryParameters()}";
private string createQueryParameters()
{
StringBuilder query = new StringBuilder(@"?");
query.Append($@"type={scope.ToString().ToLowerInvariant()}");
query.Append($@"&mode={ruleset.ShortName}");
foreach (var mod in mods)
query.Append($@"&mods[]={mod.Acronym}");
return query.ToString();
}
}
}
| mit | C# |
3377a8dd4a9cd0c4134773fbca310dac9cfc5f99 | document igraph | DasAllFolks/SharpGraphs | Graph/IGraph.cs | Graph/IGraph.cs | using System;
namespace Graph
{
/// <summary>
/// Represents a graph.
/// </summary>
/// <typeparam name="V">The vertex type.</typeparam>
/// <typeparam name="E">The edge type.</typeparam>
public interface IGraph<V, E> : IEquatable<IGraph<V, E>> where E: IEdge<V>
{
}
}
| using System;
namespace Graph
{
public interface IGraph<E, V> : IEquatable<IGraph<E, V>> where E: IEdge<V>
{
}
}
| apache-2.0 | C# |
2af42bc3e658b76591999ab7daa540f6e9e2181c | Add comments to IIntervalSet | marsop/ephemeral | IIntervalSet.cs | IIntervalSet.cs | using System;
using System.Collections.Generic;
namespace seasonal
{
/// <summary>
/// Collection of IIntervals
/// </summary>
public interface IIntervalSet : IList<IInterval>
{
bool HasOverlap { get; }
/// <summary>
/// Sum of durations of the enclosed intervals
/// </summary>
TimeSpan AggregatedDuration { get; }
/// <summary>
/// Start of the last contained Interval
/// </summary>
DateTimeOffset Start { get; }
/// <summary>
/// End of the last contained Interval
/// </summary>
DateTimeOffset End { get; }
}
}
| using System;
using System.Collections.Generic;
namespace seasonal
{
/// <summary>
/// An IntervalSet cannot have overlapping intervals inside.
/// </summary>
public interface IIntervalSet : IList<IInterval>
{
bool HasOverlap { get; }
TimeSpan AggregatedDuration { get; }
DateTimeOffset Start { get; }
DateTimeOffset End { get; }
}
} | mit | C# |
9774c90393b8b669c95ebecbac7dbe3b1b6ef1c8 | resolve #368 | rollbar/Rollbar.NET | Rollbar/Common/DateTimeUtil.cs | Rollbar/Common/DateTimeUtil.cs | namespace Rollbar.Common
{
using System;
/// <summary>
/// Utility class for date/time related conversions.
/// </summary>
public static class DateTimeUtil
{
/// <summary>
/// Converts to unix timestamp in milliseconds.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns></returns>
public static long ConvertToUnixTimestampInMilliseconds(DateTime dateTime)
{
return Convert.ToInt64(dateTime.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds);
}
/// <summary>
/// Converts to unix timestamp in seconds.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns></returns>
public static long ConvertToUnixTimestampInSeconds(DateTime dateTime)
{
return Convert.ToInt64(dateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
}
/// <summary>
/// Converts from unix timestamp in seconds.
/// </summary>
/// <param name="unixTimestampInSeconds">The unix timestamp in seconds.</param>
/// <returns>corresponding DateTimeOffset value</returns>
public static DateTimeOffset ConvertFromUnixTimestampInSeconds(long unixTimestampInSeconds)
{
DateTimeOffset timestamp = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero);
timestamp = timestamp.AddSeconds(Convert.ToDouble(unixTimestampInSeconds));
return timestamp;
}
/// <summary>
/// Tries the parse from unix timestamp in seconds string.
/// </summary>
/// <param name="inputString">The input string.</param>
/// <param name="dateTimeOffset">The date time offset.</param>
/// <returns><c>true</c> if was able to parse successfully, <c>false</c> otherwise.</returns>
public static bool TryParseFromUnixTimestampInSecondsString(string inputString, out DateTimeOffset dateTimeOffset)
{
if (long.TryParse(inputString, out long unixTimestamp))
{
dateTimeOffset = DateTimeUtil.ConvertFromUnixTimestampInSeconds(unixTimestamp);
return true;
}
dateTimeOffset = default;
return false;
}
}
}
| namespace Rollbar.Common
{
using System;
/// <summary>
/// Utility class for date/time related conversions.
/// </summary>
public static class DateTimeUtil
{
/// <summary>
/// Converts to unix timestamp in milliseconds.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns></returns>
public static long ConvertToUnixTimestampInMilliseconds(DateTime dateTime)
{
return Convert.ToInt64(dateTime.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds);
}
/// <summary>
/// Converts to unix timestamp in seconds.
/// </summary>
/// <param name="dateTime">The date time.</param>
/// <returns></returns>
public static long ConvertToUnixTimestampInSeconds(DateTime dateTime)
{
return Convert.ToInt64(dateTime.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
}
/// <summary>
/// Converts from unix timestamp in seconds.
/// </summary>
/// <param name="unixTimestampInSeconds">The unix timestamp in seconds.</param>
/// <returns>corresponding DateTimeOffset value</returns>
public static DateTimeOffset ConvertFromUnixTimestampInSeconds(long unixTimestampInSeconds)
{
DateTimeOffset timestamp = new DateTimeOffset(new DateTime(1970, 1, 1), TimeSpan.Zero);
timestamp = timestamp.AddSeconds(Convert.ToDouble(unixTimestampInSeconds));
return timestamp;
}
/// <summary>
/// Tries the parse from unix timestamp in seconds string.
/// </summary>
/// <param name="inputString">The input string.</param>
/// <param name="dateTimeOffset">The date time offset.</param>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
public static bool TryParseFromUnixTimestampInSecondsString(string inputString, out DateTimeOffset dateTimeOffset)
{
if (long.TryParse(inputString, out long unixTimestamp))
{
dateTimeOffset = DateTimeUtil.ConvertFromUnixTimestampInSeconds(unixTimestamp);
return true;
}
dateTimeOffset = default;
return false;
}
}
}
| mit | C# |
f36ec7a402a8b2feb2aa6e43b1d7465f7f6cc616 | Handle paging diffrently | projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection | TheCollection.Web/Controllers/BagsController.cs | TheCollection.Web/Controllers/BagsController.cs | using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents.Client;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Services;
namespace TheCollection.Web.Controllers
{
[Route("api/[controller]")]
public class BagsController : Controller
{
private readonly DocumentClient documentDbClient;
public BagsController(DocumentClient documentDbClient)
{
this.documentDbClient = documentDbClient;
}
[HttpGet()]
public async Task<SearchResult<Bag>> Bags([FromQuery] string searchterm = "", [FromQuery] int pagesize = 300, [FromQuery] int page = 0)
{
var bagsRepository = new DocumentDBRepository<Bag>(documentDbClient, "TheCollection", "Bags");
IEnumerable<Bag> bags;
if (searchterm != "")
{
bags = await bagsRepository.GetItemsAsync(searchterm, pagesize);
}
else
{
bags = await bagsRepository.GetItemsAsync();
}
return new SearchResult<Bag>
{
count = await bagsRepository.GetRowCountAsync(searchterm),
data = bags.OrderBy(bag => bag.Brand.Name)
.ThenBy(bag => bag.Hallmark)
.ThenBy(bag => bag.Serie)
.ThenBy(bag => bag.BagType?.Name)
.ThenBy(bag => bag.Flavour)
};
}
[HttpGet("{id}")]
public async Task<Bag> Bag(string id)
{
var bagsRepository = new DocumentDBRepository<Bag>(documentDbClient, "TheCollection", "Bags");
return await bagsRepository.GetItemAsync(id);
}
}
public class SearchResult<T>
{
public long count { get; set; }
public IEnumerable<T> data { get; set; }
}
}
| using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Documents.Client;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Business.Tea;
using TheCollection.Web.Services;
namespace TheCollection.Web.Controllers
{
[Route("api/[controller]")]
public class BagsController : Controller
{
private readonly DocumentClient documentDbClient;
public BagsController(DocumentClient documentDbClient)
{
this.documentDbClient = documentDbClient;
}
[HttpGet()]
public async Task<SearchResult<Bag>> Bags([FromQuery] string searchterm = "")
{
var bagsRepository = new DocumentDBRepository<Bag>(documentDbClient, "TheCollection", "Bags");
IEnumerable<Bag> bags;
if (searchterm != "")
{
bags = await bagsRepository.GetItemsAsync(searchterm, 300);
}
else
{
bags = await bagsRepository.GetItemsAsync();
}
return new SearchResult<Bag>
{
count = await bagsRepository.GetRowCountAsync(searchterm),
data = bags.OrderBy(bag => bag.Brand.Name)
.ThenBy(bag => bag.Hallmark)
.ThenBy(bag => bag.Serie)
.ThenBy(bag => bag.BagType?.Name)
.ThenBy(bag => bag.Flavour)
};
}
[HttpGet("{id}")]
public async Task<Bag> Bag(string id)
{
var bagsRepository = new DocumentDBRepository<Bag>(documentDbClient, "TheCollection", "Bags");
return await bagsRepository.GetItemAsync(id);
}
}
public class SearchResult<T>
{
public long count { get; set; }
public IEnumerable<T> data { get; set; }
}
}
| apache-2.0 | C# |
0636ea0b161ad9e250fd8e910cf12cbc9a546120 | fix build | bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,WebCentrum/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,tompipe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,tompipe/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,lars-erik/Umbraco-CMS,tompipe/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,NikRimington/Umbraco-CMS,WebCentrum/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,WebCentrum/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,rasmuseeg/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/insertMasterpagePlaceholder.aspx.designer.cs | src/Umbraco.Web/umbraco.presentation/umbraco/dialogs/insertMasterpagePlaceholder.aspx.designer.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace umbraco.presentation.umbraco.dialogs {
public partial class insertMasterpagePlaceholder {
/// <summary>
/// tb_alias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tb_alias;
protected global::umbraco.uicontrols.PropertyPanel pp_placeholder;
}
}
| //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace umbraco.presentation.umbraco.dialogs {
public partial class insertMasterpagePlaceholder {
/// <summary>
/// tb_alias control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox tb_alias;
}
}
| mit | C# |
0048da589474cf960aea075980d8b1fc1ce22f81 | Update comments | Minesweeper-6-Team-Project-Telerik/Minesweeper-6 | src2/ConsoleMinesweeper/EnumerableEx.cs | src2/ConsoleMinesweeper/EnumerableEx.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="EnumerableEx.cs" company="Telerik Academy">
// Teamwork Project "Minesweeper-6"
// </copyright>
// <summary>
// The enumerable ex.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConsoleMinesweeper
{
using System;
using System.Collections.Generic;
/// <summary>
/// The enumerable ex.
/// </summary>
public static class EnumerableEx
{
/// <summary>
/// The split by.
/// </summary>
/// <param name="str">
/// The str.
/// </param>
/// <param name="chunkLength">
/// The chunk length.
/// </param>
/// <returns>
/// The <see cref="IEnumerable"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// </exception>
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
for (var i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
{
chunkLength = str.Length - i;
}
yield return str.Substring(i, chunkLength);
}
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="EnumerableEx.cs" company="">
//
// </copyright>
// <summary>
// The enumerable ex.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ConsoleMinesweeper
{
using System;
using System.Collections.Generic;
/// <summary>
/// The enumerable ex.
/// </summary>
public static class EnumerableEx
{
/// <summary>
/// The split by.
/// </summary>
/// <param name="str">
/// The str.
/// </param>
/// <param name="chunkLength">
/// The chunk length.
/// </param>
/// <returns>
/// The <see cref="IEnumerable"/>.
/// </returns>
/// <exception cref="ArgumentException">
/// </exception>
public static IEnumerable<string> SplitBy(this string str, int chunkLength)
{
for (var i = 0; i < str.Length; i += chunkLength)
{
if (chunkLength + i > str.Length)
{
chunkLength = str.Length - i;
}
yield return str.Substring(i, chunkLength);
}
}
}
} | mit | C# |
9e3dd89cc9fcbb49c28947169d1382807a769f7f | Update PredecessorList.cs | smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk | main/Smartsheet/Api/Models/PredecessorList.cs | main/Smartsheet/Api/Models/PredecessorList.cs | // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System.Collections.Generic;
namespace Smartsheet.Api.Models
{
public class PredecessorList : ObjectValue
{
private IList<Predecessor> predecessors;
public PredecessorList() { }
public PredecessorList(IList<Predecessor> predecessors)
{
this.predecessors = predecessors;
}
/// <summary>
/// Gets the array of Predecessor objects.
/// </summary>
/// <returns> the array </returns>
public virtual IList<Predecessor> Predecessors
{
get
{
return predecessors;
}
set
{
this.predecessors = value;
}
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.PREDECESSOR_LIST; }
}
}
}
| // #[license]
// SmartsheetClient SDK for C#
// %%
// Copyright (C) 2014 SmartsheetClient
// %%
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed To in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// %[license]
using System.Collections.Generic;
namespace Smartsheet.Api.Models
{
public class PredecessorList : ObjectValue
{
private IList<Predecessor> predecessors;
public PredecessorList() { }
public PredecessorList(IList<Predecessor> predecessors)
{
this.predecessors = predecessors;
}
/// <summary>
/// Gets the array of Predecessor objects.
/// </summary>
/// <returns> the array </returns>
public virtual IList<Predecessor> Predecessors
{
get
{
return predecessors;
}
set
{
this.predecessors = value;
}
}
public virtual ObjectValueType ObjectType
{
get { return ObjectValueType.PREDECESSOR_LIST; }
}
}
}
| apache-2.0 | C# |
bef6c26296b31f56b80f2ad5087f1b2b4384796c | remove extensions because no need in netstd2.0 | neuecc/MagicOnion | src/MagicOnion/Utils/ReflectionExtensions.cs | src/MagicOnion/Utils/ReflectionExtensions.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
// Internal, Global.
internal static class ReflectionExtensions
{
public static bool IsNullable(this System.Reflection.TypeInfo type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>);
}
public static bool IsPublic(this System.Reflection.TypeInfo type)
{
return type.IsPublic;
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Text;
// Internal, Global.
internal static class ReflectionExtensions
{
public static bool IsNullable(this System.Reflection.TypeInfo type)
{
return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Nullable<>);
}
public static bool IsPublic(this System.Reflection.TypeInfo type)
{
return type.IsPublic;
}
#if NETSTANDARD
public static bool IsConstructedGenericType(this System.Reflection.TypeInfo type)
{
return type.AsType().IsConstructedGenericType;
}
public static MethodInfo GetGetMethod(this PropertyInfo propInfo)
{
return propInfo.GetMethod;
}
public static MethodInfo GetSetMethod(this PropertyInfo propInfo)
{
return propInfo.SetMethod;
}
public static bool IsEnum(this Type type)
{
return type.GetTypeInfo().IsEnum;
}
public static bool IsAbstract(this Type type)
{
return type.GetTypeInfo().IsAbstract;
}
public static Type[] GetGenericArguments(this Type type)
{
return type.GetTypeInfo().GetGenericArguments();
}
public static ConstructorInfo[] GetConstructors(this Type type)
{
return type.GetTypeInfo().GetConstructors();
}
public static MethodInfo[] GetMethods(this Type type, BindingFlags flags)
{
return type.GetTypeInfo().GetMethods(flags);
}
public static T GetCustomAttribute<T>(this Type type, bool inherit)
where T : Attribute
{
return type.GetTypeInfo().GetCustomAttribute<T>(inherit);
}
public static IEnumerable<T> GetCustomAttributes<T>(this Type type, bool inherit)
where T : Attribute
{
return type.GetTypeInfo().GetCustomAttributes<T>(inherit);
}
public static IEnumerable<Attribute> GetCustomAttributes(this Type type, bool inherit)
{
return type.GetTypeInfo().GetCustomAttributes(inherit);
}
public static bool IsAssignableFrom(this Type type, Type c)
{
return type.GetTypeInfo().IsAssignableFrom(c);
}
public static PropertyInfo GetProperty(this Type type, string name)
{
return type.GetTypeInfo().GetProperty(name);
}
public static PropertyInfo GetProperty(this Type type, string name, BindingFlags flags)
{
return type.GetTypeInfo().GetProperty(name, flags);
}
public static FieldInfo GetField(this Type type, string name, BindingFlags flags)
{
return type.GetTypeInfo().GetField(name, flags);
}
public static FieldInfo[] GetFields(this Type type, BindingFlags flags)
{
return type.GetTypeInfo().GetFields(flags);
}
public static Type[] GetInterfaces(this Type type)
{
return type.GetTypeInfo().GetInterfaces();
}
public static MethodInfo GetMethod(this Type type, string name)
{
return type.GetTypeInfo().GetMethod(name);
}
public static MethodInfo GetMethod(this Type type, string name, BindingFlags flags)
{
return type.GetTypeInfo().GetMethod(name, flags);
}
public static MethodInfo[] GetMethods(this Type type)
{
return type.GetTypeInfo().GetMethods();
}
public static ConstructorInfo GetConstructor(this Type type, Type[] types)
{
return type.GetTypeInfo().GetConstructor(types);
}
public static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingAttr, object dymmy1, Type[] types, object dummy2)
{
return type.GetTypeInfo().GetConstructors(bindingAttr).First(x =>
{
return x.GetParameters().Select(y => y.ParameterType).SequenceEqual(types);
});
}
#endif
} | mit | C# |
8f3e9e2cc07e1769245c60c1f96ed212ef1609e0 | fix build. | SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia | src/iOS/Avalonia.iOS/AvaloniaAppDelegate.cs | src/iOS/Avalonia.iOS/AvaloniaAppDelegate.cs | using Foundation;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using UIKit;
namespace Avalonia.iOS
{
public class AvaloniaAppDelegate<TApp> : UIResponder, IUIApplicationDelegate
where TApp : Application, new()
{
class SingleViewLifetime : ISingleViewApplicationLifetime
{
public AvaloniaView View;
public Control MainView
{
get => View.Content;
set => View.Content = value;
}
}
protected virtual AppBuilder CustomizeAppBuilder(AppBuilder builder) => builder.UseiOS();
[Export("window")]
public UIWindow Window { get; set; }
[Export("application:didFinishLaunchingWithOptions:")]
public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
var builder = AppBuilder.Configure<TApp>();
CustomizeAppBuilder(builder);
var lifetime = new SingleViewLifetime();
builder.AfterSetup(_ =>
{
Window = new UIWindow();
var view = new AvaloniaView();
lifetime.View = view;
Window.RootViewController = new UIViewController
{
View = view
};
});
builder.SetupWithLifetime(lifetime);
Window.Hidden = false;
return true;
}
}
}
| using Foundation;
using UIKit;
namespace Avalonia.iOS
{
public class AvaloniaAppDelegate<TApp> : UIResponder, IUIApplicationDelegate
where TApp : Application, new()
{
class SingleViewLifetime : ISingleViewApplicationLifetime
{
public AvaloniaView View;
public Control MainView
{
get => View.Content;
set => View.Content = value;
}
}
protected virtual AppBuilder CustomizeAppBuilder(AppBuilder builder) => builder.UseiOS();
[Export("window")]
public UIWindow Window { get; set; }
[Export("application:didFinishLaunchingWithOptions:")]
public bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
var builder = AppBuilder.Configure<TApp>();
CustomizeAppBuilder(builder);
var lifetime = new SingleViewLifetime();
builder.AfterSetup(_ =>
{
Window = new UIWindow();
var view = new AvaloniaView();
lifetime.View = view;
Window.RootViewController = new UIViewController
{
View = view
};
});
builder.SetupWithLifetime(lifetime);
Window.Hidden = false;
return true;
}
}
}
| mit | C# |
b7c20065a46d23a1032285cb97ed66b46129f2c8 | Fix for GetTestCases not returning current folder | avao/Qart,mcraveiro/Qart,tudway/Qart | Src/Qart.Testing/TestSystem.cs | Src/Qart.Testing/TestSystem.cs | using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Qart.Testing
{
public class TestSystem
{
public IDataStore DataStorage { get; private set; }
public TestSystem(IDataStore dataStorage)
{
DataStorage = dataStorage;
}
public TestCase GetTestCase(string id)
{
return new TestCase(id, this);
}
public IEnumerable<TestCase> GetTestCases()
{
return DataStorage.GetAllGroups().Concat(new[]{"."}).Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this));
}
}
}
| using Qart.Core.DataStore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Qart.Testing
{
public class TestSystem
{
public IDataStore DataStorage { get; private set; }
public TestSystem(IDataStore dataStorage)
{
DataStorage = dataStorage;
}
public TestCase GetTestCase(string id)
{
return new TestCase(id, this);
}
public IEnumerable<TestCase> GetTestCases()
{
return DataStorage.GetAllGroups().Where(_ => DataStorage.Contains(Path.Combine(_, ".test"))).Select(_ => new TestCase(_, this));
}
}
}
| apache-2.0 | C# |
1083e34d4737a93cfcceb9dc17b2beb46b8b29f3 | fix bug in DefineTextTag writing | Alexx999/SwfSharp | SwfSharp/Tags/DefineTextTag.cs | SwfSharp/Tags/DefineTextTag.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SwfSharp.Structs;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class DefineTextTag : SwfTag
{
public ushort CharacterID { get; set; }
public RectStruct TextBounds { get; set; }
public MatrixStruct TextMatrix { get; set; }
public IList<TextRecordStruct> TextRecords { get; set; }
public DefineTextTag(int size)
: base(TagType.DefineText, size)
{
}
protected DefineTextTag(TagType tagType, int size)
: base(tagType, size)
{
}
internal override void FromStream(BitReader reader, byte swfVersion)
{
CharacterID = reader.ReadUI16();
TextBounds = RectStruct.CreateFromStream(reader);
TextMatrix = MatrixStruct.CreateFromStream(reader);
var glyphBits = reader.ReadUI8();
var advanceBits = reader.ReadUI8();
TextRecords = new List<TextRecordStruct>();
TextRecordStruct nextTextRecord = TextRecordStruct.CreateFromStream(reader, TagType, glyphBits, advanceBits);
while (nextTextRecord.TextRecordType == 1)
{
TextRecords.Add(nextTextRecord);
nextTextRecord = TextRecordStruct.CreateFromStream(reader, TagType, glyphBits, advanceBits);
}
}
internal override void ToStream(BitWriter writer, byte swfVersion)
{
writer.WriteUI16(CharacterID);
TextBounds.ToStream(writer);
TextMatrix.ToStream(writer);
var glyphs = TextRecords.SelectMany(t => t.GlyphEntries).ToList();
var glyphBits = (byte)(glyphs.Count == 0 ? 0 : glyphs.Max(g => BitWriter.GetBitsForValue(g.GlyphIndex)));
var advanceBits = (byte)(glyphs.Count == 0 ? 0 : glyphs.Max(g => BitWriter.GetBitsForValue(g.GlyphAdvance)));
writer.WriteUI8(glyphBits);
writer.WriteUI8(advanceBits);
foreach (var textRecord in TextRecords)
{
textRecord.ToStream(writer, TagType, glyphBits, advanceBits);
}
writer.WriteUI8(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using SwfSharp.Structs;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class DefineTextTag : SwfTag
{
public ushort CharacterID { get; set; }
public RectStruct TextBounds { get; set; }
public MatrixStruct TextMatrix { get; set; }
public IList<TextRecordStruct> TextRecords { get; set; }
public DefineTextTag(int size)
: base(TagType.DefineText, size)
{
}
protected DefineTextTag(TagType tagType, int size)
: base(tagType, size)
{
}
internal override void FromStream(BitReader reader, byte swfVersion)
{
CharacterID = reader.ReadUI16();
TextBounds = RectStruct.CreateFromStream(reader);
TextMatrix = MatrixStruct.CreateFromStream(reader);
var glyphBits = reader.ReadUI8();
var advanceBits = reader.ReadUI8();
TextRecords = new List<TextRecordStruct>();
TextRecordStruct nextTextRecord = TextRecordStruct.CreateFromStream(reader, TagType, glyphBits, advanceBits);
while (nextTextRecord.TextRecordType == 1)
{
TextRecords.Add(nextTextRecord);
nextTextRecord = TextRecordStruct.CreateFromStream(reader, TagType, glyphBits, advanceBits);
}
}
internal override void ToStream(BitWriter writer, byte swfVersion)
{
writer.WriteUI16(CharacterID);
TextBounds.ToStream(writer);
TextMatrix.ToStream(writer);
var glyphs = TextRecords.SelectMany(t => t.GlyphEntries).ToList();
var glyphBits = (byte) glyphs.Max(g => BitWriter.GetBitsForValue(g.GlyphIndex));
var advanceBits = (byte) glyphs.Max(g => BitWriter.GetBitsForValue(g.GlyphAdvance));
writer.WriteUI8(glyphBits);
writer.WriteUI8(advanceBits);
foreach (var textRecord in TextRecords)
{
textRecord.ToStream(writer, TagType, glyphBits, advanceBits);
}
writer.WriteUI8(0);
}
}
}
| mit | C# |
e379e0b3aa5740778435ea22b68c37c30c83c539 | Update ShouldMatchApprovedException.cs | JoeMighty/shouldly | src/Shouldly/ShouldMatchApprovedException.cs | src/Shouldly/ShouldMatchApprovedException.cs | namespace Shouldly
{
public class ShouldMatchApprovedException : ShouldAssertException
{
public ShouldMatchApprovedException(string message, string receivedFile, string approvedFile) : base(
GenerateMessage(message, receivedFile, approvedFile))
{
}
private static string GenerateMessage(string message, string receivedFile, string approvedFile)
{
var msg = @"To approve the changes run this command:";
if (ShouldlyEnvironmentContext.IsWindows())
{
msg += $@"
copy /Y ""{receivedFile}"" ""{approvedFile}""";
}
else
{
msg += $@"
cp ""{receivedFile}"" ""{approvedFile}""";
}
msg += $@"
----------------------------
{message}";
return msg;
}
}
} | namespace Shouldly
{
public class ShouldMatchApprovedException : ShouldAssertException
{
public ShouldMatchApprovedException(string message, string receivedFile, string approvedFile) : base(
GenerateMessage(message, receivedFile, approvedFile))
{
}
private static string GenerateMessage(string message, string receivedFile, string approvedFile)
{
var msg = @"To approve the changes run this command:";
if (ShouldlyEnvironmentContext.IsWindows())
{
msg += $@"
copy /Y ""{receivedFile}"" ""{approvedFile}""";
}
else
{
msg += $@"
cp ""{receivedFile}"" ""{approvedFile}""";
}
msg += $@"
----------------------------
{message}";
return msg;
}
}
} | bsd-3-clause | C# |
d0fec6ebc6564a3c8aa71305029caf1608ee4524 | increment patch version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.19.1")]
[assembly: AssemblyInformationalVersion("0.19.1")]
/*
* Version 0.19.1
*
* - [FIX] Publishes Experiment.AutoFixture as library(dll) form, instead of
* transform source files(nuget). (BREAKING-CHANGE)
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.19.0")]
[assembly: AssemblyInformationalVersion("0.19.0")]
/*
* Version 0.19.1
*
* - [FIX] Publishes Experiment.AutoFixture as library(dll) form, instead of
* transform source files(nuget). (BREAKING-CHANGE)
*/ | mit | C# |
3a783d11d25cc13bc9ca0294b2b4dac4792d3fb0 | Change new example data | Zalodu/Schedutalk,Zalodu/Schedutalk | Schedutalk/Schedutalk/Schedutalk/ViewModel/VMMainView.cs | Schedutalk/Schedutalk/Schedutalk/ViewModel/VMMainView.cs | using Schedutalk.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace Schedutalk.ViewModel
{
public class VMMainView : VMBase
{
public ObservableCollection<MEvent> ScheduleInfo
{
get; set;
}
public ObservableCollection<MEvent> ScheduleEvents
{
get; set;
}
public VMMainView()
{
ScheduleInfo = new ObservableCollection<MEvent>();
ScheduleEvents = new ObservableCollection<MEvent>();
ScheduleInfo = getScheduleInfo();
string longText = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
ScheduleEvents.Add(new Model.MEvent { Title = "Matematics", StartDate = new Model.MDate(08, 00), EndDate = new Model.MDate(9, 00) });
ScheduleEvents.Add(new Model.MEvent { Title = "Exercise", StartDate = new Model.MDate(12, 00), EndDate = new Model.MDate(15, 00) });
ScheduleEvents.Add(new Model.MEvent { Title = "Hackathon", Information=longText, StartDate = new Model.MDate(20, 00), EndDate = new Model.MDate(23, 59) });
}
private ObservableCollection<MEvent> getScheduleInfo()
{
ObservableCollection<MEvent> scheduleInfo = new ObservableCollection<MEvent>();
for (int i = 0; i < 24; i++)
{
scheduleInfo.Add(new Model.MEvent { Title = "", StartDate = new Model.MDate(i, 00), EndDate = new Model.MDate(i, 59) });
}
return scheduleInfo;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Forms;
namespace Schedutalk.ViewModel
{
public class VMMainView : VMBase
{
public Model.Human Human
{
get; set;
}
private string greeting;
public string Greeting
{
get
{
return greeting;
}
private set
{
greeting = value;
OnPropertyChanged("Greeting");
}
}
public VMMainView()
{
Human = new Model.Human();
Human.Name = "Hello world";
}
public ICommand SayHello {
get {
return new Command(() =>
{
Greeting = $"Hello {Human.Name}";
});
}
}
}
}
| mit | C# |
5b5bc70ba92681d99f93e7dabbf1489d7bf12749 | Update SimpleXmlBondSerializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/Bond/SimpleXmlBondSerializer.cs | TIKSN.Core/Serialization/Bond/SimpleXmlBondSerializer.cs | using System.IO;
using System.Xml;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class SimpleXmlBondSerializer : SerializerBase<string>
{
protected override string SerializeInternal<T>(T obj)
{
using var output = new StringWriter();
var writer = new SimpleXmlWriter(XmlWriter.Create(output));
global::Bond.Serialize.To(writer, obj);
writer.Flush();
return output.GetStringBuilder().ToString();
}
}
}
| using System.IO;
using System.Xml;
using Bond.Protocols;
namespace TIKSN.Serialization.Bond
{
public class SimpleXmlBondSerializer : SerializerBase<string>
{
protected override string SerializeInternal<T>(T obj)
{
using (var output = new StringWriter())
{
var writer = new SimpleXmlWriter(XmlWriter.Create(output));
global::Bond.Serialize.To(writer, obj);
writer.Flush();
return output.GetStringBuilder().ToString();
}
}
}
}
| mit | C# |
59925fab3480df6a451bc1420ac698f2a1f80b22 | Increment version number | mj1856/TimeZoneNames | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")]
[assembly: AssemblyVersion("1.1.0.*")]
[assembly: AssemblyInformationalVersion("1.1.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")]
[assembly: AssemblyVersion("1.0.1.*")]
[assembly: AssemblyInformationalVersion("1.0.1")]
| mit | C# |
53ac663cd40484776555e7d61d0265a77d8744e1 | Connect with the Blockcypher API over https instead of http | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/WebClients/BlockCypher/BlockCypherClient.cs | WalletWasabi/WebClients/BlockCypher/BlockCypherClient.cs | using NBitcoin;
using Newtonsoft.Json;
using Nito.AsyncEx;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.WebClients.BlockCypher.Models;
namespace WalletWasabi.WebClients.BlockCypher
{
public class BlockCypherClient : IDisposable
{
public Network Network { get; }
private HttpClient HttpClient { get; }
public Uri BaseAddress => HttpClient.BaseAddress;
private AsyncLock AsyncLock { get; } = new AsyncLock();
public BlockCypherClient(Network network, HttpMessageHandler handler = null, bool disposeHandler = false)
{
Network = network ?? throw new ArgumentNullException(nameof(network));
if (handler != null)
{
HttpClient = new HttpClient(handler, disposeHandler);
}
else
{
HttpClient = new HttpClient();
}
if (network == Network.Main)
{
HttpClient.BaseAddress = new Uri("https://api.blockcypher.com/v1/btc/main");
}
else if (network == Network.TestNet)
{
HttpClient.BaseAddress = new Uri("https://api.blockcypher.com/v1/btc/test3");
}
else
{
throw new NotSupportedException($"{network} is not supported");
}
}
public async Task<BlockCypherGeneralInformation> GetGeneralInformationAsync(CancellationToken cancel)
{
using (await AsyncLock.LockAsync())
using (HttpResponseMessage response =
await HttpClient.GetAsync("", HttpCompletionOption.ResponseContentRead, cancel))
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException(response.StatusCode.ToString());
}
string jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<BlockCypherGeneralInformation>(jsonString);
}
}
#region IDisposable Support
private bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// dispose managed state (managed objects).
HttpClient?.Dispose();
}
// free unmanaged resources (unmanaged objects) and override a finalizer below.
// set large fields to null.
_disposedValue = true;
}
}
// override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~BlockCypherClient() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
}
| using NBitcoin;
using Newtonsoft.Json;
using Nito.AsyncEx;
using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.WebClients.BlockCypher.Models;
namespace WalletWasabi.WebClients.BlockCypher
{
public class BlockCypherClient : IDisposable
{
public Network Network { get; }
private HttpClient HttpClient { get; }
public Uri BaseAddress => HttpClient.BaseAddress;
private AsyncLock AsyncLock { get; } = new AsyncLock();
public BlockCypherClient(Network network, HttpMessageHandler handler = null, bool disposeHandler = false)
{
Network = network ?? throw new ArgumentNullException(nameof(network));
if (handler != null)
{
HttpClient = new HttpClient(handler, disposeHandler);
}
else
{
HttpClient = new HttpClient();
}
if (network == Network.Main)
{
HttpClient.BaseAddress = new Uri("http://api.blockcypher.com/v1/btc/main");
}
else if (network == Network.TestNet)
{
HttpClient.BaseAddress = new Uri("http://api.blockcypher.com/v1/btc/test3");
}
else
{
throw new NotSupportedException($"{network} is not supported");
}
}
public async Task<BlockCypherGeneralInformation> GetGeneralInformationAsync(CancellationToken cancel)
{
using (await AsyncLock.LockAsync())
using (HttpResponseMessage response =
await HttpClient.GetAsync("", HttpCompletionOption.ResponseContentRead, cancel))
{
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpRequestException(response.StatusCode.ToString());
}
string jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<BlockCypherGeneralInformation>(jsonString);
}
}
#region IDisposable Support
private bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
// dispose managed state (managed objects).
HttpClient?.Dispose();
}
// free unmanaged resources (unmanaged objects) and override a finalizer below.
// set large fields to null.
_disposedValue = true;
}
}
// override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~BlockCypherClient() {
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion IDisposable Support
}
}
| mit | C# |
4eb2c05c4fe931f5bbc18a66f22ca46139df1b7f | use pattern matching | OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | src/OmniSharp.Roslyn.CSharp/Services/ImplementTypeWorkspaceOptionsProvider.cs | src/OmniSharp.Roslyn.CSharp/Services/ImplementTypeWorkspaceOptionsProvider.cs | using System;
using System.Composition;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Options;
using OmniSharp.Options;
using OmniSharp.Roslyn.Options;
using OmniSharp.Services;
using OmniSharp.Utilities;
namespace OmniSharp.Roslyn.CSharp.Services
{
[Export(typeof(IWorkspaceOptionsProvider)), Shared]
public class ImplementTypeWorkspaceOptionsProvider : IWorkspaceOptionsProvider
{
private readonly IAssemblyLoader _assemblyLoader;
private readonly Lazy<Assembly> _csharpFeatureAssembly;
private readonly Lazy<Type> _implementTypeOptions;
[ImportingConstructor]
public ImplementTypeWorkspaceOptionsProvider(IAssemblyLoader assemblyLoader)
{
_assemblyLoader = assemblyLoader;
_csharpFeatureAssembly = _assemblyLoader.LazyLoad(Configuration.RoslynFeatures);
_implementTypeOptions = _csharpFeatureAssembly.LazyGetType("Microsoft.CodeAnalysis.ImplementType.ImplementTypeOptions");
}
public int Order => 110;
public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omniSharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
{
if (omniSharpOptions.ImplementTypeOptions.InsertionBehavior != null)
{
if (_implementTypeOptions.Value.GetField("InsertionBehavior", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is IOption insertionBehaviorOptionValue)
{
currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(insertionBehaviorOptionValue, LanguageNames.CSharp), (int)omniSharpOptions.ImplementTypeOptions.InsertionBehavior);
}
}
if (omniSharpOptions.ImplementTypeOptions.PropertyGenerationBehavior != null)
{
if (_implementTypeOptions.Value.GetField("PropertyGenerationBehavior", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) is IOption propertyGenerationBehaviorOptionValue)
{
currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(propertyGenerationBehaviorOptionValue, LanguageNames.CSharp), (int)omniSharpOptions.ImplementTypeOptions.PropertyGenerationBehavior);
}
}
return currentOptionSet;
}
}
}
| using System;
using System.Composition;
using System.Reflection;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Options;
using OmniSharp.Options;
using OmniSharp.Roslyn.Options;
using OmniSharp.Services;
using OmniSharp.Utilities;
namespace OmniSharp.Roslyn.CSharp.Services
{
[Export(typeof(IWorkspaceOptionsProvider)), Shared]
public class ImplementTypeWorkspaceOptionsProvider : IWorkspaceOptionsProvider
{
private readonly IAssemblyLoader _assemblyLoader;
private readonly Lazy<Assembly> _csharpFeatureAssembly;
private readonly Lazy<Type> _implementTypeOptions;
[ImportingConstructor]
public ImplementTypeWorkspaceOptionsProvider(IAssemblyLoader assemblyLoader)
{
_assemblyLoader = assemblyLoader;
_csharpFeatureAssembly = _assemblyLoader.LazyLoad(Configuration.RoslynFeatures);
_implementTypeOptions = _csharpFeatureAssembly.LazyGetType("Microsoft.CodeAnalysis.ImplementType.ImplementTypeOptions");
}
public int Order => 110;
public OptionSet Process(OptionSet currentOptionSet, OmniSharpOptions omniSharpOptions, IOmniSharpEnvironment omnisharpEnvironment)
{
if (omniSharpOptions.ImplementTypeOptions.InsertionBehavior != null)
{
var insertionBehaviorOptionValue = _implementTypeOptions.Value.GetField("InsertionBehavior", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as IOption;
if (insertionBehaviorOptionValue != null)
{
currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(insertionBehaviorOptionValue, LanguageNames.CSharp), (int)omniSharpOptions.ImplementTypeOptions.InsertionBehavior);
}
}
var propertyGenerationBehaviorOptionValue = _implementTypeOptions.Value.GetField("PropertyGenerationBehavior", BindingFlags.Public | BindingFlags.Static)?.GetValue(null) as IOption;
if (propertyGenerationBehaviorOptionValue != null)
{
currentOptionSet = currentOptionSet.WithChangedOption(new OptionKey(propertyGenerationBehaviorOptionValue, LanguageNames.CSharp), (int)omniSharpOptions.ImplementTypeOptions.PropertyGenerationBehavior);
}
return currentOptionSet;
}
}
}
| mit | C# |
bc171b90128eb73d2b650828cff1d1a51ed22470 | Fix returns documentation on GetRouteData() (#36881) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs | src/Http/Routing.Abstractions/src/RoutingHttpContextExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.Routing
{
/// <summary>
/// Extension methods for <see cref="HttpContext"/> related to routing.
/// </summary>
public static class RoutingHttpContextExtensions
{
/// <summary>
/// Gets the <see cref="RouteData"/> associated with the provided <paramref name="httpContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param>
/// <returns>The <see cref="RouteData"/>.</returns>
public static RouteData GetRouteData(this HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var routingFeature = httpContext.Features.Get<IRoutingFeature>();
return routingFeature?.RouteData ?? new RouteData(httpContext.Request.RouteValues);
}
/// <summary>
/// Gets a route value from <see cref="RouteData.Values"/> associated with the provided
/// <paramref name="httpContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param>
/// <param name="key">The key of the route value.</param>
/// <returns>The corresponding route value, or null.</returns>
public static object? GetRouteValue(this HttpContext httpContext, string key)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return httpContext.Features.Get<IRouteValuesFeature>()?.RouteValues[key];
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
namespace Microsoft.AspNetCore.Routing
{
/// <summary>
/// Extension methods for <see cref="HttpContext"/> related to routing.
/// </summary>
public static class RoutingHttpContextExtensions
{
/// <summary>
/// Gets the <see cref="RouteData"/> associated with the provided <paramref name="httpContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param>
/// <returns>The <see cref="RouteData"/>, or null.</returns>
public static RouteData GetRouteData(this HttpContext httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
var routingFeature = httpContext.Features.Get<IRoutingFeature>();
return routingFeature?.RouteData ?? new RouteData(httpContext.Request.RouteValues);
}
/// <summary>
/// Gets a route value from <see cref="RouteData.Values"/> associated with the provided
/// <paramref name="httpContext"/>.
/// </summary>
/// <param name="httpContext">The <see cref="HttpContext"/> associated with the current request.</param>
/// <param name="key">The key of the route value.</param>
/// <returns>The corresponding route value, or null.</returns>
public static object? GetRouteValue(this HttpContext httpContext, string key)
{
if (httpContext == null)
{
throw new ArgumentNullException(nameof(httpContext));
}
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return httpContext.Features.Get<IRouteValuesFeature>()?.RouteValues[key];
}
}
}
| apache-2.0 | C# |
6e206e285921132ec3b11602bdf7cbf88ad57f85 | set authentication style | IdentityModel/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient2,roflkins/IdentityModel.OidcClient2,roflkins/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient,IdentityModel/IdentityModel.OidcClient | src/IdentityModel.OidcClient/Infrastructure/TokenClientFactory.cs | src/IdentityModel.OidcClient/Infrastructure/TokenClientFactory.cs | using IdentityModel.Client;
using System.Net.Http;
namespace IdentityModel.OidcClient.Infrastructure
{
internal class TokenClientFactory
{
public static TokenClient Create(OidcClientOptions options)
{
var info = options.ProviderInformation;
var handler = options.BackchannelHandler ?? new HttpClientHandler();
TokenClient tokenClient;
if (options.ClientSecret.IsMissing())
{
tokenClient = new TokenClient(info.TokenEndpoint, options.ClientId, handler);
}
else
{
tokenClient = new TokenClient(info.TokenEndpoint, options.ClientId, options.ClientSecret, handler, options.TokenClientAuthenticationStyle);
}
tokenClient.Timeout = options.BackchannelTimeout;
tokenClient.AuthenticationStyle = options.TokenClientAuthenticationStyle;
return tokenClient;
}
}
} | using IdentityModel.Client;
using System.Net.Http;
namespace IdentityModel.OidcClient.Infrastructure
{
internal class TokenClientFactory
{
public static TokenClient Create(OidcClientOptions options)
{
var info = options.ProviderInformation;
var handler = options.BackchannelHandler ?? new HttpClientHandler();
TokenClient tokenClient;
if (options.ClientSecret.IsMissing())
{
tokenClient = new TokenClient(info.TokenEndpoint, options.ClientId, handler);
}
else
{
tokenClient = new TokenClient(info.TokenEndpoint, options.ClientId, options.ClientSecret, handler, options.TokenClientAuthenticationStyle);
}
tokenClient.Timeout = options.BackchannelTimeout;
return tokenClient;
}
}
} | apache-2.0 | C# |
66f5187e6a26ea480fb777d9f5abef93ce7a4e13 | Remove redundant access permission | NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,ppy/osu,ppy/osu | osu.Game/Screens/Edit/IEditorChangeHandler.cs | osu.Game/Screens/Edit/IEditorChangeHandler.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Screens.Edit
{
/// <summary>
/// Interface for a component that manages changes in the <see cref="Editor"/>.
/// </summary>
public interface IEditorChangeHandler
{
/// <summary>
/// Fired whenever a state change occurs.
/// </summary>
event Action OnStateChange;
/// <summary>
/// Begins a bulk state change event. <see cref="EndChange"/> should be invoked soon after.
/// </summary>
/// <remarks>
/// This should be invoked when multiple changes to the <see cref="Editor"/> should be bundled together into one state change event.
/// When nested invocations are involved, a state change will not occur until an equal number of invocations of <see cref="EndChange"/> are received.
/// </remarks>
/// <example>
/// When a group of <see cref="HitObject"/>s are deleted, a single undo and redo state change should update the state of all <see cref="HitObject"/>.
/// </example>
void BeginChange();
/// <summary>
/// Ends a bulk state change event.
/// </summary>
/// <remarks>
/// This should be invoked as soon as possible after <see cref="BeginChange"/> to cause a state change.
/// </remarks>
void EndChange();
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Game.Rulesets.Objects;
namespace osu.Game.Screens.Edit
{
/// <summary>
/// Interface for a component that manages changes in the <see cref="Editor"/>.
/// </summary>
public interface IEditorChangeHandler
{
/// <summary>
/// Fired whenever a state change occurs.
/// </summary>
public event Action OnStateChange;
/// <summary>
/// Begins a bulk state change event. <see cref="EndChange"/> should be invoked soon after.
/// </summary>
/// <remarks>
/// This should be invoked when multiple changes to the <see cref="Editor"/> should be bundled together into one state change event.
/// When nested invocations are involved, a state change will not occur until an equal number of invocations of <see cref="EndChange"/> are received.
/// </remarks>
/// <example>
/// When a group of <see cref="HitObject"/>s are deleted, a single undo and redo state change should update the state of all <see cref="HitObject"/>.
/// </example>
void BeginChange();
/// <summary>
/// Ends a bulk state change event.
/// </summary>
/// <remarks>
/// This should be invoked as soon as possible after <see cref="BeginChange"/> to cause a state change.
/// </remarks>
void EndChange();
}
}
| mit | C# |
e4ec2f40d9f19028efcd8d2b68ad9ddf30f888de | Remove ClientVersion from DiallerSessionSubscribeDto | Paymentsense/Dapper.SimpleSave | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/DiallerSessionSubscribeDto.cs | PS.Mothership.Core/PS.Mothership.Core.Common/Dto/DiallerSessionSubscribeDto.cs | using System;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto
{
[DataContract]
public class DiallerSessionSubscribeDto
{
[DataMember]
public Guid UserGuid { get; set; }
[DataMember]
public DateTime StartDateTime { get; set; }
[DataMember]
public string ClientIp { get; set; }
}
}
| using System;
using System.Runtime.Serialization;
namespace PS.Mothership.Core.Common.Dto
{
[DataContract]
public class DiallerSessionSubscribeDto
{
[DataMember]
public Guid UserGuid { get; set; }
[DataMember]
public DateTime StartDateTime { get; set; }
[DataMember]
public string ClientVersion { get; set; }
[DataMember]
public string ClientIp { get; set; }
}
}
| mit | C# |
4cdde422280004f4013124ba29a78cf871f52bc0 | Remove unnecessary backing field | smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,peppy/osu,ppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu | osu.Game/Overlays/Chat/Selection/ChannelSection.cs | osu.Game/Overlays/Chat/Selection/ChannelSection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Chat;
using osuTK;
namespace osu.Game.Overlays.Chat.Selection
{
public class ChannelSection : Container, IHasFilterableChildren
{
public readonly FillFlowContainer<ChannelListItem> ChannelFlow;
public IEnumerable<IFilterable> FilterableChildren => ChannelFlow.Children;
public IEnumerable<string> FilterTerms => Array.Empty<string>();
public bool MatchingFilter
{
set => this.FadeTo(value ? 1f : 0f, 100);
}
public bool FilteringActive { get; set; }
public IEnumerable<Channel> Channels
{
set => ChannelFlow.ChildrenEnumerable = value.Select(c => new ChannelListItem(c));
}
public ChannelSection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Children = new Drawable[]
{
new OsuSpriteText
{
Font = OsuFont.GetFont(size: 15, weight: FontWeight.Bold),
Text = "All Channels".ToUpperInvariant()
},
ChannelFlow = new FillFlowContainer<ChannelListItem>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Margin = new MarginPadding { Top = 25 },
Spacing = new Vector2(0f, 5f),
},
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using osu.Game.Online.Chat;
using osuTK;
namespace osu.Game.Overlays.Chat.Selection
{
public class ChannelSection : Container, IHasFilterableChildren
{
private readonly OsuSpriteText header;
public readonly FillFlowContainer<ChannelListItem> ChannelFlow;
public IEnumerable<IFilterable> FilterableChildren => ChannelFlow.Children;
public IEnumerable<string> FilterTerms => Array.Empty<string>();
public bool MatchingFilter
{
set => this.FadeTo(value ? 1f : 0f, 100);
}
public bool FilteringActive { get; set; }
public IEnumerable<Channel> Channels
{
set => ChannelFlow.ChildrenEnumerable = value.Select(c => new ChannelListItem(c));
}
public ChannelSection()
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Children = new Drawable[]
{
header = new OsuSpriteText
{
Font = OsuFont.GetFont(size: 15, weight: FontWeight.Bold),
Text = "All Channels".ToUpperInvariant()
},
ChannelFlow = new FillFlowContainer<ChannelListItem>
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Margin = new MarginPadding { Top = 25 },
Spacing = new Vector2(0f, 5f),
},
};
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.