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
014ffae7e1bbc1e74fd13ac6c3abff9046e19467
Update Transition to support all VectorEasing methods
jmeas/simple-tower
Assets/Scripts/Transition.cs
Assets/Scripts/Transition.cs
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class Transition : IEnumerator { // The GameObject being moved GameObject target; // The initial position of that game object Vector3 initial; // The Vector3 end destination Vector3 destination; // How long the animation should last float duration; // How far this animation has progressed. Goes between 0 and 1. float progress = 0; // How much time has passed in this animation float totalTime = 0; // The value of Time.time for the previous frame of this animation float lastTime; Func<Vector3, Vector3, float, Vector3> easing; // These are the options for easing functions. They map to functions in VectorEasing.cs Dictionary<string, Func<Vector3, Vector3, float, Vector3>> easingFunctions = new Dictionary<string, Func<Vector3, Vector3, float, Vector3>> { { "Linear", VectorEasing.Lerp }, { "QuadraticIn", VectorEasing.Quadratic.In }, { "QuadraticOut", VectorEasing.Quadratic.Out }, { "QuadraticInOut", VectorEasing.Quadratic.InOut }, { "CubicIn", VectorEasing.Cubic.In }, { "CubicOut", VectorEasing.Cubic.Out }, { "CubicInOut", VectorEasing.Cubic.InOut }, { "QuarticIn", VectorEasing.Quartic.In }, { "QuarticOut", VectorEasing.Quartic.Out }, { "QuarticInOut", VectorEasing.Quartic.InOut }, { "QuinticIn", VectorEasing.Quintic.In }, { "QuinticOut", VectorEasing.Quintic.Out }, { "QuinticInOut", VectorEasing.Quintic.InOut }, { "SinusoidalIn", VectorEasing.Sinusoidal.In }, { "SinusoidalOut", VectorEasing.Sinusoidal.Out }, { "SinusoidalInOut", VectorEasing.Sinusoidal.InOut }, { "ExponentialIn", VectorEasing.Exponential.In }, { "ExponentialOut", VectorEasing.Exponential.Out }, { "ExponentialInOut", VectorEasing.Exponential.InOut }, { "CircularIn", VectorEasing.Circular.In }, { "CircularOut", VectorEasing.Circular.Out }, { "CircularInOut", VectorEasing.Circular.InOut }, { "ElasticIn", VectorEasing.Elastic.In }, { "ElasticOut", VectorEasing.Elastic.Out }, { "ElasticInOut", VectorEasing.Elastic.InOut }, { "BackIn", VectorEasing.Back.In }, { "BackOut", VectorEasing.Back.Out }, { "BackInOut", VectorEasing.Back.InOut }, { "BounceIn", VectorEasing.Bounce.In }, { "BounceOut", VectorEasing.Bounce.Out }, { "BounceInOut", VectorEasing.Bounce.InOut } }; public Transition(GameObject obj, Vector3 dest, float time, string easingFunction = "Linear") { target = obj; initial = obj.transform.position; duration = time; destination = dest; easing = easingFunctions[easingFunction]; // We set the "last time" to be the current time, as this is the start of the animation. lastTime = Time.time; } public bool MoveNext() { // The current progress is how much time has passed divided by the duration, which is the // total time. This should be roughly between 0 and 1. progress = totalTime / duration; // We use our easing function to find the current position target.transform.position = easing(initial, destination, progress); // Update the total time with however much time has passed since our lastTime. totalTime += Time.time - lastTime; lastTime = Time.time; return progress < 1; } // Intentionally blank public void Reset() {} // Intentionally null object IEnumerator.Current { get { return null; } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; public class Transition : IEnumerator { // The GameObject being moved GameObject target; // The initial position of that game object Vector3 initial; // The Vector3 end destination Vector3 destination; // How long the animation should last float duration; // How far this animation has progressed. Goes between 0 and 1. float progress = 0; // How much time has passed in this animation float totalTime = 0; // The value of Time.time for the previous frame of this animation float lastTime; Func<Vector3, Vector3, float, Vector3> easing; // These are the options for easing functions. They map to functions in VectorEasing.cs Dictionary<string, Func<Vector3, Vector3, float, Vector3>> easingFunctions = new Dictionary<string, Func<Vector3, Vector3, float, Vector3>> { { "Linear", VectorEasing.Lerp }, { "QuadraticIn", VectorEasing.Quadratic.In }, { "QuadraticOut", VectorEasing.Quadratic.Out }, { "QuadraticInOut", VectorEasing.Quadratic.InOut } }; public Transition(GameObject obj, Vector3 dest, float time, string easingFunction = "Linear") { target = obj; initial = obj.transform.position; duration = time; destination = dest; easing = easingFunctions[easingFunction]; // We set the "last time" to be the current time, as this is the start of the animation. lastTime = Time.time; } public bool MoveNext() { // The current progress is how much time has passed divided by the duration, which is the // total time. This should be roughly between 0 and 1. progress = totalTime / duration; // We use our easing function to find the current position target.transform.position = easing(initial, destination, progress); // Update the total time with however much time has passed since our lastTime. totalTime += Time.time - lastTime; lastTime = Time.time; return progress < 1; } // Intentionally blank public void Reset() {} // Intentionally null object IEnumerator.Current { get { return null; } } }
mit
C#
a367464202e2b2b56d44b88d6b10f28365dbfba9
Update cargo monitor
cmdrmcdonald/EliteDangerousDataProvider
CargoMonitor/CargoMonitor.cs
CargoMonitor/CargoMonitor.cs
using Eddi; using EddiDataDefinitions; using EddiEvents; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Controls; using Utilities; namespace EddiCargoMonitor { /// <summary> /// A monitor that keeps track of cargo /// </summary> public class CargoMonitor : EDDIMonitor { // The file to log cargo public static readonly string CargoFile = Constants.DATA_DIR + @"\cargo.json"; // The cargo private List<Cargo> cargo = new List<Cargo>(); public string MonitorName() { return "Cargo monitor"; } public string MonitorVersion() { return "1.0.0"; } public string MonitorDescription() { return "Tracks your cargo and provides information to speech responder scripts."; } public CargoMonitor() { ReadCargo(); Logging.Info("Initialised " + MonitorName() + " " + MonitorVersion()); } public void Start() { // We don't actively do anything, just listen to events, so nothing to do here } public void Stop() { } public void Reload() { ReadCargo(); } public UserControl ConfigurationTabItem() { return null; } public void Handle(Event @event) { Logging.Debug("Received event " + JsonConvert.SerializeObject(@event)); // Handle the events that we care about if (@event is CargoInventoryEvent) { handleCargoInventoryEvent((CargoInventoryEvent)@event); } } private void handleCargoInventoryEvent(CargoInventoryEvent @event) { } public IDictionary<string, object> GetVariables() { IDictionary<string, object> variables = new Dictionary<string, object>(); //variables["cargo"] = configuration.materials; return variables; } private void ReadCargo() { try { cargo = JsonConvert.DeserializeObject<List<Cargo>>(File.ReadAllText(CargoFile)); } catch (Exception ex) { Logging.Warn("Failed to read cargo", ex); } if (cargo == null) { cargo = new List<Cargo>(); } } private void WriteCargo() { try { File.WriteAllText(CargoFile, JsonConvert.SerializeObject(this, Formatting.Indented)); } catch (Exception ex) { Logging.Warn("Failed to write cargo", ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EddiCargoMonitor { /// <summary> /// A monitor that keeps track of cargo /// </summary> public class CargoMonitor { } }
apache-2.0
C#
222b379e879201cdedd3a3189d9a7ddf43c7f7fd
Indent with 4 spaces
msarchet/Bundler,msarchet/Bundler
BundlerMiddleware/BundlerMiddlewareBase.cs
BundlerMiddleware/BundlerMiddlewareBase.cs
using Microsoft.Owin; using System.Net; using System.Threading.Tasks; namespace BundlerMiddleware { public abstract class BundlerMiddlewareBase : OwinMiddleware { private readonly BundlerRouteTable routes; public BundlerMiddlewareBase(OwinMiddleware next, BundlerRouteTable routes) : base(next) { this.routes = routes; } public abstract Task<string> GetContent(IOwinContext context, BundlerRoute route); public override async Task Invoke(IOwinContext context) { var path = context.Request.Path.ToString(); if (routes.Exists(path)) { var route = routes.Get(path); var content = await GetContent(context, route); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/html"; await context.Response.WriteAsync(content); } else { await Next.Invoke(context); } } } }
using Microsoft.Owin; using System.Net; using System.Threading.Tasks; namespace BundlerMiddleware { public abstract class BundlerMiddlewareBase : OwinMiddleware { private readonly BundlerRouteTable routes; public BundlerMiddlewareBase(OwinMiddleware next, BundlerRouteTable routes) : base(next) { this.routes = routes; } public abstract Task<string> GetContent(IOwinContext context, BundlerRoute route); public override async Task Invoke(IOwinContext context) { var path = context.Request.Path.ToString(); if (routes.Exists(path)) { var route = routes.Get(path); var content = await GetContent(context, route); context.Response.StatusCode = (int)HttpStatusCode.OK; context.Response.ContentType = "text/html"; await context.Response.WriteAsync(content); } else { await Next.Invoke(context); } } } }
mit
C#
635e0bbe48b4530e3ab9bfcebfd777ab0ad119bf
Fix typo
mganss/ExcelMapper
ExcelMapper/ActionInvoker.cs
ExcelMapper/ActionInvoker.cs
using System; namespace Ganss.Excel { /// <summary> /// Abstract class action invoker /// </summary> public class ActionInvoker { /// <summary> /// Invoke from an unspecified <paramref name="obj"/> type /// </summary> /// <param name="obj">mapping instance class</param> /// <param name="index">index in the collection</param> public virtual void Invoke(object obj, int index) => throw new NotImplementedException(); /// <summary> /// <see cref="ActionInvokerImpl{T}"/> factory /// </summary> /// <typeparam name="T"></typeparam> /// <param name="mappingAction"></param> /// <returns></returns> public static ActionInvoker CreateInstance<T>(Action<T, int> mappingAction) { // instanciate concrete generic invoker var invokerType = typeof(ActionInvokerImpl<>); Type[] tType = { typeof(T) }; Type constructed = invokerType.MakeGenericType(tType); object invokerInstance = Activator.CreateInstance(constructed, mappingAction); return (ActionInvoker)invokerInstance; } } /// <summary> /// Generic form <see cref="ActionInvoker"/> /// </summary> /// <typeparam name="T"></typeparam> public class ActionInvokerImpl<T> : ActionInvoker where T : class { /// <summary> /// ref to the mapping action. /// </summary> internal Action<T, int> mappingAction; /// <summary> /// Ctor /// </summary> /// <param name="mappingAction"></param> public ActionInvokerImpl(Action<T, int> mappingAction) { this.mappingAction = mappingAction; } /// <summary> /// Invoke Generic Action /// </summary> /// <param name="obj"></param> /// <param name="index"></param> public override void Invoke(object obj, int index) { if (mappingAction is null || obj is null) return; mappingAction((obj as T), index); } } }
using System; namespace Ganss.Excel { /// <summary> /// Abstract class action invoker /// </summary> public class ActionInvoker { /// <summary> /// Invoke from an unspecified <paramref name="obj"/> type /// </summary> /// <param name="obj">mapping instance class</param> /// <param name="index">index in the collection</param> public virtual void Invoke(object obj, int index) => throw new NotImplementedException(); /// <summary> /// <see cref="ActionInvokerImpl{T}"/> factory /// </summary> /// <typeparam name="T"></typeparam> /// <param name="AfterMappingAction"></param> /// <returns></returns> public static ActionInvoker CreateInstance<T>(Action<T, int> AfterMappingAction) { // instanciate concrete generic invoker var invokerType = typeof(ActionInvokerImpl<>); Type[] tType = { typeof(T) }; Type constructed = invokerType.MakeGenericType(tType); object invokerInstance = Activator.CreateInstance(constructed, AfterMappingAction); return (ActionInvoker)invokerInstance; } } /// <summary> /// Generic form <see cref="ActionInvoker"/> /// </summary> /// <typeparam name="T"></typeparam> public class ActionInvokerImpl<T> : ActionInvoker where T : class { /// <summary> /// ref to the mapping action. /// </summary> internal Action<T, int> mappingAction; /// <summary> /// Ctor /// </summary> /// <param name="mappingAction"></param> public ActionInvokerImpl(Action<T, int> mappingAction) { this.mappingAction = mappingAction; } /// <summary> /// Invoke Generic Action /// </summary> /// <param name="obj"></param> /// <param name="index"></param> public override void Invoke(object obj, int index) { if (mappingAction is null || obj is null) return; mappingAction((obj as T), index); } } }
mit
C#
f7c2d292ae1dcfe04b1dacaf24feea15f1f0304a
use completedtask
wes566/AsyncEventLib
AsyncEventLib/EventHandlerExtensions.cs
AsyncEventLib/EventHandlerExtensions.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace AsyncEventLib { public static class EventHandlerExtensions { /// <summary> /// Invokes the event handlers if there are any. Safe to call even if there aren't any /// handlers registered. If a handler has registered an async Task then this call will /// properly await all tasks. /// NOTE: the registered async Tasks will run in parallel. /// </summary> /// <param name="handlerToInvoke"></param> /// <param name="sender"></param> /// <returns></returns> public static Task InvokeAsync(this EventHandler<AsyncEventArgs> handler, object sender) { if(handler == null) { return Task.CompletedTask; } var taskList = new List<Task>(); var args = new AsyncEventArgs(taskList); handler.Invoke(sender, args); return Task.WhenAll(taskList); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; namespace AsyncEventLib { public static class EventHandlerExtensions { /// <summary> /// Invokes the event handlers if there are any. Safe to call even if there aren't any /// handlers registered. If a handler has registered an async Task then this call will /// properly await all tasks. /// NOTE: the registered async Tasks will run in parallel. /// </summary> /// <param name="handlerToInvoke"></param> /// <param name="sender"></param> /// <returns></returns> public static Task InvokeAsync(this EventHandler<AsyncEventArgs> handler, object sender) { if(handler == null) { return Task.FromResult(0); } var taskList = new List<Task>(); var args = new AsyncEventArgs(taskList); handler.Invoke(sender, args); return Task.WhenAll(taskList); } } }
mit
C#
b26ef29a23bb6bda0267f1088eab43332291347e
Update Concurrency.cs
BeardedManStudios/ForgeNetworkingRemastered,BeardedManStudios/ForgeNetworkingRemastered,BeardedManStudios/ForgeNetworkingRemastered
BeardedManStudios/Source/Concurrency.cs
BeardedManStudios/Source/Concurrency.cs
using System; using System.Collections.Generic; using System.Threading; namespace BeardedManStudios.Concurrency { // Locking for quick operations. No need to expensively block a thread. internal class SpinLock { private int @lock = 0; public void Enter(ref bool lockTaken) { if (lockTaken) throw new ArgumentException("Lock was already taken."); while (1 == Interlocked.CompareExchange(ref @lock, 1, 0)) { while (@lock == 1) ; } lockTaken = true; } public void Exit() { Interlocked.CompareExchange(ref @lock, 0, 1); } } internal class ConcurrentQueue<T> : Queue<T> { private readonly SpinLock @lock = new SpinLock(); public bool TryDequeue(out T result) { bool lockTaken = false; try { @lock.Enter(ref lockTaken); if (Count > 0) { result = Dequeue(); return true; } else { result = default(T); return false; } } finally { if (lockTaken) @lock.Exit(); } } public new void Enqueue(T item) { bool lockTaken = false; try { @lock.Enter(ref lockTaken); base.Enqueue(item); } finally { if (lockTaken) @lock.Exit(); } } } }
using System; using System.Collections.Generic; using System.Threading; namespace BeardedManStudios.Concurrency { // Locking for quick operations. No need to expensively block a thread. internal class SpinLock { private int @lock = 0; public void Enter(ref bool lockTaken) { if (lockTaken) throw new ArgumentException("Lock was already taken."); while (1 == Interlocked.CompareExchange(ref @lock, 1, 0)) { while (@lock == 0) ; } lockTaken = true; } public void Exit() { Interlocked.CompareExchange(ref @lock, 0, 1); } } internal class ConcurrentQueue<T> : Queue<T> { private readonly SpinLock @lock = new SpinLock(); public bool TryDequeue(out T result) { bool lockTaken = false; try { @lock.Enter(ref lockTaken); if (Count > 0) { result = Dequeue(); return true; } else { result = default(T); return false; } } finally { if (lockTaken) @lock.Exit(); } } public new void Enqueue(T item) { bool lockTaken = false; try { @lock.Enter(ref lockTaken); base.Enqueue(item); } finally { if (lockTaken) @lock.Exit(); } } } }
apache-2.0
C#
3a8dc1c836e8deb0257f0990e34e51d2c7477b23
Add passwords-in-version-control disclaimer to credentials file.
Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net
LearnositySDK/Credentials.cs
LearnositySDK/Credentials.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace LearnositySDK { public static class Credentials { // The consumerKey and consumerSecret are the public & private // security keys required to access Learnosity APIs and // data. Learnosity will provide keys for your own private account. // Note: The consumer secret should be in a properly secured credential // store, and *NEVER* checked into version control. // The keys listed here grant access to Learnosity's public demos account. public static string ConsumerKey = "yis0TYCu7U9V4o7M"; public static string ConsumerSecret = "74c5fd430cf1242a527f6223aebd42d30464be22"; public static string Domain = "localhost"; } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace LearnositySDK { public static class Credentials { public static string ConsumerKey = "yis0TYCu7U9V4o7M"; public static string ConsumerSecret = "74c5fd430cf1242a527f6223aebd42d30464be22"; public static string Domain = "localhost"; } }
apache-2.0
C#
b934a816b55070822cfbc2f708c9358f21f1d8d1
Update Razor EA API
wvdd007/roslyn,eriawan/roslyn,bartdesmet/roslyn,sharwell/roslyn,physhi/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,dotnet/roslyn,diryboy/roslyn,tmat/roslyn,wvdd007/roslyn,KevinRansom/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,mavasani/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,physhi/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,tmat/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,mavasani/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,AmadeusW/roslyn,eriawan/roslyn,weltkante/roslyn,weltkante/roslyn,weltkante/roslyn,eriawan/roslyn,KevinRansom/roslyn,diryboy/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn
src/Tools/ExternalAccess/Razor/RazorCSharpProximityExpressionResolver.cs
src/Tools/ExternalAccess/Razor/RazorCSharpProximityExpressionResolver.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorCSharpProximityExpressionResolverService { public static IList<string> GetProximityExpressions(SyntaxTree syntaxTree, int absoluteIndex, CancellationToken cancellationToken) => CSharpProximityExpressionsService.GetProximityExpressions(syntaxTree, absoluteIndex, cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp.Debugging; namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal static class RazorCSharpProximityExpressionResolverService { public static IList<string> GetProximityExpressions(SyntaxTree syntaxTree, int absoluteIndex) => CSharpProximityExpressionsService.GetProximityExpressions(syntaxTree, absoluteIndex); } }
mit
C#
e6f564c3af74930d7ba93d7b2d4068c52bbd2bc4
Add mouse and and touch control for full range motion.
dirty-casuals/LD38-A-Small-World
Assets/Scripts/Core/PlayerController.cs
Assets/Scripts/Core/PlayerController.cs
using System; using UnityEngine; public class PlayerController : MonoBehaviour { public enum ControlType { Keyboard, Mouse, Touch } [SerializeField] private PaddleController _paddleController; [SerializeField, Range( 0.1f, 10 )] private float _pointerResponsiveness = 3; private ControlType controlType; private Vector3 previouMousePosition; private float halfScreenHeight; private void Start() { halfScreenHeight = Screen.height / 2; } private void Update() { HandleMouseInput(); HandleTouchInput(); HandleKeyboardInput(); } private void HandleKeyboardInput() { float direction = Input.GetAxis( "Vertical" ); if( direction != 0 ) { controlType = ControlType.Keyboard; } if( controlType == ControlType.Keyboard ) { _paddleController.Direction = direction; } } private void HandleTouchInput() { if( Input.touchCount > 0 ) { controlType = ControlType.Touch; } if( controlType == ControlType.Touch ) { MoveToPoint( Input.GetTouch( 0 ).position ); } } private void HandleMouseInput() { if( !Input.mousePresent ) { return; } Vector3 mousePosition = Input.mousePosition; Vector3 mouseDelta = previouMousePosition - mousePosition; if( mouseDelta.magnitude > float.Epsilon ) { previouMousePosition = mousePosition; controlType = ControlType.Mouse; } if( controlType == ControlType.Mouse ) { MoveToPoint( mousePosition ); } } private void MoveToPoint( Vector3 screenPoint ) { Vector3 paddleScreenPosition = Camera.main.WorldToScreenPoint( _paddleController.transform.position ); Vector3 planetScreenPosition = Camera.main.WorldToScreenPoint( _paddleController.Planet.transform.position ); Vector3 paddleVector = paddleScreenPosition - planetScreenPosition; Vector3 pointerVector = screenPoint - planetScreenPosition; paddleVector.z = 0; pointerVector.z = 0; float paddleAngle = Mathf.Atan2( paddleVector.y, paddleVector.x ); float pointerAngle = Mathf.Atan2( pointerVector.y, pointerVector.x ); float angle = pointerAngle - paddleAngle; angle = Mathf.Repeat( angle, Mathf.PI * 2 ); if( angle > Mathf.PI ) { angle -= Mathf.PI * 2; } _paddleController.Direction = angle * _pointerResponsiveness; } }
using UnityEngine; public class PlayerController : MonoBehaviour { [SerializeField] private PaddleController _paddleController; private float halfScreenHeight; private void Start() { halfScreenHeight = Screen.height / 2; } private void Update() { float direction = 0.0f; if (Input.touchCount > 0) { Touch touch = Input.touches[0]; float posY = touch.position.y; if ( posY > halfScreenHeight ) { direction = 1.0f; } else if ( posY < halfScreenHeight ) { direction = -1.0f; } } else { direction = Input.GetAxis( "Vertical" ); } _paddleController.Direction = direction; } }
mit
C#
c7b09e53495b9e492c1635fe2e0aef92e6b5bf6e
add Generic Version of Register and Get Method (#908)
graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet
src/GraphQL/Utilities/GraphTypeTypeRegistry.cs
src/GraphQL/Utilities/GraphTypeTypeRegistry.cs
using System; using System.Collections.Generic; using GraphQL.Types; namespace GraphQL.Utilities { public static class GraphTypeTypeRegistry { static readonly Dictionary<Type, Type> _entries; static GraphTypeTypeRegistry() { _entries = new Dictionary<Type, Type> { [typeof(int)] = typeof(IntGraphType), [typeof(long)] = typeof(IntGraphType), [typeof(double)] = typeof(FloatGraphType), [typeof(float)] = typeof(FloatGraphType), [typeof(decimal)] = typeof(DecimalGraphType), [typeof(string)] = typeof(StringGraphType), [typeof(bool)] = typeof(BooleanGraphType), [typeof(DateTime)] = typeof(DateGraphType), [typeof(DateTimeOffset)] = typeof(DateTimeOffsetGraphType), [typeof(TimeSpan)] = typeof(TimeSpanSecondsGraphType) }; } public static void Register<T, TGraph>() where TGraph : GraphType { Register(typeof(T), typeof(TGraph)); } public static void Register(Type clrType, Type graphType) { _entries[clrType] = graphType; } public static Type Get<TClr>() { return Get(typeof(TClr)); } public static Type Get(Type clrType) { if (_entries.TryGetValue(clrType, out var graphType)) { return graphType; } return null; } } }
using System; using System.Collections.Generic; using GraphQL.Types; namespace GraphQL.Utilities { public static class GraphTypeTypeRegistry { static readonly Dictionary<Type, Type> _entries; static GraphTypeTypeRegistry() { _entries = new Dictionary<Type, Type> { [typeof(int)] = typeof(IntGraphType), [typeof(long)] = typeof(IntGraphType), [typeof(double)] = typeof(FloatGraphType), [typeof(float)] = typeof(FloatGraphType), [typeof(decimal)] = typeof(DecimalGraphType), [typeof(string)] = typeof(StringGraphType), [typeof(bool)] = typeof(BooleanGraphType), [typeof(DateTime)] = typeof(DateGraphType), [typeof(DateTimeOffset)] = typeof(DateTimeOffsetGraphType), [typeof(TimeSpan)] = typeof(TimeSpanSecondsGraphType) }; } public static void Register(Type clrType, Type graphType) { _entries[clrType] = graphType; } public static Type Get(Type clrType) { if (_entries.TryGetValue(clrType, out var graphType)) { return graphType; } return null; } } }
mit
C#
3256fd319c9a69429d5e7c7cc75c669eb90ec7f1
Fix issue where ratio was always returning "1"
janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent
Components/TemplateHelpers/Images/Ratio.cs
Components/TemplateHelpers/Images/Ratio.cs
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return (float)Width / (float)Height); } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
using System; namespace Satrabel.OpenContent.Components.TemplateHelpers { public class Ratio { private readonly float _ratio; public int Width { get; private set; } public int Height { get; private set; } public float AsFloat { get { return Width / Height; } } public Ratio(string ratioString) { Width = 1; Height = 1; var elements = ratioString.ToLowerInvariant().Split('x'); if (elements.Length == 2) { int leftPart; int rightPart; if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart)) { Width = leftPart; Height = rightPart; } } _ratio = AsFloat; } public Ratio(int width, int height) { if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger"); if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger"); Width = width; Height = height; _ratio = AsFloat; } public void SetWidth(int newWidth) { Width = newWidth; Height = Convert.ToInt32(newWidth / _ratio); } public void SetHeight(int newHeight) { Width = Convert.ToInt32(newHeight * _ratio); Height = newHeight; } } }
mit
C#
67245440b661e95d8bb9ca2995e544f35e239569
add amount to create hub commitment
LykkeCity/bitcoinservice,LykkeCity/bitcoinservice
src/BitcoinApi/Models/Offchain/CreateHubCommitmentModel.cs
src/BitcoinApi/Models/Offchain/CreateHubCommitmentModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BitcoinApi.Models.Offchain { public class CreateHubCommitmentModel { public string ClientPubKey { get; set; } public string Asset { get; set; } public decimal Amount { get; set; } public string SignedByClientChannel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BitcoinApi.Models.Offchain { public class CreateHubCommitmentModel { public string ClientPubKey { get; set; } public string Asset { get; set; } public string SignedByClientChannel { get; set; } } }
mit
C#
0282046b216ed716ca576d9eb38482eb9515ec65
Fix nullable annotations
shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,dotnet/roslyn,mavasani/roslyn,KevinRansom/roslyn,diryboy/roslyn,sharwell/roslyn,sharwell/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,weltkante/roslyn,mavasani/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,diryboy/roslyn,diryboy/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn
src/Compilers/CSharp/Portable/Syntax/ForStatementSyntax.cs
src/Compilers/CSharp/Portable/Syntax/ForStatementSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ForStatementSyntax { public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ForStatementSyntax ForStatement(VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax? condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement) => ForStatement(attributeLists: default, declaration, initializers, condition, incrementors, statement); public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax? condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) => ForStatement(attributeLists: default, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public partial class ForStatementSyntax { public ForStatementSyntax Update(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) => Update(AttributeLists, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); } } namespace Microsoft.CodeAnalysis.CSharp { public partial class SyntaxFactory { public static ForStatementSyntax ForStatement(VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, ExpressionSyntax condition, SeparatedSyntaxList<ExpressionSyntax> incrementors, StatementSyntax statement) => ForStatement(attributeLists: default, declaration, initializers, condition, incrementors, statement); public static ForStatementSyntax ForStatement(SyntaxToken forKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, SeparatedSyntaxList<ExpressionSyntax> initializers, SyntaxToken firstSemicolonToken, ExpressionSyntax condition, SyntaxToken secondSemicolonToken, SeparatedSyntaxList<ExpressionSyntax> incrementors, SyntaxToken closeParenToken, StatementSyntax statement) => ForStatement(attributeLists: default, forKeyword, openParenToken, declaration, initializers, firstSemicolonToken, condition, secondSemicolonToken, incrementors, closeParenToken, statement); } }
mit
C#
db9a27d64c2dbc38b82854c35d3f60d5822cbfbf
Allow empty semver components to be deserialised as this might be an archived component
Aqovia/OctopusPuppet
src/OctopusPuppet/DeploymentPlanner/SemVerJsonConverter.cs
src/OctopusPuppet/DeploymentPlanner/SemVerJsonConverter.cs
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace OctopusPuppet.DeploymentPlanner { public class SemVerJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); var version = token.ToString(); if (string.IsNullOrEmpty(version)) return null; return new SemVer(version); } public override bool CanConvert(Type objectType) { return typeof(SemVer).IsAssignableFrom(objectType); } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace OctopusPuppet.DeploymentPlanner { public class SemVerJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var token = JToken.Load(reader); var version = token.ToString(); return new SemVer(version); } public override bool CanConvert(Type objectType) { return typeof(SemVer).IsAssignableFrom(objectType); } } }
apache-2.0
C#
4862bfeef1847e51ee5ddd84aacab44b918fd065
set OpenFileDialog's Multiselect property to true to allow multiple archives to be selected
matortheeternal/mod-analyzer
ModAnalyzer/ViewModels/HomeViewModel.cs
ModAnalyzer/ViewModels/HomeViewModel.cs
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; using ModAnalyzer.Messages; using System.Windows.Forms; using System.Windows.Input; namespace ModAnalyzer.ViewModels { public class HomeViewModel : ViewModelBase { public ICommand BrowseCommand { get; set; } public HomeViewModel() { BrowseCommand = new RelayCommand(Browse); } private void Browse() { OpenFileDialog openFileDialog = new OpenFileDialog { Title = "Select a mod archive", Filter = "Archive Files (*.zip, *.7z, *.rar)|*.zip;*.7z;*.rar", Multiselect = true }; if (openFileDialog.ShowDialog() == DialogResult.OK) MessengerInstance.Send(new FileSelectedMessage(openFileDialog.FileName)); } } }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.CommandWpf; using ModAnalyzer.Messages; using System.Windows.Forms; using System.Windows.Input; namespace ModAnalyzer.ViewModels { public class HomeViewModel : ViewModelBase { public ICommand BrowseCommand { get; set; } public HomeViewModel() { BrowseCommand = new RelayCommand(Browse); } private void Browse() { OpenFileDialog openFileDialog = new OpenFileDialog { Title = "Select a mod archive", Filter = "Archive Files (*.zip, *.7z, *.rar)|*.zip;*.7z;*.rar" }; if (openFileDialog.ShowDialog() == DialogResult.OK) MessengerInstance.Send(new FileSelectedMessage(openFileDialog.FileName)); } } }
mit
C#
576a0b5516d2ac255bb9a5bf1580bca620c757b3
Update ActionCollection.cs
wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors,XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactivity/ActionCollection.cs
src/Avalonia.Xaml.Interactivity/ActionCollection.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Specialized; using Avalonia.Collections; namespace Avalonia.Xaml.Interactivity { /// <summary> /// Represents a collection of <see cref="IAction"/>. /// </summary> public sealed class ActionCollection : AvaloniaList<AvaloniaObject> { /// <summary> /// Initializes a new instance of the <see cref="ActionCollection"/> class. /// </summary> public ActionCollection() { CollectionChanged += ActionCollection_CollectionChanged; } private void ActionCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs eventArgs) { NotifyCollectionChangedAction collectionChange = eventArgs.Action; if (collectionChange == NotifyCollectionChangedAction.Reset) { foreach (AvaloniaObject item in this) { VerifyType(item); } } else if (collectionChange == NotifyCollectionChangedAction.Add || collectionChange == NotifyCollectionChangedAction.Replace) { AvaloniaObject changedItem = (AvaloniaObject)eventArgs.NewItems[0]; VerifyType(changedItem); } } private static void VerifyType(AvaloniaObject item) { if (!(item is IAction)) { throw new InvalidOperationException("Only IAction types are supported in an ActionCollection."); } } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Specialized; using Avalonia.Collections; namespace Avalonia.Xaml.Interactivity { /// <summary> /// Represents a collection of IActions. /// </summary> public sealed class ActionCollection : AvaloniaList<AvaloniaObject> { /// <summary> /// Initializes a new instance of the <see cref="ActionCollection"/> class. /// </summary> public ActionCollection() { CollectionChanged += ActionCollection_CollectionChanged; } private void ActionCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs eventArgs) { NotifyCollectionChangedAction collectionChange = eventArgs.Action; if (collectionChange == NotifyCollectionChangedAction.Reset) { foreach (AvaloniaObject item in this) { VerifyType(item); } } else if (collectionChange == NotifyCollectionChangedAction.Add || collectionChange == NotifyCollectionChangedAction.Replace) { AvaloniaObject changedItem = (AvaloniaObject)eventArgs.NewItems[0]; VerifyType(changedItem); } } private static void VerifyType(AvaloniaObject item) { if (!(item is IAction)) { throw new InvalidOperationException("Only IAction types are supported in an ActionCollection."); } } } }
mit
C#
8cff6b31892d0b14a961bec0ff9b82e39a97d2e3
Remove using statement.
ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,naoey/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,default0/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,RedNesto/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,ppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,ZLima12/osu-framework,ppy/osu-framework,RedNesto/osu-framework,paparony03/osu-framework,Tom94/osu-framework,smoogipooo/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,naoey/osu-framework
osu.Framework/Input/MouseState.cs
osu.Framework/Input/MouseState.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using OpenTK; using OpenTK.Input; using System.Linq; namespace osu.Framework.Input { public class MouseState : IMouseState { public IMouseState LastState; private const int mouse_button_count = (int)MouseButton.LastButton; public bool[] PressedButtons = new bool[mouse_button_count]; public IMouseState NativeState => this; public virtual int WheelDelta => Wheel - (LastState?.Wheel ?? 0); public int Wheel { get; set; } public bool HasMainButtonPressed => IsPressed(MouseButton.Left )|| IsPressed(MouseButton.Right); public bool HasAnyButtonPressed => PressedButtons.Any(b => b); public Vector2 Delta => Position - (LastState?.Position ?? Vector2.Zero); public Vector2 Position { get; protected set; } public Vector2 LastPosition => LastState?.Position ?? Position; public Vector2? PositionMouseDown { get; internal set; } public void SetLast(IMouseState last) { (last as MouseState)?.SetLast(null); LastState = last; if (last != null) PositionMouseDown = last.PositionMouseDown; } public IMouseState Clone() { var clone = (MouseState)MemberwiseClone(); clone.PressedButtons = new bool[mouse_button_count]; Array.Copy(PressedButtons, clone.PressedButtons, mouse_button_count); clone.LastState = null; return clone; } public bool IsPressed(MouseButton button) => PressedButtons[(int)button]; public void SetPressed(MouseButton button, bool pressed) => PressedButtons[(int)button] = pressed; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Collections.Generic; using OpenTK; using OpenTK.Input; using System.Linq; namespace osu.Framework.Input { public class MouseState : IMouseState { public IMouseState LastState; private const int mouse_button_count = (int)MouseButton.LastButton; public bool[] PressedButtons = new bool[mouse_button_count]; public IMouseState NativeState => this; public virtual int WheelDelta => Wheel - (LastState?.Wheel ?? 0); public int Wheel { get; set; } public bool HasMainButtonPressed => IsPressed(MouseButton.Left )|| IsPressed(MouseButton.Right); public bool HasAnyButtonPressed => PressedButtons.Any(b => b); public Vector2 Delta => Position - (LastState?.Position ?? Vector2.Zero); public Vector2 Position { get; protected set; } public Vector2 LastPosition => LastState?.Position ?? Position; public Vector2? PositionMouseDown { get; internal set; } public void SetLast(IMouseState last) { (last as MouseState)?.SetLast(null); LastState = last; if (last != null) PositionMouseDown = last.PositionMouseDown; } public IMouseState Clone() { var clone = (MouseState)MemberwiseClone(); clone.PressedButtons = new bool[mouse_button_count]; Array.Copy(PressedButtons, clone.PressedButtons, mouse_button_count); clone.LastState = null; return clone; } public bool IsPressed(MouseButton button) => PressedButtons[(int)button]; public void SetPressed(MouseButton button, bool pressed) => PressedButtons[(int)button] = pressed; } }
mit
C#
397728668004b2875a12d4382e2ba910dbbe04af
Make use of result parser in API
anderslundsgard/sun-api,anderslundsgard/sun-api
SunApi/Controllers/SunriseController.cs
SunApi/Controllers/SunriseController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using SunLib; using SunLib.Models; using SunLib.Utils; namespace SunApi.Controllers { public class SunriseController : ApiController { // Sample request so far: http://sunriseandfall.azurewebsites.net/api/sunrise?lat=57.13&lon=17.1759&date=2015-11-30 // localhost:4410/api/sunrise?lat=59.76&lon=17.13&date=2015-11-30 // GET: api/sunrise?lat=57.3&lon=17.16&2015-11-30 public Astrodata Get(double lat, double lon, DateTime date) { GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; IYrNoAdapter adapter = new YrNoAdapter(); IYrNoResultParser parser = new YrNoResultParser(); var doc = adapter.GetSunInfo(lat, lon, date); var astrodata = parser.GetAstrodataByResult(doc); return astrodata; } // GET: api/sunrise public IEnumerable<string> Get() { return new string[] { "Just", "Test", "Call" }; } //// get: api/sun/5 //public string get(int id) //{ // return "value " + id; //} //// post: api/sun //public void post([frombody]string value) //{ //} //// put: api/sun/5 //public void put(int id, [frombody]string value) //{ //} //// delete: api/sun/5 //public void delete(int id) //{ //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using SunLib; using SunLib.Models; namespace SunApi.Controllers { public class SunriseController : ApiController { // Sample request so far: http://sunriseandfall.azurewebsites.net/api/sunrise?lat=57.13&lon=17.1759&date=2015-11-30 // localhost:4410/api/sunrise?lat=59.76&lon=17.13&date=2015-11-30 // GET: api/sunrise?lat=57.3&lon=17.16&2015-11-30 public Astrodata Get(double lat, double lon, DateTime date) { GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true; YrNoAdapter adapter = new YrNoAdapter(); var result = adapter.GetSunInfo(lat, lon, date); //return result.InnerXml; return new Astrodata(); } // GET: api/sunrise public IEnumerable<string> Get() { return new string[] { "Just", "Test", "Call" }; } //// get: api/sun/5 //public string get(int id) //{ // return "value " + id; //} //// post: api/sun //public void post([frombody]string value) //{ //} //// put: api/sun/5 //public void put(int id, [frombody]string value) //{ //} //// delete: api/sun/5 //public void delete(int id) //{ //} } }
mit
C#
4b35ce84e60366ba15a972d9e2dc97cdc9fe85d2
Bump version
rucila/PushSharp,arleyandrada/PushSharp,18098924759/PushSharp,cafeburger/PushSharp,wanglj7525/PushSharp,bobqian1130/PushSharp,kouweizhong/PushSharp,ingljo/PushSharp,profporridge/PushSharp,fhchina/PushSharp,ZanoMano/PushSharp,wanglj7525/PushSharp,richardvaldivieso/PushSharp,18098924759/PushSharp,FragCoder/PushSharp,profporridge/PushSharp,fhchina/PushSharp,has-taiar/PushSharp.Web,SuPair/PushSharp,lizhi5753186/PushSharp,fanpan26/PushSharp,volkd/PushSharp,chaoscope/PushSharp,codesharpdev/PushSharp,rolltechrick/PushSharp,zoser0506/PushSharp,FragCoder/PushSharp,JeffCertain/PushSharp,codesharpdev/PushSharp,richardvaldivieso/PushSharp,kouweizhong/PushSharp,mao1350848579/PushSharp,arleyandrada/PushSharp,cafeburger/PushSharp,ingljo/PushSharp,sumalla/PushSharp,SuPair/PushSharp,yuejunwu/PushSharp,cafeburger/PushSharp,yuejunwu/PushSharp,ZanoMano/PushSharp,ZanoMano/PushSharp,JeffCertain/PushSharp,bobqian1130/PushSharp,tianhang/PushSharp,kouweizhong/PushSharp,wanglj7525/PushSharp,yuejunwu/PushSharp,bberak/PushSharp,tianhang/PushSharp,agran/PushSharp,cnbin/PushSharp,zoser0506/PushSharp,volkd/PushSharp,rolltechrick/PushSharp,18098924759/PushSharp,sskodje/PushSharp,sskodje/PushSharp,rolltechrick/PushSharp,rucila/PushSharp,codesharpdev/PushSharp,agran/PushSharp,zoser0506/PushSharp,tianhang/PushSharp,profporridge/PushSharp,fhchina/PushSharp,fanpan26/PushSharp,sskodje/PushSharp,rucila/PushSharp,FragCoder/PushSharp,mao1350848579/PushSharp,richardvaldivieso/PushSharp,fanpan26/PushSharp,SuPair/PushSharp,bobqian1130/PushSharp,sumalla/PushSharp,chaoscope/PushSharp,has-taiar/PushSharp.Web,bberak/PushSharp,ingljo/PushSharp,mao1350848579/PushSharp,sumalla/PushSharp,chaoscope/PushSharp,agran/PushSharp,JeffCertain/PushSharp,volkd/PushSharp,cnbin/PushSharp,cnbin/PushSharp
PushSharp.Common/AssemblyVersionInfo.cs
PushSharp.Common/AssemblyVersionInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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.12.0")] [assembly: AssemblyFileVersion("1.0.12.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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.11.0")] [assembly: AssemblyFileVersion("1.0.11.0")]
apache-2.0
C#
57d79d8d4d87f2bb142da0b8cb2658f3779af462
Fix filename not being populated
michaKFromParis/octokit.net,thedillonb/octokit.net,shana/octokit.net,darrelmiller/octokit.net,M-Zuber/octokit.net,gdziadkiewicz/octokit.net,TattsGroup/octokit.net,SamTheDev/octokit.net,shiftkey/octokit.net,devkhan/octokit.net,Red-Folder/octokit.net,kolbasov/octokit.net,hahmed/octokit.net,rlugojr/octokit.net,fffej/octokit.net,magoswiat/octokit.net,brramos/octokit.net,devkhan/octokit.net,Sarmad93/octokit.net,daukantas/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,Sarmad93/octokit.net,khellang/octokit.net,SLdragon1989/octokit.net,takumikub/octokit.net,shiftkey-tester/octokit.net,mminns/octokit.net,octokit-net-test-org/octokit.net,nsnnnnrn/octokit.net,ivandrofly/octokit.net,adamralph/octokit.net,fake-organization/octokit.net,SamTheDev/octokit.net,hahmed/octokit.net,eriawan/octokit.net,alfhenrik/octokit.net,chunkychode/octokit.net,dampir/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,ivandrofly/octokit.net,editor-tools/octokit.net,octokit/octokit.net,bslliw/octokit.net,thedillonb/octokit.net,gabrielweyer/octokit.net,TattsGroup/octokit.net,gabrielweyer/octokit.net,octokit-net-test-org/octokit.net,naveensrinivasan/octokit.net,ChrisMissal/octokit.net,nsrnnnnn/octokit.net,khellang/octokit.net,hitesh97/octokit.net,rlugojr/octokit.net,octokit/octokit.net,forki/octokit.net,kdolan/octokit.net,cH40z-Lord/octokit.net,mminns/octokit.net,geek0r/octokit.net,SmithAndr/octokit.net,eriawan/octokit.net,dlsteuer/octokit.net,M-Zuber/octokit.net,shiftkey/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,gdziadkiewicz/octokit.net,SmithAndr/octokit.net,alfhenrik/octokit.net,dampir/octokit.net,octokit-net-test/octokit.net,shana/octokit.net,editor-tools/octokit.net
Octokit/Models/Response/PullRequestFile.cs
Octokit/Models/Response/PullRequestFile.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Octokit.Internal; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PullRequestFile { public PullRequestFile() { } public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch) { Sha = sha; FileName = fileName; Status = status; Additions = additions; Deletions = deletions; Changes = changes; BlobUri = blobUri; RawUri = rawUri; ContentsUri = contentsUri; Patch = patch; } public string Sha { get; protected set; } [Parameter(Key = "filename")] public string FileName { get; protected set; } public string Status { get; protected set; } public int Additions { get; protected set; } public int Deletions { get; protected set; } public int Changes { get; protected set; } public Uri BlobUri { get; protected set; } public Uri RawUri { get; protected set; } public Uri ContentsUri { get; protected set; } public string Patch { get; protected set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} FileName: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Octokit { [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PullRequestFile { public PullRequestFile() { } public PullRequestFile(string sha, string fileName, string status, int additions, int deletions, int changes, Uri blobUri, Uri rawUri, Uri contentsUri, string patch) { Sha = sha; FileName = fileName; Status = status; Additions = additions; Deletions = deletions; Changes = changes; BlobUri = blobUri; RawUri = rawUri; ContentsUri = contentsUri; Patch = patch; } public string Sha { get; protected set; } public string FileName { get; protected set; } public string Status { get; protected set; } public int Additions { get; protected set; } public int Deletions { get; protected set; } public int Changes { get; protected set; } public Uri BlobUri { get; protected set; } public Uri RawUri { get; protected set; } public Uri ContentsUri { get; protected set; } public string Patch { get; protected set; } internal string DebuggerDisplay { get { return String.Format(CultureInfo.InvariantCulture, "Sha: {0} Filename: {1} Additions: {2} Deletions: {3} Changes: {4}", Sha, FileName, Additions, Deletions, Changes); } } } }
mit
C#
2aa6af0bb71a534c7fe6dafa950b9513ee083c0c
Update UI display gate number
surrealist/ParkingSpace,surrealist/ParkingSpace,surrealist/ParkingSpace
ParkingSpace.Web/Views/GateIn/Index.cshtml
ParkingSpace.Web/Views/GateIn/Index.cshtml
@using ParkingSpace.Models @{ ViewBag.Title = "Index"; var ticket = (ParkingTicket)TempData["newTicket"]; } <h2>Gate In</h2> <div class="well well-sm"> <strong>Gate:</strong> @ViewBag.GateId </div> @using (Html.BeginForm("CreateTicket", "GateIn")) { <div> Plate No.:<br /> @Html.TextBox("plateNo")<br /> <br /> <button type="submit" class="btn btn-success"> Issue Parking Ticket </button> </div> } @if (ticket != null) { <br /> <div class="well"> @ticket.Id <br /> @ticket.PlateNumber<br /> @ticket.DateIn </div> }
@using ParkingSpace.Models @{ ViewBag.Title = "Index"; var ticket = (ParkingTicket)TempData["newTicket"]; } <h2>Gate In [@ViewBag.GateId]</h2> @using (Html.BeginForm("CreateTicket", "GateIn")) { <div> Plate No.:<br /> @Html.TextBox("plateNo")<br /> <br /> <button type="submit" class="btn btn-success"> Issue Parking Ticket </button> </div> } @if (ticket != null) { <br/> <div class="well"> @ticket.Id <br /> @ticket.PlateNumber<br/> @ticket.DateIn </div> }
mit
C#
8c404ed74f5d19c52031e2e937695f00ffa13d6c
Update IShellCommandEngine.cs
tiksn/TIKSN-Framework
TIKSN.Core/Shell/IShellCommandEngine.cs
TIKSN.Core/Shell/IShellCommandEngine.cs
using System; using System.Reflection; using System.Threading.Tasks; namespace TIKSN.Shell { public interface IShellCommandEngine { void AddAssembly(Assembly assembly); void AddType(Type type); Task RunAsync(); } }
using System; using System.Reflection; using System.Threading.Tasks; namespace TIKSN.Shell { public interface IShellCommandEngine { void AddAssembly(Assembly assembly); void AddType(Type type); Task RunAsync(); } }
mit
C#
a23f669a0a5f1b284c86a4f340a6463a3535ce5d
Add documentation
c0nnex/SPAD.neXt,c0nnex/SPAD.neXt
SPAD.Interfaces/Callout/ICalloutManager.cs
SPAD.Interfaces/Callout/ICalloutManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.Callout { public interface ICallout : IDisposable { /// <summary> /// Unique id for this callout /// </summary> long CalloutID { get; } /// <summary> /// Timestamp when the callout was scheduled /// </summary> DateTime When { get; } /// <summary> /// Timespan when a reschedule will occour /// </summary> TimeSpan Delay { get; set; } /// <summary> /// Set to true if the callout should not be rescheduled /// </summary> bool Done { get; set; } /// <summary> /// True if the callout will reschedule itself /// </summary> bool Persistent { get; } /// <summary> /// Owner of the callout /// </summary> object Owner { get; } /// <summary> /// Optional parameter /// </summary> object Parameter { get; } /// <summary> /// terminate any pending schedules for this callout /// </summary> void EndSchedule(); /// <summary> /// Enforce the callout to be rescheduled (even if it was marked as one-time only) /// </summary> void Reschdedule(); } /// <summary> /// Interface for periodic scheduled tasks. /// Do not use Timers! /// </summary> public interface ICalloutManager { /// <summary> /// Create a callout (timer) /// </summary> /// <param name="owner">Owner of the callout. There is a limit of 50 callouts per owner</param> /// <param name="callback">the callback that will be called when the callout occours</param> /// <param name="parameter">optional parameter for the callback</param> /// <param name="delay">When or how often shall the callout occour. Callouts have a accurateness of +/- 150ms</param> /// <param name="persistant">if true the callout will reschedule itself again after begin executed. if false the callout will be disposed automatically after one occourance</param> /// <returns></returns> ICallout AddCallout(object owner, EventHandler<ICallout> callback, object parameter , TimeSpan delay, bool persistant); /// <summary> /// Unschedule a callout /// </summary> /// <param name="callout"></param> void RemoveCallout(ICallout callout); /// <summary> /// Unschedule a callout /// </summary> /// <param name="calloutId"></param> void RemoveCallout(long calloutId); /// <summary> /// Unschedule all callouts for a specific owner /// </summary> /// <param name="owner"></param> void RemoveAllCalloutsFor(object owner); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.Callout { public interface ICallout { long CalloutID { get; } DateTime When { get; } TimeSpan Delay { get; } bool Done { get; set; } bool Persistent { get; } object Owner { get; } object Parameter { get; } void EndSchedule(); void Reschdedule(); } public interface ICalloutManager { ICallout AddCallout(object owner, EventHandler<ICallout> callback, object parameter , TimeSpan delay, bool persistant); void RemoveCallout(ICallout callout); void RemoveAllCalloutsFor(object owner); } }
mit
C#
ba00b83fe8a8016172d891fffeede68f3ebc5826
Allow creation of tiles from bitmaps.
clicketyclack/TileExchange
TileExchange/TileSet/Tile.cs
TileExchange/TileSet/Tile.cs
/* * Copyright (C) 2017 Erik Mossberg * * This file is part of TileExchanger. * * TileExchanger is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TileExchanger is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ using System; using System.Drawing; namespace TileExchange.Tile { /// <summary> /// A single tile. /// </summary> public interface ITile { Size GetSize(); Color AverageColor(); } public class Tile : ITile { protected Bitmap image; protected Tile() { } public Size GetSize() { return image.Size; //return new Size { Width = 16, Height = 16 }; } /// <summary> /// Calculate average /// </summary> /// <returns>A new color with RGB channels matching the average of the tile.</returns> public Color AverageColor() { int r = 0; int g = 0; int b = 0; var size = GetSize(); int pixcount = size.Width * size.Height; for (var x = 0; x < size.Width; x++) { for (var y = 0; y < size.Width; y++) { var color = image.GetPixel(x, y); r += color.R; g += color.G; b += color.B; } } byte br = (Byte)(r / pixcount); byte bg = (Byte)(g / pixcount); byte bb = (Byte)(b / pixcount); return ImageProcessor.Imaging.Colors.RgbaColor.FromRgba(br, bg, bb, 0xff); } } public class Square16Tile : Tile { /// <summary> /// Initializes a new simple tile of size 16x16. /// </summary> public Square16Tile() { image = new Bitmap(16, 16); } } public class BitmapTile : Tile { /// <summary> /// Create a Tile from a bitmap. /// </summary> /// <param name="bitmap">Bitmap to base tile off.</param> public BitmapTile(Bitmap bitmap) { this.image = bitmap; } } /// <summary> /// Generated solid tile. /// </summary> public class GeneratedSolidTile : Tile { public GeneratedSolidTile(Size size, Color color) { image = new Bitmap(size.Width, size.Height); for (var x = 0; x < size.Width; x++) { for (var y = 0; y < size.Width; y++) { image.SetPixel(x, y, color); } } } } }
/* * Copyright (C) 2017 Erik Mossberg * * This file is part of TileExchanger. * * TileExchanger is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * TileExchanger is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ using System; using System.Drawing; namespace TileExchange.Tile { /// <summary> /// A single tile. /// </summary> public interface ITile { Size GetSize(); Color AverageColor(); } public class Tile : ITile { protected Bitmap image; protected Tile() { } public Size GetSize() { return image.Size; //return new Size { Width = 16, Height = 16 }; } /// <summary> /// Calculate average /// </summary> /// <returns>A new color with RGB channels matching the average of the tile.</returns> public Color AverageColor() { int r = 0; int g = 0; int b = 0; var size = GetSize(); int pixcount = size.Width * size.Height; for (var x = 0; x < size.Width; x++) { for (var y = 0; y < size.Width; y++) { var color = image.GetPixel(x, y); r += color.R; g += color.G; b += color.B; } } byte br = (Byte)(r / pixcount); byte bg = (Byte)(g / pixcount); byte bb = (Byte)(b / pixcount); return ImageProcessor.Imaging.Colors.RgbaColor.FromRgba(br, bg, bb, 0xff); } } public class Square16Tile : Tile { public Square16Tile() { image = new Bitmap(16, 16); } } /// <summary> /// Generated solid tile. /// </summary> public class GeneratedSolidTile : Tile { public GeneratedSolidTile(Size size, Color color) { image = new Bitmap(size.Width, size.Height); for (var x = 0; x < size.Width; x++) { for (var y = 0; y < size.Width; y++) { image.SetPixel(x, y, color); } } } } }
agpl-3.0
C#
930cae2e751debb01061fa8ec3a31ad9fa665e6d
Fix a ref to FinnAngelo.PomoFish
FinnAngelo/PomoFish
FinnAngelo.PomoFishTests/IconTests.cs
FinnAngelo.PomoFishTests/IconTests.cs
using Common.Logging; using FinnAngelo.PomoFish; using FinnAngelo.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Diagnostics; namespace FinnAngelo.PomoFishTests { [TestClass] public class IconTests { [TestMethod] //[Ignore] public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException() { //Given var moqLog = new Mock<ILog>(); var im = new IconManager(moqLog.Object); //When for (int a = 0; a < 150; a++) { im.SetNotifyIcon(null, Pomodoro.Resting, a); } //Then Assert.IsTrue(true, "this too, shall pass..."); } } }
using Common.Logging; using FinnAngelo.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System.Diagnostics; namespace FinnAngelo.PomoFishTests { [TestClass] public class IconTests { [TestMethod] //[Ignore] public void GivenDestroyMethod_WhenGet10000Icons_ThenNoException() { //Given var moqLog = new Mock<ILog>(); var im = new IconManager(moqLog.Object); //When for (int a = 0; a < 150; a++) { im.SetNotifyIcon(null, Pomodoro.Resting, a); } //Then Assert.IsTrue(true, "this too, shall pass..."); } } }
mit
C#
ef500361b355c1cacfb1b8100d7a4921d170cb55
support for range filter
janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent
Components/JPList/StatusDataDTO.cs
Components/JPList/StatusDataDTO.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Satrabel.OpenContent.Components.JPList { public class StatusDataDTO { #region "Common" /// <summary> /// jquery path or "default" /// </summary> public string path { get; set; } /// <summary> /// ignore regex /// </summary> public string ignore { get; set; } #endregion #region "Filtering" /// <summary> /// filter value /// </summary> public string value { get; set; } /// <summary> /// filter type: TextFilter, pathGroup, .. /// </summary> public string filterType { get; set; } /// <summary> /// list of jquery paths /// </summary> public List<string> pathGroup { get; set; } #endregion #region "Sorting" /// <summary> /// date time format /// </summary> public string dateTimeFormat { get; set; } /// <summary> /// sort order: asc/desc /// </summary> public string order { get; set; } #endregion #region "Pagination" /// <summary> /// items number - string value (it could be number or "all") /// </summary> public string number { get; set; } /// <summary> /// the current page index /// </summary> public int currentPage { get; set; } #endregion public string min { get; set; } public string max { get; set; } public string prev { get; set; } public string next { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Satrabel.OpenContent.Components.JPList { public class StatusDataDTO { #region "Common" /// <summary> /// jquery path or "default" /// </summary> public string path { get; set; } /// <summary> /// ignore regex /// </summary> public string ignore { get; set; } #endregion #region "Filtering" /// <summary> /// filter value /// </summary> public string value { get; set; } /// <summary> /// filter type: TextFilter, pathGroup, .. /// </summary> public string filterType { get; set; } /// <summary> /// list of jquery paths /// </summary> public List<string> pathGroup { get; set; } #endregion #region "Sorting" /// <summary> /// date time format /// </summary> public string dateTimeFormat { get; set; } /// <summary> /// sort order: asc/desc /// </summary> public string order { get; set; } #endregion #region "Pagination" /// <summary> /// items number - string value (it could be number or "all") /// </summary> public string number { get; set; } /// <summary> /// the current page index /// </summary> public int currentPage { get; set; } #endregion } }
mit
C#
c4ce4a7dcaafc346cea42416ee2636bf561a8563
Resolve conflict
jacobrossandersen/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //Code was edited in GitHub //Code was added in VS //Code to call Feature1 //Code to call Feature2 //Code to call Feature3 } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //Code was edited in GitHub //Code was added in VS //Code to call Feature1 //Code to call Feature2 } } }
mit
C#
18e04f3b449cb1e3e71fecb97bf9f4ad736e5df6
Change Check tests to restore default behaviour
yakimovim/verifier
Verifier.Tests/CheckTests.cs
Verifier.Tests/CheckTests.cs
using System; using EdlinSoftware.Verifier.Tests.Support; using Xunit; namespace EdlinSoftware.Verifier.Tests { public class CheckTests : IDisposable { private readonly StringVerifier _verifier; private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed; public CheckTests() { Verifier.AssertionFailed = DefaultAssertionFailed; _verifier = new StringVerifier() .AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error")); } [Fact] public void Check_Failure_ByDefault() { Assert.Throws<VerificationException>(() => _verifier.Check("failure")); } [Fact] public void Check_Success_ByDefault() { _verifier.Check("success"); } [Fact] public void Check_CustomAssert() { Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage); Assert.Equal( "error", Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message ); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { Verifier.AssertionFailed = DefaultAssertionFailed; } } }
using System; using EdlinSoftware.Verifier.Tests.Support; using Xunit; namespace EdlinSoftware.Verifier.Tests { public class CheckTests : IDisposable { private readonly StringVerifier _verifier; private static readonly Action<string> DefaultAssertionFailed = Verifier.AssertionFailed; public CheckTests() { _verifier = new StringVerifier() .AddVerifiers(sut => VerificationResult.Critical(sut == "success" ? null : "error")); } [Fact] public void Check_Failure_ByDefault() { Assert.Throws<VerificationException>(() => _verifier.Check("failure")); } [Fact] public void Check_Success_ByDefault() { _verifier.Check("success"); } [Fact] public void Check_CustomAssert() { Verifier.AssertionFailed = errorMessage => throw new InvalidOperationException(errorMessage); Assert.Equal( "error", Assert.Throws<InvalidOperationException>(() => _verifier.Check("failure")).Message ); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool isDisposing) { Verifier.AssertionFailed = DefaultAssertionFailed; } } }
mit
C#
c2ad2c7820ab5ada5e04d2a15e94d70321175f2d
Fix Pluralizer culture recognition. Fix #26.
diolive/cache,diolive/cache
DioLive.Cache/src/DioLive.Common.Localization/Pluralizer.cs
DioLive.Cache/src/DioLive.Common.Localization/Pluralizer.cs
using System.Collections.Generic; using System.Globalization; namespace DioLive.Common.Localization { public class Pluralizer { private string defaultLanguage; private Dictionary<string, ILanguagePluralizer> pluralizers; public Pluralizer(string defaultLanguage = "en-US") { this.defaultLanguage = defaultLanguage; this.pluralizers = new Dictionary<string, ILanguagePluralizer>(); } public void AddLanguage(ILanguagePluralizer pluralizer) { this.pluralizers.Add(pluralizer.Language, pluralizer); } public string this[int number] { get { var culture = CultureInfo.CurrentUICulture; while (culture != CultureInfo.InvariantCulture && !this.pluralizers.ContainsKey(culture.Name)) { culture = culture.Parent; } string cultureName = (culture != CultureInfo.InvariantCulture) ? culture.Name : this.defaultLanguage; return this.pluralizers[cultureName].Pluralize(number); } } } }
using System.Collections.Generic; using System.Globalization; namespace DioLive.Common.Localization { public class Pluralizer { private string defaultLanguage; private Dictionary<string, ILanguagePluralizer> pluralizers; public Pluralizer(string defaultLanguage = "en-US") { this.defaultLanguage = defaultLanguage; this.pluralizers = new Dictionary<string, ILanguagePluralizer>(); } public void AddLanguage(ILanguagePluralizer pluralizer) { this.pluralizers.Add(pluralizer.Language, pluralizer); } public string this[int number] { get { var culture = CultureInfo.CurrentUICulture.Name; if (!this.pluralizers.ContainsKey(culture)) { culture = this.defaultLanguage; } return this.pluralizers[culture].Pluralize(number); } } } }
mit
C#
71a2650d8739a3fa11c6a9b8e0dde4a6f45a3e8c
Use same approach as TestFonts
SixLabors/Fonts
tests/SixLabors.Fonts.Tests/TestEnvironment.cs
tests/SixLabors.Fonts.Tests/TestEnvironment.cs
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.IO; using System.Linq; using System.Reflection; namespace SixLabors.Fonts.Tests { internal static class TestEnvironment { private const string SixLaborsSolutionFileName = "SixLabors.Fonts.sln"; private const string UnicodeTestDataRelativePath = @"tests\UnicodeTestData\"; private static readonly Lazy<string> SolutionDirectoryFullPathLazy = new Lazy<string>(GetSolutionDirectoryFullPathImpl); internal static string SolutionDirectoryFullPath => SolutionDirectoryFullPathLazy.Value; /// <summary> /// Gets the correct full path to the Unicode TestData directory. /// </summary> internal static string UnicodeTestDataFullPath => GetFullPath(UnicodeTestDataRelativePath); private static string GetSolutionDirectoryFullPathImpl() { string assemblyLocation = Path.GetDirectoryName(new Uri(typeof(TestEnvironment).GetTypeInfo().Assembly.CodeBase).LocalPath); var assemblyFile = new FileInfo(assemblyLocation); DirectoryInfo directory = assemblyFile.Directory; while (!directory.EnumerateFiles(SixLaborsSolutionFileName).Any()) { try { directory = directory.Parent; } catch (Exception ex) { throw new Exception( $"Unable to find SixLabors solution directory from {assemblyLocation} because of {ex.GetType().Name}!", ex); } if (directory == null) { throw new Exception($"Unable to find SixLabors solution directory from {assemblyLocation}!"); } } return directory.FullName; } private static string GetFullPath(string relativePath) => Path.Combine(SolutionDirectoryFullPath, relativePath) .Replace('\\', Path.DirectorySeparatorChar); } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.IO; using System.Linq; using System.Reflection; namespace SixLabors.Fonts.Tests { internal static class TestEnvironment { private const string SixLaborsSolutionFileName = "SixLabors.Fonts.sln"; private const string UnicodeTestDataRelativePath = @"tests\UnicodeTestData\"; private static readonly Lazy<string> SolutionDirectoryFullPathLazy = new Lazy<string>(GetSolutionDirectoryFullPathImpl); internal static string SolutionDirectoryFullPath => SolutionDirectoryFullPathLazy.Value; /// <summary> /// Gets the correct full path to the Unicode TestData directory. /// </summary> internal static string UnicodeTestDataFullPath => GetFullPath(UnicodeTestDataRelativePath); private static string GetSolutionDirectoryFullPathImpl() { string assemblyLocation = typeof(TestEnvironment).GetTypeInfo().Assembly.Location; var assemblyFile = new FileInfo(assemblyLocation); DirectoryInfo directory = assemblyFile.Directory; while (!directory.EnumerateFiles(SixLaborsSolutionFileName).Any()) { try { directory = directory.Parent; } catch (Exception ex) { throw new Exception( $"Unable to find SixLabors solution directory from {assemblyLocation} because of {ex.GetType().Name}!", ex); } if (directory == null) { throw new Exception($"Unable to find SixLabors solution directory from {assemblyLocation}!"); } } return directory.FullName; } private static string GetFullPath(string relativePath) => Path.Combine(SolutionDirectoryFullPath, relativePath) .Replace('\\', Path.DirectorySeparatorChar); } }
apache-2.0
C#
441c27e54ca64fa701b7e9e8cb498f8149452149
add policy
IdentityModel/IdentityModel.OidcClient.Samples,IdentityModel/IdentityModel.OidcClient.Samples
WpfWebView2/WpfWebView2/MainWindow.xaml.cs
WpfWebView2/WpfWebView2/MainWindow.xaml.cs
using IdentityModel.OidcClient; using System; using System.Windows; namespace WpfWebView2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Window_Loaded(object sender, RoutedEventArgs e) { var options = new OidcClientOptions() { Authority = "https://demo.identityserver.io/", ClientId = "interactive.public", Scope = "openid profile email", RedirectUri = "http://127.0.0.1/sample-wpf-app", Browser = new WpfEmbeddedBrowser(), Policy = new Policy { RequireIdentityTokenSignature = false } }; var _oidcClient = new OidcClient(options); LoginResult loginResult; try { loginResult = await _oidcClient.LoginAsync(); } catch (Exception exception) { txbMessage.Text = $"Unexpected Error: {exception.Message}"; return; } if (loginResult.IsError) { txbMessage.Text = loginResult.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : loginResult.Error; } else { txbMessage.Text = loginResult.User.Identity.Name; } } } }
using IdentityModel.OidcClient; using System; using System.Windows; namespace WpfWebView2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Window_Loaded(object sender, RoutedEventArgs e) { var options = new OidcClientOptions() { Authority = "https://demo.identityserver.io/", ClientId = "interactive.public", Scope = "openid profile email", RedirectUri = "http://127.0.0.1/sample-wpf-app", Browser = new WpfEmbeddedBrowser() }; var _oidcClient = new OidcClient(options); LoginResult loginResult; try { loginResult = await _oidcClient.LoginAsync(); } catch (Exception exception) { txbMessage.Text = $"Unexpected Error: {exception.Message}"; return; } if (loginResult.IsError) { txbMessage.Text = loginResult.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : loginResult.Error; } else { txbMessage.Text = loginResult.User.Identity.Name; } } } }
apache-2.0
C#
9e84f2a799668dcb03492466cf1a33fa0b217e2c
Implement property converter for XPath
zpqrtbnk/Zbu.Blocks,zpqrtbnk/Zbu.Blocks
Zbu.Blocks/DataType/StructuresConverter.cs
Zbu.Blocks/DataType/StructuresConverter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Models.PublishedContent; using Zbu.Blocks.PropertyEditors; namespace Zbu.Blocks.DataType { // note: can cache the converted value at .Content level because it's just // a deserialized json and it does not reference anything outside its content. [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] [PropertyValueType(typeof(IEnumerable<StructureDataValue>))] public class StructuresConverter : IPropertyValueConverter { public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { // data == source so we can return json to xpath return source; } public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { // object == deserialized source var json = source.ToString(); if (string.IsNullOrWhiteSpace(json)) return null; var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json); foreach (var v in value) v.EnsureFragments(preview); return value; } public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview) { // we don't really want to support XML for blocks // so xpath == source == data == the original json return source; } public bool IsConverter(PublishedPropertyType propertyType) { #if UMBRACO_6 return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid; #else return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias; #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Umbraco.Core.Models; using Umbraco.Core.PropertyEditors; using Umbraco.Core.Models.PublishedContent; using Zbu.Blocks.PropertyEditors; namespace Zbu.Blocks.DataType { // note: can cache the converted value at .Content level because it's just // a deserialized json and it does not reference anything outside its content. [PropertyValueCache(PropertyCacheValue.All, PropertyCacheLevel.Content)] [PropertyValueType(typeof(IEnumerable<StructureDataValue>))] public class StructuresConverter : IPropertyValueConverter { public object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview) { var json = source.ToString(); if (string.IsNullOrWhiteSpace(json)) return null; var value = JsonSerializer.Instance.Deserialize<StructureDataValue[]>(json); foreach (var v in value) v.EnsureFragments(preview); return value; } public object ConvertSourceToObject(PublishedPropertyType propertyType, object source, bool preview) { return source; } public object ConvertSourceToXPath(PublishedPropertyType propertyType, object source, bool preview) { throw new NotImplementedException(); } public bool IsConverter(PublishedPropertyType propertyType) { #if UMBRACO_6 return propertyType.PropertyEditorGuid == StructuresDataType.DataTypeGuid; #else return propertyType.PropertyEditorAlias == StructuresPropertyEditor.StructuresAlias; #endif } } }
mit
C#
be186a8cd8236d87faf0550d07f760811814740a
Update Startup.cs
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/IISSample/Startup.cs
samples/IISSample/Startup.cs
using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.Logging; namespace IISSample { public class Startup { public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { loggerfactory.AddConsole(LogLevel.Verbose); var logger = loggerfactory.CreateLogger("Requests"); app.UseIISPlatformHandler(); app.Run(async (context) => { logger.LogVerbose("Received request: " + context.Request.Method + " " + context.Request.Path); context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello World - " + DateTimeOffset.Now + Environment.NewLine); await context.Response.WriteAsync("User - " + context.User.Identity.Name + Environment.NewLine); foreach (var header in context.Request.Headers) { await context.Response.WriteAsync(header.Key + ": " + header.Value + Environment.NewLine); } }); } } }
using System; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Http; using Microsoft.Framework.Logging; namespace IISSample { public class Startup { public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory) { loggerfactory.AddConsole(LogLevel.Verbose); var logger = loggerfactory.CreateLogger("Requests"); app.Run(async (context) => { logger.LogVerbose("Received request: " + context.Request.Method + " " + context.Request.Path); context.Response.ContentType = "text/plain"; await context.Response.WriteAsync("Hello World - " + DateTimeOffset.Now + Environment.NewLine); await context.Response.WriteAsync("User - " + context.User.Identity.Name + Environment.NewLine); foreach (var header in context.Request.Headers) { await context.Response.WriteAsync(header.Key + ": " + header.Value + Environment.NewLine); } }); } } }
apache-2.0
C#
96fbb43f770bbd6b98a9b7fda9b7e0109d8738a6
Update joining_audio.cs (#1176)
RogueException/Discord.Net,AntiTcb/Discord.Net
docs/guides/voice/samples/joining_audio.cs
docs/guides/voice/samples/joining_audio.cs
// The command's Run Mode MUST be set to RunMode.Async, otherwise, being connected to a voice channel will block the gateway thread. [Command("join", RunMode = RunMode.Async)] public async Task JoinChannel(IVoiceChannel channel = null) { // Get the audio channel channel = channel ?? (msg.Author as IGuildUser)?.VoiceChannel; if (channel == null) { await msg.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } // For the next step with transmitting audio, you would want to pass this Audio Client in to a service. var audioClient = await channel.ConnectAsync(); }
[Command("join")] public async Task JoinChannel(IVoiceChannel channel = null) { // Get the audio channel channel = channel ?? (msg.Author as IGuildUser)?.VoiceChannel; if (channel == null) { await msg.Channel.SendMessageAsync("User must be in a voice channel, or a voice channel must be passed as an argument."); return; } // For the next step with transmitting audio, you would want to pass this Audio Client in to a service. var audioClient = await channel.ConnectAsync(); }
mit
C#
6e419fd6d7385915f0b194261b8fe5701e8cafd4
Update AssemblyInfo.cs
KerbaeAdAstra/KSPNameGen,KerbaeAdAstra/KSPNameGen
KSPNameGen/Properties/AssemblyInfo.cs
KSPNameGen/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("KSPNameGen")] [assembly: AssemblyDescription("Free (gratis and libre) name generator for Kerbal Space Program")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kerbae ad Astra group")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Kerbae ad Astra group")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("0.2.1.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("KSPNameGen")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("${AuthorCopyright}")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
20fe0d0ade03c7d06319353b3307f85c07852a32
Clean ups
kotorihq/kotori-core
KotoriCore/Commands/ICommandResult.cs
KotoriCore/Commands/ICommandResult.cs
using System; using System.Collections; namespace KotoriCore.Commands { /// <summary> /// Command result interface. /// </summary> public interface ICommandResult { /// <summary> /// Gets the type of the element. /// </summary> /// <value>The type of the element.</value> Type ElementType { get; } /// <summary> /// Gets the data. /// </summary> /// <value>The data.</value> IEnumerable Data { get; } /// <summary> /// Gets the message. /// </summary> /// <value>The message.</value> string Message { get; } } }
using System; using System.Collections; namespace KotoriCore.Commands { public interface ICommandResult { Type ElementType { get; } IEnumerable Data { get; } string Message { get; } } }
mit
C#
f0758117bc73fd3c72bf2e028799c63b61bb047f
Update Android.Enums AutomatorSetting values (#476)
appium/appium-dotnet-driver
src/Appium.Net/Appium/Android/Enums/AutomatorSetting.cs
src/Appium.Net/Appium/Android/Enums/AutomatorSetting.cs
//Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //See the NOTICE file distributed with this work for additional //information regarding copyright ownership. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. namespace OpenQA.Selenium.Appium.Android.Enums { public sealed class AutomatorSetting { public static readonly string IgnoreUnimportantViews = "ignoreUnimportantViews"; public static readonly string WaitForIDLETimeout = "waitForIdleTimeout"; public static readonly string WaitForSelectorTimeout = "waitForSelectorTimeout"; public static readonly string WaitScrollAcknowledgmentTimeout = "scrollAcknowledgmentTimeout"; public static readonly string WaitActionAcknowledgmentTimeout = "actionAcknowledgmentTimeout"; public static readonly string KeyInjectionDelay = "keyInjectionDelay"; } }
//Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //See the NOTICE file distributed with this work for additional //information regarding copyright ownership. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. namespace OpenQA.Selenium.Appium.Android.Enums { public sealed class AutomatorSetting { public static readonly string IgnoreUnimportantViews = "ignoreUnimportantViews"; public static readonly string WaitForIDLETimeout = "setWaitForIdleTimeout"; public static readonly string WaitForSelectorTimeout = "setWaitForSelectorTimeout"; public static readonly string WaitScrollAcknowledgmentTimeout = "setScrollAcknowledgmentTimeout"; public static readonly string WaitActionAcknowledgmentTimeout = "setActionAcknowledgmentTimeout"; public static readonly string KeyInjectionDelay = "setKeyInjectionDelay"; } }
apache-2.0
C#
defd9dd3340f610153aecdc6c6c0f3e9416e376f
Set RxApp.DefaultExceptionHandler.
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.Exports.Reactive/ViewModels/ViewModelBase.cs
src/GitHub.Exports.Reactive/ViewModels/ViewModelBase.cs
using System; using System.Reactive; using GitHub.Logging; using ReactiveUI; using Serilog; namespace GitHub.ViewModels { /// <summary> /// Base class for view models. /// </summary> /// <remarks> /// A view model must inherit from this class in order for a view to be automatically /// found by the ViewLocator. /// </remarks> public abstract class ViewModelBase : ReactiveObject, IViewModel { static readonly ILogger logger = LogManager.ForContext<ViewModelBase>(); static ViewModelBase() { // We don't really have a better place to hook this up as we don't want to force-load // rx on package load. RxApp.DefaultExceptionHandler = Observer.Create<Exception>( ex => logger.Error(ex, "Unhandled rxui error"), ex => logger.Error(ex, "Unhandled rxui error")); } } }
using System; using GitHub.UI; using ReactiveUI; namespace GitHub.ViewModels { /// <summary> /// Base class for view models. /// </summary> /// <remarks> /// A view model must inherit from this class in order for a view to be automatically /// found by the ViewLocator. /// </remarks> public abstract class ViewModelBase : ReactiveObject, IViewModel { } }
mit
C#
c3ad7857c82b7b39cfd47fbbaf382d992b5afce2
Fix for github issue 419 : https://github.com/neo4j/neo4j-dotnet-driver/issues/419
neo4j/neo4j-dotnet-driver,neo4j/neo4j-dotnet-driver
Neo4j.Driver/Neo4j.Driver/Query.cs
Neo4j.Driver/Neo4j.Driver/Query.cs
// Copyright (c) 2002-2020 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Collections.Generic; using System.Runtime.InteropServices.ComTypes; using Neo4j.Driver.Internal; namespace Neo4j.Driver { /// <summary> /// An executable query, i.e. the queries' text and its parameters. /// </summary> public class Query { /// <summary> /// Gets the query's text. /// </summary> public string Text { get; } /// <summary> /// Gets the query's parameters. /// </summary> public IDictionary<string, object> Parameters { get; } /// <summary> /// Create a query with no query parameters. /// </summary> /// <param name="text">The query's text</param> public Query(string text) : this(text, (object) null) { } /// <summary> /// Create a query with parameters specified as anonymous objects /// </summary> /// <param name="text">The query's text</param> /// <param name="parameters">The query parameters, specified as an object which is then converted into key-value pairs.</param> public Query(string text, object parameters) : this(text, parameters.ToDictionary()) { } /// <summary> /// Create a query /// </summary> /// <param name="text">The query's text</param> /// <param name="parameters">The query's parameters, whose values should not be changed while the query is used in a session/transaction.</param> public Query(string text, IDictionary<string, object> parameters) { Text = text; Parameters = parameters ?? new Dictionary<string, object>(); } /// <summary> /// Print the query. /// </summary> /// <returns>A string representation of the query.</returns> public override string ToString() { return $"`{Text}`, {Parameters.ToContentString()}"; } } }
// Copyright (c) 2002-2020 "Neo4j," // Neo4j Sweden AB [http://neo4j.com] // // This file is part of Neo4j. // // 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.Collections.Generic; using Neo4j.Driver.Internal; namespace Neo4j.Driver { /// <summary> /// An executable query, i.e. the queries' text and its parameters. /// </summary> public class Query { private static IDictionary<string, object> NoParameter { get; } static Query() { NoParameter = new Dictionary<string, object>(); } /// <summary> /// Gets the query's text. /// </summary> public string Text { get; } /// <summary> /// Gets the query's parameters. /// </summary> public IDictionary<string, object> Parameters { get; } /// <summary> /// Create a query with no query parameters. /// </summary> /// <param name="text">The query's text</param> public Query(string text) : this(text, (object) null) { } /// <summary> /// Create a query with parameters specified as anonymous objects /// </summary> /// <param name="text">The query's text</param> /// <param name="parameters">The query parameters, specified as an object which is then converted into key-value pairs.</param> public Query(string text, object parameters) : this(text, parameters.ToDictionary()) { } /// <summary> /// Create a query /// </summary> /// <param name="text">The query's text</param> /// <param name="parameters">The query's parameters, whose values should not be changed while the query is used in a session/transaction.</param> public Query(string text, IDictionary<string, object> parameters) { Text = text; Parameters = parameters ?? NoParameter; } /// <summary> /// Print the query. /// </summary> /// <returns>A string representation of the query.</returns> public override string ToString() { return $"`{Text}`, {Parameters.ToContentString()}"; } } }
apache-2.0
C#
d7427bd166ba5de639dd7171954e40b4e1cd0bd5
Fix error when substituting arguments
paf31/parsel
Parsel/ReplaceParametersVisitor.cs
Parsel/ReplaceParametersVisitor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Parsel { internal static class ReplaceParameter { public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s) { return f.Body.Replace(f.Parameters[0], s); } public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t) { return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], t); } public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement) { return new ReplaceParameterVisitor(parameter, replacement).Visit(body); } } internal class ReplaceParameterVisitor : ExpressionVisitor { private readonly ParameterExpression parameter; private readonly Expression replacement; public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement) { this.parameter = parameter; this.replacement = replacement; } protected override Expression VisitParameter(ParameterExpression node) { if (node.Equals(parameter)) { return replacement; } else { return base.VisitParameter(node); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Parsel { internal static class ReplaceParameter { public static Expression Apply<S, T>(this Expression<Func<S, T>> f, Expression s) { return f.Body.Replace(f.Parameters[0], s); } public static Expression Apply<S, T, V>(this Expression<Func<S, T, V>> f, Expression s, Expression t) { return f.Body.Replace(f.Parameters[0], s).Replace(f.Parameters[1], s); } public static Expression Replace(this Expression body, ParameterExpression parameter, Expression replacement) { return new ReplaceParameterVisitor(parameter, replacement).Visit(body); } } internal class ReplaceParameterVisitor : ExpressionVisitor { private readonly ParameterExpression parameter; private readonly Expression replacement; public ReplaceParameterVisitor(ParameterExpression parameter, Expression replacement) { this.parameter = parameter; this.replacement = replacement; } protected override Expression VisitParameter(ParameterExpression node) { if (node.Equals(parameter)) { return replacement; } else { return base.VisitParameter(node); } } } }
bsd-3-clause
C#
fb89d3cac6de8aced82bf1effb4e36cbc190c7e1
Update location of env vars
codeforamerica/denver-schedules-api,schlos/denver-schedules-api,codeforamerica/denver-schedules-api,schlos/denver-schedules-api
Schedules.API.Tests/SystemTests.cs
Schedules.API.Tests/SystemTests.cs
using System; using NUnit.Framework; using Centroid; namespace Schedules.API.Tests { [TestFixture, Category("System")] public class SystemTests { [Test] public void CheckThatEnvironmentVariablesExist() { dynamic config = Config.FromFile("config.json"); foreach (var variable in config.all.variables) { var value = Environment.GetEnvironmentVariable(variable); Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable)); } } } }
using System; using NUnit.Framework; using Centroid; namespace Schedules.API.Tests { [TestFixture, Category("System")] public class SystemTests { [Test] public void CheckThatEnvironmentVariablesExist() { dynamic config = Config.FromFile("config.json"); foreach (var variable in config.variables) { var value = Environment.GetEnvironmentVariable(variable); Assert.That(!String.IsNullOrEmpty(value), String.Format("{0} does not have a value.", variable)); } } } }
mit
C#
8b94ecf5e288822933c365090b728500fc64ab71
Refactor to convert to Flurl's QueryParameter.
clement911/ShopifySharp,addsb/ShopifySharp,nozzlegear/ShopifySharp
ShopifySharp/Filters/ListFilter.cs
ShopifySharp/Filters/ListFilter.cs
using Flurl; using Newtonsoft.Json; using System.Collections.Generic; using System.Reflection; namespace ShopifySharp.Filters { /// <summary> /// A generic class for filtering the results of a .ListAsync command. /// </summary> public class ListFilter : CountFilter { /// <summary> /// An optional array of order ids to retrieve. /// </summary> [JsonProperty("ids")] public IEnumerable<long> Ids { get; set; } /// <summary> /// Limit the amount of results. Default is 50, max is 250. /// </summary> [JsonProperty("limit")] public int? Limit { get; set; } /// <summary> /// Page of results to be returned. Default is 1. /// </summary> [JsonProperty("page")] public int? Page { get; set; } /// <summary> /// An optional, comma-separated list of fields to include in the response. /// </summary> [JsonProperty("fields")] public string Fields { get; set; } /// <summary> /// An optional field name to order by, followed by either ' asc' or ' desc'. /// For example, 'created_at asc' /// Not all fields are supported... /// </summary> [JsonProperty("order")] public string Order { get; set; } /// <summary> /// Parameterizes this class, with special handling for <see cref="Ids"/>. /// </summary> /// <param name="propName">The name of the property. Will match the property's <see cref="JsonPropertyAttribute"/> name — /// rather than the real property name — where applicable. Use <paramref name="property"/>.Name to get the real name.</param> /// <param name="value">The property's value.</param> /// <param name="property">The property itself.</param> /// <returns>The new parameter.</returns> public override QueryParameter ToSingleParameter(string propName, object value, PropertyInfo property) { if (propName == "ids" || propName == "Ids") { var param = new QueryParameter(propName, string.Join(",", value as IEnumerable<long>)); return param; } return base.ToSingleParameter(propName, value, property); } } }
using Newtonsoft.Json; using RestSharp; using System.Collections.Generic; using System.Reflection; namespace ShopifySharp.Filters { /// <summary> /// A generic class for filtering the results of a .ListAsync command. /// </summary> public class ListFilter : CountFilter { /// <summary> /// An optional array of order ids to retrieve. /// </summary> [JsonProperty("ids")] public IEnumerable<long> Ids { get; set; } /// <summary> /// Limit the amount of results. Default is 50, max is 250. /// </summary> [JsonProperty("limit")] public int? Limit { get; set; } /// <summary> /// Page of results to be returned. Default is 1. /// </summary> [JsonProperty("page")] public int? Page { get; set; } /// <summary> /// An optional, comma-separated list of fields to include in the response. /// </summary> [JsonProperty("fields")] public string Fields { get; set; } /// <summary> /// An optional field name to order by, followed by either ' asc' or ' desc'. /// For example, 'created_at asc' /// Not all fields are supported... /// </summary> [JsonProperty("order")] public string Order { get; set; } /// <summary> /// Parameterizes this class, with special handling for <see cref="Ids"/>. /// </summary> /// <param name="propName">The name of the property. Will match the property's <see cref="JsonPropertyAttribute"/> name — /// rather than the real property name — where applicable. Use <paramref name="property"/>.Name to get the real name.</param> /// <param name="value">The property's value.</param> /// <param name="property">The property itself.</param> /// <param name="type">The type of parameter to create.</param> /// <returns>The new parameter.</returns> public override Parameter ToSingleParameter(string propName, object value, PropertyInfo property, ParameterType type) { if (propName == "ids" || propName == "Ids") { //RestSharp does not automatically convert arrays into querystring params. var param = new Parameter() { Name = propName, Type = type, Value = string.Join(",", value as IEnumerable<long>) }; return param; } return base.ToSingleParameter(propName, value, property, type); } } }
mit
C#
5ce908e88307c3cdfe28f034d20e63ef6c8e838f
Update Milestone.cs
tiksn/TIKSN-Framework
TIKSN.Core/Versioning/Milestone.cs
TIKSN.Core/Versioning/Milestone.cs
namespace TIKSN.Versioning { public enum Milestone { // Unstable Alpha = 1, Beta = 2, ReleaseCandidate = 3, // Stable Release = 4 } }
namespace TIKSN.Versioning { public enum Milestone { // Unstable Alpha = 1, Beta = 2, ReleaseCandidate = 3, // Stable Release = 4, } }
mit
C#
6d8af1b046684a787f773f316117bcf75df1f67f
Add MemBytesUsed property to CurrentState
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Server/Web/Structures/CurrentState.cs
Server/Web/Structures/CurrentState.cs
using Server.Context; using Server.System; using System; using System.Collections.Generic; using System.Linq; namespace Server.Web.Structures { public class CurrentState { public DateTime StartTime { get; set; } public List<string> CurrentPlayers { get; } = new List<string>(); public List<VesselInfo> CurrentVessels { get; } = new List<VesselInfo>(); public List<Subspace> Subspaces { get; } = new List<Subspace>(); public int MemBytesUsed { get; } public void Refresh() { CurrentPlayers.Clear(); CurrentVessels.Clear(); Subspaces.Clear(); StartTime = TimeContext.StartTime; CurrentPlayers.AddRange(ServerContext.Clients.Values.Select(v => v.PlayerName)); CurrentVessels.AddRange(VesselStoreSystem.CurrentVessels.Values.Select(v => new VesselInfo(v))); Subspaces.AddRange(WarpContext.Subspaces.Values); BytesUsed = Environment.WorkingSet; } } }
using Server.Context; using Server.System; using System; using System.Collections.Generic; using System.Linq; namespace Server.Web.Structures { public class CurrentState { public DateTime StartTime { get; set; } public List<string> CurrentPlayers { get; } = new List<string>(); public List<VesselInfo> CurrentVessels { get; } = new List<VesselInfo>(); public List<Subspace> Subspaces { get; } = new List<Subspace>(); public void Refresh() { CurrentPlayers.Clear(); CurrentVessels.Clear(); Subspaces.Clear(); StartTime = TimeContext.StartTime; CurrentPlayers.AddRange(ServerContext.Clients.Values.Select(v => v.PlayerName)); CurrentVessels.AddRange(VesselStoreSystem.CurrentVessels.Values.Select(v => new VesselInfo(v))); Subspaces.AddRange(WarpContext.Subspaces.Values); } } }
mit
C#
908195adeed6d7cc7c9c3d06c0b2feb67464009d
Rename variable.
sharpjs/PSql,sharpjs/PSql
PSql.Core/_Commands/ExpandSqlCmdDirectivesCommand.cs
PSql.Core/_Commands/ExpandSqlCmdDirectivesCommand.cs
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; namespace PSql { [Cmdlet(VerbsData.Expand, "SqlCmdDirectives")] [OutputType(typeof(string[]))] public class ExpandSqlCmdDirectivesCommand : Cmdlet { // -Sql [Alias("s")] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowNull, AllowEmptyCollection] public string[] Sql { get; set; } // -Define [Alias("d")] [Parameter(Position = 1)] [AllowNull, AllowEmptyCollection] public Hashtable Define { get; set; } private SqlCmdPreprocessor _preprocessor; protected override void BeginProcessing() { _preprocessor = new SqlCmdPreprocessor(); InitializeVariables(_preprocessor.Variables); } protected override void ProcessRecord() { var scripts = Sql; if (scripts == null) return; foreach (var input in scripts) if (!string.IsNullOrEmpty(input)) foreach (var batch in _preprocessor.Process(input)) WriteObject(batch); } private void InitializeVariables(IDictionary<string, string> variables) { var entries = Define; if (entries == null) return; foreach (DictionaryEntry entry in entries) { if (entry.Key is null) continue; var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(key)) continue; var value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture); variables[key] = value ?? string.Empty; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Management.Automation; namespace PSql { [Cmdlet(VerbsData.Expand, "SqlCmdDirectives")] [OutputType(typeof(string[]))] public class ExpandSqlCmdDirectivesCommand : Cmdlet { // -Sql [Alias("s")] [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)] [AllowNull, AllowEmptyCollection] public string[] Sql { get; set; } // -Define [Alias("d")] [Parameter(Position = 1)] [AllowNull, AllowEmptyCollection] public Hashtable Define { get; set; } private SqlCmdPreprocessor _preprocessor; protected override void BeginProcessing() { _preprocessor = new SqlCmdPreprocessor(); InitializeVariables(_preprocessor.Variables); } protected override void ProcessRecord() { var inputs = Sql; if (inputs == null) return; foreach (var input in inputs) if (!string.IsNullOrEmpty(input)) foreach (var batch in _preprocessor.Process(input)) WriteObject(batch); } private void InitializeVariables(IDictionary<string, string> variables) { var entries = Define; if (entries == null) return; foreach (DictionaryEntry entry in entries) { if (entry.Key is null) continue; var key = Convert.ToString(entry.Key, CultureInfo.InvariantCulture); if (string.IsNullOrEmpty(key)) continue; var value = Convert.ToString(entry.Value, CultureInfo.InvariantCulture); variables[key] = value ?? string.Empty; } } } }
isc
C#
1ee9aa4e4ce85f1b6dfba88b4a92e3fa75d67930
make COM ReolutionRequestType compatible with API enum
s-rogonov/diadocsdk-csharp,halex2005/diadocsdk-csharp,asvyazin/diadocsdk-csharp,asvyazin/diadocsdk-csharp,diadoc/diadocsdk-csharp,s-rogonov/diadocsdk-csharp,ichaynikov/diadocsdk-csharp,ichaynikov/diadocsdk-csharp,halex2005/diadocsdk-csharp,basmus/diadocsdk-csharp,diadoc/diadocsdk-csharp,basmus/diadocsdk-csharp
src/Com/ResolutionRequestType.cs
src/Com/ResolutionRequestType.cs
using System.Runtime.InteropServices; using System.Xml.Serialization; namespace Diadoc.Api.Com { [ComVisible(true)] [Guid("8B280FD8-0E8E-4FCC-8586-288DD94A7437")] //NOTE: Это хотели, чтобы можно было использовать XML-сериализацию для классов [XmlType(TypeName = "ResolutionRequestType", Namespace = "https://diadoc-api.kontur.ru")] public enum ResolutionRequestType { UnknownResolutionRequestType = Proto.Events.ResolutionRequestType.UnknownResolutionRequestType, ApprovementRequest = Proto.Events.ResolutionRequestType.ApprovementRequest, SignatureRequest = Proto.Events.ResolutionRequestType.SignatureRequest, ApprovementSignatureRequest = Proto.Events.ResolutionRequestType.ApprovementSignatureRequest } }
using System.Runtime.InteropServices; using System.Xml.Serialization; namespace Diadoc.Api.Com { [ComVisible(true)] [Guid("8B280FD8-0E8E-4FCC-8586-288DD94A7437")] //NOTE: Это хотели, чтобы можно было использовать XML-сериализацию для классов [XmlType(TypeName = "ResolutionRequestType", Namespace = "https://diadoc-api.kontur.ru")] public enum ResolutionRequestType { ApprovementRequest = Proto.Events.ResolutionRequestType.ApprovementRequest, SignatureRequest = Proto.Events.ResolutionRequestType.SignatureRequest, ApprovementSignatureRequest = Proto.Events.ResolutionRequestType.ApprovementSignatureRequest } }
mit
C#
7975bd12c6480362669a3c48811ca676551c8895
fix status details property. Change from authentication to authenticated
watson-developer-cloud/unity-sdk,watson-developer-cloud/unity-sdk,watson-developer-cloud/unity-sdk
Scripts/Services/Discovery/V1/Model/StatusDetails.cs
Scripts/Services/Discovery/V1/Model/StatusDetails.cs
/** * (C) Copyright IBM Corp. 2021. * * 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 Newtonsoft.Json; namespace IBM.Watson.Discovery.V1.Model { /// <summary> /// Object that contains details about the status of the authentication process. /// </summary> public class StatusDetails { /// <summary> /// Indicates whether the credential is accepted by the target data source. /// </summary> [JsonProperty("authenticated", NullValueHandling = NullValueHandling.Ignore)] public bool? Authenticated { get; set; } /// <summary> /// If `authenticated` is `false`, a message describes why the authentication was unsuccessful. /// </summary> [JsonProperty("error_message", NullValueHandling = NullValueHandling.Ignore)] public string ErrorMessage { get; set; } } }
/** * (C) Copyright IBM Corp. 2021. * * 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 Newtonsoft.Json; namespace IBM.Watson.Discovery.V1.Model { /// <summary> /// Object that contains details about the status of the authentication process. /// </summary> public class StatusDetails { /// <summary> /// Indicates whether the credential is accepted by the target data source. /// </summary> [JsonProperty("authentication", NullValueHandling = NullValueHandling.Ignore)] public bool? Authentication { get; set; } /// <summary> /// If `authentication` is `false`, a message describes why the authentication was unsuccessful. /// </summary> [JsonProperty("error_message", NullValueHandling = NullValueHandling.Ignore)] public string ErrorMessage { get; set; } } }
apache-2.0
C#
e157f28e2d38a27e076d2a0254132f904f1823a8
Disable parallel test execution for RhinoMock integration tests (#847)
AutoFixture/AutoFixture,zvirja/AutoFixture,Pvlerick/AutoFixture,sean-gilliam/AutoFixture
Src/AutoRhinoMockUnitTest/Properties/AssemblyInfo.cs
Src/AutoRhinoMockUnitTest/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using Xunit; // 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: 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("1489ac72-1967-48b8-a302-79b2900acbe3")] [assembly: CollectionBehavior(DisableTestParallelization = true)]
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: 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("1489ac72-1967-48b8-a302-79b2900acbe3")]
mit
C#
11703d166f2c28cf5a1e2377def268fc2b853447
Update SharedAssemblyInfo.cs
SuperJMN/Avalonia,Perspex/Perspex,susloparovdenis/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,akrisiun/Perspex,MrDaedra/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jazzay/Perspex,jkoritzinsky/Perspex,OronDF343/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,OronDF343/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,susloparovdenis/Perspex,grokys/Perspex,wieslawsoltes/Perspex,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia
src/Shared/SharedAssemblyInfo.cs
src/Shared/SharedAssemblyInfo.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using System.Resources; [assembly: AssemblyCompany("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCopyright("Copyright AvaloniaUI 2016")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("Avalonia")] [assembly: AssemblyTrademark("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("0.4.1")] [assembly: AssemblyFileVersion("0.4.1")] [assembly: AssemblyInformationalVersion("0.4.1")]
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Reflection; using System.Resources; [assembly: AssemblyCompany("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCopyright("Copyright AvaloniaUI 2016")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("Avalonia")] [assembly: AssemblyTrademark("")] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("0.4.0")] [assembly: AssemblyFileVersion("0.4.0")] [assembly: AssemblyInformationalVersion("0.4.0")]
mit
C#
0075384957720993bd4933401f45110ce188afed
Remove FillText in InvertedCanvas too
verybadcat/CSharpMath
CSharpMath.Rendering/FrontEnd/InvertedCanvas.cs
CSharpMath.Rendering/FrontEnd/InvertedCanvas.cs
using System; using CSharpMath.Structures; namespace CSharpMath.Rendering.FrontEnd { using FrontEnd; [Obsolete("Not ready", true)] public class InvertedCanvas : ICanvas { public InvertedCanvas(ICanvas canvas) => _canvas = canvas ?? throw new ArgumentNullException(nameof(canvas), "The supplied canvas cannot be null."); private readonly ICanvas _canvas; float Invert(float origY) => origY * -1 + _canvas.Height; public float Width => _canvas.Width; public float Height => _canvas.Height; public Color DefaultColor { get => _canvas.DefaultColor; set => _canvas.DefaultColor = value; } public Color? CurrentColor { get => _canvas.CurrentColor; set => _canvas.CurrentColor = value; } public PaintStyle CurrentStyle { get => _canvas.CurrentStyle; set => _canvas.CurrentStyle = value; } public void DrawLine(float x1, float y1, float x2, float y2, float lineThickness) => _canvas.DrawLine(x1, Invert(y1), x2, Invert(y2), lineThickness); public void FillRect(float left, float top, float width, float height) => _canvas.FillRect(left, Invert(top), width, height); public GlyphPath StartDrawingNewGlyph() => _canvas.StartDrawingNewGlyph(); public void Restore() => _canvas.Restore(); public void Save() => _canvas.Save(); public void Scale(float sx, float sy) => _canvas.Scale(sx, sy); public void StrokeRect(float left, float top, float width, float height) => _canvas.StrokeRect(left, Invert(top), width, height); public void Translate(float dx, float dy) => _canvas.Translate(dx, dy); } }
using System; using CSharpMath.Structures; namespace CSharpMath.Rendering.FrontEnd { using FrontEnd; [Obsolete("Not ready", true)] public class InvertedCanvas : ICanvas { public InvertedCanvas(ICanvas canvas) => _canvas = canvas ?? throw new ArgumentNullException(nameof(canvas), "The supplied canvas cannot be null."); private readonly ICanvas _canvas; float Invert(float origY) => origY * -1 + _canvas.Height; public float Width => _canvas.Width; public float Height => _canvas.Height; public Color DefaultColor { get => _canvas.DefaultColor; set => _canvas.DefaultColor = value; } public Color? CurrentColor { get => _canvas.CurrentColor; set => _canvas.CurrentColor = value; } public PaintStyle CurrentStyle { get => _canvas.CurrentStyle; set => _canvas.CurrentStyle = value; } public void DrawLine(float x1, float y1, float x2, float y2, float lineThickness) => _canvas.DrawLine(x1, Invert(y1), x2, Invert(y2), lineThickness); public void FillRect(float left, float top, float width, float height) => _canvas.FillRect(left, Invert(top), width, height); public void FillText(string text, float x, float y, float pointSize) => _canvas.FillText(text, x, Invert(y), pointSize); public GlyphPath StartDrawingNewGlyph() => _canvas.StartDrawingNewGlyph(); public void Restore() => _canvas.Restore(); public void Save() => _canvas.Save(); public void Scale(float sx, float sy) => _canvas.Scale(sx, sy); public void StrokeRect(float left, float top, float width, float height) => _canvas.StrokeRect(left, Invert(top), width, height); public void Translate(float dx, float dy) => _canvas.Translate(dx, dy); } }
mit
C#
5d3283d74670b4504fe92f02d2343a1c214ed5e1
Update StatsController.cs - implemented edit, create and delete methods
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/Controllers/StatsController.cs
NinjaHive.WebApp/Controllers/StatsController.cs
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class StatsController : Controller { private readonly IQueryProcessor queryProcessor; private readonly ICommandHandler<EditStatCommand> editStatCommandHandler; private readonly ICommandHandler<DeleteStatCommand> deleteStatCommand; public StatsController( IQueryProcessor queryProcessor, ICommandHandler<EditStatCommand> editStatCommandHandler, ICommandHandler<DeleteStatCommand> deleteStatCommand) { this.queryProcessor = queryProcessor; this.editStatCommandHandler = editStatCommandHandler; this.deleteStatCommand = deleteStatCommand; } public ActionResult Index() { var stats = this.queryProcessor.Execute(new GetAllStatsQuery()); return View(stats); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(StatInfo stat) { stat.Id = Guid.NewGuid(); var command = new EditStatCommand(stat, createNew: true); this.editStatCommandHandler.Handle(command); var redirectUri = UrlProvider<StatsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } public ActionResult Edit(Guid statId) { var stat = this.queryProcessor.Execute(new GetEntityByIdQuery<StatInfo>(statId)); return View(stat); } public ActionResult Delete(StatInfo stat) { var command = new DeleteStatCommand() { Stat = stat }; deleteStatCommand.Handle(command); var redirectUri = UrlProvider<StatsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } } }
using System; using System.Web.Mvc; using NinjaHive.Contract.Commands; using NinjaHive.Contract.DTOs; using NinjaHive.Contract.Queries; using NinjaHive.Core; using NinjaHive.WebApp.Services; namespace NinjaHive.WebApp.Controllers { public class StatsController : Controller { private StatInfo[] example; public StatsController() { example = new StatInfo[1]; example[0] = new StatInfo(); example[0].Id = new Guid(); example[0].Agility = 0; example[0].Defense = 10; example[0].Health = -23; example[0].Intelligence = 0; } public ActionResult Index() { return View(example); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(StatInfo stat) { stat.Id = Guid.NewGuid(); var redirectUri = UrlProvider<StatsController>.GetRouteValues(c => c.Index()); return RedirectToRoute(redirectUri); } public ActionResult Edit(Guid statId) { return View(example[0]); } } }
apache-2.0
C#
098c8e9dad1d76da2d048879b9605cd3b1a314ae
Add JsonFormater
senioroman4uk/PathFinder
PathFinder.EntryPoint/App_Start/WebApiConfig.cs
PathFinder.EntryPoint/App_Start/WebApiConfig.cs
using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; using Newtonsoft.Json.Serialization; namespace PathFinder.EntryPoint { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First(); jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace PathFinder.EntryPoint { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } } }
mit
C#
6135298dc20ae7a10d01bc5f0270721c27168bf0
Use client code generator
ithoughtdk/SalamanderDemos
Ducklings/Ducklings.sdml.cs
Ducklings/Ducklings.sdml.cs
// This is a generated file using Salamander; namespace Ducklings { public sealed partial class PondOf : Relation { } public sealed partial class Pond : IdNode<long> { private Property<int> _ducklingCount; public int DucklingCount { get { return _ducklingCount.Value; } set { _ducklingCount.Value = value; } } protected override void OnMount() { base.OnMount(); _ducklingCount = Mount<int>(nameof(_ducklingCount)); } } public abstract partial class Nature : Transaction { public IDirectory<Pond, long> Ponds { get; private set; } protected override void OnMount() { Ponds = Directory<Pond, long>(); } } public sealed partial class Origin : Nature { } public sealed partial class TransferDucklings : Nature { public long SourcePondId { set { _source = Ponds.First(node => node.Id == value); } } public long DestinationPondId { set { _destination = Ponds.First(node => node.Id == value); } } private Pond _source; private Pond _destination; } }
// This is a generated file using Salamander; namespace Ducklings { public sealed partial class PondOf : Relation { } public sealed partial class Pond : IdNode<long> { private Property<int> _ducklingCount; public int DucklingCount { get { return _ducklingCount.Value; } set { _ducklingCount.Value = value; } } protected override void OnMount() { base.OnMount(); _ducklingCount = Mount<int>(nameof(_ducklingCount)); } } public abstract partial class Nature : Transaction { public IDirectory<Pond, long> Ponds { get; private set; } protected override void OnMount() { Ponds = Directory<Pond, long>(); } } public sealed partial class Origin : Nature { } public sealed partial class TransferDucklings : Nature { public long SourcePondId { set { _source = Ponds.First(pond => pond.Id == value); } } public long DestinationPondId { set { _destination = Ponds.First(pond => pond.Id == value); } } private Pond _source; private Pond _destination; } }
mit
C#
0e20c7d8e03e06216397bdb753ff506770aeb749
Update use agent for v2
IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner
MultiMiner.Win/UserAgent.cs
MultiMiner.Win/UserAgent.cs
namespace MultiMiner.Win { public static class UserAgent { public const string AgentString = "MultiMiner/V2"; } }
namespace MultiMiner.Win { public static class UserAgent { public const string AgentString = "MultiMiner/V1"; } }
mit
C#
a1965682ec0f82dd4d8cbf554a39cbff9e6b1636
remove temp logs
Mazyod/PhoenixSharp
PhoenixTests/SocketTests.cs
PhoenixTests/SocketTests.cs
using System; using NUnit.Framework; using Phoenix; namespace PhoenixTests { [TestFixture()] public class SocketTests { [Test()] public void BuffersDataWhenNotConnectedTest() { var socket = new Socket("ws://localhost:1234", null, new MockWebsocketFactory()); socket.Connect(); var conn = socket.conn as MockWebsocketAdapter; conn.mockState = WebsocketState.Connecting; Assert.AreEqual(socket.sendBuffer.Count, 0); socket.Push(new Message()); Assert.AreEqual(conn.callSend.Count, 0); Assert.AreEqual(socket.sendBuffer.Count, 1); var callback = socket.sendBuffer[0]; callback(); Assert.AreEqual(conn.callSend.Count, 1); } /** Test Github Issue #19: * phx_join never sent if socket is not open by the time Join is called. */ [Test()] public void FlushSendBufferTest() { var socket = new Socket("ws://localhost:1234", null, new MockWebsocketFactory()); socket.Connect(); var conn = socket.conn as MockWebsocketAdapter; conn.mockState = WebsocketState.Connecting; var channel = socket.Channel("test"); channel.Join(); Assert.AreEqual(socket.sendBuffer.Count, 1); conn.mockState = WebsocketState.Open; socket.FlushSendBuffer(); Assert.AreEqual(socket.sendBuffer.Count, 0); Assert.AreEqual(conn.callSend.Count, 1); var joinEvent = Message.OutBoundEvent.phx_join.ToString(); Assert.That(conn.callSend[0].Contains(joinEvent)); } } }
using System; using NUnit.Framework; using Phoenix; namespace PhoenixTests { [TestFixture()] public class SocketTests { [Test()] public void BuffersDataWhenNotConnectedTest() { var socket = new Socket("ws://localhost:1234", null, new MockWebsocketFactory()); socket.Connect(); var conn = socket.conn as MockWebsocketAdapter; conn.mockState = WebsocketState.Connecting; Assert.AreEqual(socket.sendBuffer.Count, 0); socket.Push(new Message()); Assert.AreEqual(conn.callSend.Count, 0); Assert.AreEqual(socket.sendBuffer.Count, 1); var callback = socket.sendBuffer[0]; callback(); Assert.AreEqual(conn.callSend.Count, 1); } /** describe("flushSendBuffer", function(){ beforeEach(function(){ socket = new Socket("/socket") socket.connect() }) it("calls callbacks in buffer when connected", function(){ socket.conn.readyState = 1 // open const spy1 = sinon.spy() const spy2 = sinon.spy() const spy3 = sinon.spy() socket.sendBuffer.push(spy1) socket.sendBuffer.push(spy2) socket.flushSendBuffer() assert.ok(spy1.calledOnce) assert.ok(spy2.calledOnce) assert.equal(spy3.callCount, 0) }) it("empties sendBuffer", function(){ socket.conn.readyState = 1 // open socket.sendBuffer.push(() => {}) socket.flushSendBuffer() assert.deepEqual(socket.sendBuffer.length, 0) }) }) */ /** Test Github Issue #19: * phx_join never sent if socket is not open by the time Join is called. */ [Test()] public void FlushSendBufferTest() { var socket = new Socket("ws://localhost:1234", null, new MockWebsocketFactory()); socket.Connect(); var conn = socket.conn as MockWebsocketAdapter; conn.mockState = WebsocketState.Connecting; var channel = socket.Channel("test"); channel.Join(); Assert.AreEqual(socket.sendBuffer.Count, 1); conn.mockState = WebsocketState.Open; socket.FlushSendBuffer(); Assert.AreEqual(socket.sendBuffer.Count, 0); Assert.AreEqual(conn.callSend.Count, 1); var joinEvent = Message.OutBoundEvent.phx_join.ToString(); Assert.That(conn.callSend[0].Contains(joinEvent)); } } }
mit
C#
9f533334c34a79bff4784a592e25d4778ba3644b
Remove unneeded reference to PrismApplication base class.
ryanjfitz/SimpSim.NET
SimpSim.NET.WPF/App.xaml.cs
SimpSim.NET.WPF/App.xaml.cs
using System.Windows; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
using System.Windows; using Prism.DryIoc; using Prism.Ioc; using SimpSim.NET.WPF.ViewModels; using SimpSim.NET.WPF.Views; namespace SimpSim.NET.WPF { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication { protected override Window CreateShell() { return Container.Resolve<MainWindow>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterSingleton<SimpleSimulator>(); containerRegistry.Register<IUserInputService, UserInputService>(); containerRegistry.Register<IDialogServiceAdapter, DialogServiceAdapter>(); containerRegistry.RegisterSingleton<StateSaver>(); containerRegistry.RegisterDialog<AssemblyEditorDialog, AssemblyEditorDialogViewModel>(); } } }
mit
C#
34fa0897fa7be865a8b5bcbe430530d101a92caf
add at loading labelMatrix characteristics
fredatgithub/Matrix
TheMatrixHasYou/FormMain.cs
TheMatrixHasYou/FormMain.cs
using System; using System.Drawing; using System.Windows.Forms; namespace TheMatrixHasYou { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private readonly string[] _texte = {"Knock knock Neo..","Wake up Neo....", "The Matrix has you....", "Follow the white rabbit...." }; private int _numeroChaine = 0; private int _nombreDeChaineTotal = 0; private int _curseurChaine = 0; private void FormMain_Load(object sender, EventArgs e) { labelMatrix.ForeColor = Color.Green; labelMatrix.Size = new Size(new Point(14)); labelMatrix.Text = string.Empty; _nombreDeChaineTotal = _texte.Length; timer1.Interval = 200; } private void timer1_Tick(object sender, EventArgs e) { labelMatrix.Text += _texte[_numeroChaine].Substring(_curseurChaine, 1); if (_curseurChaine >= _texte[_numeroChaine].Length - 1) { labelMatrix.Text = string.Empty; if (_numeroChaine + 1 >= _texte.Length) { _numeroChaine = 0; _curseurChaine = 0; } else { _numeroChaine++; _curseurChaine = 0; } } else { _curseurChaine++; } } } }
using System; using System.Windows.Forms; namespace TheMatrixHasYou { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private readonly string[] _texte = {"Knock knock Neo..","Wake up Neo....", "The Matrix has you....", "Follow the white rabbit...." }; private int _numeroChaine = 0; private int _nombreDeChaineTotal = 0; private int _curseurChaine = 0; private void FormMain_Load(object sender, EventArgs e) { labelMatrix.Text = string.Empty; _nombreDeChaineTotal = _texte.Length; timer1.Interval = 200; } private void timer1_Tick(object sender, EventArgs e) { labelMatrix.Text += _texte[_numeroChaine].Substring(_curseurChaine, 1); if (_curseurChaine >= _texte[_numeroChaine].Length - 1) { labelMatrix.Text = string.Empty; if (_numeroChaine + 1 >= _texte.Length) { _numeroChaine = 0; _curseurChaine = 0; } else { _numeroChaine++; _curseurChaine = 0; } } else { _curseurChaine++; } } } }
mit
C#
f70f5eef3c30fb6d852f7527126a9804e55b5f68
Change TODO comments to reference current issue on Sockets perf counters.
wtgodbe/corefx,cydhaselton/corefx,wtgodbe/corefx,fgreinacher/corefx,jlin177/corefx,dotnet-bot/corefx,ravimeda/corefx,tstringer/corefx,mazong1123/corefx,Petermarcu/corefx,dotnet-bot/corefx,Petermarcu/corefx,twsouthwick/corefx,fgreinacher/corefx,yizhang82/corefx,axelheer/corefx,stone-li/corefx,alexperovich/corefx,cydhaselton/corefx,rjxby/corefx,Ermiar/corefx,wtgodbe/corefx,stone-li/corefx,Ermiar/corefx,alphonsekurian/corefx,weltkante/corefx,YoupHulsebos/corefx,shmao/corefx,lggomez/corefx,richlander/corefx,alexperovich/corefx,seanshpark/corefx,marksmeltzer/corefx,nchikanov/corefx,rahku/corefx,DnlHarvey/corefx,DnlHarvey/corefx,zhenlan/corefx,the-dwyer/corefx,ellismg/corefx,Priya91/corefx-1,shimingsg/corefx,mmitche/corefx,twsouthwick/corefx,iamjasonp/corefx,zhenlan/corefx,Petermarcu/corefx,dsplaisted/corefx,khdang/corefx,mmitche/corefx,jlin177/corefx,rahku/corefx,elijah6/corefx,twsouthwick/corefx,shmao/corefx,adamralph/corefx,tijoytom/corefx,elijah6/corefx,nbarbettini/corefx,nchikanov/corefx,zhenlan/corefx,marksmeltzer/corefx,rubo/corefx,twsouthwick/corefx,BrennanConroy/corefx,shimingsg/corefx,stone-li/corefx,jhendrixMSFT/corefx,jlin177/corefx,jhendrixMSFT/corefx,cydhaselton/corefx,JosephTremoulet/corefx,Priya91/corefx-1,manu-silicon/corefx,Ermiar/corefx,nbarbettini/corefx,dsplaisted/corefx,cydhaselton/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,iamjasonp/corefx,ericstj/corefx,stone-li/corefx,alexperovich/corefx,richlander/corefx,shmao/corefx,rubo/corefx,billwert/corefx,elijah6/corefx,tstringer/corefx,billwert/corefx,ptoonen/corefx,tstringer/corefx,gkhanna79/corefx,jhendrixMSFT/corefx,BrennanConroy/corefx,shimingsg/corefx,jlin177/corefx,weltkante/corefx,Chrisboh/corefx,mmitche/corefx,Jiayili1/corefx,mmitche/corefx,shimingsg/corefx,yizhang82/corefx,yizhang82/corefx,krytarowski/corefx,cydhaselton/corefx,JosephTremoulet/corefx,lggomez/corefx,ptoonen/corefx,shimingsg/corefx,rahku/corefx,mazong1123/corefx,lggomez/corefx,stephenmichaelf/corefx,Chrisboh/corefx,gkhanna79/corefx,ViktorHofer/corefx,lggomez/corefx,alphonsekurian/corefx,mazong1123/corefx,krk/corefx,mazong1123/corefx,richlander/corefx,weltkante/corefx,marksmeltzer/corefx,SGuyGe/corefx,ellismg/corefx,dhoehna/corefx,shimingsg/corefx,dotnet-bot/corefx,mazong1123/corefx,iamjasonp/corefx,axelheer/corefx,Priya91/corefx-1,marksmeltzer/corefx,nbarbettini/corefx,tijoytom/corefx,parjong/corefx,jhendrixMSFT/corefx,manu-silicon/corefx,SGuyGe/corefx,MaggieTsang/corefx,nchikanov/corefx,dotnet-bot/corefx,shahid-pk/corefx,wtgodbe/corefx,tstringer/corefx,rjxby/corefx,mmitche/corefx,billwert/corefx,gkhanna79/corefx,parjong/corefx,ravimeda/corefx,ViktorHofer/corefx,tijoytom/corefx,weltkante/corefx,ericstj/corefx,krytarowski/corefx,mazong1123/corefx,MaggieTsang/corefx,khdang/corefx,shahid-pk/corefx,Petermarcu/corefx,ravimeda/corefx,marksmeltzer/corefx,krk/corefx,shahid-pk/corefx,ptoonen/corefx,yizhang82/corefx,ericstj/corefx,krk/corefx,Ermiar/corefx,yizhang82/corefx,lggomez/corefx,shimingsg/corefx,weltkante/corefx,fgreinacher/corefx,rjxby/corefx,tstringer/corefx,alexperovich/corefx,fgreinacher/corefx,alphonsekurian/corefx,Jiayili1/corefx,the-dwyer/corefx,the-dwyer/corefx,parjong/corefx,zhenlan/corefx,jhendrixMSFT/corefx,JosephTremoulet/corefx,nchikanov/corefx,ravimeda/corefx,krytarowski/corefx,rubo/corefx,JosephTremoulet/corefx,manu-silicon/corefx,richlander/corefx,elijah6/corefx,ericstj/corefx,MaggieTsang/corefx,zhenlan/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,gkhanna79/corefx,gkhanna79/corefx,the-dwyer/corefx,Petermarcu/corefx,YoupHulsebos/corefx,ravimeda/corefx,seanshpark/corefx,mazong1123/corefx,nbarbettini/corefx,ellismg/corefx,alphonsekurian/corefx,axelheer/corefx,khdang/corefx,cartermp/corefx,stone-li/corefx,YoupHulsebos/corefx,stone-li/corefx,the-dwyer/corefx,Chrisboh/corefx,tijoytom/corefx,elijah6/corefx,iamjasonp/corefx,adamralph/corefx,ravimeda/corefx,rubo/corefx,MaggieTsang/corefx,seanshpark/corefx,dotnet-bot/corefx,YoupHulsebos/corefx,MaggieTsang/corefx,ellismg/corefx,Jiayili1/corefx,cartermp/corefx,Chrisboh/corefx,parjong/corefx,shahid-pk/corefx,dsplaisted/corefx,zhenlan/corefx,zhenlan/corefx,gkhanna79/corefx,lggomez/corefx,iamjasonp/corefx,dhoehna/corefx,richlander/corefx,tstringer/corefx,ellismg/corefx,cydhaselton/corefx,adamralph/corefx,dhoehna/corefx,JosephTremoulet/corefx,dhoehna/corefx,wtgodbe/corefx,lggomez/corefx,axelheer/corefx,DnlHarvey/corefx,tijoytom/corefx,seanshpark/corefx,manu-silicon/corefx,MaggieTsang/corefx,Chrisboh/corefx,cartermp/corefx,jlin177/corefx,Priya91/corefx-1,seanshpark/corefx,manu-silicon/corefx,billwert/corefx,iamjasonp/corefx,khdang/corefx,rjxby/corefx,SGuyGe/corefx,nbarbettini/corefx,SGuyGe/corefx,stone-li/corefx,mmitche/corefx,Jiayili1/corefx,cartermp/corefx,richlander/corefx,elijah6/corefx,dotnet-bot/corefx,billwert/corefx,manu-silicon/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,ericstj/corefx,MaggieTsang/corefx,rjxby/corefx,rahku/corefx,nchikanov/corefx,twsouthwick/corefx,cartermp/corefx,marksmeltzer/corefx,alexperovich/corefx,nbarbettini/corefx,nchikanov/corefx,alphonsekurian/corefx,dhoehna/corefx,manu-silicon/corefx,billwert/corefx,ViktorHofer/corefx,richlander/corefx,ptoonen/corefx,wtgodbe/corefx,krk/corefx,weltkante/corefx,twsouthwick/corefx,Petermarcu/corefx,ViktorHofer/corefx,krytarowski/corefx,krytarowski/corefx,ptoonen/corefx,mmitche/corefx,tijoytom/corefx,nchikanov/corefx,the-dwyer/corefx,Ermiar/corefx,krytarowski/corefx,YoupHulsebos/corefx,Jiayili1/corefx,yizhang82/corefx,Jiayili1/corefx,ellismg/corefx,Chrisboh/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,Jiayili1/corefx,alexperovich/corefx,ptoonen/corefx,krk/corefx,axelheer/corefx,parjong/corefx,marksmeltzer/corefx,ViktorHofer/corefx,alexperovich/corefx,shmao/corefx,parjong/corefx,krk/corefx,nbarbettini/corefx,axelheer/corefx,seanshpark/corefx,rahku/corefx,rahku/corefx,khdang/corefx,DnlHarvey/corefx,SGuyGe/corefx,khdang/corefx,billwert/corefx,krytarowski/corefx,Petermarcu/corefx,shmao/corefx,dotnet-bot/corefx,DnlHarvey/corefx,rahku/corefx,dhoehna/corefx,elijah6/corefx,rubo/corefx,jlin177/corefx,weltkante/corefx,the-dwyer/corefx,parjong/corefx,wtgodbe/corefx,YoupHulsebos/corefx,Ermiar/corefx,gkhanna79/corefx,jhendrixMSFT/corefx,Priya91/corefx-1,shmao/corefx,ravimeda/corefx,rjxby/corefx,jlin177/corefx,shahid-pk/corefx,cartermp/corefx,dhoehna/corefx,shahid-pk/corefx,YoupHulsebos/corefx,yizhang82/corefx,ericstj/corefx,Ermiar/corefx,SGuyGe/corefx,ptoonen/corefx,rjxby/corefx,Priya91/corefx-1,stephenmichaelf/corefx,stephenmichaelf/corefx,shmao/corefx,ViktorHofer/corefx,cydhaselton/corefx,ericstj/corefx,JosephTremoulet/corefx,BrennanConroy/corefx,alphonsekurian/corefx,krk/corefx,tijoytom/corefx,twsouthwick/corefx,alphonsekurian/corefx,iamjasonp/corefx,seanshpark/corefx
src/System.Net.Sockets/src/System/Net/SocketPerfCounters.cs
src/System.Net.Sockets/src/System/Net/SocketPerfCounters.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.Net { internal enum SocketPerfCounterName { SocketConnectionsEstablished = 0, // these enum values are used as index SocketBytesReceived, SocketBytesSent, SocketDatagramsReceived, SocketDatagramsSent, } internal sealed class SocketPerfCounter { private static SocketPerfCounter s_instance; private static object s_lockObject = new object(); public static SocketPerfCounter Instance { get { if (Volatile.Read(ref s_instance) == null) { lock (s_lockObject) { if (Volatile.Read(ref s_instance) == null) { s_instance = new SocketPerfCounter(); } } } return s_instance; } } public bool Enabled { get { // TODO (#7833): Implement socket perf counters. return false; } } public void Increment(SocketPerfCounterName perfCounter) { // TODO (#7833): Implement socket perf counters. } public void Increment(SocketPerfCounterName perfCounter, long amount) { // TODO (#7833): Implement socket perf counters. } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; namespace System.Net { internal enum SocketPerfCounterName { SocketConnectionsEstablished = 0, // these enum values are used as index SocketBytesReceived, SocketBytesSent, SocketDatagramsReceived, SocketDatagramsSent, } internal sealed class SocketPerfCounter { private static SocketPerfCounter s_instance; private static object s_lockObject = new object(); public static SocketPerfCounter Instance { get { if (Volatile.Read(ref s_instance) == null) { lock (s_lockObject) { if (Volatile.Read(ref s_instance) == null) { s_instance = new SocketPerfCounter(); } } } return s_instance; } } public bool Enabled { get { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. return false; } } public void Increment(SocketPerfCounterName perfCounter) { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. } public void Increment(SocketPerfCounterName perfCounter, long amount) { // TODO (Event logging for System.Net.* #2500): Implement socket perf counters. } } }
mit
C#
11ad3fc0827488d42ddb62ca639183cea6005054
Bump version to 8.17.0
abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
src/SolutionInfo.cs
src/SolutionInfo.cs
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // versions // read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin // note: do NOT change anything here manually, use the build scripts // this is the ONLY ONE the CLR cares about for compatibility // should change ONLY when "hard" breaking compatibility (manual change) [assembly: AssemblyVersion("8.0.0")] // these are FYI and changed automatically [assembly: AssemblyFileVersion("8.17.0")] [assembly: AssemblyInformationalVersion("8.17.0")]
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // versions // read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin // note: do NOT change anything here manually, use the build scripts // this is the ONLY ONE the CLR cares about for compatibility // should change ONLY when "hard" breaking compatibility (manual change) [assembly: AssemblyVersion("8.0.0")] // these are FYI and changed automatically [assembly: AssemblyFileVersion("8.17.0")] [assembly: AssemblyInformationalVersion("8.17.0-rc2")]
mit
C#
1be97f01dfda47f2e67ec6c88295ea83057f1c89
Add console tracing
tomliversidge/protoactor-dotnet,tomliversidge/protoactor-dotnet,masteryee/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,raskolnikoov/protoactor-dotnet,AsynkronIT/protoactor-dotnet,masteryee/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,raskolnikoov/protoactor-dotnet
examples/DependencyInjection/Startup.cs
examples/DependencyInjection/Startup.cs
using System; using System.Threading; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Proto; namespace DependencyInjection { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddProtoActor(props => { //attached console tracing props.RegisterProps<DIActor>(p => p.WithReceiveMiddleware(next => async c => { Console.WriteLine($"enter {c.Actor.GetType().FullName} {c.Message.GetType().FullName}"); await next(c); Console.WriteLine($"exit {c.Actor.GetType().FullName} {c.Message.GetType().FullName}"); })); }); services.AddTransient<IActorManager, ActorManager>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) { loggerFactory.AddConsole(LogLevel.Debug); //attach logger to proto logging just in case Proto.Log.SetLoggerFactory(loggerFactory); //This is only for demo purposes done in the service initialization var actorManager = app.ApplicationServices.GetRequiredService<IActorManager>(); actorManager.Activate(); //never do this Thread.Sleep(TimeSpan.FromSeconds(2)); //notice, there is no second creation! actorManager.Activate(); } } }
using System; using System.Threading; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Proto; namespace DependencyInjection { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddProtoActor(); services.AddTransient<IActorManager, ActorManager>(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime) { loggerFactory.AddConsole(LogLevel.Debug); //attach logger to proto logging just in case Proto.Log.SetLoggerFactory(loggerFactory); //This is only for demo purposes done in the service initialization var actorManager = app.ApplicationServices.GetRequiredService<IActorManager>(); actorManager.Activate(); //never do this Thread.Sleep(TimeSpan.FromSeconds(2)); //notice, there is no second creation! actorManager.Activate(); } } }
apache-2.0
C#
a4974899f4e67336371786abda3e671ad29db717
add DefaultParametersFeature to v2
mvalipour/xbehave.net,hitesh97/xbehave.net,modulexcite/xbehave.net,hitesh97/xbehave.net,xbehave/xbehave.net,adamralph/xbehave.net,mvalipour/xbehave.net,modulexcite/xbehave.net
src/test/Xbehave.Features.Net40/DefaultParametersFeature.cs
src/test/Xbehave.Features.Net40/DefaultParametersFeature.cs
// <copyright file="DefaultParametersFeature.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Test.Acceptance { using System; using System.Linq; using FluentAssertions; using Xbehave.Features.Infrastructure; using Xbehave.Test.Acceptance.Infrastructure; // In order to have terse code // As a developer // I want to declare hold local state using scenario method parameters public static class DefaultParametersFeature { [Scenario] public static void ScenarioWithParameters() { var feature = default(Type); var results = default(Result[]); "Given a feature with a scenario with four parameters and step asserting each one is a default value" .f(() => feature = typeof(FeatureWithAScenarioWithAFourParametersAndAStepAssertingEachOneIsADefaultValue)); "When the test runner runs the feature" .f(() => results = TestRunner.Run(feature).ToArray()); "Then each result should be a pass" .f(() => results.Should().ContainItemsAssignableTo<Pass>( results.ToDisplayString("each result should be a pass"))); "And there should be 4 results" .f(() => results.Length.Should().Be(4)); } private static class FeatureWithAScenarioWithAFourParametersAndAStepAssertingEachOneIsADefaultValue { [Scenario] public static void Scenario(string w, int x, object y, int? z) { "Then w should be the default value of string" .f(() => w.Should().Be(default(string))); "And x should be the default value of int" .f(() => x.Should().Be(default(int))); "And y should be the default value of object" .f(() => y.Should().Be(default(object))); "And z should be the default value of int?" .f(() => z.Should().Be(default(int?))); } } } }
// <copyright file="DefaultParametersFeature.cs" company="xBehave.net contributors"> // Copyright (c) xBehave.net contributors. All rights reserved. // </copyright> namespace Xbehave.Test.Acceptance { using System; using System.Linq; using FluentAssertions; using Xbehave.Features.Infrastructure; using Xbehave.Test.Acceptance.Infrastructure; // In order to have terse code // As a developer // I want to declare hold local state using scenario method parameters public static class DefaultParametersFeature { #if !V2 [Scenario] public static void ScenarioWithParameters() { var feature = default(Type); var results = default(Result[]); "Given a feature with a scenario with four parameters and step asserting each one is a default value" .f(() => feature = typeof(FeatureWithAScenarioWithAFourParametersAndAStepAssertingEachOneIsADefaultValue)); "When the test runner runs the feature" .f(() => results = TestRunner.Run(feature).ToArray()); "Then each result should be a pass" .f(() => results.Should().ContainItemsAssignableTo<Pass>( results.ToDisplayString("each result should be a pass"))); "And there should be 4 results" .f(() => results.Length.Should().Be(4)); } private static class FeatureWithAScenarioWithAFourParametersAndAStepAssertingEachOneIsADefaultValue { [Scenario] public static void Scenario(string w, int x, object y, int? z) { "Then w should be the default value of string" .f(() => w.Should().Be(default(string))); "And x should be the default value of int" .f(() => x.Should().Be(default(int))); "And y should be the default value of object" .f(() => y.Should().Be(default(object))); "And z should be the default value of int?" .f(() => z.Should().Be(default(int?))); } } #endif } }
mit
C#
4eefa7c6cd689ca6372eed7ec6c4d84eda8a1e76
Refactor UITestFixture
atata-framework/atata-sample-app-tests
test/AtataSampleApp.UITests/UITestFixture.cs
test/AtataSampleApp.UITests/UITestFixture.cs
using Atata; using NUnit.Framework; namespace AtataSampleApp.UITests { [TestFixture] public abstract class UITestFixture { public static AtataConfig Config => AtataConfig.Current; [SetUp] public void SetUp() { AtataContext.Configure().Build(); } [TearDown] public void TearDown() { AtataContext.Current?.CleanUp(); } protected static UsersPage Login() => Go.To<SignInPage>() .Email.Set(Config.Account.Email) .Password.Set(Config.Account.Password) .SignIn(); } }
using Atata; using NUnit.Framework; namespace AtataSampleApp.UITests { [TestFixture] public class UITestFixture { public AtataConfig Config { get { return AtataConfig.Current; } } [SetUp] public void SetUp() { AtataContext.Configure().Build(); } [TearDown] public void TearDown() { if (AtataContext.Current != null) AtataContext.Current.CleanUp(); } protected UsersPage Login() { return Go.To<SignInPage>(). Email.Set(Config.Account.Email). Password.Set(Config.Account.Password). SignIn(); } } }
apache-2.0
C#
35a4e80ddd138fe3a74514d300a55335880a70fd
Update JsonHelpers.cs
jordansjones/Cex.io-Api-Client
src/Cex.io/Helpers/JsonHelpers.cs
src/Cex.io/Helpers/JsonHelpers.cs
using System; using System.Globalization; using System.Linq; namespace Nextmethod.Cex { internal static class JsonHelpers { internal static bool ContainsProperty(dynamic This, string name) { if (This == null || string.IsNullOrEmpty(name)) return false; var jo = This as JsonObject; if (jo != null) { return jo.ContainsKey(name); } var ja = This as JsonArray; if (ja != null) { return false; } if ((This is bool) || Equals(This, bool.FalseString) || Equals(This, bool.TrueString)) return false; return This.GetType().GetProperty(name); } internal static decimal ToDecimal(dynamic value) { if (value == null) return default(decimal); var valueType = value.GetType(); if (valueType == typeof (decimal)) return value; if (valueType == typeof (double)) return (decimal)value; // return decimal.Parse(value, CultureInfo.InvariantCulture); This not work for me return Convert.ToDecimal(value); // Simple fix for me } } }
using System; using System.Globalization; using System.Linq; namespace Nextmethod.Cex { internal static class JsonHelpers { internal static bool ContainsProperty(dynamic This, string name) { if (This == null || string.IsNullOrEmpty(name)) return false; var jo = This as JsonObject; if (jo != null) { return jo.ContainsKey(name); } var ja = This as JsonArray; if (ja != null) { return false; } if ((This is bool) || Equals(This, bool.FalseString) || Equals(This, bool.TrueString)) return false; return This.GetType().GetProperty(name); } internal static decimal ToDecimal(dynamic value) { if (value == null) return default(decimal); var valueType = value.GetType(); if (valueType == typeof (decimal)) return value; if (valueType == typeof (double)) return (decimal)value; return decimal.Parse(value, CultureInfo.InvariantCulture); } } }
mit
C#
a6ba4f008671ae1ed07d50ea6048569f39130ae1
replace accidentally reverted fix
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Demo/NakedFunctions.Rest.App.Demo/NakedObjectsRunSettings.cs
Demo/NakedFunctions.Rest.App.Demo/NakedObjectsRunSettings.cs
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Data.Entity.Core.Objects; using System.Data.Entity.Core.Objects.DataClasses; using System.Linq; using AdventureWorksFunctionalModel; using AdventureWorksModel; using AdventureWorksModel.Sales; using Microsoft.Extensions.Configuration; using NakedObjects.Architecture.Menu; using NakedObjects.Core.Configuration; using NakedObjects.Menu; using NakedObjects.Meta.Audit; using NakedObjects.Meta.Authorization; using NakedObjects.Persistor.Entity.Configuration; namespace NakedObjects.Rest.App.Demo { public static class NakedObjectsRunSettings { private static string[] ModelNamespaces { get { return new string[] {"AdventureWorksModel"}; } } private static Type[] Types => new Type [] { }; private static Type[] Services => AWModelConfiguration.Services().ToArray(); private static Type[] FunctionalTypes => AWModelConfiguration.DomainTypes().ToArray(); private static Type[] Functions => AWModelConfiguration.ObjectFunctions().ToArray(); public static ReflectorConfiguration ReflectorConfig() { ReflectorConfiguration.NoValidate = true; return new ReflectorConfiguration(Types, Services, ModelNamespaces, MainMenus); } public static FunctionalReflectorConfiguration FunctionalReflectorConfig() => new FunctionalReflectorConfiguration(FunctionalTypes, Functions); public static EntityObjectStoreConfiguration EntityObjectStoreConfig(IConfiguration configuration) { var config = new EntityObjectStoreConfiguration(); var cs = configuration.GetConnectionString("AdventureWorksContext"); config.UsingContext(() => new AdventureWorksContext(cs)); return config; } public static IAuditConfiguration AuditConfig() => null; public static IAuthorizationConfiguration AuthorizationConfig() => null; public static IMenu[] MainMenus(IMenuFactory factory) => AWModelConfiguration.MainMenus().Select(kvp => factory.NewMenu(kvp.Value, true, kvp.Key)).ToArray(); } }
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and limitations under the License. using System; using System.Data.Entity.Core.Objects; using System.Data.Entity.Core.Objects.DataClasses; using System.Linq; using AdventureWorksFunctionalModel; using AdventureWorksModel; using AdventureWorksModel.Sales; using Microsoft.Extensions.Configuration; using NakedObjects.Architecture.Menu; using NakedObjects.Core.Configuration; using NakedObjects.Menu; using NakedObjects.Meta.Audit; using NakedObjects.Meta.Authorization; using NakedObjects.Persistor.Entity.Configuration; namespace NakedObjects.Rest.App.Demo { public static class NakedObjectsRunSettings { private static string[] ModelNamespaces { get { return new string[] {"AdventureWorksModel"}; } } private static Type[] Types => new Type [] { }; private static Type[] Services => AWModelConfiguration.Services().ToArray(); private static Type[] FunctionalTypes => AWModelConfiguration.ObjectFunctions().ToArray(); private static Type[] Functions => AWModelConfiguration.DomainTypes().ToArray(); public static ReflectorConfiguration ReflectorConfig() { ReflectorConfiguration.NoValidate = true; return new ReflectorConfiguration(Types, Services, ModelNamespaces, MainMenus); } public static FunctionalReflectorConfiguration FunctionalReflectorConfig() => new FunctionalReflectorConfiguration(FunctionalTypes, Functions); public static EntityObjectStoreConfiguration EntityObjectStoreConfig(IConfiguration configuration) { var config = new EntityObjectStoreConfiguration(); var cs = configuration.GetConnectionString("AdventureWorksContext"); config.UsingContext(() => new AdventureWorksContext(cs)); return config; } public static IAuditConfiguration AuditConfig() => null; public static IAuthorizationConfiguration AuthorizationConfig() => null; public static IMenu[] MainMenus(IMenuFactory factory) => AWModelConfiguration.MainMenus().Select(kvp => factory.NewMenu(kvp.Value, true, kvp.Key)).ToArray(); } }
apache-2.0
C#
23c8a1f61325f5de1a4c2741f7e12052cf2afb0c
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.75.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.74.*")]
mit
C#
9dbcb8e3eccc5f737d4ecee1a68aace3997c392d
Use && instead of & to perform AND operation
steven-r/Oberon0Compiler
oberon0/Expressions/Operations/OpRelOp2.cs
oberon0/Expressions/Operations/OpRelOp2.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [UsedImplicitly] internal class OpRelOp2 : BinaryOperation { protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters) { if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst) { var left = (ConstantExpression)bin.LeftHandSide; var right = (ConstantExpression)bin.RightHandSide; bool res = false; switch (operationParameters.Operation) { case OberonGrammarLexer.AND: res = left.ToBool() && right.ToBool(); break; case OberonGrammarLexer.OR: res = left.ToBool() || right.ToBool(); break; } return new ConstantBoolExpression(res); } return bin; // expression remains the same } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; [ArithmeticOperation(OberonGrammarLexer.OR, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [ArithmeticOperation(OberonGrammarLexer.AND, BaseTypes.Bool, BaseTypes.Bool, BaseTypes.Bool)] [UsedImplicitly] internal class OpRelOp2 : BinaryOperation { protected override Expression BinaryOperate(BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters) { if (bin.LeftHandSide.IsConst && bin.RightHandSide.IsConst) { var left = (ConstantExpression)bin.LeftHandSide; var right = (ConstantExpression)bin.RightHandSide; bool res = false; switch (operationParameters.Operation) { case OberonGrammarLexer.AND: res = left.ToBool() & right.ToBool(); break; case OberonGrammarLexer.OR: res = left.ToBool() || right.ToBool(); break; } return new ConstantBoolExpression(res); } return bin; // expression remains the same } } }
mit
C#
1d59e422cdc1624adf347e3ca055b73b6a977c7b
include milliseconds at TimestampLoggerToken
lucas-miranda/Raccoon
Raccoon/Logger/Tokens/TimestampLoggerToken.cs
Raccoon/Logger/Tokens/TimestampLoggerToken.cs
namespace Raccoon.Log { public class TimestampLoggerToken : LoggerToken, System.IEquatable<TimestampLoggerToken> { public TimestampLoggerToken(System.DateTime dateTime) { DateTime = dateTime; Timestamp = dateTime.ToString("dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture); } public TimestampLoggerToken(System.DateTime dateTime, string timestampFormat) { DateTime = dateTime; Timestamp = dateTime.ToString(timestampFormat, System.Globalization.CultureInfo.InvariantCulture); } public System.DateTime DateTime { get; private set; } public string Timestamp { get; private set; } public bool IsEarlier(TimestampLoggerToken timestampToken) { return DateTime.CompareTo(timestampToken.DateTime) < 0; } public bool IsLater(TimestampLoggerToken timestampToken) { return DateTime.CompareTo(timestampToken.DateTime) > 0; } public override bool Equals(LoggerToken token) { if (!(token is TimestampLoggerToken timestampToken)) { return false; } return Equals(timestampToken); } public virtual bool Equals(TimestampLoggerToken token) { return token.DateTime.Equals(DateTime); } } }
namespace Raccoon.Log { public class TimestampLoggerToken : LoggerToken, System.IEquatable<TimestampLoggerToken> { public TimestampLoggerToken(System.DateTime dateTime) { DateTime = dateTime; Timestamp = dateTime.ToString("dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture); } public TimestampLoggerToken(System.DateTime dateTime, string timestampFormat) { DateTime = dateTime; Timestamp = dateTime.ToString(timestampFormat, System.Globalization.CultureInfo.InvariantCulture); } public System.DateTime DateTime { get; private set; } public string Timestamp { get; private set; } public bool IsEarlier(TimestampLoggerToken timestampToken) { return DateTime.CompareTo(timestampToken.DateTime) < 0; } public bool IsLater(TimestampLoggerToken timestampToken) { return DateTime.CompareTo(timestampToken.DateTime) > 0; } public override bool Equals(LoggerToken token) { if (!(token is TimestampLoggerToken timestampToken)) { return false; } return Equals(timestampToken); } public virtual bool Equals(TimestampLoggerToken token) { return token.DateTime.Equals(DateTime); } } }
mit
C#
162ac9fecf4879cb0320244babcd64d8b7cf0a08
Fix incorrect matching for cases header matches
ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework
osu.Framework/Graphics/Containers/SearchContainer.cs
osu.Framework/Graphics/Containers/SearchContainer.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Framework.Graphics.Containers { public class SearchContainer : SearchContainer<Drawable> { } public class SearchContainer<T> : FillFlowContainer<T> where T : Drawable { private string searchTerm; /// <summary> /// A string that should match the <see cref="IFilterable"/> children /// </summary> public string SearchTerm { get => searchTerm; set { searchTerm = value; var terms = value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Children.OfType<IFilterable>().ForEach(child => match(child, terms)); } } private static bool match(IFilterable filterable, IEnumerable<string> terms) { //Words matched by parent is not needed to match children var childTerms = terms.Where(term => !filterable.FilterTerms.Any(filterTerm => filterTerm.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0)).ToArray(); var hasFilterableChildren = filterable as IHasFilterableChildren; bool matching = childTerms.Length == 0; //We need to check the children and should any child match this matches as well if (hasFilterableChildren != null) foreach (IFilterable child in hasFilterableChildren.FilterableChildren) matching |= match(child, childTerms); return filterable.MatchingFilter = matching; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Framework.Graphics.Containers { public class SearchContainer : SearchContainer<Drawable> { } public class SearchContainer<T> : FillFlowContainer<T> where T : Drawable { private string searchTerm; /// <summary> /// A string that should match the <see cref="IFilterable"/> children /// </summary> public string SearchTerm { get => searchTerm; set { searchTerm = value; var terms = value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Children.OfType<IFilterable>().ForEach(child => match(child, terms)); } } private static bool match(IFilterable filterable, IEnumerable<string> terms) { //Words matched by parent is not needed to match children var childTerms = terms.Where(term => !filterable.FilterTerms.Any(filterTerm => filterTerm.IndexOf(term, StringComparison.InvariantCultureIgnoreCase) >= 0)).ToArray(); var hasFilterableChildren = filterable as IHasFilterableChildren; bool matching = childTerms.Length == 0; //We need to check the children and should any child match this matches aswell if (hasFilterableChildren != null) foreach (IFilterable searchableChildren in hasFilterableChildren.FilterableChildren) matching |= match(searchableChildren, childTerms); return filterable.MatchingFilter = matching; } } }
mit
C#
330dd458bd92228038a50a79c948662cffdea3d0
Trim whitespace.
EVAST9919/osu,nyaamara/osu,UselessToucan/osu,DrabWeb/osu,ppy/osu,Frontear/osuKyzer,2yangk23/osu,Drezi126/osu,Nabile-Rahmani/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,Damnae/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,ZLima12/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,tacchinotacchi/osu,RedNesto/osu,smoogipooo/osu,smoogipoo/osu,naoey/osu,johnneijzen/osu,osu-RP/osu-RP,peppy/osu-new,peppy/osu,naoey/osu,NeoAdonis/osu,2yangk23/osu
osu.Game/Overlays/Options/Sections/MaintenanceSection.cs
osu.Game/Overlays/Options/Sections/MaintenanceSection.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Graphics; using OpenTK; namespace osu.Game.Overlays.Options.Sections { public class MaintenanceSection : OptionsSection { public override string Header => "Maintenance"; public override FontAwesome Icon => FontAwesome.fa_wrench; public MaintenanceSection() { FlowContent.Spacing = new Vector2(0, 5); Children = new Drawable[] { }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Graphics; using OpenTK; namespace osu.Game.Overlays.Options.Sections { public class MaintenanceSection : OptionsSection { public override string Header => "Maintenance"; public override FontAwesome Icon => FontAwesome.fa_wrench; public MaintenanceSection() { FlowContent.Spacing = new Vector2(0, 5); Children = new Drawable[] { }; } } }
mit
C#
2a8b9cf7939d54fed4a8eeaa61e7d555bcf2025f
bump version
mawax/InfoBridge.SuperLinq
src/InfoBridge.SuperLinq.Core/Properties/AssemblyInfo.cs
src/InfoBridge.SuperLinq.Core/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("InfoBridge.SuperLinq.Core")] [assembly: AssemblyDescription("Primarily SuperLinq is a LINQ provider for the NetServer Web Services, more specially for the ArchiveAgent. By default it utilizes the dynamic archive provider to query any table in the SuperOffice database but it can actually be used to query any archive provider.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("InfoBridge Software B.V.")] [assembly: AssemblyProduct("SuperLinq")] [assembly: AssemblyCopyright("Copyright © InfoBridge Software B.V. 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d4f987c8-a1d0-48ec-a331-8ed2eb664ee7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("InfoBridge.SuperLinq.Core")] [assembly: AssemblyDescription("Primarily SuperLinq is a LINQ provider for the NetServer Web Services, more specially for the ArchiveAgent. By default it utilizes the dynamic archive provider to query any table in the SuperOffice database but it can actually be used to query any archive provider.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("InfoBridge Software B.V.")] [assembly: AssemblyProduct("SuperLinq")] [assembly: AssemblyCopyright("Copyright © InfoBridge Software B.V. 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d4f987c8-a1d0-48ec-a331-8ed2eb664ee7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
mit
C#
b3f2913570d2119c824e1d2e4fb99b29f81220c0
Fix FileDateCondition edge cases for when file doesn't exist
synhershko/NAppUpdate,jinlook/NAppUpdate,halotron/NAppUpdate,lexruster/NAppUpdate,miguel-misstipsi/NAppUpdate2,group6tech/NAppUpdate2,vbjay/NAppUpdate,johnrossell/NAppUpdate
src/NAppUpdate.Framework/Conditions/FileDateCondition.cs
src/NAppUpdate.Framework/Conditions/FileDateCondition.cs
using System; using System.IO; using NAppUpdate.Framework.Common; namespace NAppUpdate.Framework.Conditions { [Serializable] public class FileDateCondition : IUpdateCondition { public FileDateCondition() { Timestamp = DateTime.MinValue; } [NauField("localPath", "The local path of the file to check. If not set but set under a FileUpdateTask, the LocalPath of the task will be used. Otherwise this condition will be ignored." , false)] public string LocalPath { get; set; } [NauField("timestamp", "Date-time to compare with", true)] public DateTime Timestamp { get; set; } [NauField("what", "Comparison action to perform. Accepted values: newer, is, older. Default: older.", false)] public string ComparisonType { get; set; } public bool IsMet(Tasks.IUpdateTask task) { if (Timestamp == DateTime.MinValue) return true; string localPath = !string.IsNullOrEmpty(LocalPath) ? LocalPath : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string; // local path is invalid, we can't check for anything so we will return as if the condition was met if (string.IsNullOrEmpty(localPath)) return true; // if the file doesn't exist it has a null timestamp, and therefore the condition result depends on the ComparisonType if (!File.Exists(localPath)) return ComparisonType.Equals("older", StringComparison.InvariantCultureIgnoreCase); // File timestamps seem to be off by a little bit (conversion rounding?), so the code below // gets around that var dt = File.GetLastWriteTime(localPath); var localPlus = dt.AddSeconds(2).ToFileTimeUtc(); var localMinus = dt.AddSeconds(-2).ToFileTimeUtc(); var remoteFileDateTime = Timestamp.ToFileTimeUtc(); bool result; switch (ComparisonType) { case "newer": result = localMinus > remoteFileDateTime; break; case "is": result = localMinus <= remoteFileDateTime && remoteFileDateTime <= localPlus; break; default: result = localPlus < remoteFileDateTime; break; } return result; } } }
using System; using System.IO; using NAppUpdate.Framework.Common; namespace NAppUpdate.Framework.Conditions { [Serializable] public class FileDateCondition : IUpdateCondition { public FileDateCondition() { Timestamp = DateTime.MinValue; } [NauField("localPath", "The local path of the file to check. If not set but set under a FileUpdateTask, the LocalPath of the task will be used. Otherwise this condition will be ignored." , false)] public string LocalPath { get; set; } [NauField("timestamp", "Date-time to compare with", true)] public DateTime Timestamp { get; set; } [NauField("what", "Comparison action to perform. Accepted values: newer, is, older. Default: older.", false)] public string ComparisonType { get; set; } public bool IsMet(Tasks.IUpdateTask task) { if (Timestamp == DateTime.MinValue) return true; string localPath = !string.IsNullOrEmpty(LocalPath) ? LocalPath : Utils.Reflection.GetNauAttribute(task, "LocalPath") as string; if (string.IsNullOrEmpty(localPath) || !File.Exists(localPath)) return true; // File timestamps seem to be off by a little bit (conversion rounding?), so the code below // gets around that DateTime dt = File.GetLastWriteTime(localPath); long localPlus = dt.AddSeconds(2).ToFileTimeUtc(); long localMinus = dt.AddSeconds(-2).ToFileTimeUtc(); long remoteFileDateTime = Timestamp.ToFileTimeUtc(); bool result; switch (ComparisonType) { case "newer": result = localMinus > remoteFileDateTime; break; case "is": result = localMinus <= remoteFileDateTime && remoteFileDateTime <= localPlus; break; default: result = localPlus < remoteFileDateTime; break; } return result; } } }
apache-2.0
C#
0cfdad401438245d4c2ffe681456cbfa99ef912a
return to default responsive view
wangkanai/Detection
sample/ResponsivePage/Startup.cs
sample/ResponsivePage/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Wangkanai.Detection.Models; namespace ResponsivePage { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDetection(options => { options.Responsive.DefaultTablet = Device.Tablet; options.Responsive.DefaultMobile = Device.Mobile; options.Responsive.DefaultDesktop = Device.Desktop; }); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseDetection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Wangkanai.Detection.Models; namespace ResponsivePage { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDetection(options => { options.Responsive.DefaultTablet = Device.Mobile; options.Responsive.DefaultMobile = Device.Mobile; options.Responsive.DefaultDesktop = Device.Desktop; }); services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseDetection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
apache-2.0
C#
eaac162b2ce929eaeef90ae2868eb9f9304116dc
Create proper class destructor
admoexperience/admo-kinect,admoexperience/admo-kinect
Admo/Utilities/ShortCutHandler.cs
Admo/Utilities/ShortCutHandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Class handles shortcuts and sending them using System.Windows; using System.Windows.Input; using Admo.classes; using NLog; namespace Admo.Utilities { public class ShortCutHandler { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly Window _mainWindow; private readonly List<HotKey> _hotKeys = new List<HotKey>(); public ShortCutHandler(Window main) { _mainWindow = main; _hotKeys.Add(CreateKey(Key.F1)); _hotKeys.Add(CreateKey(Key.F2)); _hotKeys.Add(CreateKey(Key.F3)); _hotKeys.Add(CreateKey(Key.F4)); _hotKeys.Add(CreateKey(Key.F5)); _hotKeys.Add(CreateKey(Key.F6)); _hotKeys.Add(CreateKey(Key.F7)); _hotKeys.Add(CreateKey(Key.F8)); _hotKeys.Add(CreateKey(Key.F9)); _hotKeys.Add(CreateKey(Key.F10)); } ~ShortCutHandler() { foreach (var key in _hotKeys) { key.Dispose(); } } private HotKey CreateKey(Key x) { var hotKey = new HotKey(ModifierKeys.Control | ModifierKeys.Shift, x, _mainWindow); hotKey.HotKeyPressed += OnKeyPress; return hotKey; } private void OnKeyPress(HotKey key) { Logger.Debug("Key Pressed "+ (int)key.Key); //Magic to Convert F1 into index 0 and F10 into index 9 var index =((int)key.Key - (int) Key.F1); var pods = Config.ListInstalledPods(); if (index >= 0 && index < pods.Count) { Config.SetPodFile(pods[index].PodName); } else { Logger.Warn("Key combo is not linked to a pod file"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Class handles shortcuts and sending them using System.Windows; using System.Windows.Input; using Admo.classes; using NLog; namespace Admo.Utilities { public class ShortCutHandler { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly Window _mainWindow; private readonly List<HotKey> _hotKeys = new List<HotKey>(); public ShortCutHandler(Window main) { _mainWindow = main; _hotKeys.Add(CreateKey(Key.F1)); _hotKeys.Add(CreateKey(Key.F2)); _hotKeys.Add(CreateKey(Key.F3)); _hotKeys.Add(CreateKey(Key.F4)); _hotKeys.Add(CreateKey(Key.F5)); _hotKeys.Add(CreateKey(Key.F6)); _hotKeys.Add(CreateKey(Key.F7)); _hotKeys.Add(CreateKey(Key.F8)); _hotKeys.Add(CreateKey(Key.F9)); _hotKeys.Add(CreateKey(Key.F10)); } public ~ShortCutHandler() { foreach (var key in _hotKeys) { key.Dispose(); } } private HotKey CreateKey(Key x) { var hotKey = new HotKey(ModifierKeys.Control | ModifierKeys.Shift, x, _mainWindow); hotKey.HotKeyPressed += OnKeyPress; return hotKey; } private void OnKeyPress(HotKey key) { Logger.Debug("Key Pressed "+ (int)key.Key); //Magic to Convert F1 into index 0 and F10 into index 9 var index =((int)key.Key - (int) Key.F1); var pods = Config.ListInstalledPods(); if (index >= 0 && index < pods.Count) { Config.SetPodFile(pods[index].PodName); } else { Logger.Warn("Key combo is not linked to a pod file"); } } } }
mit
C#
a6f33bb3bd05d3bf1523914d589b17d22f565074
Fix plots can't edit bug
leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net
Joinrpg/Helpers/MarkDownHelper.cs
Joinrpg/Helpers/MarkDownHelper.cs
using System.Linq; using System.Web; using CommonMark; using JetBrains.Annotations; using JoinRpg.DataModel; using JoinRpg.Helpers.Web; namespace JoinRpg.Web.Helpers { public static class MarkDownHelper { /// <summary> /// Converts markdown to HtmlString with all sanitization /// </summary> [CanBeNull] public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString) { return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml(); } public static string ToPlainText([CanBeNull] this MarkdownString markdownString) { if (markdownString?.Contents == null) { return null; } return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml().Trim(); } private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString) { var settings = CommonMarkSettings.Default.Clone(); settings.RenderSoftLineBreaksAsLineBreaks = true; return CommonMarkConverter.Convert(markdownString.Contents, settings); } public static MarkdownString TakeWords(this MarkdownString markdownString, int words) { if (markdownString?.Contents == null) { return null; } var w = words; var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count(); var mdContents = markdownString.Contents.Substring(0, idx); return new MarkdownString(mdContents); } } }
using System.Linq; using System.Web; using CommonMark; using JetBrains.Annotations; using JoinRpg.DataModel; using JoinRpg.Helpers.Web; namespace JoinRpg.Web.Helpers { public static class MarkDownHelper { /// <summary> /// Converts markdown to HtmlString with all sanitization /// </summary> [CanBeNull] public static HtmlString ToHtmlString([CanBeNull] this MarkdownString markdownString) { return markdownString?.Contents == null ? null : markdownString.RenderMarkDownToHtmlUnsafe().SanitizeHtml(); } public static string ToPlainText([CanBeNull] this MarkdownString markdownString) { if (markdownString?.Contents == null) { return null; } return markdownString.RenderMarkDownToHtmlUnsafe().RemoveHtml(); } private static UnSafeHtml RenderMarkDownToHtmlUnsafe(this MarkdownString markdownString) { var settings = CommonMarkSettings.Default.Clone(); settings.RenderSoftLineBreaksAsLineBreaks = true; return CommonMarkConverter.Convert(markdownString.Contents, settings); } public static MarkdownString TakeWords(this MarkdownString markdownString, int words) { if (markdownString?.Contents == null) { return null; } var w = words; var idx = markdownString.Contents.TakeWhile(c => (w -= char.IsWhiteSpace(c) ? 1 : 0) > 0 && c != '\n').Count(); var mdContents = markdownString.Contents.Substring(0, idx); return new MarkdownString(mdContents); } } }
mit
C#
5cbb0050abe01e861c4e934737101ea6454bfc8a
Refactor tests to have initialise method
Joey-Softwire/ELO,Joey-Softwire/ELO
src/EloWeb.Tests.UnitTests/PlayersTests.cs
src/EloWeb.Tests.UnitTests/PlayersTests.cs
using System; using System.Linq; using EloWeb.Models; using NUnit.Framework; using System.Collections.Generic; namespace EloWeb.Tests.UnitTests { class PlayersTests { [TestFixtureSetUp] public void TestSetup() { InitialiseTestPlayers(); InitialiseTestGames(); } [Test] public void CanParsePlayerDescriptionText() { var player = Players.PlayerByName("Richard"); Assert.AreEqual("Richard", player.Name); Assert.AreEqual(1000, player.Rating); } [Test] public void CanGetPlayerTotalGamesWon() { var player = Players.PlayerByName("Frank"); Assert.AreEqual(2, player.GamesWon); } [Test] public void CanGetPlayerTotalGamesLost() { var player = Players.PlayerByName("Frank"); Assert.AreEqual(1, player.GamesLost); } private void InitialiseTestPlayers() { Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" }); } private void InitialiseTestGames() { Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" }); } } }
using System; using System.Linq; using EloWeb.Models; using NUnit.Framework; using System.Collections.Generic; namespace EloWeb.Tests.UnitTests { class PlayersTests { [Test] public void CanParsePlayerDescriptionText() { InitialiseTestPlayers(); InitialiseTestGames(); var player = Players.PlayerByName("Richard"); Assert.AreEqual("Richard", player.Name); Assert.AreEqual(1000, player.Rating); } [Test] public void CanGetPlayerTotalGamesWon() { InitialiseTestPlayers(); InitialiseTestGames(); var player = Players.PlayerByName("Frank"); Assert.AreEqual(2, player.GamesWon); } [Test] public void CanGetPlayerTotalGamesLost() { InitialiseTestPlayers(); InitialiseTestGames(); var player = Players.PlayerByName("Frank"); Assert.AreEqual(1, player.GamesLost); } private void InitialiseTestPlayers() { Players.Initialise(new List<String>() { "Peter", "Frank", "Richard" }); } private void InitialiseTestGames() { Games.Initialise(new List<String>() { "Peter beat Frank", "Frank beat Peter", "Frank beat Peter" }); } } }
unlicense
C#
cd40b1479d9c5015f1febb88e527021b2e6c43d8
bump pluton version
Notulp/Pluton,Notulp/Pluton
Pluton/Properties/AssemblyInfo.cs
Pluton/Properties/AssemblyInfo.cs
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Pluton")] [assembly: AssemblyDescription("A server mod for the active branch of the survival sandbox game Rust")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pluton")] [assembly: AssemblyCopyright("Pluton Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.2.1.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
using System.Reflection; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle("Pluton")] [assembly: AssemblyDescription("A server mod for the active branch of the survival sandbox game Rust")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pluton")] [assembly: AssemblyCopyright("Pluton Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion("1.2.0.*")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")]
mit
C#
6747a3956196f7cbe2bbbf05712a5d652143d3ea
test juan 20180414
DigitalPlatform/chord,DigitalPlatform/chord,DigitalPlatform/chord,renyh1013/chord,renyh1013/chord,renyh1013/chord
dp2Tools/Program.cs
dp2Tools/Program.cs
// 20180514 test2 //test juan //test juan 20180414 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace dp2Tools { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() //test { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form_main()); } } }
// 20180514 test2 //test juan using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace dp2Tools { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() //test { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form_main()); } } }
apache-2.0
C#
e9196b81488c62947a241a513a8af2c42076f8d0
Copy list before iterating to prevent modifications during iteration
thomaslevesque/NHotkey
src/NHotkey.Wpf/WeakReferenceCollection.cs
src/NHotkey.Wpf/WeakReferenceCollection.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace NHotkey.Wpf { class WeakReferenceCollection<T> : IEnumerable<T> where T : class { private readonly List<WeakReference> _references = new List<WeakReference>(); public IEnumerator<T> GetEnumerator() { var references = _references.ToList(); foreach (var reference in references) { var target = reference.Target; if (target != null) yield return (T) target; } Trim(); } public void Add(T item) { _references.Add(new WeakReference(item)); } public void Remove(T item) { _references.RemoveAll(r => (r.Target ?? item) == item); } public void Trim() { _references.RemoveAll(r => !r.IsAlive); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
using System; using System.Collections; using System.Collections.Generic; namespace NHotkey.Wpf { class WeakReferenceCollection<T> : IEnumerable<T> where T : class { private readonly List<WeakReference> _references = new List<WeakReference>(); public IEnumerator<T> GetEnumerator() { foreach (var reference in _references) { var target = reference.Target; if (target != null) yield return (T) target; } Trim(); } public void Add(T item) { _references.Add(new WeakReference(item)); } public void Remove(T item) { _references.RemoveAll(r => (r.Target ?? item) == item); } public void Trim() { _references.RemoveAll(r => !r.IsAlive); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } }
apache-2.0
C#
b5acdb7c9bd117339e8216339b12fee401061740
Update IPathSize.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Model/Path/IPathSize.cs
src/Core2D/Model/Path/IPathSize.cs
 namespace Core2D.Path { /// <summary> /// Defines path size contract. /// </summary> public interface IPathSize : IObservableObject, IStringExporter { /// <summary> /// Gets or sets width value. /// </summary> double Width { get; set; } /// <summary> /// Gets or sets height value. /// </summary> double Height { get; set; } } }
 namespace Core2D.Path { /// <summary> /// Defines path size contract. /// </summary> public interface IPathSize : IObservableObject { /// <summary> /// Gets or sets width value. /// </summary> double Width { get; set; } /// <summary> /// Gets or sets height value. /// </summary> double Height { get; set; } } }
mit
C#
e109436276938ed8ca7027685102d6354b0972bb
Bump to 2.0.0
exira/ges-runner
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ges-runner")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EventstoreWinServiceWrapper")] [assembly: AssemblyCopyright("Copyright © Tomas Jansson - 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("736CC839-0641-49E6-B8DF-58CA146EA121")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.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("EventstoreWinServiceWrapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EventstoreWinServiceWrapper")] [assembly: AssemblyCopyright("Copyright © Tomas Jansson - 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("49c2abeb-f3a0-4144-a43a-f4bce3456ff7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
mit
C#
03498b3c616851e53ccbb785b63bba8e47f06186
Update comment about this Interface usage - maybe we can remove this later on
robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS
src/Umbraco.Web/UI/IAssignedApp.cs
src/Umbraco.Web/UI/IAssignedApp.cs
namespace Umbraco.Web.UI { /// <summary> /// This is used for anything that is assigned to an app /// </summary> /// <remarks> /// Currently things that need to be assigned to an app in order for user security to work are: /// LegacyDialogTask /// </remarks> public interface IAssignedApp { /// <summary> /// Returns the app alias that this element belongs to /// </summary> string AssignedApp { get; } } }
namespace Umbraco.Web.UI { /// <summary> /// This is used for anything that is assigned to an app /// </summary> /// <remarks> /// Currently things that need to be assigned to an app in order for user security to work are: /// dialogs, ITasks, editors /// </remarks> public interface IAssignedApp { /// <summary> /// Returns the app alias that this element belongs to /// </summary> string AssignedApp { get; } } }
mit
C#
281a2c1bda8ce8e2b0a8b0dba08e07b0ee121b97
Change processor logic
marska/wundercal
src/Wundercal/CalendarProcessor.cs
src/Wundercal/CalendarProcessor.cs
using System; using System.Configuration; using Wundercal.Services; namespace Wundercal { internal class CalendarProcessor : ICalendarProcessor { private readonly ICalendarService _calendarService; private readonly IWunderlistService _wunderlistService; public CalendarProcessor(ICalendarService calendarService, IWunderlistService wunderlistService) { _calendarService = calendarService; _wunderlistService = wunderlistService; } public void Execute() { Console.WriteLine("Executing processor ..."); var events = _calendarService.GetCalendarEvents(DateTime.Today); if (events.Count > 0) { var listId = string.IsNullOrEmpty(Settings.WunderlistListName) ? _wunderlistService.GetListId("inbox") : _wunderlistService.GetListId(Settings.WunderlistListName); events.ForEach(@event => { Console.WriteLine("Adding task: " + @event.Summary); var taskId = _wunderlistService.CreateTask(listId, $"{Settings.TaskTags} {@event.Summary}", @event.StartDate); _wunderlistService.CreateReminder(taskId, @event.StartDate); }); } } } }
using System; using System.Configuration; using Wundercal.Services; namespace Wundercal { internal class CalendarProcessor : ICalendarProcessor { private readonly ICalendarService _calendarService; private readonly IWunderlistService _wunderlistService; public CalendarProcessor(ICalendarService calendarService, IWunderlistService wunderlistService) { _calendarService = calendarService; _wunderlistService = wunderlistService; } public void Execute() { Console.WriteLine("Executing processor ..."); var events = _calendarService.GetCalendarEvents(DateTime.Today.AddDays(1)); if (events.Count > 0) { var listId = string.IsNullOrEmpty(Settings.WunderlistListName) ? _wunderlistService.GetListId("inbox") : _wunderlistService.GetListId(Settings.WunderlistListName); events.ForEach(@event => { Console.WriteLine("Adding task: " + @event.Summary); var taskId = _wunderlistService.CreateTask(listId, $"{Settings.TaskTags} {@event.Summary}", @event.StartDate); _wunderlistService.CreateReminder(taskId, @event.StartDate); }); } } } }
apache-2.0
C#
2fd6ea525c7763be2ce18592ad80eda06d4b7f67
Set campaign Content
shahriarhossain/MailChimp.Api.Net
MailChimp.Api.Net/Services/Campaigns/MCCampaignContent.cs
MailChimp.Api.Net/Services/Campaigns/MCCampaignContent.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using MailChimp.Api.Net.Domain.Campaigns; using MailChimp.Api.Net.Enum; using MailChimp.Api.Net.Helper; using Newtonsoft.Json; namespace MailChimp.Api.Net.Services.Campaigns { // ============================================================================================= // AUTHOR : Shahriar Hossain // PURPOSE : Manage the HTML, plain-text, and template content for your MailChimp campaigns // ============================================================================================= internal class MCCampaignContent { ///<summary> ///Get campaign content ///</summary> internal async Task<RootContent> GetCampaignContentAsync(string campaign_id) { string endpoint = Authenticate.EndPoint(TargetTypes.campaigns, SubTargetType.content, SubTargetType.not_applicable, campaign_id); return await BaseOperation.GetAsync<RootContent>(endpoint); } ///<summary> ///Set campaign content ///</summary> internal async Task<dynamic> SetCampaignContentAsync(string campaign_id, ContentSetting setting, ContentTemplate contentTemplate) { string endpoint = Authenticate.EndPoint(TargetTypes.campaigns, SubTargetType.content, SubTargetType.not_applicable, campaign_id); RootContent content = new RootContent() { template = contentTemplate, plain_text = setting.plain_text, html = setting.html, url = setting.url }; return await BaseOperation.PutAsync<RootContent>(endpoint, content); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using MailChimp.Api.Net.Domain.Campaigns; using MailChimp.Api.Net.Enum; using MailChimp.Api.Net.Helper; using Newtonsoft.Json; namespace MailChimp.Api.Net.Services.Campaigns { // ============================================================================================= // AUTHOR : Shahriar Hossain // PURPOSE : Manage the HTML, plain-text, and template content for your MailChimp campaigns // ============================================================================================= internal class MCCampaignContent { ///<summary> ///Get campaign content ///</summary> internal async Task<RootContent> GetCampaignContentAsync(string campaign_id) { string endpoint = Authenticate.EndPoint(TargetTypes.campaigns, SubTargetType.content, SubTargetType.not_applicable, campaign_id); return await BaseOperation.GetAsync<RootContent>(endpoint); } } }
mit
C#
009bcfd84202684bd0e01f866f00c5f51a2e7004
Update XRecordTests.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D
tests/Core2D.UnitTests/Data/Database/XRecordTests.cs
tests/Core2D.UnitTests/Data/Database/XRecordTests.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Data.Database; using Xunit; namespace Core2D.UnitTests { public class XRecordTests { [Fact] [Trait("Core2D.Data", "Database")] public void Inherits_From_ObservableObject() { var target = new XRecord(); Assert.True(target is ObservableObject); } [Fact] [Trait("Core2D.Data", "Database")] public void Values_Not_Null() { var target = new XRecord(); Assert.NotNull(target.Values); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Data.Database; using Xunit; namespace Core2D.UnitTests { public class XRecordTests { [Fact] [Trait("Core2D.Data", "Database")] public void Inherits_From_ObservableObject() { var target = new XRecord(); Assert.True(target is ObservableObject); } [Fact] [Trait("Core2D.Data", "Database")] public void Columns_Not_Null() { var target = new XRecord(); Assert.NotNull(target.Columns); } [Fact] [Trait("Core2D.Data", "Database")] public void Values_Not_Null() { var target = new XRecord(); Assert.NotNull(target.Values); } } }
mit
C#
bf4ed2f6456076e56751066d6ec4e388ddbd9ffe
Remove unused using
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/IdentitySample.Mvc/Models/SampleData.cs
samples/IdentitySample.Mvc/Models/SampleData.cs
using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace IdentitySample.Models { public static class SampleData { public static async Task InitializeIdentityDatabaseAsync(IServiceProvider serviceProvider) { using (var db = serviceProvider.GetRequiredService<ApplicationDbContext>()) { if (await db.Database.EnsureCreatedAsync()) { await CreateAdminUser(serviceProvider); } } } /// <summary> /// Creates a store manager user who can manage the inventory. /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> private static async Task CreateAdminUser(IServiceProvider serviceProvider) { var options = serviceProvider.GetRequiredService<IOptions<IdentityDbContextOptions>>().Value; const string adminRole = "Administrator"; var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); if (!await roleManager.RoleExistsAsync(adminRole)) { await roleManager.CreateAsync(new IdentityRole(adminRole)); } var user = await userManager.FindByNameAsync(options.DefaultAdminUserName); if (user == null) { user = new ApplicationUser { UserName = options.DefaultAdminUserName }; await userManager.CreateAsync(user, options.DefaultAdminPassword); await userManager.AddToRoleAsync(user, adminRole); await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed")); } } } }
using System; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.Data.Entity.SqlServer; using Microsoft.Framework.DependencyInjection; using Microsoft.Framework.OptionsModel; namespace IdentitySample.Models { public static class SampleData { public static async Task InitializeIdentityDatabaseAsync(IServiceProvider serviceProvider) { using (var db = serviceProvider.GetRequiredService<ApplicationDbContext>()) { if (await db.Database.EnsureCreatedAsync()) { await CreateAdminUser(serviceProvider); } } } /// <summary> /// Creates a store manager user who can manage the inventory. /// </summary> /// <param name="serviceProvider"></param> /// <returns></returns> private static async Task CreateAdminUser(IServiceProvider serviceProvider) { var options = serviceProvider.GetRequiredService<IOptions<IdentityDbContextOptions>>().Value; const string adminRole = "Administrator"; var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>(); var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>(); if (!await roleManager.RoleExistsAsync(adminRole)) { await roleManager.CreateAsync(new IdentityRole(adminRole)); } var user = await userManager.FindByNameAsync(options.DefaultAdminUserName); if (user == null) { user = new ApplicationUser { UserName = options.DefaultAdminUserName }; await userManager.CreateAsync(user, options.DefaultAdminPassword); await userManager.AddToRoleAsync(user, adminRole); await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed")); } } } }
apache-2.0
C#
af9d358a0ef4aeba658d4c26e63c4dfc1bd4e8e3
Revert Utils.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Helpers/Utils.cs
WalletWasabi.Gui/Helpers/Utils.cs
using Avalonia.Threading; using System; using System.IO; using System.Threading.Tasks; namespace WalletWasabi.Gui.Helpers { public static class Utils { public static bool DetectLLVMPipeRasterizer() { try { var shellResult = ShellUtils.ExecuteShellCommand("glxinfo | grep renderer", ""); if (!string.IsNullOrWhiteSpace(shellResult.Output) && shellResult.Output.Contains("llvmpipe")) { return true; } } catch { // do nothing } return false; } } }
using Avalonia.Threading; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; namespace WalletWasabi.Gui.Helpers { public static class Utils { public static bool DetectLLVMPipeRasterizer() { try { var shellResult = ShellUtils.ExecuteShellCommand("glxinfo | grep renderer", ""); if (!string.IsNullOrWhiteSpace(shellResult.Output) && shellResult.Output.Contains("llvmpipe")) { return true; } } catch { // do nothing } return false; } } }
mit
C#
493670faba289e42b1e2bb37197dff87549b1aaa
Add reload
Tunsy/splatline-miami
splatlinemiami/Assets/Scripts/Weapons/Weapon.cs
splatlinemiami/Assets/Scripts/Weapons/Weapon.cs
using UnityEngine; using System.Collections; public class Weapon : MonoBehaviour { public Bullet bullet; public float fireCooldown; public AudioClip shootSound; public AudioClip reloadSound; public int maxBulletCount; public int reloadTime; private int currentBulletCount; private bool isReloading; public void Start() { currentBulletCount = maxBulletCount; } public virtual void Shoot() { if (!isReloading) { // Play the shooting sound effect if (shootSound) AudioSource.PlayClipAtPoint(shootSound, transform.position); // Convert the angle of the player to the velocity of the bullet and shoot it forward GameObject currentBullet = (GameObject)Instantiate(bullet.gameObject, transform.position, GetComponentInParent<Transform>().transform.rotation); Vector2 angle = Quaternion.AngleAxis(transform.rotation.eulerAngles.z + Random.Range(-3f, 3f), Vector3.forward) * Vector3.up; currentBullet.GetComponent<Rigidbody2D>().velocity = angle * currentBullet.GetComponent<Bullet>().bulletSpeed; // Reload if ammo count is 0 currentBulletCount--; if (currentBulletCount <= 0) { Reload(); } } } public void Reload() { isReloading = true; //Start a timer System.Timers.Timer atimer = new System.Timers.Timer(); atimer.AutoReset = false; atimer.Elapsed += new System.Timers.ElapsedEventHandler(reloadBullet); atimer.Interval = reloadTime; atimer.Start(); if (reloadSound) { AudioSource.PlayClipAtPoint(reloadSound, transform.position); } } private void reloadBullet(object source, System.Timers.ElapsedEventArgs e) { currentBulletCount = maxBulletCount; isReloading = false; } }
using UnityEngine; using System.Collections; public class Weapon : MonoBehaviour { public Bullet bullet; public float fireCooldown; public AudioClip shootSound; public int maxBulletCount; private int currentBulletCount; private bool isReloading; public void Start() { currentBulletCount = maxBulletCount; } public virtual void Shoot() { if (!isReloading) { // Play the shooting sound effect if (shootSound) AudioSource.PlayClipAtPoint(shootSound, transform.position); // Convert the angle of the player to the velocity of the bullet and shoot it forward GameObject currentBullet = (GameObject)Instantiate(bullet.gameObject, transform.position, GetComponentInParent<Transform>().transform.rotation); Vector2 angle = Quaternion.AngleAxis(transform.rotation.eulerAngles.z + Random.Range(-3f, 3f), Vector3.forward) * Vector3.up; currentBullet.GetComponent<Rigidbody2D>().velocity = angle * currentBullet.GetComponent<Bullet>().bulletSpeed; // Reload if ammo count is 0 currentBulletCount--; if (currentBulletCount <= 0) { Reload(); } } } public void Reload() { //Start a timer //Play a reload sound //Restart bullet count //Be able to shoot again after timer ends } }
mit
C#
811d8a2578661a5eb9596e3c3c6cb366192baa08
remove no longer needed supression
acple/ParsecSharp
ParsecSharp/GlobalSuppressions.cs
ParsecSharp/GlobalSuppressions.cs
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")]
using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Style", "IDE0071:Simplify interpolation", Justification = "IDE0071 considerably decreases the performance of string construction")] [assembly: SuppressMessage("Style", "IDE0071WithoutSuggestion")]
mit
C#
12f1c4f8615d742842b08f1ab8c552abdd5c91d2
Make case insensitive matching
mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy
src/Manos/Manos.Routing/StringMatchOperation.cs
src/Manos/Manos.Routing/StringMatchOperation.cs
// // Copyright (C) 2010 Jackson Harper ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Specialized; using Manos.Collections; namespace Manos.Routing { public class StringMatchOperation : IMatchOperation { private string str; public StringMatchOperation (string str) { String = str; } public string String { get { return str; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("StringMatch operations should not use empty strings."); str = value.ToLower(); } } public bool IsMatch (string input, int start, out DataDictionary data, out int end) { if (!StartsWith (input, start, String)) { data = null; end = start; return false; } data = null; end = start + String.Length; return true; } public static bool StartsWith (string input, int start, string str) { string lowerInput = input.ToLower (); if (lowerInput.Length < str.Length + start) return false; for (int i = 0; i < str.Length; i++) { if (lowerInput [start + i] != str [i]) return false; } return true; } } }
// // Copyright (C) 2010 Jackson Harper ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // using System; using System.Collections.Specialized; using Manos.Collections; namespace Manos.Routing { public class StringMatchOperation : IMatchOperation { private string str; public StringMatchOperation (string str) { String = str; } public string String { get { return str; } set { if (value == null) throw new ArgumentNullException ("value"); if (value.Length == 0) throw new ArgumentException ("StringMatch operations should not use empty strings."); str = value; } } public bool IsMatch (string input, int start, out DataDictionary data, out int end) { if (!StartsWith (input, start, String)) { data = null; end = start; return false; } data = null; end = start + String.Length; return true; } public static bool StartsWith (string input, int start, string str) { if (input.Length < str.Length + start) return false; for (int i = 0; i < str.Length; i++) { if (input [start + i] != str [i]) return false; } return true; } } }
mit
C#
8b884aed710fce0a5ba9a0dd13a67b65f48c0579
Refactor to allow for multiple rooms
Endure-Game/Endure
Assets/Scripts/RoomManager.cs
Assets/Scripts/RoomManager.cs
using UnityEngine; using System; using System.Collections.Generic; using Random = UnityEngine.Random; public class RoomManager : MonoBehaviour { [Serializable] public class Count { public int minimum; public int maximum; public Count (int min, int max) { minimum = min; maximum = max; } } public int rows = 32; public int columns = 32; public Count coinCount = new Count (4, 10); public Count blockingCount = new Count (5, 20); public GameObject[] floorTiles; public GameObject[] outerWallTiles; //need game objects for collectible items obstacles etc public GameObject[] coins; public GameObject[] blocks; private GameObject[,] rooms; List<Vector3> InitializeList () { List<Vector3> gridPositions = new List<Vector3> (); gridPositions.Clear (); for (int x = 1; x < columns - 1; x ++) { for(int y = 1; y < rows - 1; y ++){ gridPositions.Add(new Vector3 (x, y, 0f)); } } return gridPositions; } GameObject RoomSetup () { GameObject room = new GameObject ("Room"); Transform roomHolder = room.transform; for (int x = 0; x < columns; x ++) { for(int y = 0; y < rows; y ++){ GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)]; if ((x == 0 || x == columns - 1 || y == 0 || y == rows - 1) && x != 15 && y != 15) { toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)]; } float width = this.columns; float height = this.rows; float tileWidth = 1; float tileHeight = 1; GameObject instance = Instantiate (toInstantiate, new Vector3(x + tileWidth / 2 - width / 2, y + tileHeight / 2 - height / 2, 0f),Quaternion.identity) as GameObject; instance.transform.SetParent (roomHolder); } } return room; } Vector3 RandomPosition (List <Vector3> gridPositions) { int randomIndex = Random.Range (0, gridPositions.Count); Vector3 randomPosition = gridPositions [randomIndex]; gridPositions.RemoveAt (randomIndex); return randomPosition; } void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum, List<Vector3> gridPositions) { int objectCount = Random.Range (minimum, maximum + 1); for (int i = 0; i < objectCount; i++) { Vector3 randomPosition = RandomPosition(gridPositions); GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)]; Instantiate(tileChoice, randomPosition, Quaternion.identity); } } public void SetupRoom () { this.rooms = new GameObject[1, 1]; this.rooms[0, 0] = RoomSetup (); List<Vector3> gridPositions = InitializeList (); //this is where we would call LayoutObjectAtRandom, we don't have any health, items, weapons, etc. yet //we do have an item though so... LayoutObjectAtRandom (coins, coinCount.minimum, coinCount.maximum, gridPositions); LayoutObjectAtRandom (blocks, blockingCount.minimum, blockingCount.maximum, gridPositions); } public GameObject GetRoom (int x, int y) { return this.rooms [x, y]; } }
using UnityEngine; using System; using System.Collections.Generic; using Random = UnityEngine.Random; public class RoomManager : MonoBehaviour { [Serializable] public class Count { public int minimum; public int maximum; public Count (int min, int max) { minimum = min; maximum = max; } } public int rows = 32; public int columns = 32; public Count coinCount = new Count (4, 10); public Count blockingCount = new Count (5, 20); public GameObject[] floorTiles; public GameObject[] outerWallTiles; //need game objects for collectible items obstacles etc public GameObject[] coins; public GameObject[] blocks; private List <Vector3> gridPositions = new List<Vector3> (); private GameObject[,] rooms; void InitializeList () { gridPositions.Clear (); for (int x = 1; x < columns - 1; x ++) { for(int y = 1; y < rows - 1; y ++){ gridPositions.Add(new Vector3 (x, y, 0f)); } } } void RoomSetup () { GameObject room = new GameObject ("Room"); this.rooms [0, 0] = room; Transform roomHolder = room.transform; for (int x = 0; x < columns; x ++) { for(int y = 0; y < rows; y ++){ GameObject toInstantiate = floorTiles[Random.Range(0, floorTiles.Length)]; if ((x == 0 || x == columns - 1 || y == 0 || y == rows - 1) && x != 15 && y != 15) { toInstantiate = outerWallTiles[Random.Range(0, outerWallTiles.Length)]; } float width = this.columns; float height = this.rows; float tileWidth = 1; float tileHeight = 1; GameObject instance = Instantiate (toInstantiate, new Vector3(x + tileWidth / 2 - width / 2, y + tileHeight / 2 - height / 2, 0f),Quaternion.identity) as GameObject; instance.transform.SetParent (roomHolder); } } } Vector3 RandomPosition () { int randomIndex = Random.Range (0, gridPositions.Count); Vector3 randomPosition = gridPositions [randomIndex]; gridPositions.RemoveAt (randomIndex); return randomPosition; } void LayoutObjectAtRandom (GameObject[] tileArray, int minimum, int maximum) { int objectCount = Random.Range (minimum, maximum + 1); for (int i = 0; i < objectCount; i++) { Vector3 randomPosition = RandomPosition(); GameObject tileChoice = tileArray[Random.Range(0, tileArray.Length)]; Instantiate(tileChoice, randomPosition, Quaternion.identity); } } public void SetupRoom () { this.rooms = new GameObject[1, 1]; RoomSetup (); InitializeList (); //this is where we would call LayoutObjectAtRandom, we don't have any health, items, weapons, etc. yet //we do have an item though so... LayoutObjectAtRandom (coins, coinCount.minimum, coinCount.maximum); LayoutObjectAtRandom (blocks, blockingCount.minimum, blockingCount.maximum); } public GameObject GetRoom (int x, int y) { return this.rooms [x, y]; } }
mit
C#
6e0aa5118b7c403021a8df5f3c3b0d5f0237b6a8
Add player start pos handling
Ludoratoire/LD39-133mhz
Assets/scripts/GameManager.cs
Assets/scripts/GameManager.cs
using AlpacaSound; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { private static GameManager _sInstance; public static GameManager Instance { get { return _sInstance; } private set { _sInstance = value; } } public GameObject player; public GameObject startPos; public Camera gameCamera; public int powerAvailable = 133; public int speedFactor = 100; public int life = 3; public int score = 0; public List<GameTask> taskList; protected RetroPixel _retroPixel; void Start () { if (_sInstance == null) _sInstance = this; else { Destroy(this); return; } _retroPixel = gameCamera.GetComponent<RetroPixel>(); _retroPixel.enabled = false; taskList = new List<GameTask>(); taskList.Add(new GravityTask()); taskList.Add(new LuminosityTask()); taskList.Add(new ResolutionTask()); taskList.Add(new JumpTask()); taskList.Add(new MobilityTask()); taskList.Add(new CollisionTask()); taskList.Add(new ScrollingTask()); } // Tasks public GameTask GetTask(string name) { return taskList.Find(x => x.name == name); } // Retro Pixel public void SetRetroFactor(int factor) { if (factor == 100) _retroPixel.enabled = false; else _retroPixel.enabled = true; _retroPixel.horizontalResolution = (int) (1280 * factor / 100); _retroPixel.verticalResolution = (int) (768 * factor / 100); } public void ResetPlayerPos() { foreach (var c in player.GetComponents<Collider2D>()) { c.enabled = true; } player.transform.position = startPos.transform.position; } }
using AlpacaSound; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { private static GameManager _sInstance; public static GameManager Instance { get { return _sInstance; } private set { _sInstance = value; } } public GameObject player; public Camera gameCamera; public int powerAvailable = 133; public int speedFactor = 100; public int life = 3; public int score = 0; public List<GameTask> taskList; protected RetroPixel _retroPixel; void Start () { if (_sInstance == null) _sInstance = this; else { Destroy(this); return; } _retroPixel = gameCamera.GetComponent<RetroPixel>(); _retroPixel.enabled = false; taskList = new List<GameTask>(); taskList.Add(new GravityTask()); taskList.Add(new LuminosityTask()); taskList.Add(new ResolutionTask()); taskList.Add(new JumpTask()); taskList.Add(new MobilityTask()); taskList.Add(new CollisionTask()); taskList.Add(new ScrollingTask()); } // Tasks public GameTask GetTask(string name) { return taskList.Find(x => x.name == name); } // Retro Pixel public void SetRetroFactor(int factor) { if (factor == 100) _retroPixel.enabled = false; else _retroPixel.enabled = true; _retroPixel.horizontalResolution = (int) (1280 * factor / 100); _retroPixel.verticalResolution = (int) (768 * factor / 100); } }
apache-2.0
C#
6772c9d2b6d05c985174f514aa8df2aacd33a201
Comment the asset deletion handler. It can be abused and is not currently needed.
TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim
OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs
OpenSim/Server/Handlers/Asset/AssetServerDeleteHandler.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Server.Handlers.Asset { public class AssetServerDeleteHandler : BaseStreamHandler { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_AssetService; public AssetServerDeleteHandler(IAssetService service) : base("DELETE", "/assets") { m_AssetService = service; } public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { bool result = false; string[] p = SplitParams(path); if (p.Length > 0) { // result = m_AssetService.Delete(p[0]); } XmlSerializer xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Server.Handlers.Asset { public class AssetServerDeleteHandler : BaseStreamHandler { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IAssetService m_AssetService; public AssetServerDeleteHandler(IAssetService service) : base("DELETE", "/assets") { m_AssetService = service; } public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { bool result = false; string[] p = SplitParams(path); if (p.Length > 0) { result = m_AssetService.Delete(p[0]); } XmlSerializer xs = new XmlSerializer(typeof(bool)); return ServerUtils.SerializeResult(xs, result); } } }
bsd-3-clause
C#
5a39439206af6a704200de2ff3f8d67bc449eb04
Add async methods
mwarger/ZendeskApi_v2,CKCobra/ZendeskApi_v2,mattnis/ZendeskApi_v2
ZendeskApi_v2/Requests/Targets.cs
ZendeskApi_v2/Requests/Targets.cs
using System.Collections.Generic; #if ASYNC using System.Threading.Tasks; #endif using ZendeskApi_v2.Models.Targets; namespace ZendeskApi_v2.Requests { public interface ITargets : ICore { #if SYNC GroupTargetResponse GetAllTargets(); IndividualTargetResponse GetTarget(long id); IndividualTargetResponse CreateTarget(BaseTarget target); IndividualTargetResponse UpdateTarget(BaseTarget target); bool DeleteTarget(long id); #endif #if ASYNC Task<GroupTargetResponse> GetAllTargetsAsync(); Task<IndividualTargetResponse> GetTargetAsync(long id); Task<IndividualTargetResponse> CreateTargetAsync(BaseTarget target); Task<IndividualTargetResponse> UpdateTargetAsync(BaseTarget target); Task<bool> DeleteTargetAsync(long id); #endif } public class Targets : Core, ITargets { public Targets(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken) : base(yourZendeskUrl, user, password, apiToken, p_OAuthToken) { } #if SYNC public GroupTargetResponse GetAllTargets() { return GenericGet<GroupTargetResponse>("targets.json"); } public IndividualTargetResponse GetTarget(long id) { return GenericGet<IndividualTargetResponse>(string.Format("targets/{0}.json", id)); } public IndividualTargetResponse CreateTarget(BaseTarget target) { var body = new { target }; return GenericPost<IndividualTargetResponse>("targets.json", body); } public IndividualTargetResponse UpdateTarget(BaseTarget target) { var body = new { target }; return GenericPut<IndividualTargetResponse>(string.Format("targets/{0}.json", target.Id), body); } public bool DeleteTarget(long id) { return GenericDelete(string.Format("targets/{0}.json", id)); } #endif #if ASYNC public async Task<GroupTargetResponse> GetAllTargetsAsync() { return await GenericGetAsync<GroupTargetResponse>("targets.json"); } public async Task<IndividualTargetResponse> GetTargetAsync(long id) { return await GenericGetAsync<IndividualTargetResponse>(string.Format("targets/{0}.json", id)); } public async Task<IndividualTargetResponse> CreateTargetAsync(BaseTarget target) { var body = new { target }; return await GenericPostAsync<IndividualTargetResponse>("targets.json", body); } public async Task<IndividualTargetResponse> UpdateTargetAsync(BaseTarget target) { var body = new { target }; return await GenericPutAsync<IndividualTargetResponse>(string.Format("targets/{0}.json", target.Id), body); } public async Task<bool> DeleteTargetAsync(long id) { return await GenericDeleteAsync(string.Format("targets/{0}.json", id)); } #endif } }
using System.Collections.Generic; #if ASYNC using System.Threading.Tasks; #endif using ZendeskApi_v2.Models.Targets; namespace ZendeskApi_v2.Requests { public interface ITargets : ICore { #if SYNC GroupTargetResponse GetAllTargets(); IndividualTargetResponse GetTarget(long id); IndividualTargetResponse CreateTarget(BaseTarget target); IndividualTargetResponse UpdateTarget(BaseTarget target); bool DeleteTarget(long id); #endif #if ASYNC #endif } public class Targets : Core, ITargets { public Targets(string yourZendeskUrl, string user, string password, string apiToken, string p_OAuthToken) : base(yourZendeskUrl, user, password, apiToken, p_OAuthToken) { } #if SYNC public GroupTargetResponse GetAllTargets() { return GenericGet<GroupTargetResponse>("targets.json"); } public IndividualTargetResponse GetTarget(long id) { return GenericGet<IndividualTargetResponse>(string.Format("targets/{0}.json", id)); } public IndividualTargetResponse CreateTarget(BaseTarget target) { var body = new { target }; return GenericPost<IndividualTargetResponse>("targets.json", body); } public IndividualTargetResponse UpdateTarget(BaseTarget target) { var body = new { target }; return GenericPut<IndividualTargetResponse>(string.Format("targets/{0}.json", target.Id), body); } public bool DeleteTarget(long id) { return GenericDelete(string.Format("targets/{0}.json", id)); } #endif #if ASYNC #endif } }
apache-2.0
C#
fca92793228b4d9628510fbb5596ad4d7352f640
update languages icon to globe instead of flag
tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,hfloyd/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,WebCentrum/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,WebCentrum/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,tompipe/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS
src/Umbraco.Web/Trees/LanguageTreeController.cs
src/Umbraco.Web/Trees/LanguageTreeController.cs
using System.Net.Http.Formatting; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Trees { [UmbracoTreeAuthorize(Constants.Trees.Languages)] [Tree(Constants.Applications.Settings, Constants.Trees.Languages, null, sortOrder: 4)] [PluginController("UmbracoTrees")] [CoreTree] public class LanguageTreeController : TreeController { protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) { //We don't have any child nodes & only use the root node to load a custom UI return new TreeNodeCollection(); } protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) { //We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI return null; } /// <summary> /// Helper method to create a root model for a tree /// </summary> /// <returns></returns> protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = string.Format("{0}/{1}/{2}", Constants.Applications.Settings, Constants.Trees.Languages, "overview"); root.Icon = "icon-globe"; root.HasChildren = false; root.MenuUrl = null; return root; } } }
using System.Net.Http.Formatting; using Umbraco.Web.Models.Trees; using Umbraco.Web.Mvc; using Umbraco.Web.WebApi.Filters; using Constants = Umbraco.Core.Constants; namespace Umbraco.Web.Trees { [UmbracoTreeAuthorize(Constants.Trees.Languages)] [Tree(Constants.Applications.Settings, Constants.Trees.Languages, null, sortOrder: 4)] [PluginController("UmbracoTrees")] [CoreTree] public class LanguageTreeController : TreeController { protected override TreeNodeCollection GetTreeNodes(string id, FormDataCollection queryStrings) { //We don't have any child nodes & only use the root node to load a custom UI return new TreeNodeCollection(); } protected override MenuItemCollection GetMenuForNode(string id, FormDataCollection queryStrings) { //We don't have any menu item options (such as create/delete/reload) & only use the root node to load a custom UI return null; } /// <summary> /// Helper method to create a root model for a tree /// </summary> /// <returns></returns> protected override TreeNode CreateRootNode(FormDataCollection queryStrings) { var root = base.CreateRootNode(queryStrings); //this will load in a custom UI instead of the dashboard for the root node root.RoutePath = string.Format("{0}/{1}/{2}", Constants.Applications.Settings, Constants.Trees.Languages, "overview"); root.Icon = "icon-flag-alt"; root.HasChildren = false; root.MenuUrl = null; return root; } } }
mit
C#
2f1fa62b5f2e6e80f7bcb1c29b4ddde49b05f7be
Add command help attribute to AddConfigCommand
appharbor/appharbor-cli
src/AppHarbor/Commands/AddConfigCommand.cs
src/AppHarbor/Commands/AddConfigCommand.cs
namespace AppHarbor.Commands { [CommandHelp("Add configuration variable to application", options: "[KEY=VALUE]")] public class AddConfigCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddConfigCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("No configuration variables are specified"); } var applicationId = _applicationConfiguration.GetApplicationId(); foreach (var argument in arguments) { var splitted = argument.Split('='); _appharborClient.CreateConfigurationVariable(applicationId, splitted[0], splitted[1]); } } } }
namespace AppHarbor.Commands { public class AddConfigCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddConfigCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { if (arguments.Length == 0) { throw new CommandException("No configuration variables are specified"); } var applicationId = _applicationConfiguration.GetApplicationId(); foreach (var argument in arguments) { var splitted = argument.Split('='); _appharborClient.CreateConfigurationVariable(applicationId, splitted[0], splitted[1]); } } } }
mit
C#
27f259f3c574b777e4dea227c3506da4f2b69553
Fix AS path decoding
mstrother/BmpListener
src/BmpListener/Bgp/PathAttributeASPath.cs
src/BmpListener/Bgp/PathAttributeASPath.cs
using System; using System.Collections.Generic; using System.Linq; namespace BmpListener.Bgp { public class PathAttributeASPath : PathAttribute { public IList<ASPathSegment> ASPaths { get; } = new List<ASPathSegment>(); public override void Decode(ArraySegment<byte> data) { for (var i = 0; i < Length;) { //ValidateASPath(data); var segmentType = (ASPathSegment.Type)data.First(); var asCount = data.ElementAt(1); var asList = new List<int>(); //TO DO 2 byte asn data for (var j = 0; j < asCount;) { var asn = BigEndian.ToInt32(data, j * 4 + 2); asList.Add(asn); j++; } var asPathSegment = new ASPathSegment(segmentType, asList); ASPaths.Add(asPathSegment); var offset = 4 * asCount + 2; data = new ArraySegment<byte>(data.Array, data.Offset + offset, data.Count - offset); i += offset; } } //public bool ValidateASPath(byte[] data, int offset) //{ // if (data.Type % 2 != 0 || data.Type < 2) // { // return false; // } // if (data[data.Type] == 0 || data.Array[data.Type] > 4) // { // return false; // } // var asnCount = data[data.Offset + 1]; // if (asnCount == 0) // { // return false; // } // if (2 + asnCount * 4 > data.Count) // { // return false; // } // return true; //} } }
using System; using System.Collections.Generic; using System.Linq; namespace BmpListener.Bgp { public class PathAttributeASPath : PathAttribute { public IList<ASPathSegment> ASPaths { get; } = new List<ASPathSegment>(); public override void Decode(ArraySegment<byte> data) { for (int i = 0; i < Length;) { //ValidateASPath(data); var segmentType = (ASPathSegment.Type)data.First(); var asnCount = data.ElementAt(1); var asnList = new List<int>(); //TO DO 2 byte asn data //for (int maxOffset = 4 * asnCount + offset; offset < maxOffset;) //{ // Array.Reverse(data, offset, 4); // var asn = BitConverter.ToInt32(data, offset); // asnList.Add(asn); // offset += 4; //} var asPathSegment = new ASPathSegment(segmentType, asnList); ASPaths.Add(asPathSegment); i += 4 * asnCount + 2; } } //public bool ValidateASPath(byte[] data, int offset) //{ // if (data.Type % 2 != 0 || data.Type < 2) // { // return false; // } // if (data[data.Type] == 0 || data.Array[data.Type] > 4) // { // return false; // } // var asnCount = data[data.Offset + 1]; // if (asnCount == 0) // { // return false; // } // if (2 + asnCount * 4 > data.Count) // { // return false; // } // return true; //} } }
mit
C#
bc14e845a7ac477b6303f4455ad5aee04410c139
Add simple test for Gst.Base.ByteReader to the buffer tests
freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,Forage/gstreamer-sharp,Forage/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,Forage/gstreamer-sharp,GStreamer/gstreamer-sharp,Forage/gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp
tests/BufferTest.cs
tests/BufferTest.cs
// // Authors // Khaled Mohammed ([email protected]) // // (C) 2006 // using System; using NUnit.Framework; using Gst; [TestFixture] public class BufferTest { [TestFixtureSetUp] public void Init() { Application.Init(); } [Test] public void TestCaps() { Gst.Buffer buffer = new Gst.Buffer (4); Caps caps = Caps.FromString ("audio/x-raw-int"); Assert.IsNull (buffer.Caps, "buffer.Caps should be null"); buffer.Caps = caps; Assert.IsNotNull (buffer.Caps, "buffer.Caps is null"); Caps caps2 = Caps.FromString ("audio/x-raw-float"); buffer.Caps = caps2; Assert.AreNotEqual (buffer.Caps, caps); Assert.AreEqual (buffer.Caps, caps2); buffer.Caps = null; Assert.IsNull (buffer.Caps, "buffer.Caps should be null"); } [Test] public void TestSubbuffer() { Gst.Buffer buffer = new Gst.Buffer (4); Gst.Buffer sub = buffer.CreateSub (1, 2); Assert.IsNotNull (sub); Assert.AreEqual (sub.Size, 2, "subbuffer has wrong size"); } [Test] public void TestIsSpanFast() { Gst.Buffer buffer = new Gst.Buffer (4); Gst.Buffer sub1 = buffer.CreateSub (0, 2); Assert.IsNotNull (sub1, "CreateSub of buffer returned null"); Gst.Buffer sub2 = buffer.CreateSub (2, 2); Assert.IsNotNull (sub2, "CreateSub of buffer returned null"); Assert.IsFalse (buffer.IsSpanFast (sub2), "a parent buffer can not be SpanFasted"); Assert.IsFalse (sub1.IsSpanFast (buffer), "a parent buffer can not be SpanFasted"); Assert.IsTrue (sub1.IsSpanFast (sub2), "two subbuffers next to each other should be SpanFast"); } private void ArrayIsEqual (byte[] a, byte[] b) { Assert.IsTrue (a.Length == b.Length); for (int i = 0; i < a.Length; i++) Assert.IsTrue (a[i] == b[i]); } [Test] public void TestBufferData() { byte[] data = new byte[] {0, 1, 2, 3, 4, 5}; Gst.Buffer buffer = new Gst.Buffer (data); ArrayIsEqual (data, buffer.ToByteArray ()); Gst.Base.ByteReader reader = new Gst.Base.ByteReader (buffer); byte b; Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 0 && 0 == data[reader.Pos-1]); Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 1 && 1 == data[reader.Pos-1]); Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 2 && 2 == data[reader.Pos-1]); Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 3 && 3 == data[reader.Pos-1]); Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 4 && 4 == data[reader.Pos-1]); Assert.IsTrue (reader.GetUint8 (out b)); Assert.IsTrue (b == 5 && 5 == data[reader.Pos-1]); Assert.IsFalse (reader.GetUint8 (out b)); Assert.IsTrue (reader.Pos == buffer.Size); } }
// // Authors // Khaled Mohammed ([email protected]) // // (C) 2006 // using System; using NUnit.Framework; using Gst; [TestFixture] public class BufferTest { [TestFixtureSetUp] public void Init() { Application.Init(); } [Test] public void TestCaps() { Gst.Buffer buffer = new Gst.Buffer (4); Caps caps = Caps.FromString ("audio/x-raw-int"); Assert.IsNull (buffer.Caps, "buffer.Caps should be null"); buffer.Caps = caps; Assert.IsNotNull (buffer.Caps, "buffer.Caps is null"); Caps caps2 = Caps.FromString ("audio/x-raw-float"); buffer.Caps = caps2; Assert.AreNotEqual (buffer.Caps, caps); Assert.AreEqual (buffer.Caps, caps2); buffer.Caps = null; Assert.IsNull (buffer.Caps, "buffer.Caps should be null"); } [Test] public void TestSubbuffer() { Gst.Buffer buffer = new Gst.Buffer (4); Gst.Buffer sub = buffer.CreateSub (1, 2); Assert.IsNotNull (sub); Assert.AreEqual (sub.Size, 2, "subbuffer has wrong size"); } [Test] public void TestIsSpanFast() { Gst.Buffer buffer = new Gst.Buffer (4); Gst.Buffer sub1 = buffer.CreateSub (0, 2); Assert.IsNotNull (sub1, "CreateSub of buffer returned null"); Gst.Buffer sub2 = buffer.CreateSub (2, 2); Assert.IsNotNull (sub2, "CreateSub of buffer returned null"); Assert.IsFalse (buffer.IsSpanFast (sub2), "a parent buffer can not be SpanFasted"); Assert.IsFalse (sub1.IsSpanFast (buffer), "a parent buffer can not be SpanFasted"); Assert.IsTrue (sub1.IsSpanFast (sub2), "two subbuffers next to each other should be SpanFast"); } private void ArrayIsEqual (byte[] a, byte[] b) { Assert.IsTrue (a.Length == b.Length); for (int i = 0; i < a.Length; i++) Assert.IsTrue (a[i] == b[i]); } [Test] public void TestBufferData() { byte[] data = new byte[] {0, 1, 2, 3, 4, 5}; Gst.Buffer buffer = new Gst.Buffer (data); ArrayIsEqual (data, buffer.ToByteArray ()); } }
lgpl-2.1
C#
c18dcd0ab616e7bef853a76dc949eb10f78212e3
Adjust Index action
moodlenetcore/simple-elearning-rx-app,moodlenetcore/simple-elearning-rx-app,moodlenetcore/simple-elearning-rx-app
backend/SimpleELearning.Api/Controllers/HomeController.cs
backend/SimpleELearning.Api/Controllers/HomeController.cs
using Microsoft.AspNetCore.Mvc; namespace SimpleELearning.Api.Controllers { public class HomeController : BaseController { // GET swagger [HttpGet] public IActionResult Index() { return Redirect("./swagger"); } } }
using Microsoft.AspNetCore.Mvc; namespace SimpleELearning.Api.Controllers { public class HomeController : BaseController { // GET api/courses [HttpGet] public IActionResult Index() { return Redirect("./swagger"); } } }
mit
C#
e0cf0e92ae4134e83f51c05f7cb18ed19fc0780a
Fix issue where test writer was writing when nothing was listening.
FoundatioFx/Foundatio,Bartmax/Foundatio,vebin/Foundatio,wgraham17/Foundatio,exceptionless/Foundatio
src/Core/Tests/Utility/TestOutputWriter.cs
src/Core/Tests/Utility/TestOutputWriter.cs
using System; using System.Diagnostics; using System.IO; using System.Text; using Xunit.Abstractions; namespace Foundatio.Tests.Utility { public class TestOutputWriter : TextWriter { private readonly ITestOutputHelper _output; public TestOutputWriter(ITestOutputHelper output) { _output = output; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override void WriteLine(string value) { try { _output.WriteLine(value); } catch (Exception ex) { Trace.WriteLine(ex); } } public override void WriteLine() { WriteLine(String.Empty); } } }
using System; using System.IO; using System.Text; using Xunit.Abstractions; namespace Foundatio.Tests.Utility { public class TestOutputWriter : TextWriter { private readonly ITestOutputHelper _output; public TestOutputWriter(ITestOutputHelper output) { _output = output; } public override Encoding Encoding { get { return Encoding.UTF8; } } public override void WriteLine(string value) { _output.WriteLine(value); } public override void WriteLine() { _output.WriteLine(String.Empty); } } }
apache-2.0
C#
d5955b1e94fd89faf2c2a033e6eecc60a6b4888e
Use CloudConfigurationManager to access appSettings for Azure roles
LionLai/Elmah.AzureTableStorage,FreedomMercenary/Elmah.AzureTableStorage,MisinformedDNA/Elmah.AzureTableStorage
src/Elmah.AzureTableStorage/ElmahHelper.cs
src/Elmah.AzureTableStorage/ElmahHelper.cs
using Microsoft.WindowsAzure; using System; using System.Collections; using System.Configuration; namespace Elmah.AzureTableStorage { /// <summary> /// Includes methods that are internal to Elmah, but are useful. TODO: Investigate making these public in Elmah. /// </summary> public static class ElmahHelper { public static T Find<T>(this IDictionary dict, object key, T @default) { if (dict == null) throw new ArgumentNullException("dict"); return (T)(dict[key] ?? @default); } public static string GetConnectionString(IDictionary config) { // // First look for a connection string name that can be // subsequently indexed into the <connectionStrings> section of // the configuration to get the actual connection string. // string connectionStringName = config.Find("connectionStringName", string.Empty); if (connectionStringName.Length > 0) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (settings == null) return string.Empty; return settings.ConnectionString ?? string.Empty; } // // Connection string name not found so see if a connection // string was given directly. // var connectionString = config.Find("connectionString", string.Empty); if (connectionString.Length > 0) return connectionString; // // As a last resort, check for another setting called // connectionStringAppKey. The specifies the key in // <appSettings> that contains the actual connection string to // be used. // var connectionStringAppKey = config.Find("connectionStringAppKey", string.Empty); return connectionStringAppKey.Length > 0 ? CloudConfigurationManager.GetSetting(connectionStringAppKey) : string.Empty; } } }
using System; using System.Collections; using System.Configuration; namespace Elmah.AzureTableStorage { /// <summary> /// Includes methods that are internal to Elmah, but are useful. TODO: Investigate making these public in Elmah. /// </summary> public static class ElmahHelper { public static T Find<T>(this IDictionary dict, object key, T @default) { if (dict == null) throw new ArgumentNullException("dict"); return (T)(dict[key] ?? @default); } public static string GetConnectionString(IDictionary config) { // // First look for a connection string name that can be // subsequently indexed into the <connectionStrings> section of // the configuration to get the actual connection string. // string connectionStringName = config.Find("connectionStringName", string.Empty); if (connectionStringName.Length > 0) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[connectionStringName]; if (settings == null) return string.Empty; return settings.ConnectionString ?? string.Empty; } // // Connection string name not found so see if a connection // string was given directly. // var connectionString = config.Find("connectionString", string.Empty); if (connectionString.Length > 0) return connectionString; // // As a last resort, check for another setting called // connectionStringAppKey. The specifies the key in // <appSettings> that contains the actual connection string to // be used. // var connectionStringAppKey = config.Find("connectionStringAppKey", string.Empty); return connectionStringAppKey.Length > 0 ? ConfigurationManager.AppSettings[connectionStringAppKey] : string.Empty; } } }
apache-2.0
C#