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
57725ccce10ae9e8cacb15e19735bbcfeebed945
Change a modifier of class 'TokenEntries'
lury-lang/lury-lexer
lury-lexer/TokenEntry.cs
lury-lexer/TokenEntry.cs
// // TokenEnrty.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace Lury.Compiling.Lexer { /// <summary> /// 出力されるトークンを区別するためのクラスです。 /// </summary> public class TokenEntry { #region -- Public Properties -- /// <summary> /// トークン名を表す文字列を取得します。 /// </summary> public string Name { get; private set; } #endregion #region -- Constructors -- /// <summary> /// トークン名を指定して新しい TokenEntry クラスのインスタンスを初期化します。 /// </summary> /// <param name="name">トークン名。</param> public TokenEntry(string name) { this.Name = name; } #endregion } }
// // TokenEnrty.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace Lury.Compiling.Lexer { /// <summary> /// 出力されるトークンを区別するための抽象クラスです。 /// </summary> public abstract class TokenEntry { #region -- Public Properties -- /// <summary> /// トークン名を表す文字列を取得します。 /// </summary> public string Name { get; private set; } #endregion #region -- Constructors -- /// <summary> /// トークン名を指定して新しい TokenEntry クラスのインスタンスを初期化します。 /// </summary> /// <param name="name">トークン名。</param> public TokenEntry(string name) { this.Name = name; } #endregion } }
mit
C#
85cf1d38729848cedb0311243e7ad01c67eabea3
Fix UNC path regex
cjmurph/PmsService,cjmurph/PmsService
PlexServiceTray/DriveMapViewModel.cs
PlexServiceTray/DriveMapViewModel.cs
using PlexServiceCommon; using System.ComponentModel.DataAnnotations; namespace PlexServiceTray { public class DriveMapViewModel : ObservableObject { [Required(ErrorMessage = "Please enter a UNC path to map")] [RegularExpression(@"^\\\\[a-zA-Z0-9\.\-_]{1,}(\\[a-zA-Z0-9\.\x20\-_]{1,}[\$]{0,1}){1,}$", ErrorMessage = "Please enter a UNC path to map")] public string ShareName { get => _driveMap.ShareName; set { if (_driveMap.ShareName == value) { return; } _driveMap.ShareName = value; OnPropertyChanged("ShareName"); } } [Required(ErrorMessage = "Please enter a single character A-Z")] [RegularExpression("[a-zA-Z]", ErrorMessage = "Please enter a single character A-Z")] public string DriveLetter { get => _driveMap.DriveLetter; set { if (_driveMap.DriveLetter == value) { return; } _driveMap.DriveLetter = value; OnPropertyChanged("DriveLetter"); } } private readonly DriveMap _driveMap; public DriveMapViewModel(DriveMap driveMap) { _driveMap = driveMap; ValidationContext = this; } public DriveMap GetDriveMap() { return _driveMap; } } }
using PlexServiceCommon; using System.ComponentModel.DataAnnotations; namespace PlexServiceTray { public class DriveMapViewModel : ObservableObject { [Required(ErrorMessage = "Please enter a UNC path to map")] [RegularExpression(@"", ErrorMessage = "Please enter a UNC path to map")] public string ShareName { get => _driveMap.ShareName; set { if (_driveMap.ShareName == value) { return; } _driveMap.ShareName = value; OnPropertyChanged("ShareName"); } } [Required(ErrorMessage = "Please enter a single character A-Z")] [RegularExpression("[a-zA-Z]", ErrorMessage = "Please enter a single character A-Z")] public string DriveLetter { get => _driveMap.DriveLetter; set { if (_driveMap.DriveLetter == value) { return; } _driveMap.DriveLetter = value; OnPropertyChanged("DriveLetter"); } } private readonly DriveMap _driveMap; public DriveMapViewModel(DriveMap driveMap) { _driveMap = driveMap; ValidationContext = this; } public DriveMap GetDriveMap() { return _driveMap; } } }
mit
C#
c97784e3d711a66c5b38659d9637c45481265154
make comment more descriptive
Recognos/Metrics.NET,Liwoj/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET
Src/Metrics/MetricData/GaugeValue.cs
Src/Metrics/MetricData/GaugeValue.cs
 namespace Metrics.MetricData { /// <summary> /// Combines the value of a gauge (a double) with the defined unit for the value. /// </summary> public sealed class GaugeValueSource : MetricValueSource<double> { public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit, MetricTags tags) : base(name, value, unit, tags) { } } }
 namespace Metrics.MetricData { /// <summary> /// Combines the value of a gauge with the defined unit for the value. /// </summary> public sealed class GaugeValueSource : MetricValueSource<double> { public GaugeValueSource(string name, MetricValueProvider<double> value, Unit unit, MetricTags tags) : base(name, value, unit, tags) { } } }
apache-2.0
C#
11aaa6bcee2f9f1c23458c93341ac50869daa18e
Add more test coverage
ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework.Tests/Lists/TestEnumerableExtensions.cs
osu.Framework.Tests/Lists/TestEnumerableExtensions.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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Framework.Tests.Lists { [TestFixture] public class TestEnumerableExtensions { [Test] public void TestCommonPrefix() { string[] arr = { "abcd", "abdc" }; Assert.AreEqual("ab", arr.GetCommonPrefix()); arr = new[] { "123.456", "123.789" }; Assert.AreEqual("123.", arr.GetCommonPrefix()); arr = new[] { "123.456", "123.789", "435", "123.789" }; Assert.AreEqual(string.Empty, arr.GetCommonPrefix()); } [Test] public void TestEmptyEnumerable() { Assert.AreEqual(string.Empty, Enumerable.Empty<string>().GetCommonPrefix()); } } }
// 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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Framework.Tests.Lists { [TestFixture] public class TestEnumerableExtensions { [Test] public void TestCommonPrefix() { string[] arr = { "abcd", "abdc" }; Assert.AreEqual("ab", arr.GetCommonPrefix()); arr = new[] { "123.456", "123.789" }; Assert.AreEqual("123.", arr.GetCommonPrefix()); } [Test] public void TestEmptyEnumerable() { Assert.AreEqual(string.Empty, Enumerable.Empty<string>().GetCommonPrefix()); } } }
mit
C#
23a5792fcf105ab20500dcdba29792322011ef81
Fix stray character in xmldoc
ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Input/Handlers/Tablet/ITabletHandler.cs
osu.Framework/Input/Handlers/Tablet/ITabletHandler.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 osu.Framework.Bindables; using osuTK; namespace osu.Framework.Input.Handlers.Tablet { /// <summary> /// An interface to access OpenTabletDriverHandler. /// Can be considered for removal when we no longer require dual targeting against netstandard. /// </summary> public interface ITabletHandler { /// <summary> /// The offset of the area which should be mapped to the game window. /// </summary> Bindable<Vector2> AreaOffset { get; } /// <summary> /// The size of the area which should be mapped to the game window. /// </summary> Bindable<Vector2> AreaSize { get; } /// <summary> /// Information on the currently connected tablet device. May be null if no tablet is detected. /// </summary> IBindable<TabletInfo> Tablet { get; } BindableBool Enabled { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osuTK; namespace osu.Framework.Input.Handlers.Tablet { /// <summary> /// An interface to access OpenTabletDriverHandler. /// Can be considered for removal when we no longer require dual targeting against netstandard. /// </summary> public interface ITabletHandler { /// <summary> /// The offset of the area which should be mapped to the game window. /// </summary> Bindable<Vector2> AreaOffset { get; } /// <summary> /// The size of the area which should be mapped to the game window. /// </summary> Bindable<Vector2> AreaSize { get; } /// <summary> /// Information on the currently connected tablet device./ May be null if no tablet is detected. /// </summary> IBindable<TabletInfo> Tablet { get; } BindableBool Enabled { get; } } }
mit
C#
3809f68fbf21fe2bae3f118cb2b2ce81c1ba91ca
Revert "Retry"
Gabyche/CarBase
Assets/CarBaseController.cs
Assets/CarBaseController.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class AxleInfo { public WheelCollider leftWheel; public WheelCollider rightWheel; public bool brake; public bool motor; public bool steering; } public class CarBaseController : MonoBehaviour { public List<AxleInfo> axleInfos; public float maxMotorTorque; public float maxBrakeTorque; public float maxSteeringAngle; public Rigidbody voiture; private Quaternion cylRotationRight = Quaternion.AngleAxis (270, Vector3.right); private Quaternion cylRotationUp = Quaternion.AngleAxis (90, Vector3.forward); // finds the corresponding visual wheel // correctly applies the transform public void ApplyLocalPositionToVisuals(WheelCollider collider) { if (collider.transform.childCount == 0) { return; } Transform visualWheel = collider.transform.GetChild(0); Vector3 position; Quaternion rotation; collider.GetWorldPose(out position, out rotation); visualWheel.transform.position = position; visualWheel.transform.rotation = rotation*cylRotationRight*cylRotationUp; } public void FixedUpdate() { float brake=0; float motor=0; if (Input.GetAxis ("Vertical") < 0 && voiture.velocity.magnitude > 0.001f) { brake = - maxBrakeTorque * Input.GetAxis ("Vertical"); } else { motor = maxMotorTorque * Input.GetAxis ("Vertical"); } float steering = maxSteeringAngle * Input.GetAxis("Horizontal"); foreach (AxleInfo axleInfo in axleInfos) { if (axleInfo.steering) { axleInfo.leftWheel.steerAngle = steering; axleInfo.rightWheel.steerAngle = steering; } if (axleInfo.motor) { axleInfo.leftWheel.motorTorque = motor; axleInfo.rightWheel.motorTorque = motor; } if (axleInfo.brake){ axleInfo.leftWheel.brakeTorque = brake; axleInfo.rightWheel.brakeTorque = brake; } ApplyLocalPositionToVisuals(axleInfo.leftWheel); ApplyLocalPositionToVisuals(axleInfo.rightWheel); } } public bool Forwarding() { AxleInfo axle = axleInfos [0]; return (axle.leftWheel.rpm >= 0); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class AxleInfo { public WheelCollider leftWheel; public WheelCollider rightWheel; public bool brake; public bool motor; public bool steering; } public class CarBaseController : MonoBehaviour { public List<AxleInfo> axleInfos; public float maxMotorTorque; public float maxBrakeTorque; public float maxSteeringAngle; public Rigidbody voiture; private Quaternion cylRotationRight = Quaternion.AngleAxis (270, Vector3.right); private Quaternion cylRotationUp = Quaternion.AngleAxis (90, Vector3.forward); // finds the corresponding visual wheel // correctly applies the transform public void ApplyLocalPositionToVisuals(WheelCollider collider) { if (collider.transform.childCount == 0) { return; } Transform visualWheel = collider.transform.GetChild(0); Vector3 position; Quaternion rotation; collider.GetWorldPose(out position, out rotation); visualWheel.transform.position = position; visualWheel.transform.rotation = rotation*cylRotationRight*cylRotationUp; } public void FixedUpdate() { float brake=0; float motor=0; if (Input.GetAxis ("Vertical") < 0 && voiture.velocity.magnitude > 0) { brake = - maxBrakeTorque * Input.GetAxis ("Vertical"); } else { motor = maxMotorTorque * Input.GetAxis ("Vertical"); } print(motor); //print (brake); //print (voiture.velocity); float steering = maxSteeringAngle * Input.GetAxis("Horizontal"); foreach (AxleInfo axleInfo in axleInfos) { if (axleInfo.steering) { axleInfo.leftWheel.steerAngle = steering; axleInfo.rightWheel.steerAngle = steering; } if (axleInfo.motor) { axleInfo.leftWheel.motorTorque = motor; axleInfo.rightWheel.motorTorque = motor; } if (axleInfo.brake){ axleInfo.leftWheel.brakeTorque = brake; axleInfo.rightWheel.brakeTorque = brake; } ApplyLocalPositionToVisuals(axleInfo.leftWheel); ApplyLocalPositionToVisuals(axleInfo.rightWheel); } } }
artistic-2.0
C#
6ce8dae2ebd54d97b9cc1f22c8eeda305ac36357
fix Pause/Resume on iOS
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/iOS/UrhoSurface.cs
Bindings/iOS/UrhoSurface.cs
using System; using System.Threading.Tasks; using System.Runtime.InteropServices; using CoreGraphics; using UIKit; namespace Urho.iOS { public class UrhoSurface : UIView { [DllImport("@rpath/Urho.framework/Urho", CallingConvention = CallingConvention.Cdecl)] static extern void SDL_SetExternalViewPlaceholder(IntPtr viewPtr, IntPtr windowPtr); TaskCompletionSource<bool> initTaskSource = new TaskCompletionSource<bool>(); public Task InitializeTask => initTaskSource.Task; public UrhoSurface() { UrhoPlatformInitializer.DefaultInit(); initTaskSource = new TaskCompletionSource<bool>(); BackgroundColor = UIColor.Black; } public UrhoSurface(CGRect frame) : base(frame) { UrhoPlatformInitializer.DefaultInit(); BackgroundColor = UIColor.Black; initTaskSource = new TaskCompletionSource<bool>(); } public void Pause() { if (!Urho.Application.HasCurrent) return; Urho.Application.Current.Engine.PauseMinimized = true; Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_LOST); Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_MINIMIZED); } public void Resume() { if (!Urho.Application.HasCurrent) return; Urho.Application.Current.Engine.PauseMinimized = false; Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_GAINED); Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_RESTORED); } public override void MovedToWindow() { base.MovedToWindow(); var wndHandle = Window?.Handle; SDL_SetExternalViewPlaceholder(Handle, wndHandle ?? IntPtr.Zero); if (wndHandle != null) { initTaskSource.TrySetResult (true); } else { initTaskSource = new TaskCompletionSource<bool> (); } } } }
using System; using System.Threading.Tasks; using System.Runtime.InteropServices; using CoreGraphics; using UIKit; namespace Urho.iOS { public class UrhoSurface : UIView { [DllImport("@rpath/Urho.framework/Urho", CallingConvention = CallingConvention.Cdecl)] static extern void SDL_SetExternalViewPlaceholder(IntPtr viewPtr, IntPtr windowPtr); TaskCompletionSource<bool> initTaskSource = new TaskCompletionSource<bool>(); public Task InitializeTask => initTaskSource.Task; public UrhoSurface() { UrhoPlatformInitializer.DefaultInit(); initTaskSource = new TaskCompletionSource<bool>(); BackgroundColor = UIColor.Black; } public UrhoSurface(CGRect frame) : base(frame) { UrhoPlatformInitializer.DefaultInit(); BackgroundColor = UIColor.Black; initTaskSource = new TaskCompletionSource<bool>(); } public void Pause() { Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_LOST); Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_MINIMIZED); } public void Resume() { Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_FOCUS_GAINED); Sdl.SendWindowEvent(SdlWindowEvent.SDL_WINDOWEVENT_RESTORED); } public override void MovedToWindow() { base.MovedToWindow(); var wndHandle = Window?.Handle; SDL_SetExternalViewPlaceholder(Handle, wndHandle ?? IntPtr.Zero); if (wndHandle != null) { initTaskSource.TrySetResult (true); } else { initTaskSource = new TaskCompletionSource<bool> (); } } } }
mit
C#
8e5be3c86dfafd434f3aeb807e366f694f2c8af9
Refactor how parameters are checked
graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,joemcbride/graphql-dotnet
src/GraphQL/Resolvers/MethodModelBinderResolver.cs
src/GraphQL/Resolvers/MethodModelBinderResolver.cs
using System; using System.Linq; using System.Reflection; using GraphQL.Types; namespace GraphQL.Resolvers { public class MethodModelBinderResolver<T> : IFieldResolver { private readonly IDependencyResolver _dependencyResolver; private readonly MethodInfo _methodInfo; private readonly ParameterInfo[] _parameters; private readonly Type _type; public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; _type = typeof(T); _methodInfo = methodInfo; _parameters = _methodInfo.GetParameters(); } public object Resolve(ResolveFieldContext context) { object[] arguments = null; if (_parameters.Any()) { arguments = new object[_parameters.Length]; var index = 0; if (typeof(ResolveFieldContext) == _parameters[index].ParameterType) { arguments[index] = context; index++; } if (context.Source?.GetType() == _parameters[index].ParameterType) { arguments[index] = context.Source; index++; } foreach (var parameter in _parameters.Skip(index)) { arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType); index++; } } var target = _dependencyResolver.Resolve(_type); if (target == null) { var parentType = context.ParentType != null ? $"{context.ParentType.Name}." : null; throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {parentType}{context.FieldName}"); } return _methodInfo.Invoke(target, arguments); } } }
using System; using System.Linq; using System.Reflection; using GraphQL.Types; namespace GraphQL.Resolvers { public class MethodModelBinderResolver<T> : IFieldResolver { private readonly IDependencyResolver _dependencyResolver; private readonly MethodInfo _methodInfo; private readonly ParameterInfo[] _parameters; private readonly Type _type; public MethodModelBinderResolver(MethodInfo methodInfo, IDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; _type = typeof(T); _methodInfo = methodInfo; _parameters = _methodInfo.GetParameters(); } public object Resolve(ResolveFieldContext context) { var index = 0; var arguments = new object[_parameters.Length]; if (_parameters.Any() && typeof(ResolveFieldContext) == _parameters[index].ParameterType) { arguments[index] = context; index++; } if (_parameters.Any() && context.Source?.GetType() == _parameters[index].ParameterType) { arguments[index] = context.Source; index++; } foreach (var parameter in _parameters.Skip(index)) { arguments[index] = context.GetArgument(parameter.Name, parameter.ParameterType); index++; } var target = _dependencyResolver.Resolve(_type); if (target == null) { throw new InvalidOperationException($"Could not resolve an instance of {_type.Name} to execute {context.FieldName}"); } return _methodInfo.Invoke(target, arguments); } } }
mit
C#
bb59d19c1c4662ee4f737f09e894b7bc385d51fa
Implement IsValidDestination for Queen
ProgramFOX/Chess.NET
ChessDotNet/Pieces/Queen.cs
ChessDotNet/Pieces/Queen.cs
using System; namespace ChessDotNet.Pieces { public class Queen : ChessPiece { public override Player Owner { get; set; } public Queen(Player owner) { Owner = owner; } public override string GetFenCharacter() { return Owner == Player.White ? "Q" : "q"; } public override bool IsValidDestination(Position origin, Position destination, ChessGame game) { return new Bishop(Owner).IsValidDestination(origin, destination, game) || new Rook(Owner).IsValidDestination(origin, destination, game); } } }
namespace ChessDotNet.Pieces { public class Queen : ChessPiece { public override Player Owner { get; set; } public Queen(Player owner) { Owner = owner; } public override string GetFenCharacter() { return Owner == Player.White ? "Q" : "q"; } } }
mit
C#
314e44574d0b05c8110b579207dfa1127d18e94d
fix recursion
JohanLarsson/Gu.Wpf.Geometry
Gu.Wpf.Geometry.Demo/Converters/ElementToBoundsRectConverter.cs
Gu.Wpf.Geometry.Demo/Converters/ElementToBoundsRectConverter.cs
namespace Gu.Wpf.Geometry.Demo.Converters { using System; using System.Windows; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; [ValueConversion(typeof(FrameworkElement), typeof(Rect))] public sealed class ElementToBoundsRectConverter : MarkupExtension, IValueConverter { public Type AncestorType { get; set; } public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { var element = (FrameworkElement)value; var parent = element?.Parent as FrameworkElement; while (parent != null) { if (parent.GetType() == this.AncestorType) { return element.TransformToVisual(parent) .TransformBounds(new Rect(element.DesiredSize)); } parent = parent.Parent as FrameworkElement; } throw new InvalidOperationException("Did not find parent."); } object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotSupportedException($"{nameof(ElementToBoundsRectConverter)} can only be used in OneWay bindings"); } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }
namespace Gu.Wpf.Geometry.Demo.Converters { using System; using System.Windows; using System.Windows.Data; using System.Windows.Markup; using System.Windows.Media; [ValueConversion(typeof(FrameworkElement), typeof(Rect))] public sealed class ElementToBoundsRectConverter : MarkupExtension, IValueConverter { public Type AncestorType { get; set; } public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { var element = (FrameworkElement)value; DependencyObject parent = element.Parent; while (parent != null) { if (parent.GetType() == this.AncestorType) { return element.TransformToVisual((Visual)parent).TransformBounds(new Rect(element.DesiredSize)); } parent = element.Parent; } throw new InvalidOperationException("Did not find parent."); } object IValueConverter.ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new System.NotSupportedException($"{nameof(ElementToBoundsRectConverter)} can only be used in OneWay bindings"); } public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }
mit
C#
cf99aefb45d96eafc146c5c8e687387501c6f89c
Fix ArgumentNullException configuring pools via Remoting
nwoolls/MultiMiner,IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner
MultiMiner.Win/Extensions/ApplicationConfigurationExtensions.cs
MultiMiner.Win/Extensions/ApplicationConfigurationExtensions.cs
using MultiMiner.Utility.Serialization; using System.Linq; namespace MultiMiner.Win.Extensions { public static class ApplicationConfigurationExtensions { public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject) { Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application(); ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns"); if (modelObject.HiddenColumns != null) transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray(); return transferObject; } public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject) { Data.Configuration.Application modelObject = new Data.Configuration.Application(); ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns"); if (transferObject.HiddenColumns != null) modelObject.HiddenColumns = transferObject.HiddenColumns.ToList(); return modelObject; } } }
using MultiMiner.Utility.Serialization; using System.Linq; namespace MultiMiner.Win.Extensions { public static class ApplicationConfigurationExtensions { public static Remoting.Data.Transfer.Configuration.Application ToTransferObject(this Data.Configuration.Application modelObject) { Remoting.Data.Transfer.Configuration.Application transferObject = new Remoting.Data.Transfer.Configuration.Application(); ObjectCopier.CopyObject(modelObject, transferObject, "HiddenColumns"); transferObject.HiddenColumns = modelObject.HiddenColumns.ToArray(); return transferObject; } public static Data.Configuration.Application ToModelObject(this Remoting.Data.Transfer.Configuration.Application transferObject) { Data.Configuration.Application modelObject = new Data.Configuration.Application(); ObjectCopier.CopyObject(transferObject, modelObject, "HiddenColumns"); modelObject.HiddenColumns = transferObject.HiddenColumns.ToList(); return modelObject; } } }
mit
C#
c6b99e34140b5a4afb8bff907c2152e9771f6f2f
Update TMDbClientTrending.cs
LordMike/TMDbLib
TMDbLib/Client/TMDbClientTrending.cs
TMDbLib/Client/TMDbClientTrending.cs
using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.General; using TMDbLib.Objects.Search; using TMDbLib.Objects.Trending; using TMDbLib.Rest; namespace TMDbLib.Client { public partial class TMDbClient { public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/movie/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString().ToLower()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false); return resp; } public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/tv/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false); return resp; } public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/person/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false); return resp; } } }
using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.General; using TMDbLib.Objects.Search; using TMDbLib.Objects.Trending; using TMDbLib.Rest; namespace TMDbLib.Client { public partial class TMDbClient { public async Task<SearchContainer<SearchMovie>> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/movie/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchMovie> resp = await req.GetOfT<SearchContainer<SearchMovie>>(cancellationToken).ConfigureAwait(false); return resp; } public async Task<SearchContainer<SearchTv>> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/tv/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchTv> resp = await req.GetOfT<SearchContainer<SearchTv>>(cancellationToken).ConfigureAwait(false); return resp; } public async Task<SearchContainer<SearchPerson>> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/person/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); if (page >= 1) req.AddQueryString("page", page.ToString()); SearchContainer<SearchPerson> resp = await req.GetOfT<SearchContainer<SearchPerson>>(cancellationToken).ConfigureAwait(false); return resp; } } }
mit
C#
2e31b09e4fe443cf1f124696480d41c10d7e8284
Increment version number in assembly info
fox091/TournamentTeamMaker
TeamMaker/Properties/AssemblyInfo.cs
TeamMaker/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TeamMaker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TeamMaker")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("71703720-56ba-4e6a-9004-239a9836693b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2")] [assembly: AssemblyFileVersion("1.0.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TeamMaker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TeamMaker")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("71703720-56ba-4e6a-9004-239a9836693b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
7d88d6f0fe5a40294e8adba82b0291a7605bc09f
fix fluent builder test
chrismckelt/WebMinder,chrismckelt/WebMinder,chrismckelt/WebMinder
Core.Tests/CreateFixture.cs
Core.Tests/CreateFixture.cs
using WebMinder.Core.Rules.IpBlocker; using WebMinder.Core.Runners; using Xunit; namespace WebMinder.Core.Tests { public class CreateFixture { [Fact] public void CreatesRuleSaysWhatItDoes() { const string rulesetname = "abcd"; const string rulesetdesc = "xyz"; var rule = Create<IpAddressBlockerRule, IpAddressRequest> .RuleSet() .With(y => y.RuleSetName = rulesetname) .With(x => x.ErrorDescription = rulesetdesc) .Build(); Assert.Equal(rulesetname, rule.Rule.RuleSetName); Assert.Equal(rulesetdesc, rule.Rule.ErrorDescription); } } }
using WebMinder.Core.Rules.IpBlocker; using WebMinder.Core.Runners; using Xunit; namespace WebMinder.Core.Tests { public class CreateFixture { [Fact] public void CreatesRuleSaysWhatItDoes() { const string rulesetname = "abcd"; const string rulesetdesc = "xyz"; var rule = Create<IpAddressBlockerRule, IpAddressRequest> .RuleSet() .With(y => y.RuleSetName = rulesetname) .With(x => x.ErrorDescription = rulesetdesc) .Build(); Assert.Equal(rulesetname, rule.Rule.RuleSetName); Assert.Equal(rulesetname, rule.Rule.RuleSetName); } } }
apache-2.0
C#
594eaa0d97475e678c676f2c8d6ef2fe20ff74fd
Handle not having a current session
bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity
src/BugsnagUnity/SessionTracker.cs
src/BugsnagUnity/SessionTracker.cs
using BugsnagUnity.Payload; namespace BugsnagUnity { public interface ISessionTracker { void StartSession(); Session CurrentSession { get; } } class SessionTracker : ISessionTracker { private IClient Client { get; } private Session _currentSession; public Session CurrentSession { get => _currentSession?.Copy(); private set => _currentSession = value; } internal SessionTracker(IClient client) { Client = client; } public void StartSession() { var session = new Session(); CurrentSession = session; var payload = new SessionReport(Client.Configuration, Client.User, session); Client.Send(payload); } } }
using BugsnagUnity.Payload; namespace BugsnagUnity { public interface ISessionTracker { void StartSession(); Session CurrentSession { get; } } class SessionTracker : ISessionTracker { private IClient Client { get; } private Session _currentSession; public Session CurrentSession { get => _currentSession.Copy(); private set => _currentSession = value; } internal SessionTracker(IClient client) { Client = client; } public void StartSession() { var session = new Session(); CurrentSession = session; var payload = new SessionReport(Client.Configuration, Client.User, session); Client.Send(payload); } } }
mit
C#
1fbd7f602eb4036ca0009d7de2438a38368fee3d
Reduce temporary list of titles
Lidefeath/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE
Source/ACE/Network/GameEvent/Events/GameEventCharacterTitles.cs
Source/ACE/Network/GameEvent/Events/GameEventCharacterTitles.cs
namespace ACE.Network.GameEvent { public class GameEventCharacterTitle : GameEventPacket { public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } } public GameEventCharacterTitle(Session session) : base(session) { } protected override void WriteEventBody() { fragment.Payload.Write(1u); fragment.Payload.Write(1u); // TODO: get current title from database fragment.Payload.Write(10u); // TODO: get player's title list from database for (uint i = 1; i <= 10; i++) fragment.Payload.Write(i); } } }
namespace ACE.Network.GameEvent { public class GameEventCharacterTitle : GameEventPacket { public override GameEventOpcode Opcode { get { return GameEventOpcode.CharacterTitle; } } public GameEventCharacterTitle(Session session) : base(session) { } protected override void WriteEventBody() { fragment.Payload.Write(1u); fragment.Payload.Write(1u); // TODO: get current title from database fragment.Payload.Write(1000u); // TODO: get player's title list from database for (uint i = 1; i <= 1000; i++) fragment.Payload.Write(i); } } }
agpl-3.0
C#
9bb2597c9247fed168ca427a2a6017a27dbe6871
Add framerate parameter in `AnimatorBase.DisplayUndoable`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/OpenGl/Animation/AnimatorBase.cs
SolidworksAddinFramework/OpenGl/Animation/AnimatorBase.cs
using System; using System.Collections.Generic; using System.Numerics; using System.Reactive.Disposables; using System.Reactive.Linq; using SolidWorks.Interop.sldworks; using Weingartner.Exceptional.Reactive; namespace SolidworksAddinFramework.OpenGl.Animation { public abstract class AnimatorBase : IRenderable { public abstract TimeSpan Duration { get; } public abstract IReadOnlyList<IAnimationSection> Sections { get; } public IDisposable DisplayUndoable(IModelDoc2 modelDoc, double framerate = 30, int layer = 0) { OnStart(DateTime.Now); var d = new CompositeDisposable(); OpenGlRenderer.DisplayUndoable(this, modelDoc, layer).DisposeWith(d); Redraw(modelDoc, framerate).DisposeWith(d); return d; } public abstract void OnStart(DateTime startTime); public abstract void Render(DateTime time); public Tuple<Vector3, float> BoundingSphere { get { throw new NotImplementedException(); } } public void ApplyTransform(Matrix4x4 transform) { throw new NotImplementedException(); } private static IDisposable Redraw(IModelDoc2 doc, double framerate = 30) { return Observable.Interval(TimeSpan.FromSeconds(1.0 / framerate)) .ToObservableExceptional() .ObserveOnSolidworksThread() .Subscribe(_ => doc.GraphicsRedraw2()); } } }
using System; using System.Collections.Generic; using System.Numerics; using System.Reactive.Disposables; using System.Reactive.Linq; using SolidWorks.Interop.sldworks; using Weingartner.Exceptional.Reactive; namespace SolidworksAddinFramework.OpenGl.Animation { public abstract class AnimatorBase : IRenderable { public abstract TimeSpan Duration { get; } public abstract IReadOnlyList<IAnimationSection> Sections { get; } public IDisposable DisplayUndoable(IModelDoc2 modelDoc, int layer = 0) { OnStart(DateTime.Now); var d = new CompositeDisposable(); OpenGlRenderer.DisplayUndoable(this, modelDoc, layer).DisposeWith(d); Redraw(modelDoc).DisposeWith(d); return d; } public abstract void OnStart(DateTime startTime); public abstract void Render(DateTime time); public Tuple<Vector3, float> BoundingSphere { get { throw new NotImplementedException(); } } public void ApplyTransform(Matrix4x4 transform) { throw new NotImplementedException(); } private static IDisposable Redraw(IModelDoc2 doc, double framerate = 30) { return Observable.Interval(TimeSpan.FromSeconds(1.0 / framerate)) .ToObservableExceptional() .ObserveOnSolidworksThread() .Subscribe(_ => doc.GraphicsRedraw2()); } } }
mit
C#
a46a4056fc236fd3afb6040496581a10ba41bf56
Fix Plot return to index
joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net
Joinrpg/Views/Plot/Create.cshtml
Joinrpg/Views/Plot/Create.cshtml
@model JoinRpg.Web.Models.Plot.AddPlotFolderViewModel @{ ViewBag.Title = "Добавить сюжет"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <p>Начните работу с того, что создайте сюжет. Сюжет — это история, она состоит из вводных, которые вы даете персонажам или локациям. Все поля на этой странице — только для мастеров, игроки их не увидят.</p> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ProjectId) <div class="form-group"> @Html.LabelFor(model => model.PlotFolderMasterTitle, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.PlotFolderMasterTitle, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PlotFolderMasterTitle, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.TodoField, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.TodoField, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.TodoField, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Создать сюжет" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Назад к списку сюжетов", "Index", new {Model.ProjectId}, null) </div>
@model JoinRpg.Web.Models.Plot.AddPlotFolderViewModel @{ ViewBag.Title = "Добавить сюжет"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <p>Начните работу с того, что создайте сюжет. Сюжет — это история, она состоит из вводных, которые вы даете персонажам или локациям. Все поля на этой странице — только для мастеров, игроки их не увидят.</p> <hr /> @Html.ValidationSummary(true, "", new { @class = "text-danger" }) @Html.HiddenFor(model => model.ProjectId) <div class="form-group"> @Html.LabelFor(model => model.PlotFolderMasterTitle, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.PlotFolderMasterTitle, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.PlotFolderMasterTitle, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.TodoField, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.TodoField, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.TodoField, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Создать сюжет" class="btn btn-default" /> </div> </div> </div> } <div> @Html.ActionLink("Back to List", "Index") </div>
mit
C#
b9458307115d57ee464ef6aa6463c63eb11536a5
Add Operator Overloads to Vertex Struct
Silvertorch5/RobustEngine
Graphics/Vertex.cs
Graphics/Vertex.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RobustEngine.Graphics { public struct Vertex { public float X, Y, Z; public const int Stride = 12; public static readonly Vertex Zero = new Vertex(0,0); public static readonly Vertex UnitX = new Vertex(1,0); public static readonly Vertex UnitY = new Vertex(0,1); public static readonly Vertex One = new Vertex(1,1); public Vertex(float x, float y, float z = 0) { X = x; Y = y; Z = z; } #region OPERATORS OH BOY #region VECTOR MATH public static Vertex operator *(Vertex A, Vertex B) { return new Vertex(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } public static Vertex operator +(Vertex A, Vertex B) { return new Vertex(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vertex operator -(Vertex A, Vertex B) { return new Vertex(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vertex operator /(Vertex A, Vertex B) { return new Vertex(A.X / B.X, A.Y / B.Y, A.Z / B.Z); } #endregion #region INT MATH public static Vertex operator *(Vertex A, int B) { return new Vertex(A.X * B, A.Y * B, A.Z * B); } public static Vertex operator +(Vertex A, int B) { return new Vertex(A.X + B, A.Y + B, A.Z + B); } public static Vertex operator -(Vertex A, int B) { return new Vertex(A.X - B, A.Y - B, A.Z - B); } public static Vertex operator /(Vertex A, int B) { return new Vertex(A.X / B, A.Y / B, A.Z / B); } #endregion #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RobustEngine.Graphics { public struct Vertex { public float X, Y, Z; public const int Stride = 12; public static readonly Vertex Zero = new Vertex(0,0); public static readonly Vertex UnitX = new Vertex(1,0); public static readonly Vertex UnitY = new Vertex(0,1); public static readonly Vertex One = new Vertex(1,1); public Vertex(float x, float y, float z = 0) { X = x; Y = y; Z = z; } public static Vertex operator *(Vertex A, Vertex B) { return new Vertex(A.X * B.X, A.Y * B.Y, A.Z * B.Z); } public static Vertex operator +(Vertex A, Vertex B) { return new Vertex(A.X + B.X, A.Y + B.Y, A.Z + B.Z); } public static Vertex operator -(Vertex A, Vertex B) { return new Vertex(A.X - B.X, A.Y - B.Y, A.Z - B.Z); } public static Vertex operator /(Vertex A, Vertex B) { return new Vertex(A.X / B.X, A.Y / B.Y, A.Z / B.Z); } } }
mit
C#
07f2325cb78d7cc503c30b9b1717b7245f4c2554
Change button name
Vtek/PowerBI.Api.Client
src/XamarinClient/Page/RootPage.cs
src/XamarinClient/Page/RootPage.cs
using System; using Xamarin.Forms; namespace XamarinClient { /// <summary> /// Root page. /// </summary> public class RootPage : ContentPage { public RootPage() { InitializeComponent(); Bind(); } void InitializeComponent() { var layout = new StackLayout { VerticalOptions = LayoutOptions.Center }; var button = new Button { VerticalOptions = LayoutOptions.Center, Text = "Insert", IsEnabled = false }; button.SetBinding<MainViewModel>(Button.CommandProperty, vm => vm.InsertCommand); layout.Children.Add(button); Content = layout; } void Bind() { var viewModel = new MainViewModel(); viewModel.Insert += async (sender, e) => await DisplayAlert("Insertion", "Données bien insérée !", "OK"); BindingContext = viewModel; } } }
using System; using Xamarin.Forms; namespace XamarinClient { /// <summary> /// Root page. /// </summary> public class RootPage : ContentPage { public RootPage() { InitializeComponent(); Bind(); } void InitializeComponent() { var layout = new StackLayout { VerticalOptions = LayoutOptions.Center }; var button = new Button { VerticalOptions = LayoutOptions.Center, Text = "Connect", IsEnabled = false }; button.SetBinding<MainViewModel>(Button.CommandProperty, vm => vm.InsertCommand); layout.Children.Add(button); Content = layout; } void Bind() { var viewModel = new MainViewModel(); viewModel.Insert += async (sender, e) => await DisplayAlert("Insertion", "Données bien insérée !", "OK"); BindingContext = viewModel; } } }
mit
C#
cdfe95c15930ac6e0072699d7f7ab2c0725fccaf
Add AcentColour and xmldoc.
smoogipooo/osu,ZLima12/osu,NeoAdonis/osu,Damnae/osu,ppy/osu,johnneijzen/osu,nyaamara/osu,tacchinotacchi/osu,Drezi126/osu,Frontear/osuKyzer,DrabWeb/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,johnneijzen/osu,Nabile-Rahmani/osu,ppy/osu,UselessToucan/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,RedNesto/osu,peppy/osu,naoey/osu,peppy/osu,naoey/osu,NeoAdonis/osu,ZLima12/osu,ppy/osu,naoey/osu,2yangk23/osu,osu-RP/osu-RP,smoogipoo/osu,EVAST9919/osu,peppy/osu,UselessToucan/osu
osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs
osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using OpenTK.Graphics; using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Taiko.Judgements; namespace osu.Game.Modes.Taiko.Objects.Drawable { public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo> { /// <summary> /// The colour used for various elements of this DrawableHitObject. /// </summary> public virtual Color4 AccentColour { get; } public DrawableTaikoHitObject(TaikoHitObject hitObject) : base(hitObject) { LifetimeStart = HitObject.StartTime - HitObject.PreEmpt; LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt; } protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo(); protected override void UpdateState(ArmedState state) { } /// <summary> /// Sets the scroll position of the DrawableHitObject relative to the offset between /// a time value and the HitObject's StartTime. /// </summary> /// <param name="time"></param> protected void UpdateScrollPosition(double time) { MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt)); } protected override void Update() { UpdateScrollPosition(Time.Current); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Modes.Objects.Drawables; using osu.Game.Modes.Taiko.Judgements; namespace osu.Game.Modes.Taiko.Objects.Drawable { public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo> { public DrawableTaikoHitObject(TaikoHitObject hitObject) : base(hitObject) { LifetimeStart = HitObject.StartTime - HitObject.PreEmpt; LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt; } protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo(); protected override void UpdateState(ArmedState state) { } protected void UpdateScrollPosition(double time) { MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt)); } protected override void Update() { UpdateScrollPosition(Time.Current); } } }
mit
C#
0a8bb3f1636984ae38199b78b053573077fd0f27
clean up
edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk
tests/InMemoryDataStoreTest.cs
tests/InMemoryDataStoreTest.cs
using System.IO; using FHSDK.Services; using FHSDK.Services.Data; using FHSDK.Sync; using FHSDKPortable; using Newtonsoft.Json.Linq; using Xunit; namespace tests { public class InMemoryDataStoreTest { private readonly string _dataPersistFile; private readonly IIOService _ioService; public InMemoryDataStoreTest() { FHClient.Init(); _ioService = ServiceFinder.Resolve<IIOService>(); var dataDir = _ioService.GetDataPersistDir(); var dataPersistDir = Path.Combine(dataDir, "syncTestDir"); _dataPersistFile = Path.Combine(dataPersistDir, ".test_data_file"); } [Fact] public void TestInsertIntoDataStore() { //given IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>(); var obj = new JObject(); obj["key"] = "value"; //when dataStore.Insert("key1", obj); dataStore.Insert("key2", obj); //then var list = dataStore.List(); Assert.Equal(2, list.Count); Assert.NotNull(list["key1"]); var result = dataStore.Get("key1"); Assert.Equal(obj, result); } [Fact] public void TestSaveDataStoreToJson() { //given IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>(); dataStore.PersistPath = _dataPersistFile; var obj = new JObject(); obj["key"] = "value"; //when dataStore.Insert("main-key", obj); dataStore.Save(); //then Assert.True(_ioService.Exists(_dataPersistFile)); var content = _ioService.ReadFile(_dataPersistFile); Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content); } } }
using System.IO; using FHSDK.Services; using FHSDK.Services.Data; using FHSDK.Sync; using FHSDKPortable; using Newtonsoft.Json.Linq; using Xunit; namespace tests { public class InMemoryDataStoreTest { private string _dataPersistDir; private string _dataPersistFile; private IIOService _ioService; public InMemoryDataStoreTest() { FHClient.Init(); _ioService = ServiceFinder.Resolve<IIOService>(); var dataDir = _ioService.GetDataPersistDir(); _dataPersistDir = Path.Combine(dataDir, "syncTestDir"); _dataPersistFile = Path.Combine(_dataPersistDir, ".test_data_file"); } [Fact] public void TestInsertIntoDataStore() { //given IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>(); var obj = new JObject(); obj["key"] = "value"; //when dataStore.Insert("key1", obj); dataStore.Insert("key2", obj); //then var list = dataStore.List(); Assert.Equal(2, list.Count); Assert.NotNull(list["key1"]); var result = dataStore.Get("key1"); Assert.Equal(obj, result); } [Fact] public void TestSaveDataStoreToJson() { //given IDataStore<JObject> dataStore = new InMemoryDataStore<JObject>(); dataStore.PersistPath = _dataPersistFile; var obj = new JObject(); obj["key"] = "value"; //when dataStore.Insert("main-key", obj); dataStore.Save(); //then Assert.True(_ioService.Exists(_dataPersistFile)); var content = _ioService.ReadFile(_dataPersistFile); Assert.Equal("{\"main-key\":{\"key\":\"value\"}}", content); } } }
apache-2.0
C#
529816fb307ac071e2ca031606144eb8377e523b
Fix generated code spelling mistake. Closes #796
sschmid/Entitas-CSharp,sschmid/Entitas-CSharp
Addons/Entitas.VisualDebugging.CodeGeneration.Plugins/Entitas.VisualDebugging.CodeGeneration.Plugins/ContextObserverGenerator.cs
Addons/Entitas.VisualDebugging.CodeGeneration.Plugins/Entitas.VisualDebugging.CodeGeneration.Plugins/ContextObserverGenerator.cs
using System.Linq; using DesperateDevs.CodeGeneration; using DesperateDevs.Utils; using Entitas.CodeGeneration.Plugins; namespace Entitas.VisualDebugging.CodeGeneration.Plugins { public class ContextObserverGenerator : ICodeGenerator { public string name { get { return "Context Observer"; } } public int priority { get { return 0; } } public bool runInDryMode { get { return true; } } const string CONTEXTS_TEMPLATE = @"public partial class Contexts { #if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR) [Entitas.CodeGeneration.Attributes.PostConstructor] public void InitializeContextObservers() { try { ${contextObservers} } catch(System.Exception) { } } public void CreateContextObserver(Entitas.IContext context) { if (UnityEngine.Application.isPlaying) { var observer = new Entitas.VisualDebugging.Unity.ContextObserver(context); UnityEngine.Object.DontDestroyOnLoad(observer.gameObject); } } #endif } "; const string CONTEXT_OBSERVER_TEMPLATE = @" CreateContextObserver(${contextName});"; public CodeGenFile[] Generate(CodeGeneratorData[] data) { var contextNames = data .OfType<ContextData>() .Select(d => d.GetContextName()) .OrderBy(contextName => contextName) .ToArray(); return new[] { new CodeGenFile( "Contexts.cs", generateContextsClass(contextNames), GetType().FullName) }; } string generateContextsClass(string[] contextNames) { var contextObservers = string.Join("\n", contextNames .Select(contextName => CONTEXT_OBSERVER_TEMPLATE .Replace("${contextName}", contextName.LowercaseFirst()) ).ToArray()); return CONTEXTS_TEMPLATE .Replace("${contextObservers}", contextObservers); } } }
using System.Linq; using DesperateDevs.CodeGeneration; using DesperateDevs.Utils; using Entitas.CodeGeneration.Plugins; namespace Entitas.VisualDebugging.CodeGeneration.Plugins { public class ContextObserverGenerator : ICodeGenerator { public string name { get { return "Context Observer"; } } public int priority { get { return 0; } } public bool runInDryMode { get { return true; } } const string CONTEXTS_TEMPLATE = @"public partial class Contexts { #if (!ENTITAS_DISABLE_VISUAL_DEBUGGING && UNITY_EDITOR) [Entitas.CodeGeneration.Attributes.PostConstructor] public void InitializeContexObservers() { try { ${contextObservers} } catch(System.Exception) { } } public void CreateContextObserver(Entitas.IContext context) { if (UnityEngine.Application.isPlaying) { var observer = new Entitas.VisualDebugging.Unity.ContextObserver(context); UnityEngine.Object.DontDestroyOnLoad(observer.gameObject); } } #endif } "; const string CONTEXT_OBSERVER_TEMPLATE = @" CreateContextObserver(${contextName});"; public CodeGenFile[] Generate(CodeGeneratorData[] data) { var contextNames = data .OfType<ContextData>() .Select(d => d.GetContextName()) .OrderBy(contextName => contextName) .ToArray(); return new[] { new CodeGenFile( "Contexts.cs", generateContextsClass(contextNames), GetType().FullName) }; } string generateContextsClass(string[] contextNames) { var contextObservers = string.Join("\n", contextNames .Select(contextName => CONTEXT_OBSERVER_TEMPLATE .Replace("${contextName}", contextName.LowercaseFirst()) ).ToArray()); return CONTEXTS_TEMPLATE .Replace("${contextObservers}", contextObservers); } } }
mit
C#
3437f02a99423472e784c441ffbc822e55408a4c
Update Index.cshtml
infosecdev/botforge,roxberry/botforge,roxberry/botforge,infosecdev/botforge
botforge/Views/Home/Index.cshtml
botforge/Views/Home/Index.cshtml
@{ ViewBag.Title = "ROBOTS!"; } <div class="hero-unit"> <img src="~/img/logo2.png" style="width:300px;" alt="The Robot Forge" /> <img src="~/img/banner2.png" /> <p class="lead">The Robot Forge is where robot makers come to learn about robotics, build robots from components and software and interact with other robot makers.</p> </div> <div class="row"> <div class="span4"> <h2> <img src="~/img/robot.png" style="width:32px;margin-right:15px;"/> <img src="~/img/Learn.png" /></h2> <p>Robotics is a pathway to learning hardware and software engineering. Follow us for weekly classes and activities.</p> <p><a class="btn" href="~/Views/Home/Learn.cshtml">Learn more &raquo;</a></p> </div> <div class="span4"> <h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" /> <img src="~/img/Build.png" /></h2> <p>Make robots by assemblying actuators, sensors, controllers and writing programs. This is where we show off some of prototypes and production models.</p> <p><a class="btn" href="~/Views/Home/Build.cshtml">Learn more &raquo;</a></p> </div> <div class="span4"> <h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" /> <img src="~/img/Interact.png" /></h2> <p>Robot makers are everywhere. Here you can read about the latest creations and participate in a safe social network of like minded creators.</p> <p><a class="btn" href="~/Views/Home/Interact.cshtml">Learn more &raquo;</a></p> </div> </div>
@{ ViewBag.Title = "The Robot Forge"; } <div class="hero-unit"> <img src="~/img/logo2.png" style="width:300px;" alt="The Robot Forge" /> <img src="~/img/banner2.png" /> <p class="lead">The Robot Forge is where robot makers come to learn about robotics, build robots from components and software and interact with other robot makers.</p> </div> <div class="row"> <div class="span4"> <h2> <img src="~/img/robot.png" style="width:32px;margin-right:15px;"/> <img src="~/img/Learn.png" /></h2> <p>Robotics is a pathway to learning hardware and software engineering. Follow us for weekly classes and activities.</p> <p><a class="btn" href="~/Views/Home/Learn.cshtml">Learn more &raquo;</a></p> </div> <div class="span4"> <h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" /> <img src="~/img/Build.png" /></h2> <p>Make robots by assemblying actuators, sensors, controllers and writing programs. This is where we show off some of prototypes and production models.</p> <p><a class="btn" href="~/Views/Home/Build.cshtml">Learn more &raquo;</a></p> </div> <div class="span4"> <h2><img src="~/img/robot.png" style="width:32px;margin-right:15px;" /> <img src="~/img/Interact.png" /></h2> <p>Robot makers are everywhere. Here you can read about the latest creations and participate in a safe social network of like minded creators.</p> <p><a class="btn" href="~/Views/Home/Interact.cshtml">Learn more &raquo;</a></p> </div> </div>
mit
C#
277c613e552daaf4c7f42714421b452c08344cf5
Fix silly mistake in DI configuration
csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil
Agiil.Web/App_Start/ContainerFactoryProviderExtensions.cs
Agiil.Web/App_Start/ContainerFactoryProviderExtensions.cs
using System; using System.Web.Http; using Agiil.Bootstrap.DiConfiguration; using Autofac; namespace Agiil.Web.App_Start { public static class ContainerFactoryProviderExtensions { public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config) { if(provider == null) throw new ArgumentNullException(nameof(provider)); if(config == null) throw new ArgumentNullException(nameof(config)); var diFactory = provider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration; if(diFactory == null) throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}."); diFactory.SetHttpConfiguration(config); return diFactory.GetContainer(); } } }
using System; using System.Web.Http; using Agiil.Bootstrap.DiConfiguration; using Autofac; namespace Agiil.Web.App_Start { public static class ContainerFactoryProviderExtensions { public static IContainer GetContainer(this ContainerFactoryProvider provider, HttpConfiguration config) { if(provider == null) throw new ArgumentNullException(nameof(provider)); if(config == null) throw new ArgumentNullException(nameof(config)); var factoryProvider = new ContainerFactoryProvider(); var diFactory = factoryProvider.GetContainerBuilderFactory() as IContainerFactoryWithHttpConfiguration; if(diFactory == null) throw new InvalidOperationException($"The configured container builder factory must implement {nameof(IContainerFactoryWithHttpConfiguration)}."); diFactory.SetHttpConfiguration(config); return diFactory.GetContainer(); } } }
mit
C#
c4c9753214bb84c5e423ce422db7acca46227c2b
Return localized resource
gjulianm/AncoraMVVM
AncoraMVVM.Phone/Converters/PhoneEnumToStringConverter.cs
AncoraMVVM.Phone/Converters/PhoneEnumToStringConverter.cs
using System.Windows; using System.Windows.Data; using AncoraMVVM.Base.Converters; namespace AncoraMVVM.Phone.Converters { public class PhoneEnumToStringConverter : BaseEnumToStringConverter, IValueConverter { protected override string GetLocalizedString(string id) { return Application.Current.Resources[id] as string; } } }
using System.Windows.Data; using AncoraMVVM.Base.Converters; namespace AncoraMVVM.Phone.Converters { public class PhoneEnumToStringConverter : BaseEnumToStringConverter, IValueConverter { protected override string GetLocalizedString(string id) { throw new System.NotImplementedException(); } } }
mpl-2.0
C#
fd4ca91d6f7c47c9ce97eed2c91b686cac391447
Fix a bug where toggleready returns an exception when provided with the wrong number of arguments (#9631)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Server/GameTicking/Commands/ToggleReadyCommand.cs
Content.Server/GameTicking/Commands/ToggleReadyCommand.cs
using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; namespace Content.Server.GameTicking.Commands { [AnyCommand] sealed class ToggleReadyCommand : IConsoleCommand { public string Command => "toggleready"; public string Description => ""; public string Help => ""; public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; if (args.Length != 1) { shell.WriteError(Loc.GetString("shell-wrong-arguments-number")); return; } if (player == null) { return; } var ticker = EntitySystem.Get<GameTicker>(); ticker.ToggleReady(player, bool.Parse(args[0])); } } }
using Content.Shared.Administration; using Robust.Server.Player; using Robust.Shared.Console; namespace Content.Server.GameTicking.Commands { [AnyCommand] sealed class ToggleReadyCommand : IConsoleCommand { public string Command => "toggleready"; public string Description => ""; public string Help => ""; public void Execute(IConsoleShell shell, string argStr, string[] args) { var player = shell.Player as IPlayerSession; if (player == null) { return; } var ticker = EntitySystem.Get<GameTicker>(); ticker.ToggleReady(player, bool.Parse(args[0])); } } }
mit
C#
85ed140631e10d14875a183457066e74b55623b8
Add simple successfully checking property to AsyncResponseData
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/AsyncResponseData.cs
Scripts/AsyncResponseData.cs
using LiteNetLib.Utils; namespace LiteNetLibManager { public struct AsyncResponseData<TResponse> where TResponse : INetSerializable { public ResponseHandlerData RequestHandler { get; private set; } public AckResponseCode ResponseCode { get; private set; } public TResponse Response { get; private set; } public bool IsSuccess { get { return ResponseCode == AckResponseCode.Success; } } public AsyncResponseData(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response) { RequestHandler = requestHandler; ResponseCode = responseCode; Response = response; } } }
using LiteNetLib.Utils; namespace LiteNetLibManager { public struct AsyncResponseData<TResponse> where TResponse : INetSerializable { public ResponseHandlerData RequestHandler { get; private set; } public AckResponseCode ResponseCode { get; private set; } public TResponse Response { get; private set; } public AsyncResponseData(ResponseHandlerData requestHandler, AckResponseCode responseCode, TResponse response) { RequestHandler = requestHandler; ResponseCode = responseCode; Response = response; } } }
mit
C#
3ee576240de73918c6455d500c0644b1f2c4c54b
Improve tests
Fody/Stamp
Tests/TaskTests.cs
Tests/TaskTests.cs
using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Mono.Cecil; using NUnit.Framework; [TestFixture] public class TaskTests { private Assembly assembly; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private string beforeAssemblyPath; private string afterAssemblyPath; public TaskTests() { beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll")); #if (!DEBUG) beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release"); #endif afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll"); File.Copy(beforeAssemblyPath, afterAssemblyPath, true); using (var moduleDefinition = ModuleDefinition.ReadModule(beforeAssemblyPath)) { var currentDirectory = AssemblyLocation.CurrentDirectory(); var weavingTask = new ModuleWeaver { ModuleDefinition = moduleDefinition, AddinDirectoryPath = currentDirectory, SolutionDirectoryPath = currentDirectory, AssemblyFilePath = afterAssemblyPath, }; weavingTask.Execute(); moduleDefinition.Write(afterAssemblyPath); weavingTask.AfterWeaving(); } assembly = Assembly.LoadFile(afterAssemblyPath); } [Test] public void EnsureAttributeExists() { var customAttributes = (AssemblyInformationalVersionAttribute)assembly .GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false) .First(); AssertVersionWithSha(customAttributes.InformationalVersion); } [Test] public void Win32Resource() { var versionInfo = FileVersionInfo.GetVersionInfo(afterAssemblyPath); AssertVersionWithSha(versionInfo.ProductVersion); Assert.IsNotNull(versionInfo.FileVersion); Assert.IsNotEmpty(versionInfo.FileVersion); Assert.AreEqual("1.0.0.0",versionInfo.FileVersion); } private static void AssertVersionWithSha(string version) { Assert.IsNotNull(version); Assert.IsNotEmpty(version); StringAssert.Contains("1.0.0.0", version, "Missing number"); StringAssert.Contains("Head:", version, message: "Missing Head"); StringAssert.Contains("Sha:", version, message: "Missing Sha"); Trace.WriteLine(version); } #if(DEBUG) [Test] public void PeVerify() { Verifier.Verify(beforeAssemblyPath, afterAssemblyPath); } #endif }
using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Mono.Cecil; using NUnit.Framework; [TestFixture] public class TaskTests { private Assembly assembly; // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable private string beforeAssemblyPath; private string afterAssemblyPath; public TaskTests() { beforeAssemblyPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, @"..\..\..\AssemblyToProcess\bin\Debug\AssemblyToProcess.dll")); #if (!DEBUG) beforeAssemblyPath = beforeAssemblyPath.Replace("Debug", "Release"); #endif afterAssemblyPath = beforeAssemblyPath.Replace(".dll", "2.dll"); File.Copy(beforeAssemblyPath, afterAssemblyPath, true); using (var moduleDefinition = ModuleDefinition.ReadModule(beforeAssemblyPath)) { var currentDirectory = AssemblyLocation.CurrentDirectory(); var weavingTask = new ModuleWeaver { ModuleDefinition = moduleDefinition, AddinDirectoryPath = currentDirectory, SolutionDirectoryPath = currentDirectory, AssemblyFilePath = afterAssemblyPath, }; weavingTask.Execute(); moduleDefinition.Write(afterAssemblyPath); weavingTask.AfterWeaving(); } assembly = Assembly.LoadFile(afterAssemblyPath); } [Test] public void EnsureAttributeExists() { var customAttributes = (AssemblyInformationalVersionAttribute)assembly .GetCustomAttributes(typeof (AssemblyInformationalVersionAttribute), false) .First(); Assert.IsNotNull(customAttributes.InformationalVersion); Assert.IsNotEmpty(customAttributes.InformationalVersion); Trace.WriteLine(customAttributes.InformationalVersion); } [Test] public void Win32Resource() { var versionInfo = FileVersionInfo.GetVersionInfo(afterAssemblyPath); Assert.IsNotNull(versionInfo.ProductVersion); Assert.IsNotEmpty(versionInfo.ProductVersion); Assert.IsNotNull(versionInfo.FileVersion); Assert.IsNotEmpty(versionInfo.FileVersion); Trace.WriteLine(versionInfo.ProductVersion); Trace.WriteLine(versionInfo.FileVersion); } #if(DEBUG) [Test] public void PeVerify() { Verifier.Verify(beforeAssemblyPath, afterAssemblyPath); } #endif }
mit
C#
693ca83135753921aee5c08f377f700ce6014fce
Allow trial_period_start to be null
xamarin/XamarinStripe,haithemaraissia/XamarinStripe
XamarinStripe/StripePlan.cs
XamarinStripe/StripePlan.cs
/* * Copyright 2011 Joe Dluzen * * Author(s): * Joe Dluzen (jdluzen@gmail.com) * * 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 Newtonsoft.Json; namespace Xamarin.Payments.Stripe { [JsonObject (MemberSerialization.OptIn)] public class StripePlan : StripeId { [JsonProperty (PropertyName = "livemode")] public bool LiveMode { get; set; } [JsonProperty (PropertyName = "amount")] public int Amount { get; set; } [JsonProperty (PropertyName = "currency")] public string Currency { get; set; } // deleted was deleted /* [JsonProperty(PropertyName = "deleted")] public bool? Deleted { get; set; } */ [JsonProperty(PropertyName = "identifier")] public string Identifier { get; set; } [JsonProperty (PropertyName = "interval")] public StripePlanInterval Interval { get; set; } [JsonProperty (PropertyName = "name")] public string Name { get; set; } [JsonProperty (PropertyName = "trial_period_days")] public int? TrialPeriod { get; set; } } }
/* * Copyright 2011 Joe Dluzen * * Author(s): * Joe Dluzen (jdluzen@gmail.com) * * 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 Newtonsoft.Json; namespace Xamarin.Payments.Stripe { [JsonObject (MemberSerialization.OptIn)] public class StripePlan : StripeId { [JsonProperty (PropertyName = "livemode")] public bool LiveMode { get; set; } [JsonProperty (PropertyName = "amount")] public int Amount { get; set; } [JsonProperty (PropertyName = "currency")] public string Currency { get; set; } // deleted was deleted /* [JsonProperty(PropertyName = "deleted")] public bool? Deleted { get; set; } */ [JsonProperty(PropertyName = "identifier")] public string Identifier { get; set; } [JsonProperty (PropertyName = "interval")] public StripePlanInterval Interval { get; set; } [JsonProperty (PropertyName = "name")] public string Name { get; set; } [JsonProperty (PropertyName = "trial_period_days")] public int TrialPeriod { get; set; } } }
apache-2.0
C#
ebf5572bc43162d0b28e3f3b9b6255177199d3f0
Configure Sensor dynamically
jcapellman/jcTM,jcapellman/jcTM
csharp/jcTM.UWP.IoT/MainPage.xaml.cs
csharp/jcTM.UWP.IoT/MainPage.xaml.cs
using Windows.UI.Xaml.Controls; using GrovePi; using GrovePi.Sensors; using jcTM.PCL.Handlers; namespace jcTM.UWP.IoT { public sealed partial class MainPage : Page { private ITemperatureSensor _sensor; public MainPage() { this.InitializeComponent(); ConfigureSensor(); ReadTemperature(); } // Run through the 3 Analog Pins private void ConfigureSensor() { var device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin0, TemperatureSensorModel.OnePointTwo); if (device != null) { _sensor = device; } device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin1, TemperatureSensorModel.OnePointTwo); if (device != null) { _sensor = device; } device = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin2, TemperatureSensorModel.OnePointTwo); if (device != null) { _sensor = device; } } private async void ReadTemperature() { var tempHandler = new TemperatureHandler(); while (true) { var temperature = _sensor.TemperatureInCelcius(); var convertedTemperature = ((9.0/5.0)*temperature) + 32; tempHandler.RecordTemperature(convertedTemperature); await System.Threading.Tasks.Task.Delay(5000); } } } }
using Windows.UI.Xaml.Controls; using GrovePi; using GrovePi.Sensors; using jcTM.PCL.Handlers; namespace jcTM.UWP.IoT { public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); ReadTemperature(); } private async void ReadTemperature() { var tempHandler = new TemperatureHandler(); while (true) { var temperature = DeviceFactory.Build.TemperatureSensor(Pin.AnalogPin0, TemperatureSensorModel.OnePointTwo).TemperatureInCelcius(); var convertedTemperature = ((9.0/5.0)*temperature) + 32; tempHandler.RecordTemperature(convertedTemperature); await System.Threading.Tasks.Task.Delay(5000); } } } }
mit
C#
23dcd526e3c9c1b54d273e9a48729c64c231605e
Add nullcheck for CI
ZLima12/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/Visual/TestCaseScreenshot.cs
osu.Framework.Tests/Visual/TestCaseScreenshot.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Platform; using osu.Framework.Testing; using OpenTK; using OpenTK.Graphics; using SixLabors.ImageSharp; namespace osu.Framework.Tests.Visual { public class TestCaseScreenshot : TestCase { [Resolved] private GameHost host { get; set; } private Sprite display; [BackgroundDependencyLoader] private void load() { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Masking = true, BorderColour = Color4.Green, BorderThickness = 2, Child = display = new Sprite { RelativeSizeAxes = Axes.Both } }; AddStep("take screenshot", takeScreenshot); } private void takeScreenshot() { if (host.Window == null) return; host.TakeScreenshotAsync().ContinueWith(t => Schedule(() => { var image = t.Result; var tex = new Texture(image.Width, image.Height); tex.SetData(new TextureUpload(new RawTexture(image.Width, image.Height, image.SavePixelData()))); display.Texture = tex; })); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.OpenGL.Textures; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Platform; using osu.Framework.Testing; using OpenTK; using OpenTK.Graphics; using SixLabors.ImageSharp; namespace osu.Framework.Tests.Visual { public class TestCaseScreenshot : TestCase { [Resolved] private GameHost host { get; set; } private Sprite display; [BackgroundDependencyLoader] private void load() { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Masking = true, BorderColour = Color4.Green, BorderThickness = 2, Child = display = new Sprite { RelativeSizeAxes = Axes.Both } }; AddStep("take screenshot", takeScreenshot); } private void takeScreenshot() => host.TakeScreenshotAsync().ContinueWith(t => Schedule(() => { var image = t.Result; var tex = new Texture(image.Width, image.Height); tex.SetData(new TextureUpload(new RawTexture(image.Width, image.Height, image.SavePixelData()))); display.Texture = tex; })); } }
mit
C#
78943a21d81fc6658a5be485f354b7f925b4636e
Update osu.Game/Beatmaps/ControlPoints/IControlPoint.cs
peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Beatmaps/ControlPoints/IControlPoint.cs
osu.Game/Beatmaps/ControlPoints/IControlPoint.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. namespace osu.Game.Beatmaps.ControlPoints { public interface IControlPoint { /// <summary> /// The time at which the control point takes effect. /// </summary> double Time { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Beatmaps.ControlPoints { public interface IControlPoint { /// <summary> /// The time at which the control point takes effect. /// </summary> public double Time { get; } } }
mit
C#
457f7e32c323d95383e5bb72e7229b98473f3ebd
Update update url
MatthiWare/UpdateLib
UpdateLib/TestApp/Program.cs
UpdateLib/TestApp/Program.cs
using MatthiWare.UpdateLib; using MatthiWare.UpdateLib.Logging; using MatthiWare.UpdateLib.Logging.Writers; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TestApp { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { try { // we still want our updater to have visual styles in case of update cmd argument switch Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Updater.Instance .ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml") //.ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml") .ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug) .ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter())) .ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter())) .ConfigureUnsafeConnections(true) .ConfigureCacheInvalidation(TimeSpan.FromSeconds(30)) .ConfigureUpdateNeedsAdmin(false) .ConfigureInstallationMode(InstallationMode.Shared) .Initialize(); Application.Run(new Form1()); } catch (Exception e) { Console.WriteLine(e.ToString()); MessageBox.Show(e.ToString()); } } } }
using MatthiWare.UpdateLib; using MatthiWare.UpdateLib.Logging; using MatthiWare.UpdateLib.Logging.Writers; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace TestApp { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { try { // we still want our updater to have visual styles in case of update cmd argument switch Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Updater.Instance //.ConfigureUpdateUrl("https://raw.githubusercontent.com/MatthiWare/UpdateLib.TestApp.UpdateExample/master/Dev/updatefile.xml") .ConfigureUpdateUrl("http://matthiware.dev/UpdateLib/Dev/updatefile.xml") .ConfigureLogger((logger) => logger.LogLevel = LoggingLevel.Debug) .ConfigureLogger((logger) => logger.Writers.Add(new ConsoleLogWriter())) .ConfigureLogger((logger) => logger.Writers.Add(new FileLogWriter())) .ConfigureUnsafeConnections(true) .ConfigureCacheInvalidation(TimeSpan.FromSeconds(30)) .ConfigureUpdateNeedsAdmin(false) .ConfigureInstallationMode(InstallationMode.Shared) .Initialize(); Application.Run(new Form1()); } catch (Exception e) { Console.WriteLine(e.ToString()); MessageBox.Show(e.ToString()); } } } }
agpl-3.0
C#
956e303c5a245b6ed2ff74acf07da36679f4d982
Delete a comma
imba-tjd/CSharp-Code-Repository
单个文件的程序/pingt.cs
单个文件的程序/pingt.cs
using System; using System.Diagnostics; // 对tcping的简单封装,自动使用443 class PingT { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("参数不正确"); Environment.Exit(1); } // 无论输入主机还是网址都能运行,后者会自动提取出主机;但为了使用Uri,又要当输入前者时加上协议 string url = args[0].Trim(); if (!url.StartsWith("http")) url = "http://" + url; string host = new Uri(url).Host; Process.Start(new ProcessStartInfo("cmd", $"/C tcping -n 8 {host} 443") { UseShellExecute = false }).WaitForExit(); } }
using System; using System.Diagnostics; // 对tcping的简单封装,自动使用443 class PingT { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("参数不正确"); Environment.Exit(1); } // 无论输入主机还是网址都能运行,后者会自动提取出主机,;但为了使用Uri,又要当输入前者时加上协议 string url = args[0].Trim(); if (!url.StartsWith("http")) url = "http://" + url; string host = new Uri(url).Host; Process.Start(new ProcessStartInfo("cmd", $"/C tcping -n 8 {host} 443") { UseShellExecute = false }).WaitForExit(); } }
mit
C#
d3c58c848deba41d97cb71fbce36b4d89a515555
Add licence header
naoey/osu,NeoAdonis/osu,ZLima12/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,2yangk23/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,peppy/osu,naoey/osu,UselessToucan/osu,smoogipoo/osu,Frontear/osuKyzer,peppy/osu-new,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,Drezi126/osu,smoogipooo/osu,ppy/osu,ppy/osu,peppy/osu,johnneijzen/osu,Nabile-Rahmani/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapProcessor.cs
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapProcessor.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapProcessor : BeatmapProcessor<CatchBaseHit> { public override void PostProcess(Beatmap<CatchBaseHit> beatmap) { if (beatmap.ComboColors.Count == 0) return; int comboIndex = 0; int colourIndex = 0; CatchBaseHit lastObj = null; foreach (var obj in beatmap.HitObjects) { if (obj.NewCombo) { if (lastObj != null) lastObj.LastInCombo = true; comboIndex = 0; colourIndex = (colourIndex + 1) % beatmap.ComboColors.Count; } obj.ComboIndex = comboIndex++; obj.ComboColour = beatmap.ComboColors[colourIndex]; lastObj = obj; } } } }
using osu.Game.Beatmaps; using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapProcessor : BeatmapProcessor<CatchBaseHit> { public override void PostProcess(Beatmap<CatchBaseHit> beatmap) { if (beatmap.ComboColors.Count == 0) return; int comboIndex = 0; int colourIndex = 0; CatchBaseHit lastObj = null; foreach (var obj in beatmap.HitObjects) { if (obj.NewCombo) { if (lastObj != null) lastObj.LastInCombo = true; comboIndex = 0; colourIndex = (colourIndex + 1) % beatmap.ComboColors.Count; } obj.ComboIndex = comboIndex++; obj.ComboColour = beatmap.ComboColors[colourIndex]; lastObj = obj; } } } }
mit
C#
e7367377ad6a29abc7efc8fb48bee8c709f3d948
Fix test on OSX
BlueMountainCapital/Deedle,AtwooTM/Deedle,buybackoff/Deedle,BlueMountainCapital/Deedle,buybackoff/Deedle,AtwooTM/Deedle,caioproiete/Deedle,filmor/Deedle,tpetricek/Deedle,filmor/Deedle,buybackoff/Deedle,tpetricek/Deedle,filmor/Deedle,caioproiete/Deedle,Dependencies/Deedle,jeyoor/Deedle,BlueMountainCapital/Deedle,jeyoor/Deedle,tpetricek/Deedle,Dependencies/Deedle,jeyoor/Deedle,AtwooTM/Deedle,caioproiete/Deedle,Dependencies/Deedle
tests/Deedle.CSharp.Tests/Frame.cs
tests/Deedle.CSharp.Tests/Frame.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Deedle; using System.Runtime.CompilerServices; using System.IO; namespace Deedle.CSharp.Tests { /* ---------------------------------------------------------------------------------- * Test calling Frame.Zip from C# * --------------------------------------------------------------------------------*/ public class FrameZipTests { public static Frame<int, string> LoadMSFT([CallerFilePath] string source = "") { var file = Path.Combine(Path.GetDirectoryName(source), ".." + Path.DirectorySeparatorChar + "Deedle.Tests" + Path.DirectorySeparatorChar + "data" + Path.DirectorySeparatorChar + "MSFT.csv"); return Frame.ReadCsv(file, inferRows:10); } [Test] public static void CanSubtractNumericalValues() { var df = LoadMSFT(); var actual = df.Zip<float, float, float>(df, (n1, n2) => n1 - n2).GetAllValues<float>().Sum(); Assert.AreEqual(0.0, actual); } } /* ---------------------------------------------------------------------------------- * Test data frame dynamic * --------------------------------------------------------------------------------*/ public class DynamicFrameTests { [Test] public static void CanAddSeriesDynamically() { for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right { var df = new FrameBuilder.Columns<int, string> { { "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.4} }.Series } }.Frame; dynamic dfd = df; dfd.Test1 = new[] { 1, 2 }; dfd.Test2 = df.GetSeries<double>("Test"); dfd.Test3 = new Dictionary<int, string> { { 1, "A" }, { 2, "B" } }; var row = df.Rows[2]; Assert.AreEqual(22.4, row["Test"]); Assert.AreEqual(2, row["Test1"]); Assert.AreEqual(22.4, row["Test2"]); Assert.AreEqual("B", ((KeyValuePair<int, string>)row["Test3"]).Value); } } [Test] public static void CanGetSeriesDynamically() { for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right { var df = new FrameBuilder.Columns<int, string> { { "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.2} }.Series } }.Frame; dynamic dfd = df; Series<int, double> s0 = dfd.Test; dynamic s1 = dfd.Test; Assert.AreEqual(11.1, s0[1]); Assert.AreEqual(11.1, s1[1]); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using Deedle; using System.Runtime.CompilerServices; using System.IO; namespace Deedle.CSharp.Tests { /* ---------------------------------------------------------------------------------- * Test calling Frame.Zip from C# * --------------------------------------------------------------------------------*/ public class FrameZipTests { public static Frame<int, string> LoadMSFT([CallerFilePath] string source = "") { var file = Path.Combine(Path.GetDirectoryName(source), @"..\Deedle.Tests\data\MSFT.csv"); return Frame.ReadCsv(file, inferRows:10); } [Test] public static void CanSubtractNumericalValues() { var df = LoadMSFT(); var actual = df.Zip<float, float, float>(df, (n1, n2) => n1 - n2).GetAllValues<float>().Sum(); Assert.AreEqual(0.0, actual); } } /* ---------------------------------------------------------------------------------- * Test data frame dynamic * --------------------------------------------------------------------------------*/ public class DynamicFrameTests { [Test] public static void CanAddSeriesDynamically() { for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right { var df = new FrameBuilder.Columns<int, string> { { "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.4} }.Series } }.Frame; dynamic dfd = df; dfd.Test1 = new[] { 1, 2 }; dfd.Test2 = df.GetSeries<double>("Test"); dfd.Test3 = new Dictionary<int, string> { { 1, "A" }, { 2, "B" } }; var row = df.Rows[2]; Assert.AreEqual(22.4, row["Test"]); Assert.AreEqual(2, row["Test1"]); Assert.AreEqual(22.4, row["Test2"]); Assert.AreEqual("B", ((KeyValuePair<int, string>)row["Test3"]).Value); } } [Test] public static void CanGetSeriesDynamically() { for (int i = 1; i <= 2; i++) // Run this twice, to check that instance references are right { var df = new FrameBuilder.Columns<int, string> { { "Test", new SeriesBuilder<int> { {1, 11.1}, {2,22.2} }.Series } }.Frame; dynamic dfd = df; Series<int, double> s0 = dfd.Test; dynamic s1 = dfd.Test; Assert.AreEqual(11.1, s0[1]); Assert.AreEqual(11.1, s1[1]); } } } }
bsd-2-clause
C#
dee514939f5e97f9f88a6f05df3ae6ae7364e70c
Move to modern nuget. Make Sprite compile by stubbing missing interface methods.
eylvisaker/AgateLib
AgateLib.Tests/UnitTests/Extensions/ListExtensions.cs
AgateLib.Tests/UnitTests/Extensions/ListExtensions.cs
using System.Collections.Generic; using AgateLib.Extensions.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AgateLib.UnitTests.Extensions { [TestClass] public class ListExtensions { [TestMethod] public void SortPrimitives() { List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 }; Assert.AreEqual(10, li.Count); li.InsertionSort(); for (int i = 0; i < li.Count; i++) Assert.AreEqual(i + 1, li[i]); } [TestMethod] public void InsertionSortTest() { List<int> list = new List<int> { 4, 2, 3, 1, 6, 7, 8, 9 }; list.InsertionSort(); Assert.AreEqual(1, list[0]); Assert.AreEqual(9, list[list.Count - 1]); } } }
using System.Collections.Generic; using AgateLib.Extensions.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AgateLib.UnitTests.Extensions { [TestClass] public class ListExtensions { [TestMethod] public void SortPrimitives() { List<int> li = new List<int> { 1, 6, 2, 3, 8, 10, 9, 7, 4, 5 }; Assert.AreEqual(10, li.Count); li.InsertionSort(); for (int i = 0; i < li.Count; i++) Assert.AreEqual(i + 1, li[i]); } } }
mit
C#
ac6dd367e638298e1fb832af208d66ba757b217f
Update to version number
ForkandBeard/Alferd-Spritesheet-Unpacker
ASU/Properties/AssemblyInfo.cs
ASU/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ASU")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ASU")] [assembly: AssemblyCopyright("Copyright © www.forkandbeard.co.uk 2014")] [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("e203a411-3418-4854-8dd6-feee98945489")] // 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("14.0.0.0")] [assembly: AssemblyFileVersion("14.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ASU")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ASU")] [assembly: AssemblyCopyright("Copyright © www.forkandbeard.co.uk 2014")] [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("e203a411-3418-4854-8dd6-feee98945489")] // 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("13.0.0.0")] [assembly: AssemblyFileVersion("13.0.0.0")]
mit
C#
e518dd8a960659ed0ec711f95e58331ed254c7f4
Add new file userAuth.cpl/Droid/MainActivity.cs
ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl
userAuth.cpl/Droid/MainActivity.cs
userAuth.cpl/Droid/MainActivity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } }
mit
C#
d487d341ed754b5ad8756a69e2d53936d88a92f7
Add new file userAuth.cpl/Droid/MainActivity.cs
ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl
userAuth.cpl/Droid/MainActivity.cs
userAuth.cpl/Droid/MainActivity.cs
� using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } namespace userAuth.cpl.Droid.WuickSort { } }
� using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } namespace }
mit
C#
a8b5b06755ab1e07c49c164d0307d82f15a4894f
Update MichaelRidland.cs
beraybentesen/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,MabroukENG/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin
src/Firehose.Web/Authors/MichaelRidland.cs
src/Firehose.Web/Authors/MichaelRidland.cs
using Firehose.Web.Infrastructure; using System; using System.Collections.Generic; namespace Firehose.Web.Authors { public class MichaelRidland : IAmAXamarinMVP { public string FirstName => "Michael"; public string LastName => "Ridland"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "michael@xam-consulting.com"; public string Title => "director of a Xamarin consultancy"; public Uri WebSite => new Uri("http://www.michaelridland.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://www.michaelridland.com/feed/"); } } public string TwitterHandle => "rid00z"; public DateTime FirstAwarded => new DateTime(2015, 4, 1); public string GravatarHash => ""; } }
using Firehose.Web.Infrastructure; using System; using System.Collections.Generic; namespace Firehose.Web.Authors { public class MichaelRidland : IAmAXamarinMVP { public string FirstName => "Michael"; public string LastName => "Ridland"; public string StateOrRegion => "Sydney, Australia"; public string EmailAddress => "michael@xam-consulting.com"; public string Title => "Xamarin Developer / Xamarin MVP"; public Uri WebSite => new Uri("http://www.michaelridland.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://www.michaelridland.com/feed/"); } } public string TwitterHandle => "rid00z"; public DateTime FirstAwarded => new DateTime(2015, 4, 1); public string GravatarHash => ""; } }
mit
C#
33d7a3e284d0da14898c56808f1020a89ca9cd1d
Update version number
HoLLy-HaCKeR/osu-BackgroundChanger
osu!BackgroundChanger/Properties/AssemblyInfo.cs
osu!BackgroundChanger/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("osu!BackgroundChanger")] [assembly: AssemblyDescription("Modifies osu!seasonal.dll to change your menu backgrounds without requiring supporter!")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("osu!BackgroundChanger")] [assembly: AssemblyCopyright("Copyright © HoLLy 2017")] [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("361d4adc-b684-4512-8f01-360ff7fb27b9")] // 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.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("osu!BackgroundChanger")] [assembly: AssemblyDescription("Modifies osu!seasonal.dll to change your menu backgrounds without requiring supporter!")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("osu!BackgroundChanger")] [assembly: AssemblyCopyright("Copyright © HoLLy 2017")] [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("361d4adc-b684-4512-8f01-360ff7fb27b9")] // 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.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
mit
C#
fd359989018e64754803479cd636166150b4a752
Update ObservableHelper.cs
keith-hall/reactive-animation
src/ObservableHelper.cs
src/ObservableHelper.cs
using System; using System.Drawing; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Windows.Forms; namespace ReactiveAnimation { public static class ObservableHelper { private static IObservable<Rectangle> PositionBasedOnControl<TEventArgs>(IObservable<EventPattern<object, TEventArgs>> events, Control ctrl, Func<Control, Rectangle> getNewPosition) where TEventArgs : EventArgs { return Observable.Defer(() => Observable.Repeat(getNewPosition(ctrl), 1)).Concat(events.Select(e => getNewPosition(ctrl)).ObserveOn(ctrl)); } public static IObservable<Rectangle> PositionBasedOnControl(Control ctrlDestination, Func<Control, Rectangle> getNewPosition) { return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrlDestination.Move += ev, ev => { if (ctrlDestination != null && !ctrlDestination.IsDisposed) ctrlDestination.Move -= ev; }), ctrlDestination, getNewPosition); } public static IObservable<Rectangle> PositionBasedOnParent(Control ctrl, Func<Control, Rectangle> getNewPosition) { return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrl.Parent.ClientSizeChanged += ev, ev => { if (ctrl != null && !ctrl.IsDisposed) ctrl.Parent.ClientSizeChanged -= ev; }), ctrl, getNewPosition); } /// <summary> /// convert a value to an observable that will never change /// </summary> /// <param name="constantValue">the fixed value</param> /// <returns>an observable with the constant value specified</returns> public static IObservable<T> FixedValue<T>(T constantValue) { return Enumerable.Repeat(constantValue, 1).ToObservable(); } /// <summary> /// get an observable rectangle that will contain a control's position relative to it's parent /// </summary> /// <param name="ctrl">the control</param> /// <returns>an observable with the position relative to it's parent</returns> public static IObservable<Rectangle> FixedPositionRelativeToParent(Control ctrl) { var ps = ctrl.Parent.ClientSize; var originalXPerc = (float)ctrl.Left / (float)ps.Width; var originalYPerc = (float)ctrl.Top / (float)ps.Height; return PositionBasedOnParent(ctrl, c => new Rectangle((int)((float)c.Parent.ClientSize.Width * originalXPerc), (int)((float)c.Parent.ClientSize.Height * originalYPerc), c.Width, c.Height)); } /// <summary> /// get an observable coupled with it's previous value /// </summary> /// <param name="source">the source observable</param> /// <param name="projection">the projection to apply to get the output</param> /// <returns>an observable coupled with it's previous value</returns> public static IObservable<TOutput> ObserveWithPrevious<TSource, TOutput> (IObservable<TSource> source, Func<TSource, TSource, TOutput> projection) { return source.Scan(Tuple.Create(default(TSource), default(TSource)), (previous, current) => projection(previous.Item2, current)); } } }
using System; using System.Drawing; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Windows.Forms; namespace ReactiveAnimation { public static class ObservableHelper { private static IObservable<Rectangle> PositionBasedOnControl<TEventArgs>(IObservable<EventPattern<object, TEventArgs>> events, Control ctrl, Func<Control, Rectangle> getNewPosition) where TEventArgs : EventArgs { return Observable.Defer(() => Observable.Repeat(getNewPosition(ctrl), 1)).Concat(events.Select(e => getNewPosition(ctrl)).ObserveOn(ctrl)); } public static IObservable<Rectangle> PositionBasedOnControl(Control ctrlDestination, Func<Control, Rectangle> getNewPosition) { return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrlDestination.Move += ev, ev => { if (ctrlDestination != null && !ctrlDestination.IsDisposed) ctrlDestination.Move -= ev; }), ctrlDestination, getNewPosition); } public static IObservable<Rectangle> PositionBasedOnParent(Control ctrl, Func<Control, Rectangle> getNewPosition) { return PositionBasedOnControl(Observable.FromEventPattern(ev => ctrl.Parent.ClientSizeChanged += ev, ev => { if (ctrl != null && !ctrl.IsDisposed) ctrl.Parent.ClientSizeChanged -= ev; }), ctrl, getNewPosition); } /// <summary> /// convert a value to an observable that will never change /// </summary> /// <param name="constantValue">the fixed value</param> /// <returns>an observable with the constant value specified</returns> public static IObservable<T> FixedValue<T>(T constantValue) { return Enumerable.Repeat(constantValue, 1).ToObservable(); } /// <summary> /// get an observable rectangle that will contain a control's position relative to it's parent /// </summary> /// <param name="ctrl">the control</param> /// <returns>an observable with the position relative to it's parent</returns> public static IObservable<Rectangle> FixedPositionRelativeToParent(Control ctrl) { var ps = ctrl.Parent.ClientSize; var originalXPerc = (float)ctrl.Left / (float)ps.Width; var originalYPerc = (float)ctrl.Top / (float)ps.Height; return PositionBasedOnParent(ctrl, c => new Rectangle((int)((float)c.Parent.ClientSize.Width * originalXPerc), (int)((float)c.Parent.ClientSize.Height * originalYPerc), c.Width, c.Height)); } } }
apache-2.0
C#
5d75e9bc30c2d2dbdabab8317b5b22b1fa973cab
set version
rodkings/Untappd.Net,tparnell8/Untappd.Net,tparnell8/Untappd.Net,rodkings/Untappd.Net
src/Untappd.Net/Properties/AssemblyInfo.cs
src/Untappd.Net/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Untappd.Net")] [assembly: AssemblyDescription("C# Untappd Wrapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tommy Parnell")] [assembly: AssemblyProduct("Untappd.Net")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d8571a44-2e86-43a3-b64a-2364614c6934")] // 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("0.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Untappd.Net")] [assembly: AssemblyDescription("C# Untappd Wrapper")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Tommy Parnell")] [assembly: AssemblyProduct("Untappd.Net")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d8571a44-2e86-43a3-b64a-2364614c6934")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
1555b07dd4d094c7c125e7764e9789ccb2c9f1d4
Use var. Rider finally understands it here ;)
jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr,jp7677/hellocoreclr
src/HelloCoreClrApp/WebApi/Actions/SayHelloWorldAction.cs
src/HelloCoreClrApp/WebApi/Actions/SayHelloWorldAction.cs
using System.Threading.Tasks; using HelloCoreClrApp.Data; using HelloCoreClrApp.WebApi.Messages; using Serilog; namespace HelloCoreClrApp.WebApi.Actions { public class SayHelloWorldAction : ISayHelloWorldAction { private static readonly ILogger Log = Serilog.Log.ForContext<SayHelloWorldAction>(); private readonly IDataService dataService; public SayHelloWorldAction(IDataService dataService) { this.dataService = dataService; } public async Task<SayHelloWorldResponse> Execute(string name) { Log.Information("Calculating result."); var res = Rules.SayHelloWorldRule.Process(name); if (res.Item2) await SaveGreeting(res.Item1); return new SayHelloWorldResponse { Greeting = res.Item1 }; } private async Task SaveGreeting(string greeting) { Log.Information("Save greeting."); await dataService.SaveGreeting(greeting); } } }
using System; using System.Threading.Tasks; using HelloCoreClrApp.Data; using HelloCoreClrApp.WebApi.Messages; using Serilog; namespace HelloCoreClrApp.WebApi.Actions { public class SayHelloWorldAction : ISayHelloWorldAction { private static readonly ILogger Log = Serilog.Log.ForContext<SayHelloWorldAction>(); private readonly IDataService dataService; public SayHelloWorldAction(IDataService dataService) { this.dataService = dataService; } public async Task<SayHelloWorldResponse> Execute(string name) { Log.Information("Calculating result."); Tuple<string, bool> res = Rules.SayHelloWorldRule.Process(name); if (res.Item2) await SaveGreeting(res.Item1); return new SayHelloWorldResponse { Greeting = res.Item1 }; } private async Task SaveGreeting(string greeting) { Log.Information("Save greeting."); await dataService.SaveGreeting(greeting); } } }
mit
C#
d9b1bfc98f58dcbde14f924c02b3335950a22c77
Fix Fault with GameObject injection
HelloKitty/SceneJect,HelloKitty/SceneJect
src/SceneJect.Common/Services/DefaultGameObjectFactory.cs
src/SceneJect.Common/Services/DefaultGameObjectFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Common { public class DefaultGameObjectFactory : IGameObjectFactory { /// <summary> /// Service for resolving dependencies. /// </summary> private IResolver resolverService { get; } public DefaultGameObjectFactory(IResolver resolver) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); resolverService = resolver; } /// <summary> /// Creates an empty <see cref="GameObject"/>. /// </summary> /// <returns>A non-null empty <see cref="GameObject"/>.</returns> public GameObject Create() { //Default GameObjects don't require dependencies return new GameObject(); } /// <summary> /// Creates an instance of the prefab <see cref="GameObject"/>. /// </summary> /// <param name="prefab">Prefab to create an instance of.</param> /// <returns>A non-null instance of the provided <see cref="GameObject"/> <paramref name="prefab"/>.</returns> public GameObject Create(GameObject prefab) { //Create the GameObject and inject dependencies return InjectDependencies(GameObject.Instantiate(prefab)); } private GameObject InjectDependencies(GameObject obj) { //Now inject dependencies into its components InjecteeLocator<MonoBehaviour> injecteeLocator = new InjecteeLocator<MonoBehaviour>(obj); foreach (MonoBehaviour mb in injecteeLocator) { Injector injecter = new Injector(mb, resolverService); injecter.Inject(); } return obj; } /// <summary> /// Creates an instance of the prefab <see cref="GameObject"/> with the provided position and rotation. /// </summary> /// <param name="prefab">Prefab to create an instance of.</param> /// <returns>A non-null instance of the provided <see cref="GameObject"/> <paramref name="prefab"/>.</returns> public GameObject Create(GameObject prefab, Vector3 position, Quaternion rotation) { return InjectDependencies(GameObject.Instantiate(prefab, position, rotation) as GameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; namespace SceneJect.Common { public class DefaultGameObjectFactory : IGameObjectFactory { /// <summary> /// Service for resolving dependencies. /// </summary> private IResolver resolverService { get; } public DefaultGameObjectFactory(IResolver resolver) { if (resolver == null) throw new ArgumentNullException(nameof(resolver), $"Provided {nameof(IResolver)} service provided is null."); resolverService = resolver; } /// <summary> /// Creates an empty <see cref="GameObject"/>. /// </summary> /// <returns>A non-null empty <see cref="GameObject"/>.</returns> public GameObject Create() { //Default GameObjects don't require dependencies return new GameObject(); } /// <summary> /// Creates an instance of the prefab <see cref="GameObject"/>. /// </summary> /// <param name="prefab">Prefab to create an instance of.</param> /// <returns>A non-null instance of the provided <see cref="GameObject"/> <paramref name="prefab"/>.</returns> public GameObject Create(GameObject prefab) { //Create the GameObject and inject dependencies return InjectDependencies(GameObject.Instantiate(prefab)); } private GameObject InjectDependencies(GameObject obj) { //Now inject dependencies into its components InjecteeLocator<MonoBehaviour> injecteeLocator = new InjecteeLocator<MonoBehaviour>(obj); foreach (MonoBehaviour mb in injecteeLocator) { Injector injecter = new Injector(obj, resolverService); injecter.Inject(); } return obj; } /// <summary> /// Creates an instance of the prefab <see cref="GameObject"/> with the provided position and rotation. /// </summary> /// <param name="prefab">Prefab to create an instance of.</param> /// <returns>A non-null instance of the provided <see cref="GameObject"/> <paramref name="prefab"/>.</returns> public GameObject Create(GameObject prefab, Vector3 position, Quaternion rotation) { return InjectDependencies(GameObject.Instantiate(prefab, position, rotation) as GameObject); } } }
mit
C#
b0ccd614805c9d89dc1da5f3e5fb5b43ab164dd1
Fix weird code formatting
UselessToucan/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,smoogipoo/osu,NeoAdonis/osu,ZLima12/osu,naoey/osu,2yangk23/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,ZLima12/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,naoey/osu,johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,smoogipooo/osu,naoey/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu
build.cake
build.cake
#addin "nuget:?package=CodeFileSanity&version=0.0.21" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2018.2.2" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var osuSolution = new FilePath("./osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Restore") .Does(() => { DotNetCoreRestore(osuSolution.FullPath); }); Task("Compile") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(osuSolution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, NoRestore = true, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles("**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(nVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
#addin "nuget:?package=CodeFileSanity&version=0.0.21" #addin "nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2018.2.2" #tool "nuget:?package=NVika.MSBuild&version=1.0.1" /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var osuSolution = new FilePath("./osu.sln"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Restore") .Does(() => { DotNetCoreRestore(osuSolution.FullPath); }); Task("Compile") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(osuSolution.FullPath, new DotNetCoreBuildSettings { Configuration = configuration, NoRestore = true, }); }); Task("Test") .IsDependentOn("Compile") .Does(() => { var testAssemblies = GetFiles("**/*.Tests/bin/**/*.Tests.dll"); DotNetCoreVSTest(testAssemblies, new DotNetCoreVSTestSettings { Logger = AppVeyor.IsRunningOnAppVeyor ? "Appveyor" : $"trx", Parallel = true, ToolTimeout = TimeSpan.FromMinutes(10), }); }); // windows only because both inspectcore and nvika depend on net45 Task("InspectCode") .WithCriteria(IsRunningOnWindows()) .IsDependentOn("Compile") .Does(() => { var nVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(nVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
mit
C#
3d74b9de81b9be46bdb7d4d1f3cf8641d670995f
Fix Cake script not running tests from SimpSim.NET.Tests project.
ryanjfitz/SimpSim.NET
build.cake
build.cake
#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore("SimpSim.NET.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration)); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { DotNetCoreTest("./SimpSim.NET.Tests/SimpSim.NET.Tests.csproj"); NUnit3("./**/bin/" + configuration + "/SimpSim.NET.Presentation.Tests.dll", new NUnit3Settings { NoResults = true }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#tool nuget:?package=NUnit.ConsoleRunner&version=3.4.0 ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Restore-NuGet-Packages") .Does(() => { NuGetRestore("SimpSim.NET.sln"); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { MSBuild("SimpSim.NET.sln", settings => settings.SetConfiguration(configuration)); }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { NUnit3("./**/bin/" + configuration + "/*.Tests.dll", new NUnit3Settings { NoResults = true }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
mit
C#
1f82f34e44e86ef67e8b07d879fb8d019f8c8ff6
Fix broken dnu restore
jamesqo/flavor.net,jamesqo/flavor.net
build.cake
build.cake
var target = Argument("target", "Default"); var config = Argument("configuration", "Release"); Task("Restore") .Does(() => { var files = GetFiles("**/project.json"); foreach (var file in files) DNURestore(file); }); Task("Build") .IsDependentOn("Restore") .Does(() => { MSBuild("flavor.net.sln", new MSBuildSettings() .SetConfiguration(config)); }); Task("Test") .Does(() => { var format = "artifacts/bin/flavor.net.tests/{0}/**/flavor.net.tests.dll"; var pattern = string.Format(format, config); XUnit2(GetFiles(pattern)); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test"); Task("Publish") .IsDependentOn("Default") .Does(() => { var format = "artifacts/bin/flavor.net/{0}/flavor.net.*.nupkg"; var pattern = string.Format(format, config); var package = GetFiles(pattern) .Select(f => f.FullPath) .Single(p => !p.EndsWith("symbols.nupkg")); NuGetPush(package, new NuGetPushSettings()); }); RunTarget(target);
var target = Argument("target", "Default"); var config = Argument("configuration", "Release"); Task("Build") .Does(() => { DNURestore(); MSBuild("flavor.net.sln", new MSBuildSettings() .SetConfiguration(config)); }); Task("Test") .Does(() => { var pattern = string.Format("artifacts/bin/flavor.net.tests/{0}/**/flavor.net.tests.dll", config); XUnit2(GetFiles(pattern)); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test"); Task("Publish") .IsDependentOn("Default") .Does(() => { var pattern = string.Format("artifacts/bin/flavor.net/{0}/flavor.net.*.nupkg", config); var package = GetFiles(pattern) .Select(f => f.FullPath) .Single(p => !p.EndsWith("symbols.nupkg")); NuGetPush(package, new NuGetPushSettings()); }); RunTarget(target);
bsd-2-clause
C#
f47751bd7f9e4f1649bc7e7b57280d14de2344e0
add build step
IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.5.0"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Build /////////////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration, }; var projects = GetFiles("./src/**/*.csproj"); foreach(var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.5.0"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
a94224c5014121b0f47d36883da5e7f4b8c24f14
Remove extra newline
braintree/braintree_dotnet,scottmeyer/braintree_dotnet,scottmeyer/braintree_dotnet,scottmeyer/braintree_dotnet,scottmeyer/braintree_dotnet,braintree/braintree_dotnet
Braintree/Disbursement.cs
Braintree/Disbursement.cs
using System; using System.Collections; using System.Collections.Generic; namespace Braintree { public class Disbursement { public virtual string Id { get; protected set; } public virtual decimal? Amount { get; protected set; } public virtual string ExceptionMessage { get; protected set; } public virtual DateTime? DisbursementDate { get; protected set; } public virtual string FollowUpAction { get; protected set; } public virtual MerchantAccount MerchantAccount { get; protected set; } public virtual List<string> TransactionIds { get; protected set; } public virtual bool? Success { get; protected set; } public virtual bool? Retry { get; protected set; } private IBraintreeGateway gateway; public Disbursement(NodeWrapper node, IBraintreeGateway gateway) { Id = node.GetString("id"); Amount = node.GetDecimal("amount"); ExceptionMessage = node.GetString("exception-message"); DisbursementDate = node.GetDateTime("disbursement-date"); FollowUpAction = node.GetString("follow-up-action"); MerchantAccount = new MerchantAccount(node.GetNode("merchant-account")); TransactionIds = new List<string>(); foreach (var stringNode in node.GetList("transaction-ids/item")) { TransactionIds.Add(stringNode.GetString(".")); } Success = node.GetBoolean("success"); Retry = node.GetBoolean("retry"); this.gateway = gateway; } [Obsolete("Mock Use Only")] protected internal Disbursement() { } public virtual ResourceCollection<Transaction> Transactions() { var gateway = new TransactionGateway(this.gateway); var searchRequest = new TransactionSearchRequest(). Ids.IncludedIn(TransactionIds.ToArray()); return gateway.Search(searchRequest); } } }
using System; using System.Collections; using System.Collections.Generic; namespace Braintree { public class Disbursement { public virtual string Id { get; protected set; } public virtual decimal? Amount { get; protected set; } public virtual string ExceptionMessage { get; protected set; } public virtual DateTime? DisbursementDate { get; protected set; } public virtual string FollowUpAction { get; protected set; } public virtual MerchantAccount MerchantAccount { get; protected set; } public virtual List<string> TransactionIds { get; protected set; } public virtual bool? Success { get; protected set; } public virtual bool? Retry { get; protected set; } private IBraintreeGateway gateway; public Disbursement(NodeWrapper node, IBraintreeGateway gateway) { Id = node.GetString("id"); Amount = node.GetDecimal("amount"); ExceptionMessage = node.GetString("exception-message"); DisbursementDate = node.GetDateTime("disbursement-date"); FollowUpAction = node.GetString("follow-up-action"); MerchantAccount = new MerchantAccount(node.GetNode("merchant-account")); TransactionIds = new List<string>(); foreach (var stringNode in node.GetList("transaction-ids/item")) { TransactionIds.Add(stringNode.GetString(".")); } Success = node.GetBoolean("success"); Retry = node.GetBoolean("retry"); this.gateway = gateway; } [Obsolete("Mock Use Only")] protected internal Disbursement() { } public virtual ResourceCollection<Transaction> Transactions() { var gateway = new TransactionGateway(this.gateway); var searchRequest = new TransactionSearchRequest(). Ids.IncludedIn(TransactionIds.ToArray()); return gateway.Search(searchRequest); } } }
mit
C#
49ca151d1dd74c2290e1f7e96d15b4048801f64d
Clean more tests directories.
mono/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000,jonathanpeppers/Embeddinator-4000,mono/Embeddinator-4000,mono/Embeddinator-4000
build.cake
build.cake
#!mono .cake/Cake/Cake.exe #tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); #load "build/Utils.cake" #load "build/Android.cake" #load "build/Tests.cake" #load "build/Packaging.cake" Task("Clean") .Does(() => { CleanDirectory("./build/lib"); CleanDirectory("./build/obj"); CleanDirectories("./tests/common/c"); CleanDirectories("./tests/common/java"); CleanDirectories("./tests/common/mk"); CleanDirectories(GetDirectories("./tests/**/obj")); CleanDirectories(GetDirectories("./tests/**/bin")); CleanDirectories(GetDirectories("./tests/android/**/build")); }); Task("NuGet-Restore") .Does(() => { NuGetRestore("./Embeddinator-4000.sln"); }); Task("Build-Binder") .IsDependentOn("Clean") .IsDependentOn("Generate-Project-Files") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./build/projects/Embeddinator-4000.csproj", settings => settings.SetConfiguration(configuration).SetVerbosity(Verbosity.Minimal)); }); Task("Generate-Project-Files") .Does(() => { var os = IsRunningOnWindows() ? "windows" : "macosx"; Premake(File("./build/premake5.lua"), $"--outdir=.. --os={os}", "vs2015"); }); Task("Default") .IsDependentOn("Build-Binder"); Task("AppVeyor") .IsDependentOn("Generate-Android") .IsDependentOn("Generate-Android-PCL") .IsDependentOn("Generate-Android-NetStandard") .IsDependentOn("Generate-Android-FSharp") .IsDependentOn("Build-CSharp-Tests"); Task("Travis") .IsDependentOn("Build-Binder") .IsDependentOn("Build-C-Tests"); RunTarget(target);
#!mono .cake/Cake/Cake.exe #tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); #load "build/Utils.cake" #load "build/Android.cake" #load "build/Tests.cake" #load "build/Packaging.cake" Task("Clean") .Does(() => { CleanDirectory("./build/lib"); CleanDirectory("./build/obj"); CleanDirectories(GetDirectories("./tests/**/obj")); CleanDirectories(GetDirectories("./tests/**/bin")); CleanDirectories(GetDirectories("./tests/android/**/build")); }); Task("NuGet-Restore") .Does(() => { NuGetRestore("./Embeddinator-4000.sln"); }); Task("Build-Binder") .IsDependentOn("Clean") .IsDependentOn("Generate-Project-Files") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./build/projects/Embeddinator-4000.csproj", settings => settings.SetConfiguration(configuration).SetVerbosity(Verbosity.Minimal)); }); Task("Generate-Project-Files") .Does(() => { var os = IsRunningOnWindows() ? "windows" : "macosx"; Premake(File("./build/premake5.lua"), $"--outdir=.. --os={os}", "vs2015"); }); Task("Default") .IsDependentOn("Build-Binder"); Task("AppVeyor") .IsDependentOn("Generate-Android") .IsDependentOn("Generate-Android-PCL") .IsDependentOn("Generate-Android-NetStandard") .IsDependentOn("Generate-Android-FSharp") .IsDependentOn("Build-CSharp-Tests"); Task("Travis") .IsDependentOn("Build-Binder") .IsDependentOn("Build-C-Tests"); RunTarget(target);
mit
C#
eeff886c0b7a4b286a6e3941d257ddfbca9ba6ed
Adjust settings in cake
jamesmontemagno/Censored,jamesmontemagno/Censored
build.cake
build.cake
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Default").Does (() => { NuGetRestore ("./Censored.sln"); DotNetBuild ("./Censored.sln", c => c.Configuration = "Release"); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./Censored.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Default").Does (() => { NuGetRestore ("./Censored.sln"); DotNetBuild ("./Censored.sln", c => c.Configuration = "Release"); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./Censored.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./" }); }); RunTarget (TARGET);
mit
C#
33ac9a51b0b0db3d5f32e08704dfd5438aeb1ba5
Fix for new Boo assemblies.
codechip/rhino-tools,brumschlag/rhino-tools,brumschlag/rhino-tools,codechip/rhino-tools
rhino-dsl/Rhino.DSL.Tests/OrderDSL/BaseOrderActionsDSL.cs
rhino-dsl/Rhino.DSL.Tests/OrderDSL/BaseOrderActionsDSL.cs
namespace Rhino.DSL.Tests.OrderDSL { using System.Collections; using System.Collections.Specialized; using Boo.Lang; using Boo.Lang.Compiler.Ast; public abstract class BaseOrderActionsDSL { public delegate bool Condition(); public delegate void Action(); protected OrderedDictionary conditionsAndActions = new OrderedDictionary(); public User User; public Order Order; public decimal discountPrecentage; public bool shouldSuggestUpgradeToPreferred; public bool shouldApplyFreeShipping; protected void addDiscountPrecentage(decimal precentage) { this.discountPrecentage = precentage; } protected void suggestUpgradeToPreferred() { shouldSuggestUpgradeToPreferred = true; } protected void applyFreeShipping() { shouldApplyFreeShipping = true; } [Meta] public static Expression when(Expression expression, Expression action) { BlockExpression condition = new BlockExpression(); condition.Body.Add(new ReturnStatement(expression)); return new MethodInvocationExpression( new ReferenceExpression("When"), condition, action ); } protected void When(Condition condition, Action action) { conditionsAndActions[condition] = action; } public abstract void Prepare(); public void Execute() { foreach (DictionaryEntry entry in conditionsAndActions) { Condition condition = (Condition) entry.Key; if(condition()) { Action action = (Action) entry.Value; action(); break; } } } } }
namespace Rhino.DSL.Tests.OrderDSL { using System.Collections; using System.Collections.Specialized; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.MetaProgramming; public abstract class BaseOrderActionsDSL { public delegate bool Condition(); public delegate void Action(); protected OrderedDictionary conditionsAndActions = new OrderedDictionary(); public User User; public Order Order; public decimal discountPrecentage; public bool shouldSuggestUpgradeToPreferred; public bool shouldApplyFreeShipping; protected void addDiscountPrecentage(decimal precentage) { this.discountPrecentage = precentage; } protected void suggestUpgradeToPreferred() { shouldSuggestUpgradeToPreferred = true; } protected void applyFreeShipping() { shouldApplyFreeShipping = true; } [Meta] public static Expression when(Expression expression, Expression action) { BlockExpression condition = new BlockExpression(); condition.Body.Add(new ReturnStatement(expression)); return new MethodInvocationExpression( new ReferenceExpression("When"), condition, action ); } protected void When(Condition condition, Action action) { conditionsAndActions[condition] = action; } public abstract void Prepare(); public void Execute() { foreach (DictionaryEntry entry in conditionsAndActions) { Condition condition = (Condition) entry.Key; if(condition()) { Action action = (Action) entry.Value; action(); break; } } } } }
bsd-3-clause
C#
7184590828de769a53ce890f775df147502ecec1
resolve correct name for RoleNameSetter
eShopWorld/devopsflex-telemetry
src/DevOpsFlex.Telemetry/Processors/RoleNameSetter.cs
src/DevOpsFlex.Telemetry/Processors/RoleNameSetter.cs
namespace DevOpsFlex.Telemetry.Processors { using System; using JetBrains.Annotations; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; /// <summary> /// Sets the 'cloud_RoleName' role name attribute on a AI telemetry item /// </summary> /// <remarks>See https://docs.microsoft.com/en-us/azure/application-insights/app-insights-monitor-multi-role-apps </remarks> /// <example> /// &lt;TelemetryProcessors&gt; /// &lt;!-- Insert this in ApplicationInsights.config --&gt; /// &lt;Add Type="DevOpsFlex.Telemetry.RoleNameSetter, DevOpsFlex.Telemetry"&gt; /// &lt;RoleName>MyApplication&lt;/RoleName&gt; /// &lt;/Add&gt; /// &lt;/TelemetryProcessors&gt; /// /// // OR /// // alternatively, you can initialize the filter in code. In an initialization class (Global.asax.cs) - insert the processor into the chain: /// /// var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder; /// builder.Use((next) => new RoleNameSetter(next) { RoleName = "MyApplication" }); /// builder.Build(); /// </example> public class RoleNameSetter : ITelemetryProcessor { public static string RoleName { get; set; } private ITelemetryProcessor Next { get; } public RoleNameSetter([NotNull] ITelemetryProcessor next) { #if DEBUG Next = next ?? throw new ArgumentNullException(nameof(next)); #endif RoleName = System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name; // this will not resolve for an ASP.NET application. } public void Process(ITelemetry item) { if (item?.Context != null) { if (string.IsNullOrWhiteSpace(item.Context.Cloud.RoleName)) item.Context.Cloud.RoleName = RoleName; } Next.Process(item); } } }
namespace DevOpsFlex.Telemetry.Processors { using System; using JetBrains.Annotations; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.Extensibility; /// <summary> /// Sets the 'cloud_RoleName' role name attribute on a AI telemetry item /// </summary> /// <remarks>See https://docs.microsoft.com/en-us/azure/application-insights/app-insights-monitor-multi-role-apps </remarks> /// <example> /// &lt;TelemetryProcessors&gt; /// &lt;!-- Insert this in ApplicationInsights.config --&gt; /// &lt;Add Type="DevOpsFlex.Telemetry.RoleNameSetter, DevOpsFlex.Telemetry"&gt; /// &lt;RoleName>MyApplication&lt;/RoleName&gt; /// &lt;/Add&gt; /// &lt;/TelemetryProcessors&gt; /// /// // OR /// // alternatively, you can initialize the filter in code. In an initialization class (Global.asax.cs) - insert the processor into the chain: /// /// var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder; /// builder.Use((next) => new RoleNameSetter(next) { RoleName = "MyApplication" }); /// builder.Build(); /// </example> public class RoleNameSetter : ITelemetryProcessor { public static string RoleName { get; set; } private ITelemetryProcessor Next { get; } public RoleNameSetter([NotNull] ITelemetryProcessor next) { #if DEBUG Next = next ?? throw new ArgumentNullException(nameof(next)); #endif RoleName = System.Reflection.Assembly.GetEntryAssembly()?.FullName; // this will not resolve for an ASP.NET application. } public void Process(ITelemetry item) { if (item?.Context != null) { if (string.IsNullOrWhiteSpace(item.Context.Cloud.RoleName)) item.Context.Cloud.RoleName = RoleName; } Next.Process(item); } } }
mit
C#
d2482c8db3a7efcecf40327f9750d39a2a83d94e
add column menu to grid
arst/SimplCommerce,simplcommerce/SimplCommerce,simplcommerce/SimplCommerce,arst/SimplCommerce,simplcommerce/SimplCommerce,arst/SimplCommerce,arst/SimplCommerce,simplcommerce/SimplCommerce
src/HvCommerce.Web/Areas/Admin/Views/User/List.cshtml
src/HvCommerce.Web/Areas/Admin/Views/User/List.cshtml
<h1 class="page-header">Danh sach nguoi dung</h1> @(Html.Kendo().Grid<HvCommerce.Web.Areas.Admin.ViewModels.UserList>() .Name("gridUser") .Columns(columns => { columns.Bound(p => p.Email); columns.Bound(p => p.FullName); columns.Bound(p => p.CreatedOn).Format("{0:dd/MMM/yyyy hh:mm:ss}"); columns.Bound(p => p.Id) .ClientTemplate(@"<a href='Detail/#:Id#' title='Xem chi tiết' class='btn btn-xs btn-info'> <span class='glyphicon glyphicon-circle-arrow-right'</span></a> <a href='Delete/#:Id#' title='Xóa' class='btn btn-danger btn-xs delete'> <span class='glyphicon glyphicon-remove'></span></a>") .Filterable(false).Sortable(false).Title("Actions").Width(150); }) .Pageable() .Sortable() .ColumnMenu() .Filterable(ftb => ftb.Mode(GridFilterMode.Row)) .DataSource(dataSource => dataSource .Ajax() .Sort(sort => sort.Add(x => x.CreatedOn).Descending()) .Read(read => read.Url("ListAjax")) ) ) @section scripts { <script type="text/javascript"> $(function () { $("#gridUser").on("click", ".delete", function (e) { e.preventDefault(); if (confirm("Bạn muốn xóa mục này?")) { $.post(this.href).success(function () { var grid = $("#gridUser").data("kendoGrid"); grid.dataSource.read(); }); } }); }); </script> }
<h1 class="page-header">Danh sach nguoi dung</h1> @(Html.Kendo().Grid<HvCommerce.Web.Areas.Admin.ViewModels.UserList>() .Name("gridUser") .Columns(columns => { columns.Bound(p => p.Email); columns.Bound(p => p.FullName); columns.Bound(p => p.CreatedOn).Format("{0:dd/MMM/yyyy hh:mm:ss}"); columns.Bound(p => p.Id) .ClientTemplate(@"<a href='Detail/#:Id#' title='Xem chi tiết' class='btn btn-xs btn-info'> <span class='glyphicon glyphicon-circle-arrow-right'</span></a> <a href='Delete/#:Id#' title='Xóa' class='btn btn-danger btn-xs delete'> <span class='glyphicon glyphicon-remove'></span></a>") .Filterable(false).Sortable(false).Title(" ").Width(150); }) .Pageable() .Sortable() .Filterable(ftb => ftb.Mode(GridFilterMode.Row)) .DataSource(dataSource => dataSource .Ajax() .Sort(sort => sort.Add(x => x.CreatedOn).Descending()) .Read(read => read.Url("ListAjax")) ) ) @section scripts { <script type="text/javascript"> $(function () { $("#gridUser").on("click", ".delete", function (e) { e.preventDefault(); if (confirm("Bạn muốn xóa mục này?")) { $.post(this.href).success(function () { var grid = $("#gridUser").data("kendoGrid"); grid.dataSource.read(); }); } }); }); </script> }
apache-2.0
C#
e2fb803bb27829658af2dbc65054af1c8bf21d34
add datetime to page generated from mvc
fsprojects/fsharp-dnx,fsprojects/fsharp-dnx
sample/HelloMvc/EmbeddedResources/Views/Home/Index.cshtml
sample/HelloMvc/EmbeddedResources/Views/Home/Index.cshtml
<h1>Hello from F#</h1> <h2>(by Razor)</h2> Page generated: @Html.Encode(string.Format("{0}", System.DateTime.Now))
<h1>Hello from F#</h1> <h2>(by Razor)</h2>
apache-2.0
C#
9e6d325561ef4e92d9976d78437047256d67a7a3
Update SpellingLanguages.cs
punker76/Markdown-Edit,mike-ward/Markdown-Edit
src/MarkdownEdit/SpellCheck/SpellingLanguages.cs
src/MarkdownEdit/SpellCheck/SpellingLanguages.cs
using System.ComponentModel; namespace MarkdownEdit.SpellCheck { public enum SpellingLanguages { [Description("English (Australia)")] Australian, [Description("English (Canada)")] Canadian, [Description("English (United Kingdom)")] UnitedKingdom, [Description("English (United States)")] UnitedStates, [Description("German (Germany)")] Germany, [Description("Spanish (Spain)")] Spain, [Description("Russian (Russia)")] Russian, [Description("Danish (Denmark)")] Denmark } }
using System.ComponentModel; namespace MarkdownEdit.SpellCheck { public enum SpellingLanguages { [Description("English (Australia)")] Australian, [Description("English (Canada)")] Canadian, [Description("English (United Kingdom)")] UnitedKingdom, [Description("English (United States)")] UnitedStates, [Description("German (Germany)")] Germany, [Description("Spanish (Spain)")] Spain, [Description("Russian (Russia)")] Russian, [Description("Danish (Denmark)")] Denmark [Description("Swedish (Sweden)")] Sweden } }
mit
C#
2a93ad20464d37d5806564bfdafb2eff09424691
Drop default build target (help is helpful).
FacilityApi/FacilityJavaScript,FacilityApi/FacilityJavaScript,FacilityApi/Facility,FacilityApi/FacilityCSharp,FacilityApi/FacilityJavaScript
tools/Build/Build.cs
tools/Build/Build.cs
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Faithlife.Build; using static Faithlife.Build.AppRunner; using static Faithlife.Build.BuildUtility; using static Faithlife.Build.DotNetRunner; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { var codegen = "fsdgen___"; var dotNetTools = new DotNetTools(Path.Combine("tools", "bin")).AddSource(Path.Combine("tools", "bin")); var dotNetBuildSettings = new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("FacilityApiBot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("FacilityApiBot", "facilityapi@gmail.com"), SourceCodeUrl = "https://github.com/FacilityApi/RepoName/tree/master/src", }, DotNetTools = dotNetTools, ProjectUsesSourceLink = name => !name.StartsWith("fsdgen", StringComparison.Ordinal), }; build.AddDotNetTargets(dotNetBuildSettings); build.Target("codegen") .DependsOn("build") .Does(() => codeGen(verify: false)); build.Target("verify-codegen") .DependsOn("build") .Does(() => codeGen(verify: true)); build.Target("test") .DependsOn("verify-codegen"); void codeGen(bool verify) { string configuration = dotNetBuildSettings.BuildOptions.ConfigurationOption.Value; string versionSuffix = $"cg{DateTime.UtcNow:yyyyMMddHHmmss}"; RunDotNet("pack", Path.Combine("src", codegen, $"{codegen}.csproj"), "-c", configuration, "--no-build", "--output", Path.GetFullPath(Path.Combine("tools", "bin")), "--version-suffix", versionSuffix); string packagePath = FindFiles($"tools/bin/{codegen}.*-{versionSuffix}.nupkg").Single(); string packageVersion = Regex.Match(packagePath, @"[/\\][^/\\]*\.([0-9]+\.[0-9]+\.[0-9]+(-.+)?)\.nupkg$").Groups[1].Value; string toolPath = dotNetTools.GetToolPath($"{codegen}/{packageVersion}"); string verifyOption = verify ? "--verify" : null; RunApp(toolPath, "___", "___", verifyOption); } }); }
using System; using System.IO; using System.Linq; using System.Text.RegularExpressions; using Faithlife.Build; using static Faithlife.Build.AppRunner; using static Faithlife.Build.BuildUtility; using static Faithlife.Build.DotNetRunner; internal static class Build { public static int Main(string[] args) => BuildRunner.Execute(args, build => { var codegen = "fsdgen___"; var dotNetTools = new DotNetTools(Path.Combine("tools", "bin")).AddSource(Path.Combine("tools", "bin")); var dotNetBuildSettings = new DotNetBuildSettings { DocsSettings = new DotNetDocsSettings { GitLogin = new GitLoginInfo("FacilityApiBot", Environment.GetEnvironmentVariable("BUILD_BOT_PASSWORD") ?? ""), GitAuthor = new GitAuthorInfo("FacilityApiBot", "facilityapi@gmail.com"), SourceCodeUrl = "https://github.com/FacilityApi/RepoName/tree/master/src", }, DotNetTools = dotNetTools, ProjectUsesSourceLink = name => !name.StartsWith("fsdgen", StringComparison.Ordinal), }; build.AddDotNetTargets(dotNetBuildSettings); build.Target("codegen") .DependsOn("build") .Does(() => codeGen(verify: false)); build.Target("verify-codegen") .DependsOn("build") .Does(() => codeGen(verify: true)); build.Target("test") .DependsOn("verify-codegen"); build.Target("default") .DependsOn("build"); void codeGen(bool verify) { string configuration = dotNetBuildSettings.BuildOptions.ConfigurationOption.Value; string versionSuffix = $"cg{DateTime.UtcNow:yyyyMMddHHmmss}"; RunDotNet("pack", Path.Combine("src", codegen, $"{codegen}.csproj"), "-c", configuration, "--no-build", "--output", Path.GetFullPath(Path.Combine("tools", "bin")), "--version-suffix", versionSuffix); string packagePath = FindFiles($"tools/bin/{codegen}.*-{versionSuffix}.nupkg").Single(); string packageVersion = Regex.Match(packagePath, @"[/\\][^/\\]*\.([0-9]+\.[0-9]+\.[0-9]+(-.+)?)\.nupkg$").Groups[1].Value; string toolPath = dotNetTools.GetToolPath($"{codegen}/{packageVersion}"); string verifyOption = verify ? "--verify" : null; RunApp(toolPath, "___", "___", verifyOption); } }); }
mit
C#
996bcbeb45c439a582872e3ab1390d7b28ea97dd
fix line style error
pianzide1117/Ansibility,pianzide1117/Ansibility,pianzide1117/Ansibility
src/Ansibility.Web/Services/Impl/DebuggerAnsibleCaller.cs
src/Ansibility.Web/Services/Impl/DebuggerAnsibleCaller.cs
using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Ansibility.Web.Services.Impl { internal class DebuggerAnsibleCaller : IAnsibleCaller { private readonly ILogger<DebuggerAnsibleCaller> _logger; public DebuggerAnsibleCaller(ILogger<DebuggerAnsibleCaller> logger) { _logger = logger; } async Task<string> IAnsibleCaller.ExecutePlaybookAsync(string playbook, string inventory) { _logger.LogInformation($"debug call {Environment.NewLine}playbook:{playbook}{Environment.NewLine}inventory:{inventory}"); return await Task.FromResult(Guid.NewGuid().ToString()); } async Task<PlaybookResult> IAnsibleCaller.GetResultAsync(string taskId) { return await Task.FromResult(new PlaybookResult { TaskId = taskId, Raw = "debugger ansible caller", }); } bool IAnsibleCaller.IsFinished => true; } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Ansibility.Web.Services.Impl { internal class DebuggerAnsibleCaller : IAnsibleCaller { private readonly ILogger<DebuggerAnsibleCaller> _logger; public DebuggerAnsibleCaller(ILogger<DebuggerAnsibleCaller> logger) { _logger = logger; } async Task<string> IAnsibleCaller.ExecutePlaybookAsync(string playbook, string inventory) { _logger.LogInformation($"debug call \r\nplaybook:{playbook}\r\ninventory:{inventory}"); return await Task.FromResult(Guid.NewGuid().ToString()); } async Task<PlaybookResult> IAnsibleCaller.GetResultAsync(string taskId) { return await Task.FromResult(new PlaybookResult { TaskId = taskId, Raw = "debugger ansible caller", }); } bool IAnsibleCaller.IsFinished => true; } }
mit
C#
147baa0c691991b506af8688e73606a4f15d7289
Enable value callbacks for PathKeyframeAnimation.
azchohfi/LottieUWP
LottieUWP/Animation/Keyframe/PathKeyframeAnimation.cs
LottieUWP/Animation/Keyframe/PathKeyframeAnimation.cs
using System.Collections.Generic; using System.Numerics; namespace LottieUWP.Animation.Keyframe { internal class PathKeyframeAnimation : KeyframeAnimation<Vector2?> { private PathKeyframe _pathMeasureKeyframe; private PathMeasure _pathMeasure; internal PathKeyframeAnimation(List<Keyframe<Vector2?>> keyframes) : base(keyframes) { } public override Vector2? GetValue(Keyframe<Vector2?> keyframe, float keyframeProgress) { var pathKeyframe = (PathKeyframe) keyframe; var path = pathKeyframe.Path; if (path == null || path.Contours.Count == 0) { return keyframe.StartValue; } if (ValueCallback != null) { return ValueCallback.GetValue(pathKeyframe.StartFrame.Value, pathKeyframe.EndFrame.Value, pathKeyframe.StartValue, pathKeyframe.EndValue, LinearCurrentKeyframeProgress, keyframeProgress, Progress); } if (_pathMeasureKeyframe != pathKeyframe) { _pathMeasure = new PathMeasure(path); _pathMeasureKeyframe = pathKeyframe; } return _pathMeasure.GetPosTan(keyframeProgress * _pathMeasure.Length); } } }
using System.Collections.Generic; using System.Numerics; namespace LottieUWP.Animation.Keyframe { internal class PathKeyframeAnimation : KeyframeAnimation<Vector2?> { private PathKeyframe _pathMeasureKeyframe; private PathMeasure _pathMeasure; internal PathKeyframeAnimation(List<Keyframe<Vector2?>> keyframes) : base(keyframes) { } public override Vector2? GetValue(Keyframe<Vector2?> keyframe, float keyframeProgress) { var pathKeyframe = (PathKeyframe) keyframe; var path = pathKeyframe.Path; if (path == null || path.Contours.Count == 0) { return keyframe.StartValue; } if (_pathMeasureKeyframe != pathKeyframe) { _pathMeasure = new PathMeasure(path); _pathMeasureKeyframe = pathKeyframe; } return _pathMeasure.GetPosTan(keyframeProgress * _pathMeasure.Length); } } }
apache-2.0
C#
1fdd60111826c640f66a90c16b3aa7222d41dcea
Revert "Revert "Catching exception in Vertex.ToString()""
yishn/GTPWrapper
GTPWrapper/DataTypes/Vertex.cs
GTPWrapper/DataTypes/Vertex.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.DataTypes { /// <summary> /// Represents a Go board coordinate. /// </summary> public struct Vertex { /// <summary> /// The letters in a vertex string, i.e. the letters A to Z, excluding I. /// </summary> public static string Letters = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; /// <summary> /// Gets or sets the x coordinate of the point. /// </summary> public int X; /// <summary> /// Gets or sets the y coordinate of the point. /// </summary> public int Y; /// <summary> /// Initializes a new instance of the Vertex class with the given coordinates. /// </summary> /// <param name="x">The horizontal position of the point.</param> /// <param name="y">The vertical position of the point.</param> public Vertex(int x, int y) { this.X = x; this.Y = y; } /// <summary> /// Initializes a new instance of the Vertex class with the given coordinate. /// </summary> /// <param name="vertex">The board coordinate consisting of one letter and one number.</param> public Vertex(string vertex) { this.Y = Vertex.Letters.IndexOf(vertex.ToUpper()[0]) + 1; if (this.Y == 0 || !int.TryParse(vertex.Substring(1), out this.X)) throw new System.FormatException("This is not a valid vertex string."); } /// <summary> /// Returns the vertex string. /// </summary> public override string ToString() { if (this.Y >= Vertex.Letters.Length) throw new System.FormatException("This is not a valid vertex string."); return Vertex.Letters[this.Y - 1] + this.X.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GTPWrapper.DataTypes { /// <summary> /// Represents a Go board coordinate. /// </summary> public struct Vertex { /// <summary> /// The letters in a vertex string, i.e. the letters A to Z, excluding I. /// </summary> public static string Letters = "ABCDEFGHJKLMNOPQRSTUVWXYZ"; /// <summary> /// Gets or sets the x coordinate of the point. /// </summary> public int X; /// <summary> /// Gets or sets the y coordinate of the point. /// </summary> public int Y; /// <summary> /// Initializes a new instance of the Vertex class with the given coordinates. /// </summary> /// <param name="x">The horizontal position of the point.</param> /// <param name="y">The vertical position of the point.</param> public Vertex(int x, int y) { this.X = x; this.Y = y; } /// <summary> /// Initializes a new instance of the Vertex class with the given coordinate. /// </summary> /// <param name="vertex">The board coordinate consisting of one letter and one number.</param> public Vertex(string vertex) { this.Y = Vertex.Letters.IndexOf(vertex.ToUpper()[0]) + 1; if (this.Y == 0 || !int.TryParse(vertex.Substring(1), out this.X)) throw new System.FormatException("This is not a valid vertex string."); } /// <summary> /// Returns the vertex string. /// </summary> public override string ToString() { return Vertex.Letters[this.Y - 1] + this.X.ToString(); } } }
mit
C#
1c9d0f7b345b7b481afca55fc43120a65104c411
add string.equalsIgnore
Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen
Dashen/Infrastructure/Extensions.cs
Dashen/Infrastructure/Extensions.cs
using System; using System.Collections.Generic; using System.IO; namespace Dashen.Infrastructure { public static class Extensions { public static void ForEach<T>(this IEnumerable<T> self, Action<T> action) { foreach (var item in self) { action(item); } } public static MemoryStream Reset(this MemoryStream self) { self.Position = 0; return self; } public static Boolean EqualsIgnore(this string self, string other) { return string.Equals(self, other, StringComparison.OrdinalIgnoreCase); } } }
using System; using System.Collections.Generic; using System.IO; namespace Dashen.Infrastructure { public static class Extensions { public static void ForEach<T>(this IEnumerable<T> self, Action<T> action) { foreach (var item in self) { action(item); } } public static MemoryStream Reset(this MemoryStream self) { self.Position = 0; return self; } } }
lgpl-2.1
C#
63c37874bdd9342eb2750bdd799944c3e146d9dd
Add drop-down menu for concerts.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Views/Shared/_MenuBar.cshtml
src/CGO.Web/Views/Shared/_MenuBar.cshtml
@functions { private string GetCssClass(string actionName, string controllerName) { var currentControllerName = ViewContext.RouteData.Values["controller"].ToString(); var isCurrentController = currentControllerName == controllerName; if (currentControllerName == "Home") { return GetHomeControllerLinksCssClass(actionName, isCurrentController); } return isCurrentController ? "active" : string.Empty; } private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController) { if (!isCurrentController) { return string.Empty; } var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName; return isCurrentAction ? "active" : string.Empty; } } @helper GetMenuBarLink(string linkText, string actionName, string controllerName) { <li class="dropdown @GetCssClass(actionName, controllerName)"> @if (controllerName == "Concerts" && Request.IsAuthenticated) { <a href="@Url.Action(actionName, controllerName)" class="dropdown-toggle" data-toggle="dropdown"> @linkText <b class="caret"></b> </a> <ul class="dropdown-menu"> <li>@Html.ActionLink("Administer Concerts", "List", "Concerts")</li> </ul> } else { @Html.ActionLink(linkText, actionName, controllerName) } </li> } <ul class="nav"> @GetMenuBarLink("Home", "Index", "Home") @GetMenuBarLink("Concerts", "Index", "Concerts") @GetMenuBarLink("Rehearsals", "Index", "Rehearsals") @GetMenuBarLink("About", "About", "Home") @GetMenuBarLink("Contact", "Contact", "Home") </ul>
@functions { private string GetCssClass(string actionName, string controllerName) { var currentControllerName = ViewContext.RouteData.Values["controller"].ToString(); var isCurrentController = currentControllerName == controllerName; if (currentControllerName == "Home") { return GetHomeControllerLinksCssClass(actionName, isCurrentController); } return isCurrentController ? "active" : string.Empty; } private string GetHomeControllerLinksCssClass(string actionName, bool isCurrentController) { if (!isCurrentController) { return string.Empty; } var isCurrentAction = ViewContext.RouteData.Values["action"].ToString() == actionName; return isCurrentAction ? "active" : string.Empty; } } @helper GetMenuBarLink(string linkText, string actionName, string controllerName) { <li class="@GetCssClass(actionName, controllerName)">@Html.ActionLink(linkText, actionName, controllerName)</li> } <ul class="nav"> @GetMenuBarLink("Home", "Index", "Home") @GetMenuBarLink("Concerts", "Index", "Concerts") @GetMenuBarLink("Rehearsals", "Index", "Rehearsals") @GetMenuBarLink("About", "About", "Home") @GetMenuBarLink("Contact", "Contact", "Home") </ul>
mit
C#
452859333d747105ff896e54136fbab33e84f526
Add the content type for notification attachments
mattgwagner/CertiPay.Common
CertiPay.Common.Notifications/Notifications/EmailNotification.cs
CertiPay.Common.Notifications/Notifications/EmailNotification.cs
using System; using System.Collections.Generic; namespace CertiPay.Common.Notifications { /// <summary> /// Represents an email notification sent a user, employee, or administrator /// </summary> public class EmailNotification : Notification { public static String QueueName { get { return "EmailNotifications"; } } /// <summary> /// Who the email notification should be FROM /// </summary> public String FromAddress { get; set; } /// <summary> /// A list of email addresses to CC /// </summary> public ICollection<String> CC { get; set; } = new List<String>(); /// <summary> /// A list of email addresses to BCC /// </summary> public ICollection<String> BCC { get; set; } = new List<String>(); /// <summary> /// The subject line of the email /// </summary> public String Subject { get; set; } /// <summary> /// Any attachments to the email in the form of URLs to download /// </summary> public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>(); /// <summary> /// A file may be attached to the email notification /// </summary> public class Attachment { /// <summary> /// The filename of the attachment /// </summary> public String Filename { get; set; } /// <summary> /// If provided, the Base64 encoded content of the attachment /// </summary> public String Content { get; set; } /// <summary> /// If provided, an addressable URI from which the service can download the attachment /// </summary> public String Uri { get; set; } } } }
using System; using System.Collections.Generic; namespace CertiPay.Common.Notifications { /// <summary> /// Represents an email notification sent a user, employee, or administrator /// </summary> public class EmailNotification : Notification { public static String QueueName { get { return "EmailNotifications"; } } /// <summary> /// Who the email notification should be FROM /// </summary> public String FromAddress { get; set; } /// <summary> /// A list of email addresses to CC /// </summary> public ICollection<String> CC { get; set; } = new List<String>(); /// <summary> /// A list of email addresses to BCC /// </summary> public ICollection<String> BCC { get; set; } = new List<String>(); /// <summary> /// The subject line of the email /// </summary> public String Subject { get; set; } /// <summary> /// Any attachments to the email in the form of URLs to download /// </summary> public ICollection<Attachment> Attachments { get; set; } = new List<Attachment>(); /// <summary> /// A file may be attached to the email notification by providing a URL to download /// the file (will be downloaded by the sending process) and a filename /// </summary> public class Attachment { public String Filename { get; set; } public String Uri { get; set; } } } }
mit
C#
3c572ec38912281f629136e225801023b4a3c349
Update ApplyingThemes.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Charts/SettingChartsAppearance/ApplyingThemes.cs
Examples/CSharp/Charts/SettingChartsAppearance/ApplyingThemes.cs
using System.IO; using Aspose.Cells; using Aspose.Cells.Charts; namespace Aspose.Cells.Examples.Charts.SettingChartsAppearance { public class ApplyingThemes { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate the workbook to open the file that contains a chart Workbook workbook = new Workbook(dataDir + "book1.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.Worksheets[1]; //Get the first chart in the sheet Chart chart = worksheet.Charts[0]; //Specify the FilFormat's type to Solid Fill of the first series chart.NSeries[0].Area.FillFormat.Type = Aspose.Cells.Drawing.FillType.Solid; //Get the CellsColor of SolidFill CellsColor cc = chart.NSeries[0].Area.FillFormat.SolidFill.CellsColor; //Create a theme in Accent style cc.ThemeColor = new ThemeColor(ThemeColorType.Accent6, 0.6); //Apply the them to the series chart.NSeries[0].Area.FillFormat.SolidFill.CellsColor = cc; //Save the Excel file workbook.Save(dataDir + "output.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using Aspose.Cells.Charts; namespace Aspose.Cells.Examples.Charts.SettingChartsAppearance { public class ApplyingThemes { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate the workbook to open the file that contains a chart Workbook workbook = new Workbook(dataDir + "book1.xlsx"); //Get the first worksheet Worksheet worksheet = workbook.Worksheets[1]; //Get the first chart in the sheet Chart chart = worksheet.Charts[0]; //Specify the FilFormat's type to Solid Fill of the first series chart.NSeries[0].Area.FillFormat.Type = Aspose.Cells.Drawing.FillType.Solid; //Get the CellsColor of SolidFill CellsColor cc = chart.NSeries[0].Area.FillFormat.SolidFill.CellsColor; //Create a theme in Accent style cc.ThemeColor = new ThemeColor(ThemeColorType.Accent6, 0.6); //Apply the them to the series chart.NSeries[0].Area.FillFormat.SolidFill.CellsColor = cc; //Save the Excel file workbook.Save(dataDir + "output.out.xlsx"); } } }
mit
C#
0bf026c09c68d8d5d7c41946a518f171efa54988
Bump version
kjac/FormEditor,kjac/FormEditor,kjac/FormEditor
Source/Solution/FormEditor/Properties/AssemblyInfo.cs
Source/Solution/FormEditor/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FormEditor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kenn Jacobsen")] [assembly: AssemblyProduct("FormEditor")] [assembly: AssemblyCopyright("Copyright © Kenn Jacobsen 2014")] [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("39b39b20-7b79-4259-9f04-4c005534b053")] // 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("0.9.0.2")] [assembly: AssemblyFileVersion("0.9.0.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FormEditor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kenn Jacobsen")] [assembly: AssemblyProduct("FormEditor")] [assembly: AssemblyCopyright("Copyright © Kenn Jacobsen 2014")] [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("39b39b20-7b79-4259-9f04-4c005534b053")] // 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("0.9.0.1")] [assembly: AssemblyFileVersion("0.9.0.1")]
mit
C#
acfe40a014dfae5abc489fe14cd21608df7197c0
Add license
waltersoto/PortableMD5
PortableMD5/PortableMD5/Data.cs
PortableMD5/PortableMD5/Data.cs
/* The MIT License (MIT) Copyright (c) 2015 Walter M. Soto Reyes Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace PortableMD5 { internal class Data { public Data(byte[] data) { DataArr = data; Size = data.Length; BlockCount = ((Size + 8) >> 6) + 1; var total = BlockCount << 6; Padding = new byte[total - Size]; Padding[0] = 0x80; long msg = (Size * 8); for (var i = 0; i < 8; i++) { Padding[Padding.Length - 8 + i] = (byte)msg; msg /= 269; } } public byte[] DataArr { set; get; } public int BlockCount { set; get; } public int Size { set; get; } public byte[] Padding { set; get; } } }
 namespace PortableMD5 { internal class Data { public Data(byte[] data) { DataArr = data; Size = data.Length; BlockCount = ((Size + 8) >> 6) + 1; var total = BlockCount << 6; Padding = new byte[total - Size]; Padding[0] = 0x80; long msg = (Size * 8); for (var i = 0; i < 8; i++) { Padding[Padding.Length - 8 + i] = (byte)msg; msg /= 269; } } public byte[] DataArr { set; get; } public int BlockCount { set; get; } public int Size { set; get; } public byte[] Padding { set; get; } } }
mit
C#
73e62f609747898c14c6010da3a7473525fc8313
Add ctor with day of week parameter to DayOfWeekRule
diaconesq/RecurringDates
RecurringDates/DayOfWeekRule.cs
RecurringDates/DayOfWeekRule.cs
using System; namespace RecurringDates { public class DayOfWeekRule : BaseRule { public DayOfWeekRule() { } public DayOfWeekRule(DayOfWeek dayOfWeek) { DayOfWeek = dayOfWeek; } public override bool IsMatch(DateTime day) { return day.DayOfWeek == DayOfWeek; } public override string GetDescription() { return DayOfWeek.ToString(); } public DayOfWeek DayOfWeek { get; set; } } }
using System; namespace RecurringDates { public class DayOfWeekRule : BaseRule { public override bool IsMatch(DateTime day) { return day.DayOfWeek == DayOfWeek; } public override string GetDescription() { return DayOfWeek.ToString(); } public DayOfWeek DayOfWeek { get; set; } } }
bsd-2-clause
C#
82b3dc8b5535a3f233b31b1a3a999be6a17da76e
Return any assembly that match the name, do not look at version
resgroup/nimrod,resgroup/nimrod,resgroup/nimrod,resgroup/nimrod
Nimrod/AssemblyLocator.cs
Nimrod/AssemblyLocator.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Nimrod { public static class AssemblyLocator { static ConcurrentDictionary<string, Assembly> assemblies = new ConcurrentDictionary<string, Assembly>(); public static void Init() { AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { var assemblyName = new AssemblyName(args.Name); Assembly assembly; assemblies.TryGetValue(assemblyName.Name, out assembly); // an assembly has been requested somewhere, but we don't load it Debug.Assert(assembly != null); return assembly; } static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) { var assembly = args.LoadedAssembly; var assemblyName = assembly.GetName(); // Note that we load assembly by name, not full name // This means that we forgot the version number // we should handle the version number too, // but take into account that we want to deliver the assembly if we don't find the exact same version number assemblies.TryAdd(assemblyName.Name, assembly); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Nimrod { public static class AssemblyLocator { static ConcurrentDictionary<string, Assembly> assemblies = new ConcurrentDictionary<string, Assembly>(); public static void Init() { AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); } static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { Assembly assembly; assemblies.TryGetValue(args.Name, out assembly); return assembly; } static void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args) { Assembly assembly = args.LoadedAssembly; assemblies[assembly.FullName] = assembly; } } }
mit
C#
aeb31a66b88fb055b37686071f0fa7d324a04c50
Mark as many members on Text as possible with the `readonly` modifier, so that the limited mutation remains limited and so that usages of Text as an `in` parameter can be as fast as possible by avoiding compiler-generated defensive copies.
plioi/parsley
src/Parsley/Text.cs
src/Parsley/Text.cs
namespace Parsley; public ref struct Text { int index; readonly ReadOnlySpan<char> input; int line; public Text(ReadOnlySpan<char> input) : this(input, 0, 1) { } Text(ReadOnlySpan<char> input, int index, int line) { this.input = input; this.index = index; if (index > input.Length) this.index = input.Length; this.line = line; } public readonly ReadOnlySpan<char> Peek(int characters) => index + characters >= input.Length ? input.Slice(index) : input.Slice(index, characters); public void Advance(int characters) { if (characters == 0) return; int newIndex = index + characters; int countNewLines = 0; foreach (var ch in Peek(characters)) if (ch == '\n') countNewLines++; int newLineNumber = line + countNewLines; index = newIndex; line = newLineNumber; if (index > input.Length) index = input.Length; } public readonly bool EndOfInput => index >= input.Length; public readonly bool TryMatch(Predicate<char> test, out ReadOnlySpan<char> value) { int i = index; while (i < input.Length && test(input[i])) i++; value = Peek(i - index); return value.Length > 0; } readonly int Column { get { if (index == 0) return 1; int indexOfPreviousNewLine = input[..index].LastIndexOf('\n'); return index - indexOfPreviousNewLine; } } public readonly Position Position => new(line, Column); public readonly override string ToString() => input.Slice(index).ToString(); }
namespace Parsley; public ref struct Text { int index; readonly ReadOnlySpan<char> input; int line; public Text(ReadOnlySpan<char> input) : this(input, 0, 1) { } Text(ReadOnlySpan<char> input, int index, int line) { this.input = input; this.index = index; if (index > input.Length) this.index = input.Length; this.line = line; } public ReadOnlySpan<char> Peek(int characters) => index + characters >= input.Length ? input.Slice(index) : input.Slice(index, characters); public void Advance(int characters) { if (characters == 0) return; int newIndex = index + characters; int countNewLines = 0; foreach (var ch in Peek(characters)) if (ch == '\n') countNewLines++; int newLineNumber = line + countNewLines; index = newIndex; line = newLineNumber; if (index > input.Length) index = input.Length; } public bool EndOfInput => index >= input.Length; public bool TryMatch(Predicate<char> test, out ReadOnlySpan<char> value) { int i = index; while (i < input.Length && test(input[i])) i++; value = Peek(i - index); return value.Length > 0; } int Column { get { if (index == 0) return 1; int indexOfPreviousNewLine = input[..index].LastIndexOf('\n'); return index - indexOfPreviousNewLine; } } public Position Position => new(line, Column); public override string ToString() => input.Slice(index).ToString(); }
mit
C#
26d270422baab98d6345ce03bd0b971ccc54651a
Revert version mtapi (MT4) to 1.0.35
vdemydiuk/mtapi,vdemydiuk/mtapi,vdemydiuk/mtapi
MtApi/Properties/AssemblyInfo.cs
MtApi/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MtApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DW")] [assembly: AssemblyProduct("MtApi")] [assembly: AssemblyCopyright("Copyright © DW 2011")] [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("650e3c56-dbce-45d4-a844-94bbe9f9a3bf")] // 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.35.0")] [assembly: AssemblyFileVersion("1.0.35.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MtApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DW")] [assembly: AssemblyProduct("MtApi")] [assembly: AssemblyCopyright("Copyright © DW 2011")] [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("650e3c56-dbce-45d4-a844-94bbe9f9a3bf")] // 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.36.0")] [assembly: AssemblyFileVersion("1.0.36.0")]
mit
C#
dadf3340e1b524be084226f5157325ced467bc4b
Update Cuid.cs
moonpyk/ncuid
NCuid/Cuid.cs
NCuid/Cuid.cs
using System; using System.Diagnostics; using System.Linq; namespace Cuid { public class Cuid { private static ulong _globalCounter; private const int BlockSize = 4; private const int Base = 36; private static readonly ulong DiscreteValues = (ulong)Math.Pow(Base, BlockSize); private static string Pad(string num, int size) { return s.PadLeft(size, '0').Substring(s.Length-size); } private static string RandomBlock(Random rnd) { var number = (long)(rnd.NextDouble() * DiscreteValues); number <<= 0; var r = Pad(Base36Converter.Encode(number), BlockSize ); return r; } public static string Generate() { var ts = Base36Converter.Encode(DateTime.Now.ToUnixMilliTime()); var gen = new Random(); var rnd = RandomBlock(gen) + RandomBlock(gen); var fingerprint = FingerPrint(); _globalCounter = (_globalCounter < DiscreteValues) ? _globalCounter : 0; var counter = Pad(Base36Converter.Encode(_globalCounter), BlockSize); _globalCounter++; return ("c" + ts + counter + fingerprint + rnd).ToLowerInvariant(); } public static string FingerPrint() { const int padding = 2; var pid = Pad(Base36Converter.Encode((Process.GetCurrentProcess().Id)), padding); var hostname = Environment.MachineName; var length = hostname.Length; var inputNumber = hostname.Split().Aggregate(length + 36, (prev, c) => prev + c[0]); var hostId = Pad(Base36Converter.Encode(inputNumber), padding); return pid + hostId; } } }
using System; using System.Diagnostics; using System.Linq; namespace Cuid { public class Cuid { private static ulong _globalCounter; private const int BlockSize = 4; private const int Base = 36; private static readonly ulong DiscreteValues = (ulong)Math.Pow(Base, BlockSize); //private static string Pad(string num, int size) //{ // var s = "0000 0 0000" + num; // return s.Substring(s.Length - size); //} private static string Pad(string num, int size) { var s = "000000000" + num; return s.Substring(s.Length-size); } private static string RandomBlock(Random rnd) { var number = (long)(rnd.NextDouble() * DiscreteValues); number <<= 0; var r = Pad(Base36Converter.Encode(number), BlockSize ); return r; } public static string Generate() { var ts = Base36Converter.Encode(DateTime.Now.ToUnixMilliTime()); var gen = new Random(); var rnd = RandomBlock(gen) + RandomBlock(gen); var fingerprint = FingerPrint(); _globalCounter = (_globalCounter < DiscreteValues) ? _globalCounter : 0; var counter = Pad(Base36Converter.Encode(_globalCounter), BlockSize); _globalCounter++; return ("c" + ts + counter + fingerprint + rnd).ToLowerInvariant(); } public static string FingerPrint() { const int padding = 2; var pid = Pad(Base36Converter.Encode((Process.GetCurrentProcess().Id)), padding); var hostname = Environment.MachineName; var length = hostname.Length; var inputNumber = hostname.Split().Aggregate(length + 36, (prev, c) => prev + c[0]); var hostId = Pad(Base36Converter.Encode(inputNumber), padding); return pid + hostId; } } }
mit
C#
d78687a32d9fd48f0f5beed8380b5e5c78fc8fca
Add Base58 decode tests
mcliment/CsBenc,mcliment/CsBenc
test/CsBenc.Tests/Base58EncoderTests.cs
test/CsBenc.Tests/Base58EncoderTests.cs
using NUnit.Framework; using Shouldly; namespace CsBenc.Tests { [TestFixture] [Parallelizable] public class Base58EncoderTests { private readonly Base58Encoder encoder = new Base58Encoder(); [TestCase(0UL, "1")] [TestCase(57UL, "z")] [TestCase(58UL, "21")] [TestCase(66051UL, "Ldp")] [TestCase(73300775185UL, "2vgLdhi")] [TestCase(281401388481450UL, "3CSwN61PP")] public void Encodes(ulong input, string output) { encoder.Encode(input).ShouldBe(output); } [TestCase("1", 0UL)] [TestCase("z", 57UL)] [TestCase("21", 58UL)] [TestCase("Ldp", 66051UL)] [TestCase("2vgLdhi", 73300775185UL)] [TestCase("3CSwN61PP", 281401388481450UL)] public void Decodes(string encoded, ulong output) { encoder.Decode(encoded).ShouldBe(output); } } }
using NUnit.Framework; using Shouldly; namespace CsBenc.Tests { [TestFixture] [Parallelizable] public class Base58EncoderTests { private readonly Base58Encoder encoder = new Base58Encoder(); [TestCase(0UL, "1")] [TestCase(57UL, "z")] [TestCase(58UL, "21")] [TestCase(66051UL, "Ldp")] [TestCase(73300775185UL, "2vgLdhi")] [TestCase(281401388481450UL, "3CSwN61PP")] public void Encodes(ulong input, string output) { encoder.Encode(input).ShouldBe(output); } } }
mit
C#
e111136680fecc669c0526ff3b095dd613627b06
Use property
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Models/CoinsView.cs
WalletWasabi/Models/CoinsView.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NBitcoin; using WalletWasabi.Helpers; using WalletWasabi.Models; namespace WalletWasabi.Models { public class CoinsView : IEnumerable<SmartCoin> { private IEnumerable<SmartCoin> Coins { get; } public CoinsView(IEnumerable<SmartCoin> coins) { Coins = Guard.NotNull(nameof(coins), coins); } public CoinsView UnSpent() { return new CoinsView(Coins.Where(x => x.Unspent && !x.SpentAccordingToBackend)); } public CoinsView Available() { return new CoinsView(Coins.Where(x => !x.Unavailable)); } public CoinsView CoinJoinInProcess() { return new CoinsView(Coins.Where(x => x.CoinJoinInProgress)); } public CoinsView Confirmed() { return new CoinsView(Coins.Where(x => x.Confirmed)); } public CoinsView Unconfirmed() { return new CoinsView(Coins.Where(x => !x.Confirmed)); } public CoinsView AtBlockHeight(Height height) { return new CoinsView(Coins.Where(x => x.Height == height)); } public CoinsView SpentBy(uint256 txid) { return new CoinsView(Coins.Where(x => x.SpenderTransactionId == txid)); } public CoinsView ChildrenOf(SmartCoin coin) { return new CoinsView(Coins.Where(x => x.TransactionId == coin.SpenderTransactionId)); } public CoinsView DescendantOf(SmartCoin coin) { IEnumerable<SmartCoin> Generator(SmartCoin scoin) { foreach (var child in ChildrenOf(scoin)) { foreach (var childDescendant in ChildrenOf(child)) { yield return childDescendant; } yield return child; } } return new CoinsView(Generator(coin)); } public CoinsView FilterBy(Func<SmartCoin, bool> expression) { return new CoinsView(Coins.Where(expression)); } public CoinsView OutPoints(IEnumerable<TxoRef> outPoints) { return new CoinsView(Coins.Where(x => outPoints.Any(y => y == x.GetOutPoint()))); } public Money TotalAmount() { return Coins.Sum(x => x.Amount); } public SmartCoin[] ToArray() { return Coins.ToArray(); } public IEnumerator<SmartCoin> GetEnumerator() { return Coins.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return Coins.GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NBitcoin; using WalletWasabi.Helpers; using WalletWasabi.Models; namespace WalletWasabi.Models { public class CoinsView : IEnumerable<SmartCoin> { private IEnumerable<SmartCoin> _coins; public CoinsView(IEnumerable<SmartCoin> coins) { _coins = Guard.NotNull(nameof(coins), coins); } public CoinsView UnSpent() { return new CoinsView(_coins.Where(x => x.Unspent && !x.SpentAccordingToBackend)); } public CoinsView Available() { return new CoinsView(_coins.Where(x => !x.Unavailable)); } public CoinsView CoinJoinInProcess() { return new CoinsView(_coins.Where(x => x.CoinJoinInProgress)); } public CoinsView Confirmed() { return new CoinsView(_coins.Where(x => x.Confirmed)); } public CoinsView Unconfirmed() { return new CoinsView(_coins.Where(x => !x.Confirmed)); } public CoinsView AtBlockHeight(Height height) { return new CoinsView(_coins.Where(x => x.Height == height)); } public CoinsView SpentBy(uint256 txid) { return new CoinsView(_coins.Where(x => x.SpenderTransactionId == txid)); } public CoinsView ChildrenOf(SmartCoin coin) { return new CoinsView(_coins.Where(x => x.TransactionId == coin.SpenderTransactionId)); } public CoinsView DescendantOf(SmartCoin coin) { IEnumerable<SmartCoin> Generator(SmartCoin scoin) { foreach (var child in ChildrenOf(scoin)) { foreach (var childDescendant in ChildrenOf(child)) { yield return childDescendant; } yield return child; } } return new CoinsView(Generator(coin)); } public CoinsView FilterBy(Func<SmartCoin, bool> expression) { return new CoinsView(_coins.Where(expression)); } public CoinsView OutPoints(IEnumerable<TxoRef> outPoints) { return new CoinsView(_coins.Where(x => outPoints.Any(y => y == x.GetOutPoint()))); } public Money TotalAmount() { return _coins.Sum(x => x.Amount); } public SmartCoin[] ToArray() { return _coins.ToArray(); } public IEnumerator<SmartCoin> GetEnumerator() { return _coins.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _coins.GetEnumerator(); } } }
mit
C#
d708552c55b4fa127dacf4ee7cffad8e1cb6d52b
test comment
BD-IATI/edi,BD-IATI/edi,BD-IATI/edi,BD-IATI/edi
AIMS_BD_IATI.Service/Program.cs
AIMS_BD_IATI.Service/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AIMS_BD_IATI.Library; using AIMS_BD_IATI.Library.Parser; using AIMS_BD_IATI.Library.Parser.ParserIATIv1; using AIMS_BD_IATI.Library.Parser.ParserIATIv2; namespace AIMS_BD_IATI.Service { class Program { static void Main(string[] args) { Console.WriteLine("Parsing Started..."); IParserIATI parserIATI; string activitiesURL; //Parser v2.01 parserIATI = new ParserIATIv2(); //activitiesURL = "http://datastore.iatistandard.org/api/1/access/activity.xml?recipient-country=BD&reporting-org=CA-3&stream=True" //single activity : "http://datastore.iatistandard.org/api/1/access/activity.xml?iati-identifier=CA-3-A035529001 //Params: activity.xml or activity.json, recipient-country=BD, reporting-org=CA-3 //activitiesURL = Common.iati_url + "recipient-country=" + Common.iati_recipient_country + "&reporting-org=" + "CA-3" + "&stream="+Common.iati_stream; activitiesURL = "http://localhost:1000/UploadedFiles/activity_GB-1_2.xml"; //"http://localhost:1000/UploadedFiles/activity_CA-3_2.xml"; var returnResult2 = (XmlResultv2)parserIATI.ParseIATIXML(activitiesURL); //Parser v1.05 parserIATI = new ParserIATIv1(); //activitiesURL = "http://datastore.iatistandard.org/api/1/access/activity.xml?recipient-country=BD&reporting-org=GB-1&stream=True"; //Params: activity.xml or activity.json, recipient-country=BD, reporting-org=GB-1 or XM-DAC-12-1 activitiesURL = "http://localhost:1000/UploadedFiles/activity_GB-1_2.xml"; var returnResult1 = (XmlResultv1)parserIATI.ParseIATIXML(activitiesURL); //ToDo Conversion test //XmlResultv2 returnResult2 = (XmlResultv1)returnResult1; //returnResult2.AnyAttr Console.WriteLine("Parsing completed!"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AIMS_BD_IATI.Library; using AIMS_BD_IATI.Library.Parser; using AIMS_BD_IATI.Library.Parser.ParserIATIv1; using AIMS_BD_IATI.Library.Parser.ParserIATIv2; namespace AIMS_BD_IATI.Service { class Program { static void Main(string[] args) { Console.WriteLine("Parsing Started..."); IParserIATI parserIATI; string activitiesURL; //Parser v2.01 parserIATI = new ParserIATIv2(); //activitiesURL = "http://datastore.iatistandard.org/api/1/access/activity.xml?recipient-country=BD&reporting-org=CA-3&stream=True" //single activity : "http://datastore.iatistandard.org/api/1/access/activity.xml?iati-identifier=CA-3-A035529001 //Params: activity.xml or activity.json, recipient-country=BD, reporting-org=CA-3 //activitiesURL = Common.iati_url + "recipient-country=" + Common.iati_recipient_country + "&reporting-org=" + "CA-3" + "&stream="+Common.iati_stream; activitiesURL = "http://localhost:1000/UploadedFiles/activity_GB-1_2.xml"; //"http://localhost:1000/UploadedFiles/activity_CA-3_2.xml"; var returnResult2 = (XmlResultv2)parserIATI.ParseIATIXML(activitiesURL); //Parser v1.05 parserIATI = new ParserIATIv1(); //activitiesURL = "http://datastore.iatistandard.org/api/1/access/activity.xml?recipient-country=BD&reporting-org=GB-1&stream=True"; //Params: activity.xml or activity.json, recipient-country=BD, reporting-org=GB-1 or XM-DAC-12-1 activitiesURL = "http://localhost:1000/UploadedFiles/activity_GB-1_2.xml"; var returnResult1 = (XmlResultv1)parserIATI.ParseIATIXML(activitiesURL); //ToDo Conversion //XmlResultv2 returnResult2 = (XmlResultv1)returnResult1; //returnResult2.AnyAttr Console.WriteLine("Parsing completed!"); Console.ReadLine(); } } }
agpl-3.0
C#
61022d2e3e59cc03972ef9b108b53205bd3cf85c
Fix output formats
andburn/dds-reader
DDSReader/DDSReader/DDSImage.cs
DDSReader/DDSReader/DDSImage.cs
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System; using System.IO; namespace DDSReader { public class DDSImage { private readonly Pfim.IImage _image; public byte[] Data { get { if (_image != null) return _image.Data; else return new byte[0]; } } public DDSImage(string file) { _image = Pfim.Pfim.FromFile(file); Process(); } public DDSImage(Stream stream) { if (stream == null) throw new Exception("DDSImage ctor: Stream is null"); _image = Pfim.Dds.Create(stream, new Pfim.PfimConfig()); Process(); } public DDSImage(byte[] data) { if (data == null || data.Length <= 0) throw new Exception("DDSImage ctor: no data"); _image = Pfim.Dds.Create(data, new Pfim.PfimConfig()); Process(); } public void Save(string file) { if (_image.Format == Pfim.ImageFormat.Rgba32) Save<Bgra32>(file); else if (_image.Format == Pfim.ImageFormat.Rgb24) Save<Bgr24>(file); else throw new Exception("Unsupported pixel format (" + _image.Format + ")"); } private void Process() { if (_image == null) throw new Exception("DDSImage image creation failed"); if (_image.Compressed) _image.Decompress(); } private void Save<T>(string file) where T : struct, IPixel<T> { Image<T> image = Image.LoadPixelData<T>( _image.Data, _image.Width, _image.Height); image.Save(file); } } }
using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; using System; using System.IO; namespace DDSReader { public class DDSImage { private readonly Pfim.IImage _image; public byte[] Data { get { if (_image != null) return _image.Data; else return new byte[0]; } } public DDSImage(string file) { _image = Pfim.Pfim.FromFile(file); Process(); } public DDSImage(Stream stream) { if (stream == null) throw new Exception("DDSImage ctor: Stream is null"); _image = Pfim.Dds.Create(stream, new Pfim.PfimConfig()); Process(); } public DDSImage(byte[] data) { if (data == null || data.Length <= 0) throw new Exception("DDSImage ctor: no data"); _image = Pfim.Dds.Create(data, new Pfim.PfimConfig()); Process(); } public void Save(string file) { if (_image.Format == Pfim.ImageFormat.Rgba32) Save<Rgba32>(file); else if (_image.Format == Pfim.ImageFormat.Rgb24) Save<Rgb24>(file); else throw new Exception("Unsupported pixel format (" + _image.Format + ")"); } private void Process() { if (_image == null) throw new Exception("DDSImage image creation failed"); if (_image.Compressed) _image.Decompress(); } private void Save<T>(string file) where T : struct, IPixel<T> { Image<T> image = Image.LoadPixelData<T>( _image.Data, _image.Width, _image.Height); image.Save(file); } } }
mit
C#
c6bbfcf3c343196f66a86b00ce9e911c5c28ce90
Fix interface name typo.
brendanjbaker/Bakery
src/Bakery/Mail/EmailAddress.cs
src/Bakery/Mail/EmailAddress.cs
namespace Bakery.Mail { using System; public class EmailAddress : IEmailAddress { private readonly String name; private readonly String value; public EmailAddress(String value, String name = null) { this.name = name; this.value = value; } public String Name { get { return name; } } public String Value { get { return value; } } } }
namespace Bakery.Mail { using System; public class EmailAddress : IEmailHeader { private readonly String name; private readonly String value; public EmailAddress(String value, String name = null) { this.name = name; this.value = value; } public String Name { get { return name; } } public String Value { get { return value; } } } }
mit
C#
5ec6e221cc4709a1073060245f6c457fbde16f55
Comment removed
jf3l1x/collectw
src/CollectW.Service/Program.cs
src/CollectW.Service/Program.cs
using System.ServiceProcess; namespace CollectW.Service { internal static class Program { private static void Main() { var servicesToRun = new ServiceBase[] { new Daemon() }; ServiceBase.Run(servicesToRun); } } }
using System.ServiceProcess; namespace CollectW.Service { internal static class Program { /// <summary> /// The main entry point for the application. /// </summary> private static void Main() { var servicesToRun = new ServiceBase[] { new Daemon() }; ServiceBase.Run(servicesToRun); } } }
mit
C#
a42c85cde4619e13df5ce39c86ba5b5f1a34b59a
Remove file opening issues
manio143/ShadowsOfShadows
src/Serialization/Serializer.cs
src/Serialization/Serializer.cs
using System; using System.Xml.Serialization; using System.Xml; using System.IO; using ShadowsOfShadows.Entities; using ShadowsOfShadows.Items; namespace ShadowsOfShadows.Serialization { public static class Serializer { private static string SaveFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShadowsOfShadows", "savedgames"); private static FileStream OpenFile(SaveSlot slot, bool create = false) { if (!Directory.Exists (SaveFolder)) Directory.CreateDirectory (SaveFolder); return File.Open (SaveFolder + "/" + slot + ".sav", create ? FileMode.OpenOrCreate : FileMode.Open); } public static void Save(SaveSlot slot, GameState state) { // TODO Catch exception XmlSerializer xsSubmit = new XmlSerializer(typeof(GameState), new Type[] {typeof(RegenerationConsumable), typeof(Apple), typeof(Wall), typeof(Chest)}); // TODO Is it necessary to list all the types here? var xml = ""; using (var sww = new StringWriter()) using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, state); xml = sww.ToString(); var file = new System.IO.StreamWriter(OpenFile(slot, true)); file.Write(xml); file.Close(); } } public static GameState Load(SaveSlot slot) { GameState state = null; XmlSerializer serializer = new XmlSerializer(typeof(GameState), new Type[] { typeof(RegenerationConsumable), typeof(Apple), typeof(Wall), typeof(Chest) }); // As above var reader = new StreamReader(OpenFile(slot)); state = (GameState)serializer.Deserialize(reader); reader.Close(); return state; } } }
using System; using System.Xml.Serialization; using System.Xml; using System.IO; using ShadowsOfShadows.Entities; using ShadowsOfShadows.Items; namespace ShadowsOfShadows.Serialization { public static class Serializer { private static string SaveFolder = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShadowsOfShadows", "savedgames"); public static void Save(SaveSlot slot, GameState state) { // TODO Catch exception XmlSerializer xsSubmit = new XmlSerializer(typeof(GameState), new Type[] {typeof(RegenerationConsumable), typeof(Apple), typeof(Wall), typeof(Chest)}); // TODO Is it necessary to list all the types here? var xml = ""; using (var sww = new StringWriter()) using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, state); xml = sww.ToString(); System.IO.StreamWriter file = new System.IO.StreamWriter(SaveFolder + "/" + slot + ".sav"); file.Write(xml); file.Close(); } } public static GameState loadGameState(SaveSlot slot) { GameState state = null; string path = SaveFolder + "/" + slot + ".sav"; XmlSerializer serializer = new XmlSerializer(typeof(GameState), new Type[] { typeof(RegenerationConsumable), typeof(Apple), typeof(Wall), typeof(Chest) }); // As above StreamReader reader = new StreamReader(path); state = (GameState)serializer.Deserialize(reader); reader.Close(); return state; } } }
mit
C#
a28c7d89c4d77cbe4dab7ea18bf191255c0c7612
Fix code as suggested by compiler.
Nonagon-x/Nonagon.Modular
Backend/Mono/Nonagon.Modular/DataModuleInterface.cs
Backend/Mono/Nonagon.Modular/DataModuleInterface.cs
using ServiceStack.OrmLite; namespace Nonagon.Modular { /// <summary> /// Data module interface base class. /// </summary> public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface { /// <summary> /// Gets or sets the db connection factory. /// </summary> /// <value>The db connection factory.</value> public IDbConnectionFactory DbConnectionFactory { get; private set; } protected DataModuleInterface(IDbConnectionFactory dbConnectionFactory) { DbConnectionFactory = dbConnectionFactory; } /// <summary> /// Resolve the instance of operation from type parameter. /// </summary> /// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam> protected override TOperation Resolve<TOperation>() { TOperation opt = base.Resolve<TOperation>(); var iDataModuleOperation = opt as IDataModuleOperation; if(iDataModuleOperation != null) iDataModuleOperation.DbConnectionFactory = DbConnectionFactory; return opt; } } }
using ServiceStack.OrmLite; namespace Nonagon.Modular { /// <summary> /// Data module interface base class. /// </summary> public abstract class DataModuleInterface : ModuleInterface, IDataModuleInterface { /// <summary> /// Gets or sets the db connection factory. /// </summary> /// <value>The db connection factory.</value> public IDbConnectionFactory DbConnectionFactory { get; private set; } public DataModuleInterface(IDbConnectionFactory dbConnectionFactory) { DbConnectionFactory = dbConnectionFactory; } /// <summary> /// Resolve the instance of operation from type parameter. /// </summary> /// <typeparam name="TOperation">The IDataModuleOperation to be instantiated.</typeparam> protected override TOperation Resolve<TOperation>() { TOperation opt = base.Resolve<TOperation>(); if(opt is IDataModuleOperation) (opt as IDataModuleOperation).DbConnectionFactory = DbConnectionFactory; return opt; } } }
bsd-3-clause
C#
12e54083566d81ae152fe7d361a3ca5207a0a1a6
Add \r when \n is printed from ICommandInteraction.
antmicro/AntShell
AntShell/Commands/ICommandInteraction.cs
AntShell/Commands/ICommandInteraction.cs
/* Copyright (c) 2013 Ant Micro <www.antmicro.com> Authors: * Mateusz Holenko (mholenko@antmicro.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; namespace AntShell.Commands { public interface ICommandInteraction { Stream GetRawInputStream(); string ReadLine(); void Write(char c, ConsoleColor? color = null); void WriteError(string error); string CommandToExecute { get; set; } bool QuitEnvironment { get; set; } } public static class ICommandInteractionExtensions { public static void Write(this ICommandInteraction ici, string str, ConsoleColor? color = null) { foreach(var c in str.ToCharArray()) { if(c == '\n') { ici.Write('\r', color); } ici.Write(c, color); } } public static void WriteLine(this ICommandInteraction ici, string str = "", ConsoleColor? color = null) { ici.Write(string.Format("{0}\n\r", str), color); } public static void WriteRaw(this ICommandInteraction ici, string str) { ici.Write(str); } } }
/* Copyright (c) 2013 Ant Micro <www.antmicro.com> Authors: * Mateusz Holenko (mholenko@antmicro.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; namespace AntShell.Commands { public interface ICommandInteraction { Stream GetRawInputStream(); string ReadLine(); void Write(char c, ConsoleColor? color = null); void WriteError(string error); string CommandToExecute { get; set; } bool QuitEnvironment { get; set; } } public static class ICommandInteractionExtensions { public static void Write(this ICommandInteraction ici, string str, ConsoleColor? color = null) { foreach(var c in str.ToCharArray()) { ici.Write(c, color); } } public static void WriteLine(this ICommandInteraction ici, string str = "", ConsoleColor? color = null) { ici.Write(string.Format("{0}\n\r", str), color); } public static void WriteRaw(this ICommandInteraction ici, string str) { ici.Write(str); } } }
apache-2.0
C#
113e6a21d91ddde1c1160be3be23c9a042aee70e
Update Program.cs
srinivas931/building-blocks-demo
DemoConsoleApp/DemoConsoleApp/Program.cs
DemoConsoleApp/DemoConsoleApp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World! - changed on the server"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
mit
C#
992c9bfe95d0b9779509f4144cc08de5286dbb4b
Bump version
oozcitak/imagelistview
ImageListView/Properties/AssemblyInfo.cs
ImageListView/Properties/AssemblyInfo.cs
// ImageListView - A listview control for image files // Copyright (C) 2009 Ozgur Ozcitak // // 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. // // Ozgur Ozcitak (ozcitak@yahoo.com) 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("ImageListView")] [assembly: AssemblyDescription("A ListView like control for displaying image files with asynchronously loaded thumbnails.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Özgür Özçıtak")] [assembly: AssemblyProduct("ImageListView")] [assembly: AssemblyCopyright("Copyright © 2013 Özgür Özçıtak")] [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("3eb67a8d-4c80-4c11-944d-c99ef0ec7eb9")] // 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("13.8.0.0")] [assembly: AssemblyFileVersion("13.8.0.0")]
// ImageListView - A listview control for image files // Copyright (C) 2009 Ozgur Ozcitak // // 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. // // Ozgur Ozcitak (ozcitak@yahoo.com) 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("ImageListView")] [assembly: AssemblyDescription("A ListView like control for displaying image files with asynchronously loaded thumbnails.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Özgür Özçıtak")] [assembly: AssemblyProduct("ImageListView")] [assembly: AssemblyCopyright("Copyright © 2013 Özgür Özçıtak")] [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("3eb67a8d-4c80-4c11-944d-c99ef0ec7eb9")] // 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("13.7.3.0")] [assembly: AssemblyFileVersion("13.7.3.0")]
apache-2.0
C#
21319ca80ed0e0a855fe546da88ac7f2b83e8601
remove unneeded method
rafaelalmeidatk/MonoGame.Extended,cra0zy/MonoGame.Extended,LithiumToast/MonoGame.Extended,Aurioch/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended,HyperionMT/MonoGame.Extended
Source/MonoGame.Extended/Shapes/LineF.cs
Source/MonoGame.Extended/Shapes/LineF.cs
using System; using Microsoft.Xna.Framework; using MonoGame.Extended.Particles; namespace MonoGame.Extended.Shapes { public interface IPathF : IShapeBase { Vector2 StartPoint { get; set; } Vector2 EndPoint { get; set; } } public struct LineF : IPathF { public Vector2 StartPoint { get; set; } public Vector2 EndPoint { get; set; } public RectangleF GetBoundingRectangle() { var left = MathHelper.Min(StartPoint.X, StartPoint.X); var top = MathHelper.Min(StartPoint.Y, StartPoint.Y); return new RectangleF(left, top, MathHelper.Max(StartPoint.X, StartPoint.X) - left, MathHelper.Max(StartPoint.Y, StartPoint.Y) - top); } public bool Contains(Vector2 point) { var r = GetBoundingRectangle(); //simplified cross return Math.Abs((point.X - r.Left) * r.Height - (point.Y - r.Top) * r.Width) < float.Epsilon; } public bool Contains(Point point) { var r = GetBoundingRectangle(); //simplified cross return Math.Abs((point.X - r.Left) * r.Height - (point.Y - r.Top) * r.Width) < 1.414;//TODO check for value to be right } public Vector2 PointOnOutline(float t) => StartPoint + (EndPoint - StartPoint) * t; public Vector2 ToVector() { return EndPoint - StartPoint; } } }
using System; using Microsoft.Xna.Framework; using MonoGame.Extended.Particles; namespace MonoGame.Extended.Shapes { public interface IPathF : IShapeBase { Vector2 StartPoint { get; set; } Vector2 EndPoint { get; set; } } public struct LineF : IPathF { public Vector2 StartPoint { get; set; } private void Stuff(out float left, out float top, out float width, out float height) { left = MathHelper.Min(StartPoint.X, EndPoint.X); width = MathHelper.Max(StartPoint.X, EndPoint.X) - left; top = MathHelper.Min(StartPoint.Y, EndPoint.Y); height = MathHelper.Max(StartPoint.Y, EndPoint.Y) - top; } public Vector2 EndPoint { get; set; } public RectangleF GetBoundingRectangle() { var left = MathHelper.Min(StartPoint.X, StartPoint.X); var top = MathHelper.Min(StartPoint.Y, StartPoint.Y); return new RectangleF(left, top, MathHelper.Max(StartPoint.X, StartPoint.X) - left, MathHelper.Max(StartPoint.Y, StartPoint.Y) - top); } public bool Contains(Vector2 point) { var r = GetBoundingRectangle(); //simplified cross return Math.Abs((point.X - r.Left) * r.Height - (point.Y - r.Top) * r.Width) < float.Epsilon; } public bool Contains(Point point) { var r = GetBoundingRectangle(); //simplified cross return Math.Abs((point.X - r.Left) * r.Height - (point.Y - r.Top) * r.Width) < 1.414;//TODO check for value to be right } public Vector2 PointOnOutline(float t) => StartPoint + (EndPoint - StartPoint) * t; public Vector2 ToVector() { return EndPoint - StartPoint; } } }
mit
C#
d4bd6425e39dca1540b4f45e333b22d6b7a782ec
implement IEquatable<string>
dgg/rvn-izr
src/Rvn.Izr/CreateInAttribute.cs
src/Rvn.Izr/CreateInAttribute.cs
using System; namespace Rvn.Izr { [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] internal sealed class CreateInAttribute : Attribute, IEquatable<string> { public CreateInAttribute(string database) { if (database == null) throw new ArgumentNullException("database", "Databse cannot be null"); if (string.IsNullOrWhiteSpace(database)) throw new ArgumentException("Database cannot be empty"); Database = database; } public string Database { get; private set; } public bool Equals(string other) { return StringComparer.OrdinalIgnoreCase.Equals(Database, other); } public override string ToString() { return Database; } } }
using System; namespace Rvn.Izr { [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] internal sealed class CreateInAttribute : Attribute { public CreateInAttribute(string database) { if (database == null) throw new ArgumentNullException("database", "Databse cannot be null"); if (string.IsNullOrWhiteSpace(database)) throw new ArgumentException("Database cannot be empty"); Database = database; } public string Database { get; private set; } public override string ToString() { return Database; } } }
bsd-2-clause
C#
4cf6d7ed9b2fb2b77ed1eb9aa8a1353e18acaae5
Clarify usage and give argument values names
printerpam/purpleonion,printerpam/purpleonion,neoeinstein/purpleonion
src/Xpdm.PurpleOnion/Settings.cs
src/Xpdm.PurpleOnion/Settings.cs
using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Mono.Options; namespace Xpdm.PurpleOnion { sealed class Settings { public readonly string AppName = AppDomain.CurrentDomain.FriendlyName; public Regex ToMatch { get; set; } public string OutFilename { get; set; } public string InFilename { get; set; } public string CheckDir { get; set; } public string BaseDir { get; set; } public int WorkerCount { get; set; } public List<string> ExtraArgs { get; set; } public int Verbosity { get; set; } public bool ShouldShowHelp { get; set; } OptionSet options; public Settings() { options = new OptionSet() { { "m|match=", "create hidden service directories for onion addresses found matching {REGEX}", v => { if (v != null) ToMatch = new Regex(v, RegexOptions.Compiled); } }, { "o|out=", "append generated keys to {FILE}\nexclusive of -i,-c", v => { if (v != null) OutFilename = v; } }, { "i|in=", "find matching addresses from a previous run that was saved to {FILE}\nexclusive of -o,-c, requires -m", v => { if (v != null) InFilename = v; } }, { "c|check=", "verify that {DIR} is a valid onion directory whose hostname matches its private_key\nexclusive of -i,-o", v => { if (v != null) CheckDir = v; } }, { "b|basedir=", "use {DIR} as the base working directory", v => { if (v != null) BaseDir = v; } }, { "w|workers=", "spawn {NUM} worker threads to generate keys\ndefault 2*num_proc, ignored if -i", (int v) => WorkerCount = v }, { "v", "increase output verbosity", v => { if (v != null) ++Verbosity; } }, { "h|help", "show this message and exit", v => ShouldShowHelp = v != null } }; BaseDir = "."; WorkerCount = Environment.ProcessorCount * 2; } public bool TryParse(string[] args) { try { ExtraArgs = options.Parse(args); } catch (OptionException e) { Console.Error.Write(AppName + ": "); Console.Error.WriteLine(e.Message); Console.Error.WriteLine("Try `" + AppName + " --help' for more information."); return false; } return true; } public void ShowHelp(TextWriter o) { o.WriteLine("Usage: " + AppName + " [-v] [-b] [[[-i|-o] filename] [-m regex] [-w number]|-c dir]"); o.WriteLine("Brute-forces the creation of many RSA key-pairs attempting to find one whose"); o.WriteLine("Tor onion address matches a given pattern. For the creation of vanity"); o.WriteLine("onion addresses or burning through excess entropy."); o.WriteLine(); o.WriteLine("Options:"); options.WriteOptionDescriptions(o); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; using Mono.Options; namespace Xpdm.PurpleOnion { sealed class Settings { public readonly string AppName = AppDomain.CurrentDomain.FriendlyName; public Regex ToMatch { get; set; } public string OutFilename { get; set; } public string InFilename { get; set; } public string CheckDir { get; set; } public string BaseDir { get; set; } public int WorkerCount { get; set; } public List<string> ExtraArgs { get; set; } public int Verbosity { get; set; } public bool ShouldShowHelp { get; set; } OptionSet options; public Settings() { options = new OptionSet() { { "m|match=", "create onion directories for matches", v => { if (v != null) ToMatch = new Regex(v, RegexOptions.Compiled); } }, { "o|out=", "file to which generated pairs should be written\nexclusive of -i,-c", v => { if (v != null) OutFilename = v; } }, { "i|in=", "read in a file from a previous run\nexclusive of -o,-c, requires -m", v => { if (v != null) InFilename = v; } }, { "c|check=", "verify the contents of an onion directory\nexclusive of -i,-o", v => { if (v != null) CheckDir = v; } }, { "b|basedir=", "base working directory", v => { if (v != null) BaseDir = v; } }, { "n|num=", "number of child workers to spawn\n(default: 2*num_proc)", (int v) => WorkerCount = v }, { "v", "increase output verbosity", v => { if (v != null) ++Verbosity; } }, { "h|help", "show this message and exit", v => ShouldShowHelp = v != null } }; BaseDir = "."; WorkerCount = Environment.ProcessorCount * 2; } public bool TryParse(string[] args) { try { ExtraArgs = options.Parse(args); } catch (OptionException e) { Console.Error.Write(AppName + ": "); Console.Error.WriteLine(e.Message); Console.Error.WriteLine("Try `" + AppName + " --help' for more information."); return false; } return true; } public void ShowHelp(TextWriter o) { o.WriteLine("Usage: " + AppName + " [-v] [-b] [[[-i|-o] filename] [-m regex] [-n number]|-c dir]"); o.WriteLine("Brute-forces the creation of many RSA key-pairs attempting to find one whose"); o.WriteLine("Tor onion address matches a given pattern. For the creation of vanity"); o.WriteLine("onion addresses or burning through excess entropy."); o.WriteLine(); o.WriteLine("Options:"); options.WriteOptionDescriptions(o); } } }
bsd-3-clause
C#
5035768d2319396c2fc469f96d476637edccd33c
Add inert encoders
nekno/Transcoder,nekno/Transcoder
Transcoder/Encoder.cs
Transcoder/Encoder.cs
using System; using System.Linq; namespace Transcoder { public class Encoder { public static Encoder FFMPEG = new Encoder() { FilePath = @"tools\ffmpeg\ffmpeg.exe" }; public static Encoder FFPROBE = new Encoder() { FilePath = @"tools\ffmpeg\ffprobe.exe" }; public static Encoder NULL = new Encoder() { FilePath = String.Empty }; public static Encoder QAAC = new Encoder() { FilePath = @"tools\qaac\qaac64.exe" }; public String FilePath { get; protected set; } public Boolean IsEncodingRequired { get { return !(new Encoder[] { Encoder.FFPROBE, Encoder.NULL }.Contains(this)); } } } }
using System; namespace Transcoder { public class Encoder { public static Encoder QAAC = new Encoder() { FilePath = @"tools\qaac\qaac64.exe" }; public static Encoder FFMPEG = new Encoder() { FilePath = @"tools\ffmpeg\ffmpeg.exe" }; public static Encoder FFPROBE = new Encoder() { FilePath = @"tools\ffmpeg\ffprobe.exe" }; public String FilePath { get; protected set; } } }
mit
C#
eb78bd29054de83309fbf4c1bc58835f1608a0fb
Remove dead code from nuget.cake
OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
scripts/nuget.cake
scripts/nuget.cake
#load "runhelpers.cake" private ExitStatus RunNuGetInstall(string packageIdOConfigFilePath, string version, bool excludeVersion, bool noCache, bool prerelease, string outputDirectory) { var nugetPath = Environment.GetEnvironmentVariable("NUGET_EXE"); var argList = new List<string> { "install", packageIdOConfigFilePath }; if (!string.IsNullOrWhiteSpace(version)) { argList.Add("-Version"); argList.Add(version); } if (excludeVersion) { argList.Add("-ExcludeVersion"); } if (noCache) { argList.Add("-NoCache"); } if (prerelease) { argList.Add("-Prerelease"); } if (!string.IsNullOrWhiteSpace(outputDirectory)) { argList.Add("-OutputDirectory"); argList.Add(outputDirectory); } var arguments = string.Join(" ", argList); return IsRunningOnWindows() ? Run(nugetPath, arguments) : Run("mono", $"\"{nugetPath}\" {arguments}"); } ExitStatus InstallNuGetPackage(string packageID, string version = null, bool excludeVersion = false, bool noCache = false, bool prerelease = false, string outputDirectory = null) { return RunNuGetInstall(packageID, version, excludeVersion, noCache, prerelease, outputDirectory); } ExitStatus InstallNuGetPackages(string configFilePath, bool excludeVersion = false, bool noCache = false, string outputDirectory = null) { return RunNuGetInstall(configFilePath, null, excludeVersion, noCache, false, outputDirectory); }
#load "runhelpers.cake" using System.Net; /// <summary> /// Downloads and unzips a NuGet package directly without any dependencies. /// </summary> void DownloadNuGetPackage(string packageID, string version, string outputDirectory, string feedUrl) { var outputFolder = System.IO.Path.Combine(outputDirectory, packageID); var outputFileName = System.IO.Path.ChangeExtension(outputFolder, "nupkg"); if (DirectoryExists(outputFolder)) { DeleteDirectory(outputFolder, recursive: true); } using (var client = new WebClient()) { client.DownloadFile( address: $"{feedUrl}/{packageID}/{version}", fileName: outputFileName); } Unzip(outputFileName, outputFolder); } private ExitStatus RunNuGetInstall(string packageIdOConfigFilePath, string version, bool excludeVersion, bool noCache, bool prerelease, string outputDirectory) { var nugetPath = Environment.GetEnvironmentVariable("NUGET_EXE"); var argList = new List<string> { "install", packageIdOConfigFilePath }; if (!string.IsNullOrWhiteSpace(version)) { argList.Add("-Version"); argList.Add(version); } if (excludeVersion) { argList.Add("-ExcludeVersion"); } if (noCache) { argList.Add("-NoCache"); } if (prerelease) { argList.Add("-Prerelease"); } if (!string.IsNullOrWhiteSpace(outputDirectory)) { argList.Add("-OutputDirectory"); argList.Add(outputDirectory); } var arguments = string.Join(" ", argList); return IsRunningOnWindows() ? Run(nugetPath, arguments) : Run("mono", $"\"{nugetPath}\" {arguments}"); } ExitStatus InstallNuGetPackage(string packageID, string version = null, bool excludeVersion = false, bool noCache = false, bool prerelease = false, string outputDirectory = null) { return RunNuGetInstall(packageID, version, excludeVersion, noCache, prerelease, outputDirectory); } ExitStatus InstallNuGetPackages(string configFilePath, bool excludeVersion = false, bool noCache = false, string outputDirectory = null) { return RunNuGetInstall(configFilePath, null, excludeVersion, noCache, false, outputDirectory); }
mit
C#
5397ee434438556d53e90954f23fe971aaf75feb
add deployment option
djsxp/SSDTDeployer
project/SSDTDeployer/DacHelper.cs
project/SSDTDeployer/DacHelper.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlServer.Dac; using Microsoft.SqlServer.Management.Smo; namespace SSDTDeployer { public class DacHelper { public IList<string> Logs = new List<string>(); public void DeployDacpac(string dacpacFileName, string dbName, string connectionstring) { dacpacFileName = Path.GetFullPath(dacpacFileName); var dacServices = new DacServices(connectionstring); dacServices.Message += (sender, args) => Debug.WriteLineIf(Debugger.IsAttached, args.Message); dacServices.ProgressChanged += OnDacServerProcessChanged; var package = DacPackage.Load(dacpacFileName); CancellationToken? cancellationToken = new CancellationToken(); dacServices.Deploy(package, dbName, true, new DacDeployOptions() { }, cancellationToken); } public static bool DbExists(string dataSource, string dbName) { var server = new Server(dataSource); return server.Databases[dbName] != null; } private void OnDacServerProcessChanged(object sender, DacProgressEventArgs args) { Logs.Add(String.Format("[{0}] {1} - {2}", args.OperationId, args.Status, args.Message)); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.SqlServer.Dac; using Microsoft.SqlServer.Management.Smo; namespace SSDTDeployer { public class DacHelper { public IList<string> Logs = new List<string>(); public void DeployDacpac(string dacpacFileName, string dbName, string connectionstring) { dacpacFileName = Path.GetFullPath(dacpacFileName); var dacServices = new DacServices(connectionstring); dacServices.Message += (sender, args) => Debug.WriteLineIf(Debugger.IsAttached, args.Message); dacServices.ProgressChanged += OnDacServerProcessChanged; var package = DacPackage.Load(dacpacFileName); CancellationToken? cancellationToken = new CancellationToken(); dacServices.Deploy(package, dbName, true, null, cancellationToken); } public static bool DbExists(string dataSource, string dbName) { var server = new Server(dataSource); return server.Databases[dbName] != null; } private void OnDacServerProcessChanged(object sender, DacProgressEventArgs args) { Logs.Add(String.Format("[{0}] {1} - {2}", args.OperationId, args.Status, args.Message)); } } }
mit
C#
2d32437c953c702591cc71ba46245324ee25ed11
Update EllipseShape.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Shapes/EllipseShape.cs
src/Core2D/Shapes/EllipseShape.cs
using System; using System.Collections.Generic; using Core2D.Data; using Core2D.Renderer; namespace Core2D.Shapes { /// <summary> /// Ellipse shape. /// </summary> public class EllipseShape : TextShape, IEllipseShape { /// <inheritdoc/> public override Type TargetType => typeof(IEllipseShape); /// <inheritdoc/> public override void DrawShape(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { renderer.Draw(dc, this, dx, dy); #if !USE_DRAW_NODES // TODO: base.DrawShape(dc, renderer, dx, dy); #endif } } /// <inheritdoc/> public override void DrawPoints(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { base.DrawPoints(dc, renderer, dx, dy); } } /// <inheritdoc/> public override void Bind(IDataFlow dataFlow, object db, object r) { var record = Data?.Record ?? r; dataFlow.Bind(this, db, record); base.Bind(dataFlow, db, record); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <inheritdoc/> public override bool IsDirty() { var isDirty = base.IsDirty(); return isDirty; } /// <inheritdoc/> public override void Invalidate() { base.Invalidate(); } } }
using System; using System.Collections.Generic; using Core2D.Data; using Core2D.Renderer; namespace Core2D.Shapes { /// <summary> /// Ellipse shape. /// </summary> public class EllipseShape : TextShape, IEllipseShape { /// <inheritdoc/> public override Type TargetType => typeof(IEllipseShape); /// <inheritdoc/> public override void DrawShape(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { renderer.Draw(dc, this, dx, dy); base.DrawShape(dc, renderer, dx, dy); } } /// <inheritdoc/> public override void DrawPoints(object dc, IShapeRenderer renderer, double dx, double dy) { if (State.Flags.HasFlag(ShapeStateFlags.Visible)) { base.DrawPoints(dc, renderer, dx, dy); } } /// <inheritdoc/> public override void Bind(IDataFlow dataFlow, object db, object r) { var record = Data?.Record ?? r; dataFlow.Bind(this, db, record); base.Bind(dataFlow, db, record); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { throw new NotImplementedException(); } /// <inheritdoc/> public override bool IsDirty() { var isDirty = base.IsDirty(); return isDirty; } /// <inheritdoc/> public override void Invalidate() { base.Invalidate(); } } }
mit
C#
6254cbd63b52c8482235560d1762c276723f7d0b
Copy gradient pen perf improvement to path gradient pen
jaquadro/LilyPath
LilyPath/Pens/PathGradientPen.cs
LilyPath/Pens/PathGradientPen.cs
using Microsoft.Xna.Framework; namespace LilyPath.Pens { /// <summary> /// A <see cref="Pen"/> that blends two colors across the length of the stroked path. /// </summary> public class PathGradientPen : Pen { private byte _r1; private byte _g1; private byte _b1; private byte _a1; private short _rdiff; private short _gdiff; private short _bdiff; private short _adiff; /// <summary> /// Creates a new <see cref="GradientPen"/> with the given colors and width. /// </summary> /// <param name="startColor">The starting pen color.</param> /// <param name="endColor">The ending pen color.</param> /// <param name="width">The width of the paths drawn by the pen.</param> public PathGradientPen (Color startColor, Color endColor, float width) : base(Color.White, width) { _r1 = startColor.R; _g1 = startColor.G; _b1 = startColor.B; _a1 = startColor.A; _rdiff = (short)(endColor.R - _r1); _gdiff = (short)(endColor.G - _g1); _bdiff = (short)(endColor.B - _b1); _adiff = (short)(endColor.A - _a1); } /// <summary> /// Creates a new <see cref="GradientPen"/> with the given colors and a width of 1. /// </summary> /// <param name="startColor">The starting pen color.</param> /// <param name="endColor">The ending pen color.</param> public PathGradientPen (Color startColor, Color endColor) : this(startColor, endColor, 1) { } /// <InheritDoc /> public override bool NeedsPathLength { get { return true; } } /// <InheritDoc /> protected internal override Color ColorAt (float widthPosition, float lengthPosition, float lengthScale) { return Lerp(lengthPosition * lengthScale); } private Color Lerp (float amount) { Color c0 = Color.TransparentBlack; c0.R = (byte)(_r1 + _rdiff * amount); c0.G = (byte)(_g1 + _gdiff * amount); c0.B = (byte)(_b1 + _bdiff * amount); c0.A = (byte)(_a1 + _adiff * amount); return c0; } } }
using Microsoft.Xna.Framework; namespace LilyPath.Pens { /// <summary> /// A <see cref="Pen"/> that blends two colors across the length of the stroked path. /// </summary> public class PathGradientPen : Pen { private Color _color1; private Color _color2; /// <summary> /// Creates a new <see cref="GradientPen"/> with the given colors and width. /// </summary> /// <param name="startColor">The starting pen color.</param> /// <param name="endColor">The ending pen color.</param> /// <param name="width">The width of the paths drawn by the pen.</param> public PathGradientPen (Color startColor, Color endColor, float width) : base(Color.White, width) { _color1 = startColor; _color2 = endColor; } /// <summary> /// Creates a new <see cref="GradientPen"/> with the given colors and a width of 1. /// </summary> /// <param name="startColor">The starting pen color.</param> /// <param name="endColor">The ending pen color.</param> public PathGradientPen (Color startColor, Color endColor) : this(startColor, endColor, 1) { } /// <InheritDoc /> public override bool NeedsPathLength { get { return true; } } /// <InheritDoc /> protected internal override Color ColorAt (float widthPosition, float lengthPosition, float lengthScale) { return Color.Lerp(_color1, _color2, lengthPosition * lengthScale); } } }
mit
C#
9a557e62f9ce0ae477723b1571394a8ed3aff282
Increase default test runner timeout.
tgiphil/Cosmos,jp2masa/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,trivalik/Cosmos,zarlo/Cosmos,fanoI/Cosmos,fanoI/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos
Users/Matthijs/DebugCompiler/MyEngine.cs
Users/Matthijs/DebugCompiler/MyEngine.cs
using System; using System.IO; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; using NUnit.Framework; namespace DebugCompiler { [TestFixture] public class RunKernels { [Test] public void Test([ValueSource(typeof(MySource), nameof(MySource.ProvideData))] Type kernelToRun) { Environment.CurrentDirectory = Path.GetDirectoryName(typeof(RunKernels).Assembly.Location); var xEngine = new Engine(); // Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then // that kernel will be marked as a failiure and terminated xEngine.AllowedSecondsInKernel = 600; // If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run. xEngine.RunTargets.Add(RunTargetEnum.Bochs); // If you're working on the compiler (or other lower parts), you can choose to run the compiler in process // one thing to keep in mind though, is that this only works with 1 kernel at a time! xEngine.RunIL2CPUInProcess = false; xEngine.TraceAssembliesLevel = TraceAssemblies.User; xEngine.EnableStackCorruptionChecks = true; xEngine.StackCorruptionChecksLevel = StackCorruptionDetectionLevel.AllInstructions; // Select kernels to be tested by adding them to the engine xEngine.AddKernel(kernelToRun.Assembly.Location); xEngine.OutputHandler = new TestOutputHandler(); Assert.IsTrue(xEngine.Execute()); } private class TestOutputHandler : OutputHandlerFullTextBase { protected override void Log(string message) { TestContext.WriteLine(String.Concat(DateTime.Now.ToString("hh:mm:ss.ffffff "), new String(' ', mLogLevel * 2), message)); } } } }
using System; using System.IO; using Cosmos.Build.Common; using Cosmos.TestRunner.Core; using NUnit.Framework; namespace DebugCompiler { [TestFixture] public class RunKernels { [Test] public void Test([ValueSource(typeof(MySource), nameof(MySource.ProvideData))] Type kernelToRun) { Environment.CurrentDirectory = Path.GetDirectoryName(typeof(RunKernels).Assembly.Location); var xEngine = new Engine(); // Sets the time before an error is registered. For example if set to 60 then if a kernel runs for more than 60 seconds then // that kernel will be marked as a failiure and terminated xEngine.AllowedSecondsInKernel = 300; // If you want to test only specific platforms, add them to the list, like next line. By default, all platforms are run. xEngine.RunTargets.Add(RunTargetEnum.Bochs); // If you're working on the compiler (or other lower parts), you can choose to run the compiler in process // one thing to keep in mind though, is that this only works with 1 kernel at a time! xEngine.RunIL2CPUInProcess = false; xEngine.TraceAssembliesLevel = TraceAssemblies.User; xEngine.EnableStackCorruptionChecks = true; xEngine.StackCorruptionChecksLevel = StackCorruptionDetectionLevel.AllInstructions; // Select kernels to be tested by adding them to the engine xEngine.AddKernel(kernelToRun.Assembly.Location); xEngine.OutputHandler = new TestOutputHandler(); Assert.IsTrue(xEngine.Execute()); } private class TestOutputHandler : OutputHandlerFullTextBase { protected override void Log(string message) { TestContext.WriteLine(String.Concat(DateTime.Now.ToString("hh:mm:ss.ffffff "), new String(' ', mLogLevel * 2), message)); } } } }
bsd-3-clause
C#
f17bb5b571f97e83ce95481128e49753e2409107
Update alias in usage examples
TAGC/dotnet-setversion
src/dotnet-setversion/Options.cs
src/dotnet-setversion/Options.cs
using System.Collections.Generic; using CommandLine; using CommandLine.Text; namespace dotnet_setversion { public class Options { [Option('r', "recursive", Default = false, HelpText = "Recursively search the current directory for csproj files and apply the given version to all files found. " + "Mutually exclusive to the csprojFile argument.")] public bool Recursive { get; set; } [Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).", Required = true)] public string Version { get; set; } [Value(1, MetaName = "csprojFile", Required = false, HelpText = "Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")] public string CsprojFile { get; set; } [Usage(ApplicationAlias = "setversion")] public static IEnumerable<Example> Examples { get { yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"}); yield return new Example("Explicitly specifying a csproj file", new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"}); yield return new Example("Large repo with multiple csproj files in nested directories", new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true}); } } } }
using System.Collections.Generic; using CommandLine; using CommandLine.Text; namespace dotnet_setversion { public class Options { [Option('r', "recursive", Default = false, HelpText = "Recursively search the current directory for csproj files and apply the given version to all files found. " + "Mutually exclusive to the csprojFile argument.")] public bool Recursive { get; set; } [Value(0, MetaName = "version", HelpText = "The version to apply to the given csproj file(s).", Required = true)] public string Version { get; set; } [Value(1, MetaName = "csprojFile", Required = false, HelpText = "Path to a csproj file to apply the given version. Mutually exclusive to the --recursive option.")] public string CsprojFile { get; set; } [Usage(ApplicationAlias = "dotnet setversion")] public static IEnumerable<Example> Examples { get { yield return new Example("Directory with a single csproj file", new Options {Version = "1.2.3"}); yield return new Example("Explicitly specifying a csproj file", new Options {Version = "1.2.3", CsprojFile = "MyProject.csproj"}); yield return new Example("Large repo with multiple csproj files in nested directories", new UnParserSettings {PreferShortName = true}, new Options {Version = "1.2.3", Recursive = true}); } } } }
mit
C#
de8271ad6bff2193377e12fafbccf0953d99402d
Fix out of range exceptions due to out-of-order hitobjects.
peppy/osu,UselessToucan/osu,naoey/osu,smoogipoo/osu,osu-RP/osu-RP,Nabile-Rahmani/osu,EVAST9919/osu,2yangk23/osu,smoogipooo/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,naoey/osu,Damnae/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,tacchinotacchi/osu,peppy/osu,smoogipoo/osu,naoey/osu,ppy/osu,Drezi126/osu,ZLima12/osu,peppy/osu-new,NeoAdonis/osu,Frontear/osuKyzer,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,ppy/osu,2yangk23/osu
osu.Game.Rulesets.Mania/Beatmaps/ManiaBeatmapConverter.cs
osu.Game.Rulesets.Mania/Beatmaps/ManiaBeatmapConverter.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, // We need to sort here, because the converter generates patterns HitObjects = original.HitObjects.SelectMany(converter.Convert).OrderBy(h => h.StartTime).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Beatmaps; using osu.Game.Rulesets.Mania.Objects; using System; using System.Collections.Generic; using osu.Game.Beatmaps; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using System.Linq; namespace osu.Game.Rulesets.Mania.Beatmaps { public class ManiaBeatmapConverter : BeatmapConverter<ManiaHitObject> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override Beatmap<ManiaHitObject> ConvertBeatmap(Beatmap original) { // Todo: This should be cased when we get better conversion methods var converter = new LegacyConverter(original); return new Beatmap<ManiaHitObject> { BeatmapInfo = original.BeatmapInfo, TimingInfo = original.TimingInfo, HitObjects = original.HitObjects.SelectMany(converter.Convert).ToList() }; } protected override IEnumerable<ManiaHitObject> ConvertHitObject(HitObject original, Beatmap beatmap) { // Handled by the LegacyConvereter yield return null; } } }
mit
C#
3582fefa2cd2d41212fa44d2e7966239387a5a1d
make links to photos and files dynamic based on env
AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us
src/www/Views/Shared/Components/PrimaryNav/Default.cshtml
src/www/Views/Shared/Components/PrimaryNav/Default.cshtml
@using MawMvcApp.ViewComponents @using MawMvcApp.ViewModels @inject IOptions<UrlConfig> urlConfig @model PrimaryNavViewModel <ul class="navbar-nav mr-auto"> <li class="nav-item" maw-action="Index" maw-controller="About" maw-text="about" maw-active="@Model.ActiveNavigationZone == NavigationZone.About"></li> <li class="nav-item" maw-action="Index" maw-controller="Reference" maw-text="reference" maw-active="@Model.ActiveNavigationZone == NavigationZone.Reference"></li> <li class="nav-item" maw-action="Index" maw-controller="Tools" maw-text="tools" maw-active="@Model.ActiveNavigationZone == NavigationZone.Tools"></li> <li class="nav-item" maw-action="Index" maw-controller="Games" maw-text="games" maw-active="@Model.ActiveNavigationZone == NavigationZone.Games"></li> <li class="nav-item" maw-action="Index" maw-controller="Webgl" maw-text="webgl" maw-active="@Model.ActiveNavigationZone == NavigationZone.Webgl"></li> <li class="nav-item"> <a class="nav-link px-3 remove-focus-on-click" href="@urlConfig.Value.Photos" target="_blank" rel="noopener"><svg-icon icon="Camera"></svg-icon></a> </li> <li class="nav-item"> <a class="nav-link px-3 remove-focus-on-click" href="@urlConfig.Value.Files" target="_blank" rel="noopener"><svg-icon icon="Upload"></svg-icon></a> </li> @if(Model.AuthorizedForAdmin) { <li class="nav-item" maw-action="Index" maw-controller="Admin" maw-active="@Model.ActiveNavigationZone == NavigationZone.Administration"> <svg-icon icon="Cog"></svg-icon> </li> } </ul>
@using MawMvcApp.ViewComponents @model PrimaryNavViewModel <ul class="navbar-nav mr-auto"> <li class="nav-item" maw-action="Index" maw-controller="About" maw-text="about" maw-active="@Model.ActiveNavigationZone == NavigationZone.About"></li> <li class="nav-item" maw-action="Index" maw-controller="Reference" maw-text="reference" maw-active="@Model.ActiveNavigationZone == NavigationZone.Reference"></li> <li class="nav-item" maw-action="Index" maw-controller="Tools" maw-text="tools" maw-active="@Model.ActiveNavigationZone == NavigationZone.Tools"></li> <li class="nav-item" maw-action="Index" maw-controller="Games" maw-text="games" maw-active="@Model.ActiveNavigationZone == NavigationZone.Games"></li> <li class="nav-item" maw-action="Index" maw-controller="Webgl" maw-text="webgl" maw-active="@Model.ActiveNavigationZone == NavigationZone.Webgl"></li> <li class="nav-item"> <a class="nav-link px-3 remove-focus-on-click" href="https://photos.mikeandwan.us" target="_blank" rel="noopener"><svg-icon icon="Camera"></svg-icon></a> </li> <li class="nav-item"> <a class="nav-link px-3 remove-focus-on-click" href="https://files.mikeandwan.us" target="_blank" rel="noopener"><svg-icon icon="Upload"></svg-icon></a> </li> @if(Model.AuthorizedForAdmin) { <li class="nav-item" maw-action="Index" maw-controller="Admin" maw-active="@Model.ActiveNavigationZone == NavigationZone.Administration"> <svg-icon icon="Cog"></svg-icon> </li> } </ul>
mit
C#
1c1b517c8fbfdb0f3334e81ba9637091ad9335da
Make the trigger end use the new stuff
IvionSauce/MeidoBot
IrcCalc/IrcCalc.cs
IrcCalc/IrcCalc.cs
using System.Collections.Generic; using Calculation; // Using directives for plugin use. using MeidoCommon; using System.ComponentModel.Composition; [Export(typeof(IMeidoHook))] public class Calc : IMeidoHook { public string Name { get { return "IrcCalc"; } } public string Version { get { return "1.16"; } } public Dictionary<string,string> Help { get { return new Dictionary<string, string>() { {"calc", @"calc <expression> - Calculates expression, accepted operators: ""+"", ""-"", ""*""," + @" ""/"", ""^""."} }; } } static CalcEnvironment CalcEnv = new CalcEnvironment(); public void Stop() {} [ImportingConstructor] public Calc(IIrcComm irc, IMeidoComm meido) { meido.RegisterTrigger("calc", HandleTrigger); irc.AddQueryMessageHandler(HandleMessage); } public static void HandleTrigger(IIrcMessage e) { if (e.MessageArray.Length > 1) { var exprStr = string.Join(" ", e.MessageArray, 1, e.MessageArray.Length - 1); var expr = VerifiedExpression.Parse(exprStr, CalcEnv); if (expr.Success) { double result = ShuntingYard.Calculate(expr); e.Reply( result.ToString() ); } else OutputError(e, expr); } } public static void HandleMessage(IIrcMessage e) { var expr = VerifiedExpression.Parse(e.Message, CalcEnv); // Only automatically calculate if the expression is legitimate and if it's reasonable to assume it's meant // to be a calculation (not just a single number). A minimal calculation will involve at least 3 tokens: // `number operator number`. const int minTokenCount = 3; if (expr.Success && expr.Expression.Count >= minTokenCount) { double result = ShuntingYard.Calculate(expr); e.Reply( result.ToString() ); } } static void OutputError<T>(IIrcMessage e, GenericExpression<T> expr) { string error = expr.ErrorMessage; if (expr.ErrorPosition >= 0) error += " | Postion: " + expr.ErrorPosition; e.Reply(error); } }
using System.Collections.Generic; using Calculation; // Using directives for plugin use. using MeidoCommon; using System.ComponentModel.Composition; [Export(typeof(IMeidoHook))] public class Calc : IMeidoHook { public string Name { get { return "IrcCalc"; } } public string Version { get { return "1.16"; } } public Dictionary<string,string> Help { get { return new Dictionary<string, string>() { {"calc", @"calc <expression> - Calculates expression, accepted operators: ""+"", ""-"", ""*""," + @" ""/"", ""^""."} }; } } public void Stop() {} [ImportingConstructor] public Calc(IIrcComm irc, IMeidoComm meido) { meido.RegisterTrigger("calc", HandleTrigger); irc.AddQueryMessageHandler(HandleMessage); } public static void HandleTrigger(IIrcMessage e) { if (e.MessageArray.Length > 1) { var exprStr = string.Join(" ", e.MessageArray, 1, e.MessageArray.Length - 1); var expr = TokenizedExpression.Parse(exprStr); if (expr.Success) { double result = ShuntingYard.Calculate(expr); e.Reply( result.ToString() ); } else OutputError(e, expr); } } public static void HandleMessage(IIrcMessage e) { var expr = TokenizedExpression.Parse(e.Message); // Only automatically calculate if the expression is legitimate and if it's reasonable to assume it's meant // to be a calculation (not just a single number). A minimal calculation will involve at least 3 tokens: // `number operator number`. const int minTokenCount = 3; if (expr.Success && expr.Expression.Count >= minTokenCount) { double result = ShuntingYard.Calculate(expr); e.Reply( result.ToString() ); } } static void OutputError(IIrcMessage e, TokenizedExpression expr) { string error = expr.ErrorMessage; if (expr.ErrorPosition >= 0) error += " | Postion: " + expr.ErrorPosition; e.Reply(error); } }
bsd-2-clause
C#
a0597788bc065cc6d1ed8e34f6a644f8d39557de
Use elif
ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate
Source/Boilerplate.Templates/content/Api-CSharp/Program.cs
Source/Boilerplate.Templates/content/Api-CSharp/Program.cs
namespace ApiTemplate { using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; #if (WebListener) using Microsoft.Net.Http.Server; #endif public sealed class Program { private const string HostingJsonFileName = "hosting.json"; public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile(HostingJsonFileName, optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseConfiguration(configuration) .UseContentRoot(Directory.GetCurrentDirectory()) #if (Kestrel) .UseKestrel( options => { // Do not add the Server HTTP header when using the Kestrel Web Server. options.AddServerHeader = false; }) #elif (WebListener) .UseWebListener( options => { options.ListenerSettings.Authentication.Schemes = AuthenticationSchemes.None; options.ListenerSettings.Authentication.AllowAnonymous = true; }) #endif #if (Azure) .UseAzureAppServices() #endif #if (IIS && !Azure) .UseIISIntegration() #endif .UseStartup<Startup>() .Build(); host.Run(); } } }
namespace ApiTemplate { using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; #if (WebListener) using Microsoft.Net.Http.Server; #endif public sealed class Program { private const string HostingJsonFileName = "hosting.json"; public static void Main(string[] args) { var configuration = new ConfigurationBuilder() .AddJsonFile(HostingJsonFileName, optional: true, reloadOnChange: true) .AddEnvironmentVariables() .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseConfiguration(configuration) .UseContentRoot(Directory.GetCurrentDirectory()) #if (Kestrel) .UseKestrel( options => { // Do not add the Server HTTP header when using the Kestrel Web Server. options.AddServerHeader = false; }) #endif #if (WebListener) .UseWebListener( options => { options.ListenerSettings.Authentication.Schemes = AuthenticationSchemes.None; options.ListenerSettings.Authentication.AllowAnonymous = true; }) #endif #if (Azure) .UseAzureAppServices() #endif #if (IIS && !Azure) .UseIISIntegration() #endif .UseStartup<Startup>() .Build(); host.Run(); } } }
mit
C#
03d129e491cebeb4c194406de886fe1044d7bb3b
Add [Serializable] attribute
dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute,dnm240/NSubstitute
Source/NSubstitute/Exceptions/ArgumentNotFoundException.cs
Source/NSubstitute/Exceptions/ArgumentNotFoundException.cs
using System; using System.Runtime.Serialization; namespace NSubstitute.Exceptions { [Serializable] public class ArgumentNotFoundException : SubstituteException { public ArgumentNotFoundException(string message) : base(message) { } protected ArgumentNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System.Runtime.Serialization; namespace NSubstitute.Exceptions { [Serializable] public class ArgumentNotFoundException : SubstituteException { public ArgumentNotFoundException(string message) : base(message) { } protected ArgumentNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
bsd-3-clause
C#