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
28dc69ea2301b5eea996ce648ddea47941febe37
remove unused directives
jobeland/GeneticAlgorithm
NeuralNetwork.GeneticAlgorithm/TrainingSession.cs
NeuralNetwork.GeneticAlgorithm/TrainingSession.cs
using ArtificialNeuralNetwork; using Logging; using NeuralNetwork.GeneticAlgorithm.Evaluatable; namespace NeuralNetwork.GeneticAlgorithm { public class TrainingSession : ITrainingSession { private int _sessionNumber; public INeuralNetwork NeuralNet { get; set; } private IEvaluatable _evaluatable; private bool _hasStoredSessionEval; private double _sessionEval; public TrainingSession(INeuralNetwork nn, IEvaluatable evaluatable, int sessionNumber) { NeuralNet = nn; _evaluatable = evaluatable; _sessionNumber = sessionNumber; _hasStoredSessionEval = false; _sessionEval = 0; } public void Run() { LoggerFactory.GetLogger().Log(LogLevel.Debug, string.Format("Starting training session {0}", _sessionNumber)); _evaluatable.RunEvaluation(); LoggerFactory.GetLogger().Log(LogLevel.Debug, string.Format("Stopping training session {0}", _sessionNumber)); } public double GetSessionEvaluation() { if (_hasStoredSessionEval) { return _sessionEval; } else { _sessionEval = _evaluatable.GetEvaluation(); _hasStoredSessionEval = true; } return _sessionEval; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArtificialNeuralNetwork; using Logging; using NeuralNetwork.GeneticAlgorithm.Evaluatable; namespace NeuralNetwork.GeneticAlgorithm { public class TrainingSession : ITrainingSession { private int _sessionNumber; public INeuralNetwork NeuralNet { get; set; } private IEvaluatable _evaluatable; private bool _hasStoredSessionEval; private double _sessionEval; public TrainingSession(INeuralNetwork nn, IEvaluatable evaluatable, int sessionNumber) { NeuralNet = nn; _evaluatable = evaluatable; _sessionNumber = sessionNumber; _hasStoredSessionEval = false; _sessionEval = 0; } public void Run() { LoggerFactory.GetLogger().Log(LogLevel.Debug, string.Format("Starting training session {0}", _sessionNumber)); _evaluatable.RunEvaluation(); LoggerFactory.GetLogger().Log(LogLevel.Debug, string.Format("Stopping training session {0}", _sessionNumber)); } public double GetSessionEvaluation() { if (_hasStoredSessionEval) { return _sessionEval; } else { _sessionEval = _evaluatable.GetEvaluation(); _hasStoredSessionEval = true; } return _sessionEval; } } }
mit
C#
2e6350136dd9cd36cc0804845b2eedd75a053a7f
Update InteropDescriptor.cs (#2126)
AntShares/AntShares
src/neo/SmartContract/InteropDescriptor.cs
src/neo/SmartContract/InteropDescriptor.cs
using Neo.Cryptography; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Neo.SmartContract { public class InteropDescriptor { public string Name { get; } public uint Hash { get; } public MethodInfo Handler { get; } public IReadOnlyList<InteropParameterDescriptor> Parameters { get; } public long FixedPrice { get; } public CallFlags RequiredCallFlags { get; } public bool AllowCallback { get; } internal InteropDescriptor(string name, MethodInfo handler, long fixedPrice, CallFlags requiredCallFlags, bool allowCallback) { this.Name = name; this.Hash = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(name).Sha256(), 0); this.Handler = handler; this.Parameters = handler.GetParameters().Select(p => new InteropParameterDescriptor(p)).ToList().AsReadOnly(); this.FixedPrice = fixedPrice; this.RequiredCallFlags = requiredCallFlags; this.AllowCallback = allowCallback; } public static implicit operator uint(InteropDescriptor descriptor) { return descriptor.Hash; } } }
using Neo.Cryptography; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace Neo.SmartContract { public class InteropDescriptor { public string Name { get; } public uint Hash { get; } internal MethodInfo Handler { get; } public IReadOnlyList<InteropParameterDescriptor> Parameters { get; } public long FixedPrice { get; } public CallFlags RequiredCallFlags { get; } public bool AllowCallback { get; } internal InteropDescriptor(string name, MethodInfo handler, long fixedPrice, CallFlags requiredCallFlags, bool allowCallback) { this.Name = name; this.Hash = BitConverter.ToUInt32(Encoding.ASCII.GetBytes(name).Sha256(), 0); this.Handler = handler; this.Parameters = handler.GetParameters().Select(p => new InteropParameterDescriptor(p)).ToList().AsReadOnly(); this.FixedPrice = fixedPrice; this.RequiredCallFlags = requiredCallFlags; this.AllowCallback = allowCallback; } public static implicit operator uint(InteropDescriptor descriptor) { return descriptor.Hash; } } }
mit
C#
0980f97ea2c8da99030f6f9d7b16425c35865ba5
Replace precision check with absolute equality assert
peppy/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu
osu.Game.Tests/NonVisual/Ranking/UnstableRateTest.cs
osu.Game.Tests/NonVisual/Ranking/UnstableRateTest.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.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Ranking.Statistics; namespace osu.Game.Tests.NonVisual.Ranking { [TestFixture] public class UnstableRateTest { [Test] public void TestDistributedHits() { var events = Enumerable.Range(-5, 11) .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null)); var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10))); } [Test] public void TestMissesAndEmptyWindows() { var events = new[] { new HitEvent(-100, HitResult.Miss, new HitObject(), null, null), new HitEvent(0, HitResult.Great, new HitObject(), null, null), new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null), }; var unstableRate = new UnstableRate(events); Assert.AreEqual(0, unstableRate.Value); } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Ranking.Statistics; namespace osu.Game.Tests.NonVisual.Ranking { [TestFixture] public class UnstableRateTest { [Test] public void TestDistributedHits() { var events = Enumerable.Range(-5, 11) .Select(t => new HitEvent(t - 5, HitResult.Great, new HitObject(), null, null)); var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(unstableRate.Value, 10 * Math.Sqrt(10))); } [Test] public void TestMissesAndEmptyWindows() { var events = new[] { new HitEvent(-100, HitResult.Miss, new HitObject(), null, null), new HitEvent(0, HitResult.Great, new HitObject(), null, null), new HitEvent(200, HitResult.Meh, new HitObject { HitWindows = HitWindows.Empty }, null, null), }; var unstableRate = new UnstableRate(events); Assert.IsTrue(Precision.AlmostEquals(0, unstableRate.Value)); } } }
mit
C#
08fb68ddfeddb891b2ddc9972544a0bf6f2bff68
Fix incorrect return type for spotlight request
ppy/osu,EVAST9919/osu,peppy/osu-new,UselessToucan/osu,2yangk23/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,EVAST9919/osu,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,smoogipooo/osu
osu.Game/Online/API/Requests/GetSpotlightsRequest.cs
osu.Game/Online/API/Requests/GetSpotlightsRequest.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.Collections.Generic; using Newtonsoft.Json; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetSpotlightsRequest : APIRequest<SpotlightsArray> { protected override string Target => "spotlights"; } public class SpotlightsArray { [JsonProperty("spotlights")] public List<APISpotlight> Spotlights; } }
// 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.Collections.Generic; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class GetSpotlightsRequest : APIRequest<List<APISpotlight>> { protected override string Target => "spotlights"; } }
mit
C#
89aacef59f5a211633aeea492a8715bb4e560ead
Revert disposal of pattern to avoid crashing on ubuntu
bbqchickenrobot/Eto-1,bbqchickenrobot/Eto-1,l8s/Eto,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,PowerOfCode/Eto
Source/Eto.Platform.Gtk/Drawing/TextureBrushHandler.cs
Source/Eto.Platform.Gtk/Drawing/TextureBrushHandler.cs
using System; using Eto.Drawing; namespace Eto.Platform.GtkSharp.Drawing { /// <summary> /// Handler for the <see cref="ITextureBrush"/> /// </summary> /// <copyright>(c) 2012 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class TextureBrushHandler : BrushHandler, ITextureBrush { class TextureBrushObject { public Cairo.Matrix Transform { get; set; } public Gdk.Pixbuf Pixbuf { get; set; } public float Opacity { get; set; } public TextureBrushObject () { Opacity = 1.0f; } public void Apply (GraphicsHandler graphics) { if (!object.ReferenceEquals (Transform, null)) graphics.Control.Transform (Transform); Gdk.CairoHelper.SetSourcePixbuf (graphics.Control, Pixbuf, 0, 0); var surfacePattern = graphics.Control.Source as Cairo.SurfacePattern; if (surfacePattern != null) surfacePattern.Extend = Cairo.Extend.Repeat; if (Opacity < 1.0f) { graphics.Control.Clip(); graphics.Control.PaintWithAlpha(Opacity); } else graphics.Control.Fill(); } } public IMatrix GetTransform (TextureBrush widget) { return ((TextureBrushObject)widget.ControlObject).Transform.ToEto (); } public void SetTransform (TextureBrush widget, IMatrix transform) { ((TextureBrushObject)widget.ControlObject).Transform = transform.ToCairo (); } public object Create (Image image, float opacity) { return new TextureBrushObject { Pixbuf = image.ToGdk (), Opacity = opacity }; } public override void Apply (object control, GraphicsHandler graphics) { ((TextureBrushObject)control).Apply (graphics); } public float GetOpacity (TextureBrush widget) { return ((TextureBrushObject)widget.ControlObject).Opacity; } public void SetOpacity (TextureBrush widget, float opacity) { ((TextureBrushObject)widget.ControlObject).Opacity = opacity; } } }
using System; using Eto.Drawing; namespace Eto.Platform.GtkSharp.Drawing { /// <summary> /// Handler for the <see cref="ITextureBrush"/> /// </summary> /// <copyright>(c) 2012 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class TextureBrushHandler : BrushHandler, ITextureBrush { class TextureBrushObject { public Cairo.Matrix Transform { get; set; } public Gdk.Pixbuf Pixbuf { get; set; } public float Opacity { get; set; } public TextureBrushObject () { Opacity = 1.0f; } public void Apply (GraphicsHandler graphics) { if (!object.ReferenceEquals (Transform, null)) graphics.Control.Transform (Transform); Gdk.CairoHelper.SetSourcePixbuf (graphics.Control, Pixbuf, 0, 0); using (var pattern = graphics.Control.Source as Cairo.Pattern) { var surfacePattern = pattern as Cairo.SurfacePattern; if (surfacePattern != null) surfacePattern.Extend = Cairo.Extend.Repeat; if (Opacity < 1.0f) { graphics.Control.Clip(); graphics.Control.PaintWithAlpha(Opacity); } else graphics.Control.Fill(); } } } public IMatrix GetTransform (TextureBrush widget) { return ((TextureBrushObject)widget.ControlObject).Transform.ToEto (); } public void SetTransform (TextureBrush widget, IMatrix transform) { ((TextureBrushObject)widget.ControlObject).Transform = transform.ToCairo (); } public object Create (Image image, float opacity) { return new TextureBrushObject { Pixbuf = image.ToGdk (), Opacity = opacity }; } public override void Apply (object control, GraphicsHandler graphics) { ((TextureBrushObject)control).Apply (graphics); } public float GetOpacity (TextureBrush widget) { return ((TextureBrushObject)widget.ControlObject).Opacity; } public void SetOpacity (TextureBrush widget, float opacity) { ((TextureBrushObject)widget.ControlObject).Opacity = opacity; } } }
bsd-3-clause
C#
2d448a2f0bff7caf890b3ec608c9884e2344152e
Debug statements
RootAccessOrg/kynnaugh
kynnaugh/SpeechTranscriber.cs
kynnaugh/SpeechTranscriber.cs
using Google.Cloud.Speech.V1Beta1; using Google.Protobuf; using Grpc.Auth; using Grpc.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static Google.Cloud.Speech.V1Beta1.Speech; namespace kynnaugh { class SpeechTranscriber { public SpeechTranscriber() { } public async Task<string> TranscribeSpeechAsync(byte[] speechData) { Console.WriteLine("Transcribing " + speechData.Length + " bytes of speechData"); Channel channel = new Channel("speech.googleapis.com:443", await GoogleGrpcCredentials.GetApplicationDefaultAsync()); SpeechClient client = new SpeechClient(channel); RecognitionConfig config = new RecognitionConfig { ProfanityFilter = false, Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRate = 16000, LanguageCode = "en-US", MaxAlternatives = 1 }; RecognitionAudio audio = new RecognitionAudio { Content = ByteString.CopyFrom(speechData) }; SyncRecognizeRequest req = new SyncRecognizeRequest { Audio = audio, Config = config }; SyncRecognizeResponse resp = await client.SyncRecognizeAsync(req); Console.WriteLine("Got " + resp.Results.Count + " transcription results"); if (resp.Results.Count > 0) { SpeechRecognitionResult res = resp.Results.First(); Console.WriteLine("Got " + res.Alternatives.Count + " alternatives in the first result"); if (res.Alternatives.Count > 0) { SpeechRecognitionAlternative alt = res.Alternatives[0]; Console.WriteLine("Got transcription \"" + alt + "\""); return alt.Transcript; } } Console.WriteLine("No valid transcription results"); return null; } } }
using Google.Cloud.Speech.V1Beta1; using Google.Protobuf; using Grpc.Auth; using Grpc.Core; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static Google.Cloud.Speech.V1Beta1.Speech; namespace kynnaugh { class SpeechTranscriber { public SpeechTranscriber() { } public async Task<string> TranscribeSpeechAsync(byte[] speechData) { Channel channel = new Channel("speech.googleapis.com:443", await GoogleGrpcCredentials.GetApplicationDefaultAsync()); SpeechClient client = new SpeechClient(channel); RecognitionConfig config = new RecognitionConfig { ProfanityFilter = false, Encoding = RecognitionConfig.Types.AudioEncoding.Flac, SampleRate = 16000, LanguageCode = "en-US", MaxAlternatives = 1 }; RecognitionAudio audio = new RecognitionAudio { Content = ByteString.CopyFrom(speechData) }; SyncRecognizeRequest req = new SyncRecognizeRequest { Audio = audio, Config = config }; SyncRecognizeResponse resp = await client.SyncRecognizeAsync(req); if (resp.Results.Count > 0) { SpeechRecognitionResult res = resp.Results.First(); if (res.Alternatives.Count > 0) { SpeechRecognitionAlternative alt = res.Alternatives[0]; return alt.Transcript; } } return null; } } }
apache-2.0
C#
5743c9c9fe25d7945210b79f653e59a4c6584948
Throw exception if BMP version != 3
mstrother/BmpListener
BmpListener/Bmp/BmpHeader.cs
BmpListener/Bmp/BmpHeader.cs
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { private readonly int bmpVersion = 3; public BmpHeader(byte[] data) { Version = data.First(); if (Version != bmpVersion) { throw new NotSupportedException("version error"); } Length = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int Length { get; } public BmpMessage.Type MessageType { get; } } }
using System; using System.Linq; using BmpListener; using BmpListener.Extensions; namespace BmpListener.Bmp { public class BmpHeader { public BmpHeader(byte[] data) { Version = data.First(); //if (Version != 3) //{ // throw new Exception("invalid BMP version"); //} Length = data.ToInt32(1); MessageType = (BmpMessage.Type)data.ElementAt(5); } public byte Version { get; } public int Length { get; } public BmpMessage.Type MessageType { get; } } }
mit
C#
fccceca14264102530294eccd7f073a0c4203d0a
Clear constructor body
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/ViewModels/PatientViewModel.cs
StressMeasurementSystem/ViewModels/PatientViewModel.cs
using System.Collections.Generic; using StressMeasurementSystem.Models; namespace StressMeasurementSystem.ViewModels { public class PatientViewModel { private Patient _patient; public PatientViewModel() { } } }
using System.Collections.Generic; using StressMeasurementSystem.Models; namespace StressMeasurementSystem.ViewModels { public class PatientViewModel { private Patient _patient; public PatientViewModel() { _patient = new Patient( new Patient.Name(), 0, new Patient.Organization(), new List<Patient.PhoneNumber>(), new List<Patient.Email>() ); } } }
apache-2.0
C#
fd04dc8d4b99b4a92ac3fabea75f1003b5242e27
Fix issues on first run, which takes a little longer to start up
SEEK-Jobs/pact-net,SEEK-Jobs/pact-net,SEEK-Jobs/pact-net
PactNet/Mocks/MockHttpService/Host/RubyHttpHost.cs
PactNet/Mocks/MockHttpService/Host/RubyHttpHost.cs
using System; using System.Net.Http; using System.Threading; using PactNet.Core; namespace PactNet.Mocks.MockHttpService.Host { internal class RubyHttpHost : IHttpHost { private readonly IPactCoreHost _coreHost; private readonly HttpClient _httpClient; internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient) { _coreHost = coreHost; _httpClient = httpClient; //TODO: Use the admin http client once extracted } public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) : this(new PactCoreHost<MockProviderHostConfig>( new MockProviderHostConfig(baseUri.Port, baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"), providerName, config)), new HttpClient { BaseAddress = baseUri }) { } private bool IsMockProviderServiceRunning() { try { var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/"); aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true"); var responseMessage = _httpClient.SendAsync(aliveRequest).Result; return responseMessage.IsSuccessStatusCode; } catch { return false; } } public void Start() { _coreHost.Start(); var aliveChecks = 1; while (!IsMockProviderServiceRunning()) { if (aliveChecks >= 20) { throw new PactFailureException("Could not start the mock provider service"); } Thread.Sleep(200); aliveChecks++; } } public void Stop() { _coreHost.Stop(); } } }
using System; using System.Net.Http; using System.Threading; using PactNet.Core; namespace PactNet.Mocks.MockHttpService.Host { internal class RubyHttpHost : IHttpHost { private readonly IPactCoreHost _coreHost; private readonly HttpClient _httpClient; internal RubyHttpHost(IPactCoreHost coreHost, HttpClient httpClient) { _coreHost = coreHost; _httpClient = httpClient; //TODO: Use the admin http client once extracted } public RubyHttpHost(Uri baseUri, string providerName, PactConfig config) : this(new PactCoreHost<MockProviderHostConfig>( new MockProviderHostConfig(baseUri.Port, baseUri.Scheme.ToUpperInvariant().Equals("HTTPS"), providerName, config)), new HttpClient { BaseAddress = baseUri }) { } private bool IsMockProviderServiceRunning() { var aliveRequest = new HttpRequestMessage(HttpMethod.Get, "/"); aliveRequest.Headers.Add(Constants.AdministrativeRequestHeaderKey, "true"); var responseMessage = _httpClient.SendAsync(aliveRequest).Result; return responseMessage.IsSuccessStatusCode; } public void Start() { _coreHost.Start(); var aliveChecks = 1; while (!IsMockProviderServiceRunning()) { if (aliveChecks >= 20) { throw new PactFailureException("Could not start the mock provider service"); } Thread.Sleep(200); aliveChecks++; } } public void Stop() { _coreHost.Stop(); } } }
mit
C#
1cb5853e1f66454df5420497fa2d950a844d4907
Add argument checking on commit
vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit,vbliznikov/colabedit
src/vcs-lib/VersionControl/RepositoryBranch.cs
src/vcs-lib/VersionControl/RepositoryBranch.cs
using System; using System.Collections.Generic; using System.Threading; namespace CollabEdit.VersionControl { public class RepositoryBranch<TValue, TMeta> { private object syncRoot = new Object(); public RepositoryBranch() { } public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string."); if (repository == null) throw new ArgumentNullException(nameof(repository)); Name = name; Repository = repository; Head = head; } public Repository<TValue, TMeta> Repository { get; } public string Name { get; } public Commit<TValue, TMeta> Head { get; protected set; } public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata) { if (value == null) throw new ArgumentNullException(nameof(value)); if (metadata == null) throw new ArgumentException(nameof(metadata)); if (Head != null && Head.Value.Equals(value)) return Head; // Value was not changed, so no need to create a new version. lock (syncRoot) { var commit = new Commit<TValue, TMeta>(value, metadata, Head); Head = commit; return commit; } } public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch) { throw new NotImplementedException(); } public IEnumerable<Commit<TValue, TMeta>> GetHistory() { if (Head == null) yield break; var next = Head; while (next != null) { yield return next; next = next.Parent; } } } }
using System; using System.Collections.Generic; using System.Threading; namespace CollabEdit.VersionControl { public class RepositoryBranch<TValue, TMeta> { private object syncRoot = new Object(); public RepositoryBranch() { } public RepositoryBranch(string name, Repository<TValue, TMeta> repository, Commit<TValue, TMeta> head) { if (string.IsNullOrEmpty(name)) throw new ArgumentException("Name may not be null or empty string."); if (repository == null) throw new ArgumentNullException(nameof(repository)); Name = name; Repository = repository; Head = head; } public Repository<TValue, TMeta> Repository { get; } public string Name { get; } public Commit<TValue, TMeta> Head { get; protected set; } public Commit<TValue, TMeta> Commit(TValue value, TMeta metadata) { if (Head != null && Head.Value.Equals(value)) return Head; // Value was not changed, so no need to create a new version. lock (syncRoot) { var commit = new Commit<TValue, TMeta>(value, metadata, Head); Head = commit; return commit; } } public virtual Commit<TValue, TMeta> MergeWith(RepositoryBranch<TValue, TMeta> sourceBranch) { throw new NotImplementedException(); } public IEnumerable<Commit<TValue, TMeta>> GetHistory() { if (Head == null) yield break; var next = Head; while (next != null) { yield return next; next = next.Parent; } } } }
mit
C#
b8ed3510a0b5cb7ab9eabd47f6b13d39a5d12397
Handle invalid versions
campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer
Core/Packages/PackageFileBase.cs
Core/Packages/PackageFileBase.cs
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; using NuGet.Frameworks; using NuGet.Packaging; namespace NuGetPe { public abstract class PackageFileBase : IPackageFile { protected PackageFileBase(string path) { Path = path; FrameworkNameUtility.ParseFrameworkNameFromFilePath(path, out var effectivePath); EffectivePath = effectivePath; try { TargetFramework = new FrameworkName(NuGetFramework.Parse(effectivePath).DotNetFrameworkName); } catch(ArgumentException) // could be an invalid framework/version { } } public string Path { get; private set; } public virtual string OriginalPath { get { return null; } } public abstract Stream GetStream(); public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get; } public IEnumerable<FrameworkName> SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } yield break; } } public virtual DateTimeOffset LastWriteTime { get; } = DateTimeOffset.MinValue; } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; using NuGet.Frameworks; using NuGet.Packaging; namespace NuGetPe { public abstract class PackageFileBase : IPackageFile { protected PackageFileBase(string path) { Path = path; FrameworkNameUtility.ParseFrameworkNameFromFilePath(path, out var effectivePath); TargetFramework = new FrameworkName(NuGetFramework.Parse(effectivePath).DotNetFrameworkName); EffectivePath = effectivePath; } public string Path { get; private set; } public virtual string OriginalPath { get { return null; } } public abstract Stream GetStream(); public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get; } public IEnumerable<FrameworkName> SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } yield break; } } public virtual DateTimeOffset LastWriteTime { get; } = DateTimeOffset.MinValue; } }
mit
C#
5c5ae99a92dc8cb359ccc7d812872cae736e2137
Increment version to 0.1.3
ruskom/mvc-metadata-conventions,Haacked/mvc-metadata-conventions
ModelMetadataExtensions/Properties/AssemblyInfo.cs
ModelMetadataExtensions/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ModelMetadataExtensions")] [assembly: AssemblyDescription("Extension to Model Metadata that provide convention based resource lookup")] [assembly: AssemblyCompany("Phil Haack")] [assembly: AssemblyProduct("ModelMetadataExtensions")] [assembly: AssemblyCopyright("Copyright © Phil Haack 2013")] [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("7aa5644d-b24f-4937-a24d-dee7b5b99604")] [assembly: AssemblyVersion(AssemblyConstants.AssemblyVersion)] [assembly: AssemblyFileVersion(AssemblyConstants.AssemblyVersion)] [assembly: AssemblyInformationalVersion(AssemblyConstants.PackageVersion)] internal static class AssemblyConstants { internal const string PackageVersion = "0.1.3"; internal const string PrereleaseVersion = ""; // Until we ship 1.0, this isn't necessary. internal const string AssemblyVersion = PackageVersion + ".0"; }
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ModelMetadataExtensions")] [assembly: AssemblyDescription("Extension to Model Metadata that provide convention based resource lookup")] [assembly: AssemblyCompany("Phil Haack")] [assembly: AssemblyProduct("ModelMetadataExtensions")] [assembly: AssemblyCopyright("Copyright © Phil Haack 2013")] [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("7aa5644d-b24f-4937-a24d-dee7b5b99604")] [assembly: AssemblyVersion(AssemblyConstants.AssemblyVersion)] [assembly: AssemblyFileVersion(AssemblyConstants.AssemblyVersion)] [assembly: AssemblyInformationalVersion(AssemblyConstants.PackageVersion)] internal static class AssemblyConstants { internal const string PackageVersion = "0.1.2"; internal const string PrereleaseVersion = ""; // Until we ship 1.0, this isn't necessary. internal const string AssemblyVersion = PackageVersion + ".0"; }
mit
C#
bd5729f5da33e56a78c6e31b5605f1472ba9a713
Remove commented out classes in TestObjects
Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet
Tests/WeaverTests/AssemblyToProcess/TestObjects.cs
Tests/WeaverTests/AssemblyToProcess/TestObjects.cs
using System; using Realms; namespace AssemblyToProcess { public class AllTypesObject : RealmObject { public char CharProperty { get; set; } public byte ByteProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public float SingleProperty { get; set; } public double DoubleProperty { get; set; } public bool BooleanProperty { get; set; } public string StringProperty { get; set; } public DateTimeOffset DateTimeOffsetProperty { get; set; } public char? NullableCharProperty { get; set; } public byte? NullableByteProperty { get; set; } public short? NullableInt16Property { get; set; } public int? NullableInt32Property { get; set; } public long? NullableInt64Property { get; set; } public float? NullableSingleProperty { get; set; } public double? NullableDoubleProperty { get; set; } public bool? NullableBooleanProperty { get; set; } } public class ObjectIdCharObject : RealmObject { [ObjectId] public char CharProperty { get; set; } } public class ObjectIdByteObject : RealmObject { [ObjectId] public byte ByteProperty { get; set; } } public class ObjectIdInt16Object : RealmObject { [ObjectId] public short Int16Property { get; set; } } public class ObjectIdInt32Object : RealmObject { [ObjectId] public int Int32Property { get; set; } } public class ObjectIdInt64Object : RealmObject { [ObjectId] public long Int64Property { get; set; } } public class ObjectIdStringObject : RealmObject { [ObjectId] public string StringProperty { get; set; } } }
using System; using Realms; namespace AssemblyToProcess { public class AllTypesObject : RealmObject { public char CharProperty { get; set; } public byte ByteProperty { get; set; } public short Int16Property { get; set; } public int Int32Property { get; set; } public long Int64Property { get; set; } public float SingleProperty { get; set; } public double DoubleProperty { get; set; } public bool BooleanProperty { get; set; } public string StringProperty { get; set; } public DateTimeOffset DateTimeOffsetProperty { get; set; } public char? NullableCharProperty { get; set; } public byte? NullableByteProperty { get; set; } public short? NullableInt16Property { get; set; } public int? NullableInt32Property { get; set; } public long? NullableInt64Property { get; set; } public float? NullableSingleProperty { get; set; } public double? NullableDoubleProperty { get; set; } public bool? NullableBooleanProperty { get; set; } } public class ObjectIdCharObject : RealmObject { [ObjectId] public char CharProperty { get; set; } } public class ObjectIdByteObject : RealmObject { [ObjectId] public byte ByteProperty { get; set; } } public class ObjectIdInt16Object : RealmObject { [ObjectId] public short Int16Property { get; set; } } public class ObjectIdInt32Object : RealmObject { [ObjectId] public int Int32Property { get; set; } } public class ObjectIdInt64Object : RealmObject { [ObjectId] public long Int64Property { get; set; } } public class ObjectIdStringObject : RealmObject { [ObjectId] public string StringProperty { get; set; } } //public class IndexedNullableInt32Object : RealmObject //{ // [Indexed] public int? Int32Property { get; set; } //} //public class IndexedNullableInt64Object : RealmObject //{ // [Indexed] public long? Int64Property { get; set; } //} }
apache-2.0
C#
34146843081b2606a4de37c5e9d620e81b0e63ad
Add ToJSON method
CurrencyCloud/currencycloud-net
Source/CurrencyCloud/Entity/PaymentConfirmation.cs
Source/CurrencyCloud/Entity/PaymentConfirmation.cs
using System; using Newtonsoft.Json; namespace CurrencyCloud.Entity { public class PaymentConfirmation : Entity { [JsonConstructor] public PaymentConfirmation() { } public string Id { get; set; } public string PaymentId { get; set; } public string AccountId { get; set; } public string ShortReference { get; set; } public string Status { get; set; } public string ConfirmationUrl { get; set; } public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public DateTime? ExpiresAt { get; set; } public string ToJSON() { var obj = new[] { new { Id, PaymentId, AccountId, ShortReference, Status, ConfirmationUrl, CreatedAt, UpdatedAt, ExpiresAt } }; return JsonConvert.SerializeObject(obj); } public override bool Equals(object obj) { if (!(obj is PaymentConfirmation)) { return false; } var paymentConfirmation = obj as PaymentConfirmation; return Id == paymentConfirmation.Id && PaymentId == paymentConfirmation.PaymentId && AccountId == paymentConfirmation.AccountId && ShortReference == paymentConfirmation.ShortReference && Status == paymentConfirmation.Status && ConfirmationUrl == paymentConfirmation.ConfirmationUrl && CreatedAt == paymentConfirmation.CreatedAt && ExpiresAt == paymentConfirmation.ExpiresAt; } public override int GetHashCode() { return Id.GetHashCode(); } } }
using System; using Newtonsoft.Json; namespace CurrencyCloud.Entity { public class PaymentConfirmation : Entity { [JsonConstructor] public PaymentConfirmation() { } public string Id { get; set; } public string PaymentId { get; set; } public string AccountId { get; set; } public string ShortReference { get; set; } public string Status { get; set; } public string ConfirmationUrl { get; set; } public DateTime? CreatedAt { get; set; } public DateTime? UpdatedAt { get; set; } public DateTime? ExpiresAt { get; set; } public override bool Equals(object obj) { if (!(obj is PaymentConfirmation)) { return false; } var paymentConfirmation = obj as PaymentConfirmation; return Id == paymentConfirmation.Id && PaymentId == paymentConfirmation.PaymentId && AccountId == paymentConfirmation.AccountId && ShortReference == paymentConfirmation.ShortReference && Status == paymentConfirmation.Status && ConfirmationUrl == paymentConfirmation.ConfirmationUrl && CreatedAt == paymentConfirmation.CreatedAt && ExpiresAt == paymentConfirmation.ExpiresAt; } public override int GetHashCode() { return Id.GetHashCode(); } } }
mit
C#
c78d37dea78870da0721dcaabf07010dd352baa7
Fix BSClickTabAttribute
atata-framework/atata-sample-app-tests
src/Atata.SampleApp.AutoTests.Components/BS/BSClickTabAttribute.cs
src/Atata.SampleApp.AutoTests.Components/BS/BSClickTabAttribute.cs
using System; namespace Atata.SampleApp.AutoTests { public class BSClickTabAttribute : TriggerAttribute { public BSClickTabAttribute(TriggerEvents on = TriggerEvents.BeforeAnyAction, TriggerPriority priority = TriggerPriority.Medium, TriggerScope appliesTo = TriggerScope.Self) : base(on, priority, appliesTo) { } public override void Execute<TOwner>(TriggerContext<TOwner> context) { var tabPanelControl = GetAncestorOrSelf<TOwner, BSTabPane<TOwner>>(context.Component); if (tabPanelControl == null) throw new InvalidOperationException("Cannot find tab pane."); string tabPaneId = tabPanelControl.ScopeLocator.GetElement(SearchOptions.OfAnyVisibility()).GetAttribute("id"); var findAttribute = new FindByBSTabPaneIdAttribute("#" + tabPaneId.ToString(TermCase.Kebab)); // TODO: CreateControl in Owner. var tab = tabPanelControl.Parent.Controls.Create<BSTab<TOwner>>(context.Component.Parent.ComponentName, findAttribute); if (!tab.IsActive) tab.Click(); } // TODO: Move to TriggerContext. private IUIComponent<TOwner> GetAncestorOrSelf<TOwner, TComponentToFind>(IUIComponent<TOwner> component) where TOwner : PageObject<TOwner> where TComponentToFind : IUIComponent<TOwner> { return component is TComponentToFind ? (TComponentToFind)component : component.Parent != null ? GetAncestorOrSelf<TOwner, TComponentToFind>(component.Parent) : null; } } }
using System; namespace Atata.SampleApp.AutoTests { public class BSClickTabAttribute : TriggerAttribute { public BSClickTabAttribute(TriggerEvents on = TriggerEvents.BeforeAnyAction, TriggerPriority priority = TriggerPriority.Medium, TriggerScope appliesTo = TriggerScope.Self) : base(on, priority, appliesTo) { } public override void Execute<TOwner>(TriggerContext<TOwner> context) { var tabPanelControl = GetAncestorOrSelf<TOwner, BSTabPane<TOwner>>(context.Component); if (tabPanelControl == null) throw new InvalidOperationException("Cannot find tab pane."); string tabPaneId = tabPanelControl.ScopeLocator.GetElement(SearchOptions.OfAnyVisibility()).GetAttribute("id"); var findAttribute = new FindByBSTabPaneIdAttribute("#" + tabPaneId.ToString(TermCase.Kebab)); // TODO: CreateControl in Owner. var tab = tabPanelControl.Parent.Controls.Create<BSTab<TOwner>>(context.Component.ComponentName, findAttribute); if (!tab.IsActive) tab.Click(); } // TODO: Move to TriggerContext. private IUIComponent<TOwner> GetAncestorOrSelf<TOwner, TComponentToFind>(IUIComponent<TOwner> component) where TOwner : PageObject<TOwner> where TComponentToFind : IUIComponent<TOwner> { return component is TComponentToFind ? (TComponentToFind)component : component.Parent != null ? GetAncestorOrSelf<TOwner, TComponentToFind>(component.Parent) : null; } } }
apache-2.0
C#
2503dcdf86ceb7167766e3eff3cb15e6dab0d925
Remove unused const
ronaldme/Watcher,ronaldme/Watcher,ronaldme/Watcher
Watcher.Common/Urls.cs
Watcher.Common/Urls.cs
using System; using System.Configuration; namespace Watcher.Common { public class Urls { private const string PreFixUrl = "http://api.themoviedb.org/3/"; private static readonly string SuffixUrl = "?api_key=" + ConfigurationManager.AppSettings.Get("theMovieDb"); /// <summary> /// Movie urls /// </summary> public static string SearchMovie = FormatUrl("search/movie"); public static string SearchMovieById = "movie/"; public static string UpcomingMovies = FormatUrl("movie/upcoming"); /// <summary> /// Tv urls /// </summary> public static string SearchTv = FormatUrl("search/tv"); public static string SearchTvById = "tv/"; public static string TopRated = FormatUrl("tv/top_rated"); public static string Seasons = "tv/57243/season/8" + SuffixUrl; /// <summary> /// Person urls /// </summary> public static string SearchPerson = FormatUrl("search/person"); public static string SearchPersonById = "person/"; public static string PopularPersons = FormatUrl("person/popular"); public static string PrefixImages = "http://image.tmdb.org/t/p/w185"; public static string SearchTvSeasons(int tvId, int season) { return $"{PreFixUrl}tv/{tvId}/season/{season}{SuffixUrl}"; } public static string PersonCredits(int personId) { return $"{PreFixUrl}person/{personId}/combined_credits{SuffixUrl}"; } public static string SearchBy(string searchUrl, int id) { return $"{PreFixUrl}{searchUrl}{id}{SuffixUrl}"; } private static string FormatUrl(string urlMiddlePart) { return $"{PreFixUrl}{urlMiddlePart}{SuffixUrl}"; } } }
using System; using System.Configuration; namespace Watcher.Common { public class Urls { private const string PreFixUrl = "http://api.themoviedb.org/3/"; private static readonly string SuffixUrl = "?api_key=" + ConfigurationManager.AppSettings.Get("theMovieDb"); private const string PreFixUrlNotify = "https://www.notifymyandroid.com/publicapi/notify?apikey="; /// <summary> /// Movie urls /// </summary> public static string SearchMovie = FormatUrl("search/movie"); public static string SearchMovieById = "movie/"; public static string UpcomingMovies = FormatUrl("movie/upcoming"); /// <summary> /// Tv urls /// </summary> public static string SearchTv = FormatUrl("search/tv"); public static string SearchTvById = "tv/"; public static string TopRated = FormatUrl("tv/top_rated"); public static string Seasons = "tv/57243/season/8" + SuffixUrl; /// <summary> /// Person urls /// </summary> public static string SearchPerson = FormatUrl("search/person"); public static string SearchPersonById = "person/"; public static string PopularPersons = FormatUrl("person/popular"); public static string PrefixImages = "http://image.tmdb.org/t/p/w185"; public static string SearchTvSeasons(int tvId, int season) { return $"{PreFixUrl}tv/{tvId}/season/{season}{SuffixUrl}"; } public static string PersonCredits(int personId) { return $"{PreFixUrl}person/{personId}/combined_credits{SuffixUrl}"; } public static string SearchBy(string searchUrl, int id) { return $"{PreFixUrl}{searchUrl}{id}{SuffixUrl}"; } private static string FormatUrl(string urlMiddlePart) { return $"{PreFixUrl}{urlMiddlePart}{SuffixUrl}"; } } }
mit
C#
d8b4ba4d356b83b12ab0072730194568bc7010eb
fix typo
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Zk/Models/ZkContext.cs
Zk/Models/ZkContext.cs
using System.Data.Entity; namespace Zk.Models { public class ZkContext : DbContext, IZkContext { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Zk.Models.ZkContext"/> class. /// </summary> public ZkContext() : base("ZkDatabaseConnection") { } #endregion #region Database tables public IDbSet<Crop> Crops { get; set; } #endregion } }
using System.Data.Entity; namespace Zk.Models { public class ZkContext : DbContext, IZkContext { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Zk.ZkContext"/> class. /// </summary> public ZkContext() : base("ZkDatabaseConnection") { } #endregion #region Database tables public IDbSet<Crop> Crops { get; set; } #endregion } }
mit
C#
285b199d7d82a327bb4f5a125bc4cc87223c2b85
Make IdleTracker IHandleGlobalInput
EVAST9919/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,ZLima12/osu,naoey/osu,peppy/osu,naoey/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,naoey/osu,peppy/osu-new,johnneijzen/osu,johnneijzen/osu
osu.Game/Input/IdleTracker.cs
osu.Game/Input/IdleTracker.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; namespace osu.Game.Input { public class IdleTracker : Component, IKeyBindingHandler<PlatformAction>, IHandleGlobalInput { private double lastInteractionTime; public double IdleTime => Clock.CurrentTime - lastInteractionTime; private bool updateLastInteractionTime() { lastInteractionTime = Clock.CurrentTime; return false; } public bool OnPressed(PlatformAction action) => updateLastInteractionTime(); public bool OnReleased(PlatformAction action) => updateLastInteractionTime(); protected override bool Handle(UIEvent e) { switch (e) { case KeyDownEvent _: case KeyUpEvent _: case MouseDownEvent _: case MouseUpEvent _: case MouseMoveEvent _: return updateLastInteractionTime(); default: return base.Handle(e); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; namespace osu.Game.Input { public class IdleTracker : Component, IKeyBindingHandler<PlatformAction> { private double lastInteractionTime; public double IdleTime => Clock.CurrentTime - lastInteractionTime; private bool updateLastInteractionTime() { lastInteractionTime = Clock.CurrentTime; return false; } public bool OnPressed(PlatformAction action) => updateLastInteractionTime(); public bool OnReleased(PlatformAction action) => updateLastInteractionTime(); protected override bool Handle(UIEvent e) { switch (e) { case KeyDownEvent _: case KeyUpEvent _: case MouseDownEvent _: case MouseUpEvent _: case MouseMoveEvent _: return updateLastInteractionTime(); default: return base.Handle(e); } } } }
mit
C#
a2b9dba92cce57e04a956efd1f4baa7906488373
Remove ScoreRank.F
smoogipoo/osu,ZLima12/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,2yangk23/osu,2yangk23/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,ppy/osu,johnneijzen/osu,UselessToucan/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Scoring/ScoreRank.cs
osu.Game/Scoring/ScoreRank.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.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"D")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } }
// 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.ComponentModel; namespace osu.Game.Scoring { public enum ScoreRank { [Description(@"D")] F, [Description(@"D")] D, [Description(@"C")] C, [Description(@"B")] B, [Description(@"A")] A, [Description(@"S")] S, [Description(@"S+")] SH, [Description(@"SS")] X, [Description(@"SS+")] XH, } }
mit
C#
430b675eb0bc7980667b7cab013eec0a577d75cb
Remove unnecessary code from LuceneSettings (#5438)
xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2
src/OrchardCore.Modules/OrchardCore.Lucene/Model/LuceneSettings.cs
src/OrchardCore.Modules/OrchardCore.Lucene/Model/LuceneSettings.cs
using Lucene.Net.Util; using OrchardCore.Contents.Indexing; namespace OrchardCore.Lucene.Model { public class LuceneSettings { public static readonly string[] FullTextField = new string[] { IndexingConstants.FullTextKey }; public static string StandardAnalyzer = "standardanalyzer"; public static LuceneVersion DefaultVersion = LuceneVersion.LUCENE_48; public string SearchIndex { get; set; } public string[] DefaultSearchFields { get; set; } = FullTextField; } }
using System.Collections.Generic; using Lucene.Net.Util; using OrchardCore.Contents.Indexing; namespace OrchardCore.Lucene.Model { public class LuceneSettings { public static readonly string[] FullTextField = new string[] { IndexingConstants.FullTextKey }; public static string StandardAnalyzer = "standardanalyzer"; public static LuceneVersion DefaultVersion = LuceneVersion.LUCENE_48; public string SearchIndex { get; set; } public string[] DefaultSearchFields { get; set; } = FullTextField; /// <summary> /// Gets the list of indices and their settings. /// </summary> public Dictionary<string, LuceneIndexSettings> IndexSettings { get; } = new Dictionary<string, LuceneIndexSettings>(); } }
bsd-3-clause
C#
9a588358e6b633fc37cb9fc66ca4a5c7f0720457
Improve cleanup button: add diagnostics, viewstate and mediacache folders
dsolovay/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager
src/SIM.Tool.Windows/MainWindowComponents/CleanupInstanceButton.cs
src/SIM.Tool.Windows/MainWindowComponents/CleanupInstanceButton.cs
namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Linq; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; public class CleanupInstanceButton : IMainWindowButton { [UsedImplicitly] public CleanupInstanceButton() { } public bool IsEnabled(Window mainWindow, Instance instance) { return instance != null; } public void OnClick(Window mainWindow, Instance instance) { if (instance.State != InstanceState.Stopped) { WindowHelper.ShowMessage("Stop the instance first"); return; } WindowHelper.LongRunningTask(() => DoWork(instance), "Cleaning up", mainWindow); } private void DoWork(Instance instance) { Assert.ArgumentNotNull(instance, nameof(instance)); while (instance.ProcessIds.Any()) { if (instance.State != InstanceState.Stopped) { MessageBox.Show("Stop the instance first"); } } var tempFolder = instance.TempFolderPath; if (!string.IsNullOrEmpty(tempFolder) && Directory.Exists(tempFolder)) { foreach (var dir in Directory.GetDirectories(tempFolder)) { Directory.Delete(dir, true); } foreach (var file in Directory.GetFiles(tempFolder)) { if (file.EndsWith("dictionary.data")) { continue; } File.Delete(file); } } var folders = new[] { instance.LogsFolderPath, Path.Combine(instance.WebRootPath, "App_Data/MediaCache"), Path.Combine(instance.DataFolderPath, "ViewState"), Path.Combine(instance.DataFolderPath, "Diagnostics"), }; foreach (var folder in folders) { if (string.IsNullOrEmpty(folder) || !Directory.Exists(folder)) { continue; } Directory.Delete(folder, true); Directory.CreateDirectory(folder); } } } }
namespace SIM.Tool.Windows.MainWindowComponents { using System.IO; using System.Linq; using System.Windows; using Sitecore.Diagnostics.Base; using Sitecore.Diagnostics.Base.Annotations; using SIM.Instances; using SIM.Tool.Base; using SIM.Tool.Base.Plugins; public class CleanupInstanceButton : IMainWindowButton { [UsedImplicitly] public CleanupInstanceButton() { } public bool IsEnabled(Window mainWindow, Instance instance) { return instance != null; } public void OnClick(Window mainWindow, Instance instance) { if (instance.State != InstanceState.Stopped) { WindowHelper.ShowMessage("Stop the instance first"); return; } WindowHelper.LongRunningTask(() => DoWork(instance), "Cleaning up", mainWindow); } private void DoWork(Instance instance) { Assert.ArgumentNotNull(instance, nameof(instance)); while (instance.ProcessIds.Any()) { if (instance.State != InstanceState.Stopped) { MessageBox.Show("Stop the instance first"); } } var logsFolder = instance.LogsFolderPath; if (!string.IsNullOrEmpty(logsFolder) && Directory.Exists(logsFolder)) { Directory.Delete(logsFolder, true); Directory.CreateDirectory(logsFolder); } var tempFolder = instance.TempFolderPath; if (!string.IsNullOrEmpty(tempFolder) && Directory.Exists(tempFolder)) { foreach (var dir in Directory.GetDirectories(tempFolder)) { Directory.Delete(dir, true); } foreach (var file in Directory.GetFiles(tempFolder)) { if (file.EndsWith("dictionary.data")) { continue; } File.Delete(file); } } } } }
mit
C#
9dc9cca9c30f7b027be3089cb5b9d8a6daa24abb
fix build
Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms
Xamarin.Forms.Xaml.UnitTests/Issues/Bz47703.xaml.cs
Xamarin.Forms.Xaml.UnitTests/Issues/Bz47703.xaml.cs
using System; using System.Globalization; using NUnit.Framework; namespace Xamarin.Forms.Xaml.UnitTests { public class Bz47703Converter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) return "Label:" + value; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } public class Bz47703View : Label { BindingBase displayBinding; public BindingBase DisplayBinding { get { return displayBinding; } set { displayBinding = value; if (displayBinding != null) this.SetBinding(TextProperty, DisplayBinding); } } } public partial class Bz47703 : ContentPage { public Bz47703() { InitializeComponent(); } public Bz47703(bool useCompiledXaml) { //this stub will be replaced at compile time } [TestFixture] class Tests { [TestCase(true)] [TestCase(false)] public void IValueConverterOnBindings(bool useCompiledXaml) { var page = new Bz47703(useCompiledXaml); page.BindingContext = new { Name = "Foo" }; Assert.AreEqual("Label:Foo", page.view.Text); } } } }
using System; using System.Globalization; using NUnit.Framework; namespace Xamarin.Forms.Xaml.UnitTests { public class Bz47703Converter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) return "Label:" + value; return value; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } } public class Bz47703View : Label { BindingBase displayBinding; public BindingBase DisplayBinding { get { return displayBinding; } set { displayBinding = value; if (displayBinding != null) this.SetBinding(TextProperty, DisplayBinding); } } } public partial class Bz47703 : ContentPage { public Bz47703() { InitializeComponent(); } public Bz47703(bool useCompiledXaml) { //this stub will be replaced at compile time } [TestFixture] class Tests { [TestCase(true)] [TestCase(false)] public void IValueConverterOnBindings(bool useCompiledXaml) { if (useCompiledXaml) MockCompiler.Compile(typeof(Bz47703)); var page = new Bz47703(useCompiledXaml); page.BindingContext = new { Name = "Foo" }; Assert.AreEqual("Label:Foo", page.view.Text); } } } }
mit
C#
eb876cecbb96fa52224e47071926f9e6ff2fe2a2
Bump version
Coding-Enthusiast/Watch-Only-Bitcoin-Wallet
WatchOnlyBitcoinWallet/Properties/AssemblyInfo.cs
WatchOnlyBitcoinWallet/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WatchOnlyBitcoinWallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Coding Enthusiast Coders")] [assembly: AssemblyProduct("WatchOnlyBitcoinWallet")] [assembly: AssemblyCopyright("Copyright © C.E. 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.2.0.0")] [assembly: AssemblyFileVersion("3.2.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WatchOnlyBitcoinWallet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Coding Enthusiast Coders")] [assembly: AssemblyProduct("WatchOnlyBitcoinWallet")] [assembly: AssemblyCopyright("Copyright © C.E. 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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.1.0.*")] [assembly: AssemblyFileVersion("3.1.0.0")]
mit
C#
d72b873370db0d0c51594628a0721a96a2b7fbd9
Fix failing test
appharbor/appharbor-cli
src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs
src/AppHarbor.Tests/Commands/LoginAuthCommandTest.cs
using System; using System.IO; using AppHarbor.Commands; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class LoginAuthCommandTest { [Theory, AutoData] public void ShouldSetAppHarborTokenIfUserIsntLoggedIn(string username, string password, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock) { using (var writer = new StringWriter()) { Console.SetOut(writer); using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine))) { Console.SetIn(reader); accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null); var loginCommand = new Mock<LoginAuthCommand>(accessTokenConfigurationMock.Object); loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo"); loginCommand.Object.Execute(new string[] { }); var expected = string.Format("Username: Password: Successfully logged in as {1}{0}", Environment.NewLine, username); Assert.Equal(expected, writer.ToString()); accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once()); } } } [Theory, AutoData] public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<AccessTokenConfiguration> accessTokenConfigurationMock) { accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo"); var loginCommand = new LoginAuthCommand(accessTokenConfigurationMock.Object); var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { })); Assert.Equal("You're already logged in", exception.Message); } } }
using System; using System.IO; using AppHarbor.Commands; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests.Commands { public class LoginAuthCommandTest { [Theory, AutoData] public void ShouldSetAppHarborTokenIfUserIsntLoggedIn(string username, string password, [Frozen]Mock<IAccessTokenConfiguration> accessTokenConfigurationMock) { using (var writer = new StringWriter()) { Console.SetOut(writer); using (var reader = new StringReader(string.Format("{0}{2}{1}{2}", username, password, Environment.NewLine))) { Console.SetIn(reader); accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns((string)null); var loginCommand = new Mock<LoginAuthCommand>(accessTokenConfigurationMock.Object); loginCommand.Setup(x => x.GetAccessToken(username, password)).Returns("foo"); loginCommand.Object.Execute(new string[] { }); var expected = string.Format("Username:{0}Password:{0}Successfully logged in as {1}{0}", Environment.NewLine, username); Assert.Equal(expected, writer.ToString()); accessTokenConfigurationMock.Verify(x => x.SetAccessToken("foo"), Times.Once()); } } } [Theory, AutoData] public void ShouldThrowIfUserIsAlreadyLoggedIn([Frozen]Mock<AccessTokenConfiguration> accessTokenConfigurationMock) { accessTokenConfigurationMock.Setup(x => x.GetAccessToken()).Returns("foo"); var loginCommand = new LoginAuthCommand(accessTokenConfigurationMock.Object); var exception = Assert.Throws<CommandException>(() => loginCommand.Execute(new string[] { })); Assert.Equal("You're already logged in", exception.Message); } } }
mit
C#
abebb2cbee450f16f0d3b54bab1b243faf288c8f
fix conditional compilation for net 5.0+ (#834)
kubernetes-client/csharp,kubernetes-client/csharp
src/KubernetesClient/Authentication/TokenFileAuth.cs
src/KubernetesClient/Authentication/TokenFileAuth.cs
using System.Net.Http.Headers; using System.IO; using System.Threading; using System.Threading.Tasks; using k8s.Autorest; namespace k8s.Authentication { public class TokenFileAuth : ITokenProvider { private string token; internal string TokenFile { get; set; } internal DateTime TokenExpiresAt { get; set; } public TokenFileAuth(string tokenFile) { TokenFile = tokenFile; } #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken) #else public Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken) #endif { if (TokenExpiresAt < DateTime.UtcNow) { #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER token = await File.ReadAllTextAsync(TokenFile, cancellationToken) .ContinueWith(r => r.Result.Trim(), cancellationToken) .ConfigureAwait(false); #else token = File.ReadAllText(TokenFile).Trim(); #endif // in fact, the token has a expiry of 10 minutes and kubelet // refreshes it at 8 minutes of its lifetime. setting the expiry // of 1 minute makes sure the token is reloaded regularly so // that its actual expiry is after the declared expiry here, // which is as sufficiently true as the time of reading a token // < 10-8-1 minute. TokenExpiresAt = DateTime.UtcNow.AddMinutes(1); } #if NETSTANDARD2_1_OR_GREATER || NET5_0_OR_GREATER return new AuthenticationHeaderValue("Bearer", token); #else return Task.FromResult(new AuthenticationHeaderValue("Bearer", token)); #endif } } }
using System.Net.Http.Headers; using System.IO; using System.Threading; using System.Threading.Tasks; using k8s.Autorest; namespace k8s.Authentication { public class TokenFileAuth : ITokenProvider { private string token; internal string TokenFile { get; set; } internal DateTime TokenExpiresAt { get; set; } public TokenFileAuth(string tokenFile) { TokenFile = tokenFile; } #if NETSTANDARD2_1_OR_GREATER public async Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken) #else public Task<AuthenticationHeaderValue> GetAuthenticationHeaderAsync(CancellationToken cancellationToken) #endif { if (TokenExpiresAt < DateTime.UtcNow) { #if NETSTANDARD2_1_OR_GREATER token = await File.ReadAllTextAsync(TokenFile, cancellationToken) .ContinueWith(r => r.Result.Trim(), cancellationToken) .ConfigureAwait(false); #else token = File.ReadAllText(TokenFile).Trim(); #endif // in fact, the token has a expiry of 10 minutes and kubelet // refreshes it at 8 minutes of its lifetime. setting the expiry // of 1 minute makes sure the token is reloaded regularly so // that its actual expiry is after the declared expiry here, // which is as sufficiently true as the time of reading a token // < 10-8-1 minute. TokenExpiresAt = DateTime.UtcNow.AddMinutes(1); } #if NETSTANDARD2_1_OR_GREATER return new AuthenticationHeaderValue("Bearer", token); #else return Task.FromResult(new AuthenticationHeaderValue("Bearer", token)); #endif } } }
apache-2.0
C#
2a4d5e13ffcd2441b8fd1018b251197b00ec4363
Return an empty list on zero length.
PenguinF/sandra-three
Sandra.UI/PgnSyntaxDescriptor.cs
Sandra.UI/PgnSyntaxDescriptor.cs
#region License /********************************************************************************* * PgnSyntaxDescriptor.cs * * Copyright (c) 2004-2019 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Localization; using Eutherion.Text; using Eutherion.Win.AppTemplate; using ScintillaNET; using System.Collections.Generic; using System.Linq; namespace Sandra.UI { /// <summary> /// Describes the interaction between PGN syntax and a syntax editor. /// </summary> public class PgnSyntaxDescriptor : SyntaxDescriptor<PgnSymbol, PgnErrorInfo> { public static readonly string PgnFileExtension = "pgn"; public override string FileExtension => PgnFileExtension; public override LocalizedStringKey FileExtensionLocalizedKey => LocalizedStringKeys.PgnFiles; public override (IEnumerable<TextElement<PgnSymbol>>, List<PgnErrorInfo>) Parse(string code) { int length = code.Length; if (length == 0) return (Enumerable.Empty<TextElement<PgnSymbol>>(), new List<PgnErrorInfo>()); return (new TextElement<PgnSymbol>[] { new TextElement<PgnSymbol>(new PgnSymbol()) { Length = length } }, new List<PgnErrorInfo>()); } public override Style GetStyle(SyntaxEditor<PgnSymbol, PgnErrorInfo> syntaxEditor, PgnSymbol terminalSymbol) => syntaxEditor.DefaultStyle; public override (int, int) GetErrorRange(PgnErrorInfo error) => (error.Start, error.Length); public override string GetErrorMessage(PgnErrorInfo error) => error.Message; } public class PgnSymbol { } public class PgnErrorInfo { public int Start { get; } public int Length { get; } public string Message { get; } public PgnErrorInfo(int start, int length, string message) { Start = start; Length = length; Message = message; } } }
#region License /********************************************************************************* * PgnSyntaxDescriptor.cs * * Copyright (c) 2004-2019 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion using Eutherion.Localization; using Eutherion.Text; using Eutherion.Win.AppTemplate; using ScintillaNET; using System.Collections.Generic; namespace Sandra.UI { /// <summary> /// Describes the interaction between PGN syntax and a syntax editor. /// </summary> public class PgnSyntaxDescriptor : SyntaxDescriptor<PgnSymbol, PgnErrorInfo> { public static readonly string PgnFileExtension = "pgn"; public override string FileExtension => PgnFileExtension; public override LocalizedStringKey FileExtensionLocalizedKey => LocalizedStringKeys.PgnFiles; public override (IEnumerable<TextElement<PgnSymbol>>, List<PgnErrorInfo>) Parse(string code) => (new TextElement<PgnSymbol>[] { new TextElement<PgnSymbol>(new PgnSymbol()) { Length = code.Length } }, new List<PgnErrorInfo>()); public override Style GetStyle(SyntaxEditor<PgnSymbol, PgnErrorInfo> syntaxEditor, PgnSymbol terminalSymbol) => syntaxEditor.DefaultStyle; public override (int, int) GetErrorRange(PgnErrorInfo error) => (error.Start, error.Length); public override string GetErrorMessage(PgnErrorInfo error) => error.Message; } public class PgnSymbol { } public class PgnErrorInfo { public int Start { get; } public int Length { get; } public string Message { get; } public PgnErrorInfo(int start, int length, string message) { Start = start; Length = length; Message = message; } } }
apache-2.0
C#
cf3fd31887ad16f59450b7c2883cdbba29101e06
Fix warning about OperationFeeRequestBuilderTest.TestExecute
elucidsoft/dotnetcore-stellar-sdk
stellar-dotnet-sdk-test/requests/OperationFeeRequestBuilderTest.cs
stellar-dotnet-sdk-test/requests/OperationFeeRequestBuilderTest.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace stellar_dotnet_sdk_test.requests { [TestClass] public class OperationFeeRequestBuilderTest { [TestMethod] public void TestBuilder() { Server server = new Server("https://horizon-testnet.stellar.org"); Uri uri = server.OperationFeeStats.BuildUri(); Assert.AreEqual("https://horizon-testnet.stellar.org/operation_fee_stats", uri.ToString()); } [TestMethod] public async Task TestExecute() { Server server = new Server("https://horizon-testnet.stellar.org"); var task = await server.OperationFeeStats.Execute(); Assert.AreEqual("https://horizon-testnet.stellar.org/operation_fee_stats", task.Uri.ToString()); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using stellar_dotnet_sdk; using System; using System.Collections.Generic; using System.Text; namespace stellar_dotnet_sdk_test.requests { [TestClass] public class OperationFeeRequestBuilderTest { [TestMethod] public void TestBuilder() { Server server = new Server("https://horizon-testnet.stellar.org"); Uri uri = server.OperationFeeStats.BuildUri(); Assert.AreEqual("https://horizon-testnet.stellar.org/operation_fee_stats", uri.ToString()); } [TestMethod] public async void TestExecute() { Server server = new Server("https://horizon-testnet.stellar.org"); var task = await server.OperationFeeStats.Execute(); Assert.AreEqual("https://horizon-testnet.stellar.org/operation_fee_stats", task.Uri.ToString()); } } }
apache-2.0
C#
c885a0ce9049f5f8af309c2a2e0c5963ca22ea52
Add form for setting balance in one step
mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection,mattgwagner/Cash-Flow-Projection
src/Cash-Flow-Projection/Views/Home/Index.cshtml
src/Cash-Flow-Projection/Views/Home/Index.cshtml
@model Cash_Flow_Projection.Models.Dashboard @{ ViewData["Title"] = "Home Page"; } @using (Html.BeginForm("Balance", "Home", FormMethod.Post)) { @Html.AntiForgeryToken() <input type="text" id="balance" placeholder="Set Balance" /> <button type="submit">Set</button> } <table class="table table-striped"> @foreach (var entry in Model.Entries.OrderBy(_ => _.Date)) { <tr> <td>@Html.DisplayFor(_ => entry.Date)</td> <td>@Html.DisplayFor(_ => entry.Description)</td> <td>@Html.DisplayFor(_ => entry.Amount)</td> <td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td> <td> @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post)) { @Html.AntiForgeryToken() <button type="submit">Delete</button> } </td> </tr> } </table>
@model Cash_Flow_Projection.Models.Dashboard @{ ViewData["Title"] = "Home Page"; } <table class="table table-striped"> @foreach (var entry in Model.Entries.OrderBy(_ => _.Date)) { <tr> <td>@Html.DisplayFor(_ => entry.Date)</td> <td>@Html.DisplayFor(_ => entry.Description)</td> <td>@Html.DisplayFor(_ => entry.Amount)</td> <td>@Cash_Flow_Projection.Models.Balance.BalanceAsOf(Model.Entries, entry.Date)</td> <td> @using (Html.BeginForm("Delete", "Home", new { id = entry.id }, FormMethod.Post)) { @Html.AntiForgeryToken() <button type="submit">Delete</button> } </td> </tr> } </table>
mit
C#
89412b7635175bbb32ed3ee3977ef79d12886cd1
Add Armor on Card
HearthSim/HearthDb
HearthDb/Card.cs
HearthDb/Card.cs
#region using System; using System.Linq; using HearthDb.CardDefs; using HearthDb.Enums; using static HearthDb.Enums.GameTag; #endregion namespace HearthDb { public class Card { internal Card(Entity entity) { Entity = entity; } public Entity Entity { get; } public string Id => Entity.CardId; public int DbfId => Entity.DbfId; public string Name => GetLocName(DefaultLanguage); public string Text => GetLocText(DefaultLanguage); public string FlavorText => GetLocFlavorText(DefaultLanguage); public CardClass Class => (CardClass)Entity.GetTag(CLASS); public Rarity Rarity => (Rarity)Entity.GetTag(RARITY); public CardType Type => (CardType)Entity.GetTag(CARDTYPE); public Race Race => (Race)Entity.GetTag(CARDRACE); public CardSet Set => (CardSet)Entity.GetTag(CARD_SET); public Faction Faction => (Faction)Entity.GetTag(FACTION); public int Cost => Entity.GetTag(COST); public int Attack => Entity.GetTag(ATK); public int Health => Entity.GetTag(HEALTH); public int Durability => Entity.GetTag(DURABILITY); public int Armor => Entity.GetTag(ARMOR); public string[] Mechanics { get { var mechanics = Dictionaries.Mechanics.Keys.Where(mechanic => Entity.GetTag(mechanic) > 0).Select(x => Dictionaries.Mechanics[x]); var refMechanics = Dictionaries.ReferencedMechanics.Keys.Where(mechanic => Entity.GetTag(mechanic) > 0) .Select(x => Dictionaries.ReferencedMechanics[x]); return mechanics.Concat(refMechanics).ToArray(); } } public string ArtistName => Entity.GetInnerValue(ARTISTNAME); public string[] EntourageCardIds => Entity.EntourageCards.Select(x => x.CardId).ToArray(); public Locale DefaultLanguage { get; set; } = Locale.enUS; public bool Collectible => Convert.ToBoolean(Entity.GetTag(COLLECTIBLE)); public string GetLocName(Locale lang) => Entity.GetLocString(CARDNAME, lang); public string GetLocText(Locale lang) { var text = Entity.GetLocString(CARDTEXT_INHAND, lang)?.Replace("_", "\u00A0").Trim(); if(text == null) return null; var index = text.IndexOf('@'); return index > 0 ? text.Substring(index + 1) : text; } public string GetLocFlavorText(Locale lang) => Entity.GetLocString(FLAVORTEXT, lang); } }
#region using System; using System.Linq; using HearthDb.CardDefs; using HearthDb.Enums; using static HearthDb.Enums.GameTag; #endregion namespace HearthDb { public class Card { internal Card(Entity entity) { Entity = entity; } public Entity Entity { get; } public string Id => Entity.CardId; public int DbfId => Entity.DbfId; public string Name => GetLocName(DefaultLanguage); public string Text => GetLocText(DefaultLanguage); public string FlavorText => GetLocFlavorText(DefaultLanguage); public CardClass Class => (CardClass)Entity.GetTag(CLASS); public Rarity Rarity => (Rarity)Entity.GetTag(RARITY); public CardType Type => (CardType)Entity.GetTag(CARDTYPE); public Race Race => (Race)Entity.GetTag(CARDRACE); public CardSet Set => (CardSet)Entity.GetTag(CARD_SET); public Faction Faction => (Faction)Entity.GetTag(FACTION); public int Cost => Entity.GetTag(COST); public int Attack => Entity.GetTag(ATK); public int Health => Entity.GetTag(HEALTH); public int Durability => Entity.GetTag(DURABILITY); public string[] Mechanics { get { var mechanics = Dictionaries.Mechanics.Keys.Where(mechanic => Entity.GetTag(mechanic) > 0).Select(x => Dictionaries.Mechanics[x]); var refMechanics = Dictionaries.ReferencedMechanics.Keys.Where(mechanic => Entity.GetTag(mechanic) > 0) .Select(x => Dictionaries.ReferencedMechanics[x]); return mechanics.Concat(refMechanics).ToArray(); } } public string ArtistName => Entity.GetInnerValue(ARTISTNAME); public string[] EntourageCardIds => Entity.EntourageCards.Select(x => x.CardId).ToArray(); public Locale DefaultLanguage { get; set; } = Locale.enUS; public bool Collectible => Convert.ToBoolean(Entity.GetTag(COLLECTIBLE)); public string GetLocName(Locale lang) => Entity.GetLocString(CARDNAME, lang); public string GetLocText(Locale lang) { var text = Entity.GetLocString(CARDTEXT_INHAND, lang)?.Replace("_", "\u00A0").Trim(); if(text == null) return null; var index = text.IndexOf('@'); return index > 0 ? text.Substring(index + 1) : text; } public string GetLocFlavorText(Locale lang) => Entity.GetLocString(FLAVORTEXT, lang); } }
mit
C#
0b7e1e40eb91f21557dadeade32c7f0fc66e4dab
use snappy compression
hoppity/Metrics.Kafka
src/Metrics.Kafka/Metrics.Kafka/KafkaDocument.cs
src/Metrics.Kafka/Metrics.Kafka/KafkaDocument.cs
using Kafka.Basic; using Metrics.Json; namespace Metrics.Kafka { public class KafkaDocument { public JsonObject Properties { get; set; } public Message ToMessage(string contextName) { return new Message { Key = contextName, Value = Properties.AsJson(false), Codec = Compression.Snappy }; } } }
using Kafka.Basic; using Metrics.Json; namespace Metrics.Kafka { public class KafkaDocument { public JsonObject Properties { get; set; } public Message ToMessage(string contextName) { return new Message { Key = contextName, Value = Properties.AsJson(false) }; } } }
apache-2.0
C#
99015cac15aab740d918d31abc83d732a76cd416
Fix warning
AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS
src/Package/Test/Settings/SettingsStorageTest.cs
src/Package/Test/Settings/SettingsStorageTest.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; using FluentAssertions; using Microsoft.UnitTests.Core.XUnit; using Microsoft.VisualStudio.R.Package.Shell; namespace Microsoft.VisualStudio.R.Package.Test.Settings { [ExcludeFromCodeCoverage] [Category.VsPackage.Settings] public sealed class SettingsStorageTest { [Test] public void SaveRestore() { SaveRestore("name", -2); SaveRestore("name", true); SaveRestore("name", false); SaveRestore("name", (uint)1); SaveRestore("name", "string"); SaveRestore("name", DateTime.Now); SaveRestore("name", new TestSetting("p1", 1)); } public void SaveRestore<T>(string name, T value) { var storage = new VsSettingsStorage(new TestSettingsManager()); storage.SettingExists(name).Should().BeFalse(); storage.SetSetting(name, value); storage.SettingExists(name).Should().BeTrue(); storage.GetSetting(name, value.GetType()).Should().Be(value); storage.Persist(); storage.ClearCache(); storage.SettingExists(name).Should().BeTrue(); storage.GetSetting(name, value.GetType()).Should().Be(value); } class TestSetting { public string Prop1 { get; set; } public int Prop2 { get; set; } public TestSetting(string p1, int p2) { Prop1 = p1; Prop2 = p2; } public override bool Equals(object obj) { var other = (TestSetting)obj; return other.Prop1 == this.Prop1 && other.Prop2 == this.Prop2; } public override int GetHashCode() { return base.GetHashCode(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Diagnostics.CodeAnalysis; using FluentAssertions; using Microsoft.UnitTests.Core.XUnit; using Microsoft.VisualStudio.R.Package.Shell; namespace Microsoft.VisualStudio.R.Package.Test.Settings { [ExcludeFromCodeCoverage] [Category.VsPackage.Settings] public sealed class SettingsStorageTest { [Test] public void SaveRestore() { SaveRestore("name", -2); SaveRestore("name", true); SaveRestore("name", false); SaveRestore("name", (uint)1); SaveRestore("name", "string"); SaveRestore("name", DateTime.Now); SaveRestore("name", new TestSetting("p1", 1)); } public void SaveRestore<T>(string name, T value) { var storage = new VsSettingsStorage(new TestSettingsManager()); storage.SettingExists(name).Should().BeFalse(); storage.SetSetting(name, value); storage.SettingExists(name).Should().BeTrue(); storage.GetSetting(name, value.GetType()).Should().Be(value); storage.Persist(); storage.ClearCache(); storage.SettingExists(name).Should().BeTrue(); storage.GetSetting(name, value.GetType()).Should().Be(value); } class TestSetting { public string Prop1 { get; set; } public int Prop2 { get; set; } public TestSetting(string p1, int p2) { Prop1 = p1; Prop2 = p2; } public override bool Equals(object obj) { var other = (TestSetting)obj; return other.Prop1 == this.Prop1 && other.Prop2 == this.Prop2; } } } }
mit
C#
6bcd62db5aea5d52639780a003550aa59e29a230
Update Version to 3.8.5
mono/ServiceStack.Text,gerryhigh/ServiceStack.Text,NServiceKit/NServiceKit.Text,mono/ServiceStack.Text,gerryhigh/ServiceStack.Text,NServiceKit/NServiceKit.Text
src/ServiceStack.Text/Properties/AssemblyInfo.cs
src/ServiceStack.Text/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("ServiceStack.Text")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("ServiceStack.Text")] [assembly: AssemblyCopyright("Copyright © ServiceStack 2012")] [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("a352d4d3-df2a-4c78-b646-67181a6333a6")] // 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("3.8.5.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ServiceStack.Text")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("ServiceStack.Text")] [assembly: AssemblyCopyright("Copyright © ServiceStack 2012")] [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("a352d4d3-df2a-4c78-b646-67181a6333a6")] // 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("3.8.3.0")] //[assembly: AssemblyFileVersion("1.0.0.0")]
bsd-3-clause
C#
eb68c560b5468720d27f36fb5debba188bbd8403
Move variable to inner scope where it's used
substantial/mapify-example
app/Assets/Mapify/Scripts/MapifyLevelPopulator.cs
app/Assets/Mapify/Scripts/MapifyLevelPopulator.cs
using UnityEngine; using System; using System.Collections; public class MapifyLevelPopulator { private MapifyMapIterator mapIterator; private MapifyTileRepository tileRepository; private Transform container; public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) { this.mapIterator = mapIterator; this.tileRepository = tileRepository; this.container = container; } public void Populate() { mapIterator.Iterate((character, localPosition) => { if (tileRepository.HasKey(character)) { var tile = tileRepository.Find(character); var worldPosition = container.TransformPoint(localPosition); MapifyTileSpawner.Create(tile, worldPosition, container); } }); } }
using UnityEngine; using System; using System.Collections; public class MapifyLevelPopulator { private MapifyMapIterator mapIterator; private MapifyTileRepository tileRepository; private Transform container; public MapifyLevelPopulator(MapifyMapIterator mapIterator, MapifyTileRepository tileRepository, Transform container) { this.mapIterator = mapIterator; this.tileRepository = tileRepository; this.container = container; } public void Populate() { mapIterator.Iterate((character, localPosition) => { var worldPosition = container.TransformPoint(localPosition); if (tileRepository.HasKey(character)) { var tile = tileRepository.Find(character); MapifyTileSpawner.Create(tile, worldPosition, container); } }); } }
mit
C#
5dfebbed51161810bb48fc0fe80f390a6746fbc2
change foregroud when value is null
degarashi0913/FAManagementStudio
FAManagementStudio/Views/Behaviors/GridHeaderDisplayNameBehavior.cs
FAManagementStudio/Views/Behaviors/GridHeaderDisplayNameBehavior.cs
using System.Data; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Interactivity; namespace FAManagementStudio.Views.Behaviors { public class GridHeaderDisplayNameBehavior : Behavior<DataGrid> { public GridHeaderDisplayNameBehavior() { } protected override void OnAttached() { base.OnAttached(); AssociatedObject.AutoGeneratingColumn += AssociatedObject_AutoGeneratingColumn; } private const string NullString = "(DB_Null)"; private void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { var propertyName = e.Column.Header.ToString(); e.Column.Header = (AssociatedObject.ItemsSource as DataView).Table.Columns[int.Parse(propertyName)].Caption; ((DataGridBoundColumn)e.Column).Binding.TargetNullValue = NullString; //Null Value var style = new Style(typeof(TextBlock)); var trigger = new DataTrigger { Binding = new Binding(propertyName), Value = null }; trigger.Setters.Add(new Setter(TextBlock.ForegroundProperty, new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.LightGray))); style.Triggers.Add(trigger); ((DataGridTextColumn)e.Column).ElementStyle = style; } protected override void OnDetaching() { AssociatedObject.AutoGeneratingColumn -= AssociatedObject_AutoGeneratingColumn; base.OnDetaching(); } } }
using System.Data; using System.Windows.Controls; using System.Windows.Interactivity; namespace FAManagementStudio.Views.Behaviors { public class GridHeaderDisplayNameBehavior : Behavior<DataGrid> { public GridHeaderDisplayNameBehavior() { } protected override void OnAttached() { base.OnAttached(); AssociatedObject.AutoGeneratingColumn += AssociatedObject_AutoGeneratingColumn; } private void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e) { e.Column.Header = (AssociatedObject.ItemsSource as DataView).Table.Columns[int.Parse(e.Column.Header.ToString())].Caption; } protected override void OnDetaching() { AssociatedObject.AutoGeneratingColumn -= AssociatedObject_AutoGeneratingColumn; base.OnDetaching(); } } }
mit
C#
3b7c3376124e45891c2b1ae77bc161c629110035
Correct typo (just caught my eye, no biggie).
rasmusjp/umbraco-ditto,leekelleher/umbraco-ditto,AzarinSergey/umbraco-ditto,robertjf/umbraco-ditto
tests/Our.Umbraco.Ditto.Tests/Models/ComplexModel.cs
tests/Our.Umbraco.Ditto.Tests/Models/ComplexModel.cs
using System.Globalization; namespace Our.Umbraco.Ditto.Tests.Models { using System.ComponentModel; using Our.Umbraco.Ditto.Tests.TypeConverters; using global::Umbraco.Core.Models; public class ComplexModel { public int Id { get; set; } [DittoValueResolver(typeof(NameValueResovler))] public string Name { get; set; } [UmbracoProperty("myprop")] public IPublishedContent MyProperty { get; set; } [UmbracoProperty("Id")] [TypeConverter(typeof(MockPublishedContentConverter))] public IPublishedContent MyPublishedContent { get; set; } } public class NameValueResovler : DittoValueResolver { public override object ResolveValue(ITypeDescriptorContext context, DittoValueResolverAttribute attribute, CultureInfo culture) { var content = context.Instance as IPublishedContent; if (content == null) return null; return content.Name + " Test"; } } }
using System.Globalization; namespace Our.Umbraco.Ditto.Tests.Models { using System.ComponentModel; using Our.Umbraco.Ditto.Tests.TypeConverters; using global::Umbraco.Core.Models; public class ComplexModel { public int Id { get; set; } [DittoValueResolver(typeof(NameVauleResovler))] public string Name { get; set; } [UmbracoProperty("myprop")] public IPublishedContent MyProperty { get; set; } [UmbracoProperty("Id")] [TypeConverter(typeof(MockPublishedContentConverter))] public IPublishedContent MyPublishedContent { get; set; } } public class NameVauleResovler : DittoValueResolver { public override object ResolveValue(ITypeDescriptorContext context, DittoValueResolverAttribute attribute, CultureInfo culture) { var content = context.Instance as IPublishedContent; if (content == null) return null; return content.Name + " Test"; } } }
mit
C#
84d8835961a72e74aab8346a95b40ba01f1b6c68
Update AGameManager.cs
Nicolas-Constanty/UnityTools
Assets/UnityTools/MonoBehaviour/AGameManager.cs
Assets/UnityTools/MonoBehaviour/AGameManager.cs
using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityTools.DesignPatern; // ReSharper disable once CheckNamespace namespace UnityTools { public abstract class AGameManager<T, TE> : Singleton<T> where T : MonoBehaviour where TE : struct, IConvertible { // ReSharper disable once EmptyConstructor protected AGameManager() {} protected delegate void GameAction(); protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>(); protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>(); protected override void Awake() { base.Awake(); bool init = false; foreach (TE state in Enum.GetValues(typeof(TE))) { if (!init) { init = true; } Type type = typeof(T); MethodInfo method = type.GetMethod("On" + state + "Game", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (method != null) { GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name); } method = type.GetMethod("OnFixed" + state + "Game"); if (method != null) { GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name); } } } public TE CurrentState; public T GetInstance() { return Instance; } protected virtual void Update() { if (GameStatesUpdateActions.ContainsKey(CurrentState)) GameStatesUpdateActions[CurrentState](); } protected virtual void FixedUpdate() { if (GameStatesFixedUpdateActions.ContainsKey(CurrentState)) GameStatesFixedUpdateActions[CurrentState](); } } }
using System; using System.Collections.Generic; using System.Reflection; using UnityEngine; using UnityTools.DesignPatern; // ReSharper disable once CheckNamespace namespace UnityTools { public abstract class AGameManager<T, TE> : Singleton<T> where T : MonoBehaviour where TE : struct, IConvertible { // ReSharper disable once EmptyConstructor protected AGameManager() {} protected delegate void GameAction(); protected readonly Dictionary<TE, GameAction> GameStatesUpdateActions = new Dictionary<TE, GameAction>(); protected readonly Dictionary<TE, GameAction> GameStatesFixedUpdateActions = new Dictionary<TE, GameAction>(); protected override void Awake() { base.Awake(); bool init = false; foreach (TE state in Enum.GetValues(typeof(TE))) { if (!init) { init = true; } Type type = typeof(T); MethodInfo method = type.GetMethod("On" + state + "Game"); if (method != null) { GameStatesUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name); } method = type.GetMethod("OnFixed" + state + "Game"); if (method != null) { GameStatesFixedUpdateActions[state] = (GameAction)Delegate.CreateDelegate(typeof(GameAction), this, method.Name); } } } public TE CurrentState; public T GetInstance() { return Instance; } protected virtual void Update() { if (GameStatesUpdateActions.ContainsKey(CurrentState)) GameStatesUpdateActions[CurrentState](); } protected virtual void FixedUpdate() { if (GameStatesFixedUpdateActions.ContainsKey(CurrentState)) GameStatesFixedUpdateActions[CurrentState](); } } }
mit
C#
c3613125a1c1681e70fa1787492f70e16da436f2
add table to ipobject
splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net
IPTables.Net/IpUtils/Utils/IpRouteController.cs
IPTables.Net/IpUtils/Utils/IpRouteController.cs
using System; using System.Collections.Generic; using SystemInteract; namespace IPTables.Net.IpUtils.Utils { public class IpRouteController : IpController { public IpRouteController(ISystemFactory system) : base("route", system) { } protected override bool IsSingle(string key) { if (key == "onlink" || key == "pervasive") return true; return base.IsSingle(key); } public List<IpObject> GetAll(String table = "default") { List<IpObject> r = new List<IpObject>(); var ret = Command("show", "table", table); var lines = ret[0].Trim().Split('\n'); foreach (var line in lines) { var l = line.Trim(); var obj = ParseObject(l, "to"); if (obj != null) { if (table != "default") { obj.Pairs.Add("table", table); } r.Add(obj); } } return r; } internal override String[] ExportObject(IpObject obj) { List<String> ret = new List<string>(); ret.Add(obj.Pairs["to"]); foreach (var kv in obj.Pairs) { if(kv.Key == "to") continue; ret.Add(kv.Key); ret.Add(kv.Value); } ret.AddRange(obj.Singles); return ret.ToArray(); } } }
using System; using System.Collections.Generic; using SystemInteract; namespace IPTables.Net.IpUtils.Utils { public class IpRouteController : IpController { public IpRouteController(ISystemFactory system) : base("route", system) { } protected override bool IsSingle(string key) { if (key == "onlink" || key == "pervasive") return true; return base.IsSingle(key); } public List<IpObject> GetAll(String table = "default") { List<IpObject> r = new List<IpObject>(); var ret = Command("show", "table", table); var lines = ret[0].Trim().Split('\n'); foreach (var line in lines) { var l = line.Trim(); var obj = ParseObject(l, "to"); if (obj != null) { r.Add(obj); } } return r; } internal override String[] ExportObject(IpObject obj) { List<String> ret = new List<string>(); ret.Add(obj.Pairs["to"]); foreach (var kv in obj.Pairs) { if(kv.Key == "to") continue; ret.Add(kv.Key); ret.Add(kv.Value); } ret.AddRange(obj.Singles); return ret.ToArray(); } } }
apache-2.0
C#
5d877b1be9aabf7b1b4bb6a4d0c070848e845359
Use parser for parsing
awseward/Bugsnag.NET,awseward/Bugsnag.NET
lib/Bugsnag.Common/Extensions/CommonExtensions.cs
lib/Bugsnag.Common/Extensions/CommonExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Bugsnag.Common.Extensions { public static class CommonExtensions { public static IEnumerable<Exception> Unwrap(this Exception ex) { if (ex == null) { return Enumerable.Empty<Exception>(); } else if (ex.InnerException == null) { return new Exception[] { ex }; } return new Exception[] { ex }.Concat(ex.InnerException.Unwrap()); } public static IEnumerable<string> ToLines(this Exception ex) { if (ex == null || ex.StackTrace == null) { return new string[] { string.Empty }; } return ex.StackTrace.Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries ); } static StacktraceLineParser _stacktraceLineParser = new StacktraceLineParser(); public static string FileParseFailureDefaultValue = ""; public static string ParseFile(this string line) => _stacktraceLineParser.ParseFile(line); public static string ParseMethodName(this string line) => _stacktraceLineParser.ParseMethodName(line); public static int? ParseLineNumber(this string line) => _stacktraceLineParser.ParseLineNumber(line); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Bugsnag.Common.Extensions { public static class CommonExtensions { public static IEnumerable<Exception> Unwrap(this Exception ex) { if (ex == null) { return Enumerable.Empty<Exception>(); } else if (ex.InnerException == null) { return new Exception[] { ex }; } return new Exception[] { ex }.Concat(ex.InnerException.Unwrap()); } public static IEnumerable<string> ToLines(this Exception ex) { if (ex == null || ex.StackTrace == null) { return new string[] { string.Empty }; } return ex.StackTrace.Split( new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries ); } public static string FileParseFailureDefaultValue = ""; public static string ParseFile(this string line) { var match = Regex.Match(line, "in (.+):line"); if (match.Groups.Count < 2) { return FileParseFailureDefaultValue; } return match.Groups[1].Value; } public static string ParseMethodName(this string line) { // to extract the full method name (with namespace) var match = Regex.Match(line, "at ([^)]+[)])"); if (match.Groups.Count < 2) { return line; } return match.Groups[1].Value; } public static int? ParseLineNumber(this string line) { var match = Regex.Match(line, ":line ([0-9]+)"); if (match.Groups.Count < 2) { return null; } return Convert.ToInt32(match.Groups[1].Value); } } }
mit
C#
a9d190cd1f9c60ff06e9bbc4f88632cdd5027bec
Add retry when invoking the lazy to build TagDictionary
15below/Ensconce,BlythMeister/Ensconce,BlythMeister/Ensconce,15below/Ensconce
src/Ensconce/TextRendering.cs
src/Ensconce/TextRendering.cs
using System; using System.Collections.Generic; using System.IO; using FifteenBelow.Deployment.Update; namespace Ensconce { internal static class TextRendering { private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(() => Retry.Do(BuildTagDictionary, TimeSpan.FromSeconds(5))); public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } } internal static string Render(this string s) { return s.RenderTemplate(TagDictionary); } private static TagDictionary BuildTagDictionary() { Logging.Log("Building Tag Dictionary"); var instanceName = Environment.GetEnvironmentVariable("InstanceName"); Logging.Log("Building Tag Dictionary ({0})", instanceName); var tags = new TagDictionary(instanceName); Logging.Log("Built Tag Dictionary ({0})", instanceName); Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags); if (File.Exists(Arguments.FixedPath)) { Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath)); var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5)); Logging.Log("Re-Building Tag Dictionary (Using Config File)"); tags = new TagDictionary(instanceName, configXml); Logging.Log("Built Tag Dictionary (Using Config File)"); } else { Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath)); } return tags; } } }
using System; using System.Collections.Generic; using System.IO; using FifteenBelow.Deployment.Update; namespace Ensconce { internal static class TextRendering { private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(BuildTagDictionary); public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } } internal static string Render(this string s) { return s.RenderTemplate(LazyTags.Value); } private static TagDictionary BuildTagDictionary() { Logging.Log("Building Tag Dictionary"); var instanceName = Environment.GetEnvironmentVariable("InstanceName"); Logging.Log("Building Tag Dictionary ({0})", instanceName); var tags = new TagDictionary(instanceName); Logging.Log("Built Tag Dictionary ({0})", instanceName); Arguments.FixedPath = Arguments.FixedPath.RenderTemplate(tags); if (File.Exists(Arguments.FixedPath)) { Logging.Log("Loading xml config from file {0}", Path.GetFullPath(Arguments.FixedPath)); var configXml = Retry.Do(() => File.ReadAllText(Arguments.FixedPath), TimeSpan.FromSeconds(5)); Logging.Log("Re-Building Tag Dictionary (Using Config File)"); tags = new TagDictionary(instanceName, configXml); Logging.Log("Built Tag Dictionary (Using Config File)"); } else { Logging.Log("No structure file found at: {0}", Path.GetFullPath(Arguments.FixedPath)); } return tags; } } }
mit
C#
7562db4ebd4cc03c15506d617a0df7a1979c00a5
Change Pick 'position' property to int as it represents position in team
RagtimeWilly/FplClient
src/FplClient/Data/FplPick.cs
src/FplClient/Data/FplPick.cs
using Newtonsoft.Json; namespace FplClient.Data { public class FplPick { [JsonProperty("element")] public int PlayerId { get; set; } [JsonProperty("element_type")] public int ElementType { get; set; } [JsonProperty("position")] public int TeamPosition { get; set; } [JsonProperty("points")] public int Points { get; set; } [JsonProperty("can_captain")] public bool? CanCaptain { get; set; } [JsonProperty("is_captain")] public bool IsCaptain { get; set; } [JsonProperty("is_vice_captain")] public bool IsViceCaptain { get; set; } [JsonProperty("can_sub")] public bool? CanSub { get; set; } [JsonProperty("is_sub")] public bool IsSub { get; set; } [JsonProperty("has_played")] public bool HasPlayed { get; set; } [JsonProperty("stats")] public FplPickStats Stats { get; set; } [JsonProperty("multiplier")] public int Multiplier { get; set; } } }
using Newtonsoft.Json; namespace FplClient.Data { public class FplPick { [JsonProperty("element")] public int PlayerId { get; set; } [JsonProperty("element_type")] public int ElementType { get; set; } [JsonProperty("position")] public FplPlayerPosition Position { get; set; } [JsonProperty("points")] public int Points { get; set; } [JsonProperty("can_captain")] public bool? CanCaptain { get; set; } [JsonProperty("is_captain")] public bool IsCaptain { get; set; } [JsonProperty("is_vice_captain")] public bool IsViceCaptain { get; set; } [JsonProperty("can_sub")] public bool? CanSub { get; set; } [JsonProperty("is_sub")] public bool IsSub { get; set; } [JsonProperty("has_played")] public bool HasPlayed { get; set; } [JsonProperty("stats")] public FplPickStats Stats { get; set; } [JsonProperty("multiplier")] public int Multiplier { get; set; } } }
mit
C#
3ca36e3cbf13cc7f45d99a5b9e281119936a5d02
Support passing extras to gravatar helper
synhershko/NSemble,synhershko/NSemble
NSemble.Modules.Blog/Helpers/BlogPostHelpers.cs
NSemble.Modules.Blog/Helpers/BlogPostHelpers.cs
using System; using System.Security.Cryptography; using System.Text; using NSemble.Modules.Blog.Models; using Nancy.ViewEngines.Razor; namespace NSemble.Modules.Blog.Helpers { public static class BlogPostHelpers { public static IHtmlString Gravatar(this PostComments.Comment comment, int size, string extras = null) { var ret = string.Format(@"<img src=""http://www.gravatar.com/avatar.php?gravatar_id={0}&size={1}&default=identicon"" alt=""{2}"" style=""width: {1}px; height: {1}px;"" {3}>" , GetHashedEmail(comment.Email), size, comment.Author, extras); return new NonEncodedHtmlString(ret); } private static string GetHashedEmail(string email) { if (email == null) return null; var str = email.Trim().ToLowerInvariant(); return GetMd5Hash(str); } private static string GetMd5Hash(string input) { // Create a new Stringbuilder to collect the bytes // and create a string. var sBuilder = new StringBuilder(); // Create a new instance of the MD5CryptoServiceProvider object. using (var md5Hasher = MD5.Create()) { // Convert the input string to a byte array and compute the hash. var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (var i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } } return sBuilder.ToString(); // Return the hexadecimal string. } public const string WordPressTrackingCode = @"<script src=""http://stats.wordpress.com/e-201252.js"" type=""text/javascript""></script> <script type=""text/javascript""> st_go({blog:'{0}',v:'ext',post:'0'}); var load_cmc = function(){linktracker_init({0},0,2);}; if ( typeof addLoadEvent != 'undefined' ) addLoadEvent(load_cmc); else load_cmc(); </script>"; } }
using System; using System.Security.Cryptography; using System.Text; using NSemble.Modules.Blog.Models; using Nancy.ViewEngines.Razor; namespace NSemble.Modules.Blog.Helpers { public static class BlogPostHelpers { public static IHtmlString Gravatar(this PostComments.Comment comment, int size) { var ret = string.Format(@"<img src=""http://www.gravatar.com/avatar.php?gravatar_id={0}&size={1}&default=identicon"" alt=""{2}"" width=""{1}"" height=""{1}"">" , GetHashedEmail(comment.Email), size, comment.Author); return new NonEncodedHtmlString(ret); } private static string GetHashedEmail(string email) { if (email == null) return null; var str = email.Trim().ToLowerInvariant(); return GetMd5Hash(str); } private static string GetMd5Hash(string input) { // Create a new Stringbuilder to collect the bytes // and create a string. var sBuilder = new StringBuilder(); // Create a new instance of the MD5CryptoServiceProvider object. using (var md5Hasher = MD5.Create()) { // Convert the input string to a byte array and compute the hash. var data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input)); // Loop through each byte of the hashed data // and format each one as a hexadecimal string. for (var i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } } return sBuilder.ToString(); // Return the hexadecimal string. } public const string WordPressTrackingCode = @"<script src=""http://stats.wordpress.com/e-201252.js"" type=""text/javascript""></script> <script type=""text/javascript""> st_go({blog:'{0}',v:'ext',post:'0'}); var load_cmc = function(){linktracker_init({0},0,2);}; if ( typeof addLoadEvent != 'undefined' ) addLoadEvent(load_cmc); else load_cmc(); </script>"; } }
apache-2.0
C#
4d096fb5fc6a24d2d10869dac871316895598c7d
Allow visibility via InternalsVisibleTo
edpollitt/Nerdle.AutoConfig
Nerdle.AutoConfig/TypeGeneration/TypeEmitter.cs
Nerdle.AutoConfig/TypeGeneration/TypeEmitter.cs
using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using Nerdle.AutoConfig.Exceptions; namespace Nerdle.AutoConfig.TypeGeneration { class TypeEmitter : ITypeEmitter { public const string AssemblyName = "AutoConfig.DynamicTypes"; public Type GenerateInterfaceImplementation(Type interfaceType) { EnsureTypeSuitability(interfaceType); var assemblyName = new AssemblyName(AssemblyName); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); var baseClass = typeof(object); var typeBuilder = moduleBuilder.DefineType( "AutoConfig.DynamicTypes.Implementation_Of_" + interfaceType.FullName.Replace('.', '_'), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, baseClass, new[] { interfaceType }); return typeBuilder .EmitConstructor(baseClass.GetConstructor(Type.EmptyTypes)) .EmitProperties(interfaceType.GetProperties()) .EmitProperties(interfaceType.GetInterfaces().SelectMany(i => i.GetProperties())) .CreateType(); } static void EnsureTypeSuitability(Type type) { EnsureAccessible(type); EnsureMethodless(type); } static void EnsureAccessible(Type type) { if (type.IsVisible) return; var friendAssembly = type.Assembly.GetCustomAttributes(typeof(InternalsVisibleToAttribute), false) .Cast<InternalsVisibleToAttribute>().Any(attr => attr.AssemblyName == AssemblyName); if (!friendAssembly) throw new AutoConfigTypeGenerationException( string.Format("Cannot generate an implementation of interface '{0}' because it is not externally accessible. Change your interface access modifier to 'public' or add an 'InternalsVisibleTo(\"{1}\")' assembly attribute.", type, AssemblyName)); } static void EnsureMethodless(Type type) { if (type.GetMethods().Any(method => !method.IsSpecialName) || type.GetInterfaces().SelectMany(i => i.GetMethods()).Any(method => !method.IsSpecialName)) throw new AutoConfigTypeGenerationException( string.Format("Cannot generate an implementation of interface '{0}' because it contains method definitions.", type)); } } }
using System; using System.Linq; using System.Reflection; using System.Reflection.Emit; using Nerdle.AutoConfig.Exceptions; namespace Nerdle.AutoConfig.TypeGeneration { class TypeEmitter : ITypeEmitter { public const string AssemblyName = "AutoConfig.DynamicTypes"; //public Type GenerateInterfaceImplementation<TInterface>() //{ // return GenerateInterfaceImplementation(typeof(TInterface)); //} public Type GenerateInterfaceImplementation(Type interfaceType) { EnsureTypeSuitability(interfaceType); var assemblyName = new AssemblyName(AssemblyName); var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name); var baseClass = typeof(object); var typeBuilder = moduleBuilder.DefineType( "AutoConfig.DynamicTypes._Implementation_Of_" + interfaceType.FullName.Replace('.', '_'), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, baseClass, new[] { interfaceType }); return typeBuilder .EmitConstructor(baseClass.GetConstructor(Type.EmptyTypes)) .EmitProperties(interfaceType.GetProperties()) .EmitProperties(interfaceType.GetInterfaces().SelectMany(i => i.GetProperties())) .CreateType(); } static void EnsureTypeSuitability(Type type) { if (!type.IsVisible) throw new AutoConfigTypeGenerationException( string.Format("Cannot generate an implementation of interface '{0}' because it is not externally accessible. Your interface access modifier should be set to 'public'.", type)); if (type.GetMethods().Any(method => !method.IsSpecialName) || type.GetInterfaces().SelectMany(i => i.GetMethods()).Any(method => !method.IsSpecialName)) throw new AutoConfigTypeGenerationException( string.Format("Cannot generate an implementation of interface '{0}' because it contains method definitions.", type)); } } }
mit
C#
40c61a4c63dead02966851b4461ee799afef7408
update setting
Fires1/DestinySharp
DestinySharp.Console/DestinySharpProgram.cs
DestinySharp.Console/DestinySharpProgram.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DestinySharp.Core; namespace DestinySharp.Console { class DestinySharpProgram { private static readonly string Fullmetalfireflyapikey = ""; private static DestinyServiceExplorer _service; private static string MembershipId { get; set; } private static MembershipType MembershipType { get; set; } private static string DisplayName { get; set; } static void Main(string[] args) { System.Console.WriteLine("Hello Guardian! "); // FULLMETALFIREFLY TEST VARIABLES DisplayName = "vee_teh_neenja"; MembershipType = MembershipType.PSN; //MembershipId = "4611686018434269858"; _service = new DestinyServiceExplorer(Fullmetalfireflyapikey); // testing var results = _service.SearchDestinyPlayer(DisplayName, MembershipType); // display System.Console.WriteLine("Results: {0}", results.ToString()); System.Console.WriteLine("[ E N D ]"); System.Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DestinySharp.Core; namespace DestinySharp.Console { class DestinySharpProgram { private static readonly string Fullmetalfireflyapikey = "5e7d9ff231914e179c83dc778d4cdeaa"; private static DestinyServiceExplorer _service; private static string MembershipId { get; set; } private static MembershipType MembershipType { get; set; } private static string DisplayName { get; set; } static void Main(string[] args) { System.Console.WriteLine("Hello Guardian! "); // FULLMETALFIREFLY TEST VARIABLES DisplayName = "vee_teh_neenja"; MembershipType = MembershipType.PSN; //MembershipId = "4611686018434269858"; _service = new DestinyServiceExplorer(Fullmetalfireflyapikey); // testing var results = _service.SearchDestinyPlayer(DisplayName, MembershipType); // display System.Console.WriteLine("Results: {0}", results.ToString()); System.Console.WriteLine("[ E N D ]"); System.Console.ReadLine(); } } }
mit
C#
f5a4976f2813d9b6ca1a547c90db4469075853d2
Set version 0.8.3
jaenyph/DelegateDecompiler,hazzik/DelegateDecompiler,morgen2009/DelegateDecompiler
src/DelegateDecompiler/Properties/AssemblyInfo.cs
src/DelegateDecompiler/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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.3.0")] [assembly: AssemblyFileVersion("0.8.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("DelegateDecompiler")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DelegateDecompiler")] [assembly: AssemblyCopyright("Copyright © hazzik 2012 - 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cec0a257-502b-4718-91c3-9e67555c5e1b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.2.0")] [assembly: AssemblyFileVersion("0.8.2.0")]
mit
C#
3e48ca8d241b0c87bd38a192e8bb37fd3fc0a383
Add line breaks to ease filtering by individual game
feliwir/openSage,feliwir/openSage
src/OpenSage.Game.Tests/InstalledFilesTestData.cs
src/OpenSage.Game.Tests/InstalledFilesTestData.cs
using System; using System.IO; using System.Linq; using Xunit.Abstractions; namespace OpenSage.Data.Tests { internal static class InstalledFilesTestData { private static readonly IInstallationLocator Locator; static InstalledFilesTestData() { Locator = new RegistryInstallationLocator(); } public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).First().Path; public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback) { var rootDirectories = SageGames.GetAll() .SelectMany(Locator.FindInstallations) .Select(i => i.Path); var foundAtLeastOneFile = false; foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x))) { var fileSystem = new FileSystem(rootDirectory); foreach (var file in fileSystem.Files) { if (Path.GetExtension(file.FilePath).ToLower() != fileExtension) { continue; } output.WriteLine($"Reading file {file.FilePath}."); processFileCallback(file); foundAtLeastOneFile = true; } } if (!foundAtLeastOneFile) { throw new Exception($"No files were found matching file extension {fileExtension}"); } } } }
using System; using System.IO; using System.Linq; using Xunit.Abstractions; namespace OpenSage.Data.Tests { internal static class InstalledFilesTestData { private static readonly IInstallationLocator Locator; static InstalledFilesTestData() { Locator = new RegistryInstallationLocator(); } public static string GetInstallationDirectory(SageGame game) => Locator.FindInstallations(game).First().Path; public static void ReadFiles(string fileExtension, ITestOutputHelper output, Action<FileSystemEntry> processFileCallback) { var rootDirectories = SageGames.GetAll().SelectMany(Locator.FindInstallations).Select(i => i.Path); var foundAtLeastOneFile = false; foreach (var rootDirectory in rootDirectories.Where(x => Directory.Exists(x))) { var fileSystem = new FileSystem(rootDirectory); foreach (var file in fileSystem.Files) { if (Path.GetExtension(file.FilePath).ToLower() != fileExtension) { continue; } output.WriteLine($"Reading file {file.FilePath}."); processFileCallback(file); foundAtLeastOneFile = true; } } if (!foundAtLeastOneFile) { throw new Exception($"No files were found matching file extension {fileExtension}"); } } } }
mit
C#
0082640548d3e6cab5cdfbfe0ed2cb442511ccda
Add missing licence header
johnneijzen/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,Damnae/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,NeoAdonis/osu,naoey/osu,smoogipooo/osu,ZLima12/osu,peppy/osu-new,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,2yangk23/osu,UselessToucan/osu,ZLima12/osu,naoey/osu,Nabile-Rahmani/osu,peppy/osu,ppy/osu,smoogipoo/osu,Frontear/osuKyzer,DrabWeb/osu,peppy/osu,naoey/osu,johnneijzen/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,NeoAdonis/osu,Drezi126/osu
osu.Game/Overlays/Toolbar/ToolbarDirectButton.cs
osu.Game/Overlays/Toolbar/ToolbarDirectButton.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.Allocation; using osu.Game.Graphics; namespace osu.Game.Overlays.Toolbar { internal class ToolbarDirectButton : ToolbarOverlayToggleButton { public ToolbarDirectButton() { SetIcon(FontAwesome.fa_download); } [BackgroundDependencyLoader] private void load(DirectOverlay direct) { StateContainer = direct; } } }
using osu.Framework.Allocation; using osu.Game.Graphics; namespace osu.Game.Overlays.Toolbar { internal class ToolbarDirectButton : ToolbarOverlayToggleButton { public ToolbarDirectButton() { SetIcon(FontAwesome.fa_download); } [BackgroundDependencyLoader] private void load(DirectOverlay direct) { StateContainer = direct; } } }
mit
C#
5b446953ca03201de52d9db624bd197557ae527b
Disable warnings
skwasjer/SilentHunter
src/SilentHunter.FileFormats/Dat/AnimationType.cs
src/SilentHunter.FileFormats/Dat/AnimationType.cs
namespace SilentHunter.FileFormats.Dat { /// <summary> /// The animation types for which the are specific controllers. /// </summary> public enum AnimationType : ushort { #pragma warning disable 1591 AnimationObject = 0, // No count field PositionKeyFrames = 1, PositionKeyFrames2 = 0x8001, RotationKeyFrames = 2, RotationKeyFrames2 = 0x8002, KeyFrameAnimStartParams = 4, // No count field KeyFrameAnimStartParams2 = 0x8004, // No count field MeshAnimationData = 5, MeshAnimationData2 = 0x8005, TextureAnimationData = 6, TextureAnimationData2 = 0x8006, LightAnimation = 0x0200 #pragma warning restore 1591 } }
namespace SilentHunter.FileFormats.Dat { public enum AnimationType : ushort { AnimationObject = 0, // No count field PositionKeyFrames = 1, PositionKeyFrames2 = 0x8001, RotationKeyFrames = 2, RotationKeyFrames2 = 0x8002, KeyFrameAnimStartParams = 4, // No count field KeyFrameAnimStartParams2 = 0x8004, // No count field MeshAnimationData = 5, MeshAnimationData2 = 0x8005, TextureAnimationData = 6, TextureAnimationData2 = 0x8006, LightAnimation = 0x0200 } }
apache-2.0
C#
63318b63143f2e44db2c1d174a9dde9957afedd8
Remove unused class attributes
xavierfoucrier/gmail-notifier,xavierfoucrier/gmail-notifier
code/Core.cs
code/Core.cs
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using notifier.Properties; namespace notifier { static class Core { #region #attributes #endregion #region #methods /// <summary> /// Class constructor /// </summary> static Core() { // initialize the application version number, based on scheme Major.Minor.Build-Release string[] ProductVersion = Application.ProductVersion.Split('.'); string VersionMajor = ProductVersion[0]; string VersionMinor = ProductVersion[1]; string VersionRelease = ProductVersion[2]; string VersionBuild = ProductVersion[3]; Version = "v" + VersionMajor + "." + VersionMinor + (VersionBuild != "0" ? "." + VersionBuild : "") + "-" + (VersionRelease == "0" ? "alpha" : VersionRelease == "1" ? "beta" : VersionRelease == "2" ? "rc" : VersionRelease == "3" ? "release" : ""); } /// <summary> /// Restart the application /// </summary> public static void RestartApplication() { // start a new process Process.Start(new ProcessStartInfo("cmd.exe", "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"") { WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true }); // exit the application Application.Exit(); } /// <summary> /// Log a message to the application log file /// </summary> /// <param name="message">Message to log</param> public static void Log(string message) { using (StreamWriter writer = new StreamWriter(ApplicationDataFolder + "/" + Settings.Default.LOG_FILE, true)) { writer.Write(DateTime.Now + " - " + message + Environment.NewLine); } } #endregion #region #accessors /// <summary> /// Local application data folder name /// </summary> public static string ApplicationDataFolder { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/Gmail Notifier"; /// <summary> /// Full application version number /// </summary> public static string Version { get; set; } = ""; #endregion } }
using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using notifier.Properties; namespace notifier { static class Core { #region #attributes /// <summary> /// Major version number /// </summary> private static readonly string VersionMajor = ""; /// <summary> /// Minor version number /// </summary> private static readonly string VersionMinor = ""; /// <summary> /// Release version number /// </summary> private static readonly string VersionRelease = ""; /// <summary> /// Build version number /// </summary> private static readonly string VersionBuild = ""; #endregion #region #methods /// <summary> /// Class constructor /// </summary> static Core() { // initialize the application version number, based on scheme Major.Minor.Build-Release string[] ProductVersion = Application.ProductVersion.Split('.'); VersionMajor = ProductVersion[0]; VersionMinor = ProductVersion[1]; VersionRelease = ProductVersion[2]; VersionBuild = ProductVersion[3]; Version = "v" + VersionMajor + "." + VersionMinor + (VersionBuild != "0" ? "." + VersionBuild : "") + "-" + (VersionRelease == "0" ? "alpha" : VersionRelease == "1" ? "beta" : VersionRelease == "2" ? "rc" : VersionRelease == "3" ? "release" : ""); } /// <summary> /// Restart the application /// </summary> public static void RestartApplication() { // start a new process Process.Start(new ProcessStartInfo("cmd.exe", "/C ping 127.0.0.1 -n 2 && \"" + Application.ExecutablePath + "\"") { WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true }); // exit the application Application.Exit(); } /// <summary> /// Log a message to the application log file /// </summary> /// <param name="message">Message to log</param> public static void Log(string message) { using (StreamWriter writer = new StreamWriter(ApplicationDataFolder + "/" + Settings.Default.LOG_FILE, true)) { writer.Write(DateTime.Now + " - " + message + Environment.NewLine); } } #endregion #region #accessors /// <summary> /// Local application data folder name /// </summary> public static string ApplicationDataFolder { get; set; } = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "/Gmail Notifier"; /// <summary> /// Full application version number /// </summary> public static string Version { get; set; } = ""; #endregion } }
mit
C#
04f2872de8f689ffbc57a94a7566250944546f45
Fix formatting
vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/VkShaderModule.cs
CSGL.Vulkan/VkShaderModule.cs
using System; using System.Collections.Generic; using System.IO; namespace CSGL.Vulkan { public class VkShaderModuleCreateInfo { public IList<byte> data; } public class VkShaderModule : IDisposable, INative<Unmanaged.VkShaderModule> { Unmanaged.VkShaderModule shaderModule; bool disposed = false; public VkDevice Device { get; private set; } public Unmanaged.VkShaderModule Native { get { return shaderModule; } } public VkShaderModule(VkDevice device, VkShaderModuleCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; CreateShader(info); } void CreateShader(VkShaderModuleCreateInfo mInfo) { if (mInfo.data == null) throw new ArgumentNullException(nameof(mInfo.data)); var info = new Unmanaged.VkShaderModuleCreateInfo(); info.sType = VkStructureType.ShaderModuleCreateInfo; info.codeSize = (IntPtr)mInfo.data.Count; var dataNative = new NativeArray<byte>(mInfo.data); info.pCode = dataNative.Address; using (dataNative) { var result = Device.Commands.createShaderModule(Device.Native, ref info, Device.Instance.AllocationCallbacks, out shaderModule); if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}")); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyShaderModule(Device.Native, shaderModule, Device.Instance.AllocationCallbacks); disposed = true; } ~VkShaderModule() { Dispose(false); } } public class ShaderModuleException : VulkanException { public ShaderModuleException(VkResult result, string message) : base(result, message) { } } }
using System; using System.Collections.Generic; using System.IO; namespace CSGL.Vulkan { public class VkShaderModuleCreateInfo { public IList<byte> data; } public class VkShaderModule : IDisposable, INative<Unmanaged.VkShaderModule> { Unmanaged.VkShaderModule shaderModule; bool disposed = false; public VkDevice Device { get; private set; } public Unmanaged.VkShaderModule Native { get { return shaderModule; } } public VkShaderModule(VkDevice device, VkShaderModuleCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); if (info == null) throw new ArgumentNullException(nameof(info)); Device = device; CreateShader(info); } void CreateShader(VkShaderModuleCreateInfo mInfo) { if (mInfo.data == null) throw new ArgumentNullException(nameof(mInfo.data)); var info = new Unmanaged.VkShaderModuleCreateInfo(); info.sType = VkStructureType.ShaderModuleCreateInfo; info.codeSize = (IntPtr)mInfo.data.Count; var dataPinned = new NativeArray<byte>(mInfo.data); info.pCode = dataPinned.Address; using (dataPinned) { var result = Device.Commands.createShaderModule(Device.Native, ref info, Device.Instance.AllocationCallbacks, out shaderModule); if (result != VkResult.Success) throw new ShaderModuleException(result, string.Format("Error creating shader module: {0}")); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyShaderModule(Device.Native, shaderModule, Device.Instance.AllocationCallbacks); disposed = true; } ~VkShaderModule() { Dispose(false); } } public class ShaderModuleException : VulkanException { public ShaderModuleException(VkResult result, string message) : base(result, message) { } } }
mit
C#
c516357d995a0e9629a90a32132a32350dc09cc0
Disable soundtrack extract text
villermen/runescape-cache-tools,villermen/runescape-cache-tools
RuneScapeCacheToolsTests/SoundtrackTests.cs
RuneScapeCacheToolsTests/SoundtrackTests.cs
using System; using System.IO; using System.Linq; using RuneScapeCacheToolsTests.Fixtures; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { [Collection("TestCache")] public class SoundtrackTests { private ITestOutputHelper Output { get; } private CacheFixture Fixture { get; } public SoundtrackTests(ITestOutputHelper output, CacheFixture fixture) { Output = output; Fixture = fixture; } /// <summary> /// Soundtrack names must be retrievable. /// /// Checks if GetTrackNames returns a track with name "Soundscape". /// </summary> [Fact] public void TestGetTrackNames() { var trackNames = Fixture.Soundtrack.GetTrackNames(); Output.WriteLine($"Amount of track names: {trackNames.Count}"); Assert.True(trackNames.Any(trackNamePair => trackNamePair.Value == "Soundscape"), "\"Soundscape\" did not occur in the list of track names."); } [Fact(Skip = "Doesn't work properly on Linux with oggCat")] public void TestExtract() { var startTime = DateTime.UtcNow; Fixture.Soundtrack.Extract(true, "soundscape"); const string expectedOutputPath = "output/soundtrack/Soundscape.ogg"; // Verify that Soundscape.ogg has been created Assert.True(File.Exists(expectedOutputPath), "Soundscape.ogg should've been created during extraction."); // Verify that it has been created during this test var modifiedTime = File.GetLastWriteTimeUtc(expectedOutputPath); Assert.True(modifiedTime >= startTime, "Soundscape.ogg's modiied time was not updated during extraction (so probably was not extracted)."); var version = Fixture.Soundtrack.GetVersionFromExportedTrackFile("output/soundtrack/Soundscape.ogg"); Assert.True(version > -1, "Version of Soundscape.ogg was not set."); } } }
using System; using System.IO; using System.Linq; using RuneScapeCacheToolsTests.Fixtures; using Xunit; using Xunit.Abstractions; namespace RuneScapeCacheToolsTests { [Collection("TestCache")] public class SoundtrackTests { private ITestOutputHelper Output { get; } private CacheFixture Fixture { get; } public SoundtrackTests(ITestOutputHelper output, CacheFixture fixture) { Output = output; Fixture = fixture; } /// <summary> /// Soundtrack names must be retrievable. /// /// Checks if GetTrackNames returns a track with name "Soundscape". /// </summary> [Fact] public void TestGetTrackNames() { var trackNames = Fixture.Soundtrack.GetTrackNames(); Output.WriteLine($"Amount of track names: {trackNames.Count}"); Assert.True(trackNames.Any(trackNamePair => trackNamePair.Value == "Soundscape"), "\"Soundscape\" did not occur in the list of track names."); } [Fact] public void TestExtract() { var startTime = DateTime.UtcNow; Fixture.Soundtrack.Extract(true, "soundscape"); const string expectedOutputPath = "output/soundtrack/Soundscape.ogg"; // Verify that Soundscape.ogg has been created Assert.True(File.Exists(expectedOutputPath), "Soundscape.ogg should've been created during extraction."); // Verify that it has been created during this test var modifiedTime = File.GetLastWriteTimeUtc(expectedOutputPath); Assert.True(modifiedTime >= startTime, "Soundscape.ogg's modiied time was not updated during extraction (so probably was not extracted)."); var version = Fixture.Soundtrack.GetVersionFromExportedTrackFile("output/soundtrack/Soundscape.ogg"); Assert.True(version > -1, "Version of Soundscape.ogg was not set."); } } }
mit
C#
d057fa9b7681fb852a6806054aed66fab6314a1e
Remove duplication of '10'.
alastairs/tdd-by-example
part-1/MultiCurrencyMoney/MultiCurrencyMoney/Dollar.cs
part-1/MultiCurrencyMoney/MultiCurrencyMoney/Dollar.cs
namespace MultiCurrencyMoney { public class Dollar { public Dollar(int i) { } public int Amount { get; set; } public void Times(int i) { Amount = 5 * 2; } } }
namespace MultiCurrencyMoney { public class Dollar { public Dollar(int i) { } public int Amount { get { return 10; } } public void Times(int i) { } } }
unlicense
C#
bd533eec03e5fab7de49c828c43aa2649623f5ca
Fix first Mono/RPi failure (skip the test).
zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,nodatime/nodatime,nodatime/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,jskeet/nodatime,jskeet/nodatime,malcolmr/nodatime,malcolmr/nodatime
src/NodaTime.Test/TimeZones/BclDateTimeZoneSourceTest.cs
src/NodaTime.Test/TimeZones/BclDateTimeZoneSourceTest.cs
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2012 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Linq; using NUnit.Framework; using NodaTime.TimeZones; namespace NodaTime.Test.TimeZones { [TestFixture] public class BclDateTimeZoneSourceTest { [Test] public void AllZonesMapToTheirId() { BclDateTimeZoneSource source = new BclDateTimeZoneSource(); foreach (var zone in TimeZoneInfo.GetSystemTimeZones()) { Assert.AreEqual(zone.Id, source.MapTimeZoneId(zone)); } } [Test] public void UtcDoesNotEqualBuiltIn() { var zone = new BclDateTimeZoneSource().ForId("UTC"); Assert.AreNotEqual(DateTimeZone.Utc, zone); } [Test] public void FixedOffsetDoesNotEqualBuiltIn() { // Only a few fixed zones are advertised by Windows. We happen to know this one // is wherever we run tests :) // Unfortunately, it doesn't always exist on Mono (at least not on the Rasperry Pi...) if (TestHelper.IsRunningOnMono) { return; } string id = "UTC-02"; var source = new BclDateTimeZoneSource(); Assert.Contains(id, source.GetIds().ToList()); var zone = source.ForId(id); Assert.AreNotEqual(DateTimeZone.ForOffset(Offset.FromHours(-2)), zone); Assert.AreEqual(id, zone.Id); Assert.AreEqual(Offset.FromHours(-2), zone.GetZoneInterval(NodaConstants.UnixEpoch).WallOffset); } } }
#region Copyright and license information // Copyright 2001-2009 Stephen Colebourne // Copyright 2009-2012 Jon Skeet // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Linq; using NUnit.Framework; using NodaTime.TimeZones; namespace NodaTime.Test.TimeZones { [TestFixture] public class BclDateTimeZoneSourceTest { [Test] public void AllZonesMapToTheirId() { BclDateTimeZoneSource source = new BclDateTimeZoneSource(); foreach (var zone in TimeZoneInfo.GetSystemTimeZones()) { Assert.AreEqual(zone.Id, source.MapTimeZoneId(zone)); } } [Test] public void UtcDoesNotEqualBuiltIn() { var zone = new BclDateTimeZoneSource().ForId("UTC"); Assert.AreNotEqual(DateTimeZone.Utc, zone); } [Test] public void FixedOffsetDoesNotEqualBuiltIn() { // Only a few fixed zones are advertised by Windows. We happen to know this one // is wherever we run tests :) string id = "UTC-02"; var source = new BclDateTimeZoneSource(); Assert.Contains(id, source.GetIds().ToList()); var zone = source.ForId(id); Assert.AreNotEqual(DateTimeZone.ForOffset(Offset.FromHours(-2)), zone); Assert.AreEqual(id, zone.Id); Assert.AreEqual(Offset.FromHours(-2), zone.GetZoneInterval(NodaConstants.UnixEpoch).WallOffset); } } }
apache-2.0
C#
29612a03fa71918b1363a3fcb1d61cf22cdc1f4d
Replace Enumerable.Repeat call with an one-element array.
alluran/node.net,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,mrward/nuget,xoofx/NuGet,OneGet/nuget,themotleyfool/NuGet,alluran/node.net,atheken/nuget,jholovacs/NuGet,jholovacs/NuGet,jholovacs/NuGet,OneGet/nuget,jmezach/NuGet2,mono/nuget,mrward/NuGet.V2,anurse/NuGet,akrisiun/NuGet,xoofx/NuGet,xoofx/NuGet,jmezach/NuGet2,rikoe/nuget,GearedToWar/NuGet2,oliver-feng/nuget,antiufo/NuGet2,zskullz/nuget,mono/nuget,oliver-feng/nuget,ctaggart/nuget,antiufo/NuGet2,jmezach/NuGet2,pratikkagda/nuget,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,akrisiun/NuGet,GearedToWar/NuGet2,pratikkagda/nuget,GearedToWar/NuGet2,zskullz/nuget,jmezach/NuGet2,rikoe/nuget,dolkensp/node.net,mrward/NuGet.V2,mrward/nuget,mrward/NuGet.V2,indsoft/NuGet2,jholovacs/NuGet,kumavis/NuGet,mono/nuget,RichiCoder1/nuget-chocolatey,kumavis/NuGet,mrward/nuget,themotleyfool/NuGet,xoofx/NuGet,indsoft/NuGet2,jholovacs/NuGet,mrward/nuget,chocolatey/nuget-chocolatey,xoofx/NuGet,mono/nuget,indsoft/NuGet2,GearedToWar/NuGet2,jmezach/NuGet2,chester89/nugetApi,themotleyfool/NuGet,chester89/nugetApi,xero-github/Nuget,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,mrward/NuGet.V2,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,oliver-feng/nuget,antiufo/NuGet2,antiufo/NuGet2,oliver-feng/nuget,pratikkagda/nuget,dolkensp/node.net,dolkensp/node.net,jholovacs/NuGet,antiufo/NuGet2,pratikkagda/nuget,indsoft/NuGet2,alluran/node.net,oliver-feng/nuget,zskullz/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,xoofx/NuGet,chocolatey/nuget-chocolatey,mrward/nuget,GearedToWar/NuGet2,dolkensp/node.net,rikoe/nuget,ctaggart/nuget,ctaggart/nuget,atheken/nuget,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,alluran/node.net,zskullz/nuget,mrward/nuget,OneGet/nuget,GearedToWar/NuGet2,ctaggart/nuget,OneGet/nuget,anurse/NuGet,mrward/NuGet.V2,rikoe/nuget,chocolatey/nuget-chocolatey,indsoft/NuGet2,antiufo/NuGet2
src/VisualStudio/PackageSource/AggregatePackageSource.cs
src/VisualStudio/PackageSource/AggregatePackageSource.cs
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return new[] { Instance }.Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
using System.Collections.Generic; using System.Linq; namespace NuGet.VisualStudio { public static class AggregatePackageSource { public static readonly PackageSource Instance = new PackageSource("(Aggregate source)", Resources.VsResources.AggregateSourceName); public static bool IsAggregate(this PackageSource source) { return source == Instance; } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate(this IPackageSourceProvider provider) { return Enumerable.Repeat(Instance, 1).Concat(provider.LoadPackageSources()); } public static IEnumerable<PackageSource> GetPackageSourcesWithAggregate() { return GetPackageSourcesWithAggregate(ServiceLocator.GetInstance<IVsPackageSourceProvider>()); } } }
apache-2.0
C#
f3de9261e536d01e15811cd75d903b8f4b7386bc
Update RoslynScriptRunner.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D/ScriptRunner/Roslyn/RoslynScriptRunner.cs
src/Core2D/ScriptRunner/Roslyn/RoslynScriptRunner.cs
#if !_CORERT using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; namespace Core2D.ScriptRunner.Roslyn { /// <summary> /// Roslyn C# script runner. /// </summary> public class RoslynScriptRunner : IScriptRunner { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="RoslynScriptRunner"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public RoslynScriptRunner(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<object> Execute(string code, object state) { try { if (state is ScriptState<object> previousState) { return await previousState.ContinueWithAsync(code); } var options = ScriptOptions.Default.WithImports("System"); var editor = _serviceProvider.GetService<IProjectEditor>(); return await CSharpScript.RunAsync(code, options, editor); } catch (CompilationErrorException ex) { var log = _serviceProvider.GetService<ILog>(); log?.LogException(ex); log?.LogError($"{Environment.NewLine}{ex.Diagnostics}"); } return null; } } } #endif
#if !_CORERT using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; namespace Core2D.ScriptRunner.Roslyn { /// <summary> /// Roslyn C# script runner. /// </summary> public class RoslynScriptRunner : IScriptRunner { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="RoslynScriptRunner"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public RoslynScriptRunner(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<object> Execute(string code) { var options = ScriptOptions.Default .WithImports("System"); try { var editor = _serviceProvider.GetService<IProjectEditor>(); return await CSharpScript.RunAsync(code, options, editor); } catch (CompilationErrorException ex) { var log = _serviceProvider.GetService<ILog>(); log?.LogException(ex); log?.LogError($"{Environment.NewLine}{ex.Diagnostics}"); } return null; } /// <inheritdoc/> public async Task<object> Execute(string code, object state) { if (state is ScriptState<object> previous) { try { return await previous.ContinueWithAsync(code); } catch (CompilationErrorException ex) { var log = _serviceProvider.GetService<ILog>(); log?.LogException(ex); log?.LogError($"{Environment.NewLine}{ex.Diagnostics}"); } } var options = ScriptOptions.Default .WithImports("System"); try { var editor = _serviceProvider.GetService<IProjectEditor>(); return await CSharpScript.RunAsync(code, options, editor); } catch (CompilationErrorException ex) { var log = _serviceProvider.GetService<ILog>(); log?.LogException(ex); log?.LogError($"{Environment.NewLine}{ex.Diagnostics}"); } return null; } } } #endif
mit
C#
709672c07146adead6e2184e0753b9b06c3c51f1
Add comments to explain how to use this
mavasani/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn
src/EditorFeatures/Core/Logging/FunctionIdOptions.cs
src/EditorFeatures/Core/Logging/FunctionIdOptions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Collections.Concurrent; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Internal.Log { internal static class FunctionIdOptions { private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options = new(); private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption; private static Option2<bool> CreateOption(FunctionId id) { var name = id.ToString(); // This local storage location can be set via vsregedit. Which is available on any VS Command Prompt. // // To enable logging: // // vsregedit set local [hive name] HKCU Roslyn\Internal\Performance\FunctionId [function name] dword 1 // // To disable logging // // vsregedit delete local [hive name] HKCU Roslyn\Internal\Performance\FunctionId [function name] // // If you want to set it for the default hive, use "" as the hive name (i.e. an empty argument) return new(nameof(FunctionIdOptions), name, defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name)); } private static IEnumerable<FunctionId> GetFunctionIds() => Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>(); public static IEnumerable<IOption> GetOptions() => GetFunctionIds().Select(GetOption); public static Option2<bool> GetOption(FunctionId id) => s_options.GetOrAdd(id, s_optionCreator); public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions) { var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id))); return functionId => functionIdOptions[functionId]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Collections.Concurrent; using Microsoft.CodeAnalysis.Options; using Roslyn.Utilities; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Internal.Log { internal static class FunctionIdOptions { private static readonly ConcurrentDictionary<FunctionId, Option2<bool>> s_options = new(); private static readonly Func<FunctionId, Option2<bool>> s_optionCreator = CreateOption; private static Option2<bool> CreateOption(FunctionId id) { var name = id.ToString(); return new(nameof(FunctionIdOptions), name, defaultValue: false, storageLocation: new LocalUserProfileStorageLocation(@"Roslyn\Internal\Performance\FunctionId\" + name)); } private static IEnumerable<FunctionId> GetFunctionIds() => Enum.GetValues(typeof(FunctionId)).Cast<FunctionId>(); public static IEnumerable<IOption> GetOptions() => GetFunctionIds().Select(GetOption); public static Option2<bool> GetOption(FunctionId id) => s_options.GetOrAdd(id, s_optionCreator); public static Func<FunctionId, bool> CreateFunctionIsEnabledPredicate(IGlobalOptionService globalOptions) { var functionIdOptions = GetFunctionIds().ToDictionary(id => id, id => globalOptions.GetOption(GetOption(id))); return functionId => functionIdOptions[functionId]; } } }
mit
C#
7f5a5d0527d9757b40ad1ff338eb6a3d93cad701
fix constructor
isukces/isukces.UnitedValues
app/iSukces.UnitedValues/_other/Pressure.cs
app/iSukces.UnitedValues/_other/Pressure.cs
namespace iSukces.UnitedValues { public partial struct Pressure { public Pressure(decimal value, ForceUnit force, AreaUnit area) { var areaValue = new Area(1, area) .ConvertTo(AreaUnits.SquareMeter); var forceValue = new Force(value, force) .ConvertTo(ForceUnits.Newton); Value = forceValue.Value / areaValue.Value; Unit = PressureUnits.Pascal; } } }
namespace iSukces.UnitedValues { public partial struct Pressure { public Pressure(decimal value, ForceUnit force, AreaUnit area) { var areaSqM = new Area(1, area).ConvertTo(AreaUnits.SquareMeter); Unit = PressureUnits.Pascal; Value = value / areaSqM.Value; } } }
mit
C#
56a4f1a8082de6d7b784bca0f6b4d8b307c985e7
test commit
shuyunyun-flora/GameProgramming
ConsoleApplication1/ConsoleApplication1/Program.cs
ConsoleApplication1/ConsoleApplication1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine(); Console.WriteLine("Hello, World again!"); Console.WriteLine("Hello, World again!"); Console.WriteLine("Hello, World again!"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello, World!"); Console.WriteLine(); Console.WriteLine("Hello, World again!"); } } }
mit
C#
a12a2e426d756f50c1ba0e87691db0b53c8be2db
Add integration tests for MalUserNotFoundException being thrown.
LHCGreg/mal-api,LHCGreg/mal-api
MalApi.IntegrationTests/GetAnimeListForUserTest.cs
MalApi.IntegrationTests/GetAnimeListForUserTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using MalApi; using System.Threading.Tasks; namespace MalApi.IntegrationTests { [TestFixture] public class GetAnimeListForUserTest { [Test] public void GetAnimeListForUser() { string username = "lordhighcaptain"; using (MyAnimeListApi api = new MyAnimeListApi()) { MalUserLookupResults userLookup = api.GetAnimeListForUser(username); // Just a smoke test that checks that getting an anime list returns something Assert.That(userLookup.AnimeList, Is.Not.Empty); } } [Test] public void GetAnimeListForNonexistentUserThrowsCorrectException() { using (MyAnimeListApi api = new MyAnimeListApi()) { Assert.Throws<MalUserNotFoundException>(() => api.GetAnimeListForUser("oijsfjisfdjfsdojpfsdp")); } } [Test] public void GetAnimeListForNonexistentUserThrowsCorrectExceptionAsync() { using (MyAnimeListApi api = new MyAnimeListApi()) { Assert.ThrowsAsync<MalUserNotFoundException>(() => api.GetAnimeListForUserAsync("oijsfjisfdjfsdojpfsdp")); } } } } /* Copyright 2017 Greg Najda Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using MalApi; namespace MalApi.IntegrationTests { [TestFixture] public class GetAnimeListForUserTest { [Test] public void GetAnimeListForUser() { string username = "lordhighcaptain"; using (MyAnimeListApi api = new MyAnimeListApi()) { MalUserLookupResults userLookup = api.GetAnimeListForUser(username); // Just a smoke test that checks that getting an anime list returns something Assert.That(userLookup.AnimeList, Is.Not.Empty); } } } } /* Copyright 2012 Greg Najda 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. */
apache-2.0
C#
86a126d7829f526b799f82851181b4a158b6315f
Resolve conflicts
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Models/ObservableConcurrentHashSet.cs
WalletWasabi/Models/ObservableConcurrentHashSet.cs
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace WalletWasabi.Models { public class ObservableConcurrentHashSet<T> : IReadOnlyCollection<T>, INotifyCollectionChanged, IObservable<T> { private ConcurrentHashSet<T> Set { get; } private object Lock { get; } public event EventHandler HashSetChanged; public event NotifyCollectionChangedEventHandler CollectionChanged; public ObservableConcurrentHashSet() { Set = new ConcurrentHashSet<T>(); Lock = new object(); } // Don't lock here, it results deadlock at wallet loading when filters arent synced. public int Count => Set.Count; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // Don't lock here, it results deadlock at wallet loading when filters arent synced. public IEnumerator<T> GetEnumerator() => Set.GetEnumerator(); public bool TryAdd(T item) { lock (Lock) { if (Set.TryAdd(item)) { HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, new[] { item })); return true; } return false; } } public bool TryRemove(T item) { lock (Lock) { if (Set.TryRemove(item)) { HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new[] { item })); return true; } return false; } } public void Clear() { lock (Lock) { if (Set.Count > 0) { Set.Clear(); HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } // Don't lock here, it results deadlock at wallet loading when filters arent synced. public bool Contains(T item) => Set.Contains(item); public IDisposable Subscribe(IObserver<T> observer) { throw new NotImplementedException(); } } }
using ConcurrentCollections; using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; namespace WalletWasabi.Models { public class ObservableConcurrentHashSet<T> : IReadOnlyCollection<T>,INotifyCollectionChanged, IObservable<T>// DO NOT IMPLEMENT INotifyCollectionChanged!!! That'll break and crash the software: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863 { private ConcurrentHashSet<T> Set { get; } private object Lock { get; } public event EventHandler HashSetChanged; // Keep it as is! Unless with the modification this bug won't come out: https://github.com/AvaloniaUI/Avalonia/issues/1988#issuecomment-431691863 public event NotifyCollectionChangedEventHandler CollectionChanged; public ObservableConcurrentHashSet() { Set = new ConcurrentHashSet<T>(); Lock = new object(); } // Don't lock here, it results deadlock at wallet loading when filters arent synced. public int Count => Set.Count; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); // Don't lock here, it results deadlock at wallet loading when filters arent synced. public IEnumerator<T> GetEnumerator() => Set.GetEnumerator(); public bool TryAdd(T item) { lock (Lock) { if (Set.Add(item)) { HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add,new[] {item})); return true; } return false; } } public bool TryRemove(T item) { lock (Lock) { if (Set.TryRemove(item)) { HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, new[] { item })); return true; } return false; } } public void Clear() { lock (Lock) { if (Set.Count > 0) { Set.Clear(); HashSetChanged?.Invoke(this, EventArgs.Empty); CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } } } // Don't lock here, it results deadlock at wallet loading when filters arent synced. public bool Contains(T item) => Set.Contains(item); public IDisposable Subscribe(IObserver<T> observer) { throw new NotImplementedException(); } } }
mit
C#
5408659d0e35ab7f7cdc28ab4810787b2e91ba11
Update AssemblyInfo.cs
rajfidel/appium-dotnet-driver,appium/appium-dotnet-driver,rajfidel/appium-dotnet-driver,Brillio/appium-dotnet-driver,suryarend/appium-dotnet-driver,Astro03/appium-dotnet-driver
appium-dotnet-driver/Properties/AssemblyInfo.cs
appium-dotnet-driver/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("appium-dotnet-driver")] [assembly: AssemblyDescription ("Appium Dotnet Driver")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Appium Contributors")] [assembly: AssemblyProduct ("Appium-Dotnet-Driver")] [assembly: AssemblyCopyright ("Copyright © 2014")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.2.0.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 ("appium-dotnet-driver")] [assembly: AssemblyDescription ("Appium Dotnet Driver")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("Appium Contributors")] [assembly: AssemblyProduct ("Appium-Dotnet-Driver")] [assembly: AssemblyCopyright ("Copyright © 2014")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0.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("")]
apache-2.0
C#
997cdfaee42ebb67e15bc0bcbe1162c89b0bbe6c
Add missing licence header
ppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,EVAST9919/osu,ZLima12/osu,naoey/osu,smoogipoo/osu,EVAST9919/osu,naoey/osu,ppy/osu,naoey/osu,Nabile-Rahmani/osu,peppy/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,johnneijzen/osu,UselessToucan/osu,2yangk23/osu,DrabWeb/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu,ppy/osu,peppy/osu-new,ZLima12/osu,Frontear/osuKyzer
osu.Game.Rulesets.Catch/Tests/TestCaseHyperdash.cs
osu.Game.Rulesets.Catch/Tests/TestCaseHyperdash.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] [Ignore("getting CI working")] public class TestCaseHyperdash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperdash() : base(typeof(CatchRuleset)) { } protected override Beatmap CreateBeatmap() { var beatmap = new Beatmap(); for (int i = 0; i < 512; i++) if (i % 5 < 3) beatmap.HitObjects.Add(new Fruit { X = i % 10 < 5 ? 0.02f : 0.98f, StartTime = i * 100, NewCombo = i % 8 == 0 }); return beatmap; } } }
using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] [Ignore("getting CI working")] public class TestCaseHyperdash : Game.Tests.Visual.TestCasePlayer { public TestCaseHyperdash() : base(typeof(CatchRuleset)) { } protected override Beatmap CreateBeatmap() { var beatmap = new Beatmap(); for (int i = 0; i < 512; i++) if (i % 5 < 3) beatmap.HitObjects.Add(new Fruit { X = i % 10 < 5 ? 0.02f : 0.98f, StartTime = i * 100, NewCombo = i % 8 == 0 }); return beatmap; } } }
mit
C#
f574e0611d15ec65255a86ed585f5602a1a90ac2
Fix debug output
aNutForAJarOfTuna/kafka-net,Jroland/kafka-net,EranOfer/KafkaNetClient,CenturyLinkCloud/kafka-net,gigya/KafkaNetClient,nightkid1027/kafka-net,PKRoma/kafka-net,bridgewell/kafka-net,martijnhoekstra/kafka-net,geffzhang/kafka-net,BDeus/KafkaNetClient
src/kafka-net/Default/DefaultKafkaConnectionFactory.cs
src/kafka-net/Default/DefaultKafkaConnectionFactory.cs
using System; using System.Linq; using System.Net; using System.Net.Sockets; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultKafkaConnectionFactory : IKafkaConnectionFactory { public IKafkaConnection Create(Uri kafkaAddress, int responseTimeoutMs, IKafkaLog log) { return new KafkaConnection(new KafkaTcpSocket(log, Resolve(kafkaAddress, log)), responseTimeoutMs, log); } public KafkaEndpoint Resolve(Uri kafkaAddress, IKafkaLog log) { var ipAddress = GetFirstAddress(kafkaAddress.Host, log); var ipEndpoint = new IPEndPoint(ipAddress, kafkaAddress.Port); var kafkaEndpoint = new KafkaEndpoint() { ServeUri = kafkaAddress, Endpoint = ipEndpoint }; return kafkaEndpoint; } private static IPAddress GetFirstAddress(string hostname, IKafkaLog log) { //lookup the IP address from the provided host name var addresses = Dns.GetHostAddresses(hostname); if (addresses.Length > 0) { Array.ForEach(addresses, address => log.DebugFormat("Found address {0} for {1}", address, hostname)); var selectedAddress = addresses.FirstOrDefault(item => item.AddressFamily == AddressFamily.InterNetwork) ?? addresses.First(); log.DebugFormat("Using address {0} for {1}", selectedAddress, hostname); return selectedAddress; } throw new UnresolvedHostnameException("Could not resolve the following hostname: {0}", hostname); } } }
using System; using System.Linq; using System.Net; using System.Net.Sockets; using KafkaNet.Model; using KafkaNet.Protocol; namespace KafkaNet { public class DefaultKafkaConnectionFactory : IKafkaConnectionFactory { public IKafkaConnection Create(Uri kafkaAddress, int responseTimeoutMs, IKafkaLog log) { return new KafkaConnection(new KafkaTcpSocket(log, Resolve(kafkaAddress, log)), responseTimeoutMs, log); } public KafkaEndpoint Resolve(Uri kafkaAddress, IKafkaLog log) { var ipAddress = GetFirstAddress(kafkaAddress.Host, log); var ipEndpoint = new IPEndPoint(ipAddress, kafkaAddress.Port); var kafkaEndpoint = new KafkaEndpoint() { ServeUri = kafkaAddress, Endpoint = ipEndpoint }; return kafkaEndpoint; } private static IPAddress GetFirstAddress(string hostname, IKafkaLog log) { //lookup the IP address from the provided host name var addresses = Dns.GetHostAddresses(hostname); if (addresses.Length > 0) { Array.ForEach(addresses, address => log.DebugFormat("Found address {0} for {1}", addresses, hostname)); var selectedAddress = addresses.FirstOrDefault(item => item.AddressFamily == AddressFamily.InterNetwork) ?? addresses.First(); log.DebugFormat("Using address {0} for {1}", selectedAddress, hostname); return selectedAddress; } throw new UnresolvedHostnameException("Could not resolve the following hostname: {0}", hostname); } } }
apache-2.0
C#
561a3cdced1e30aefb429930724e37ba5e99c7c9
upgrade equeue version.
tangxuehua/equeue,tangxuehua/equeue,geffzhang/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue,Aaron-Liu/equeue
src/EQueue/Properties/AssemblyInfo.cs
src/EQueue/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2")] [assembly: AssemblyFileVersion("1.2.2")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EQueue")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1")] [assembly: AssemblyFileVersion("1.2.1")]
mit
C#
5b549758020cbf4de2402ba3a3deb5bc0519e324
Improve the efficiency of puzzle 12
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle012.cs
src/ProjectEuler/Puzzles/Puzzle012.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int divisors; if (!TryParseInt32(args[0], out divisors) || divisors < 1) { Console.Error.WriteLine("The specified number of divisors is invalid."); return -1; } long triangleNumber = 0; for (int n = 1; ; n++) { triangleNumber += n; int numberOfFactors = Maths.GetFactors(triangleNumber).Count(); if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> internal sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { int divisors; if (!TryParseInt32(args[0], out divisors) || divisors < 1) { Console.Error.WriteLine("The specified number of divisors is invalid."); return -1; } for (int i = 1; ; i++) { long triangleNumber = ParallelEnumerable.Range(1, i) .Select((p) => (long)p) .Sum(); int numberOfFactors = Maths.GetFactors(triangleNumber).Count(); if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
apache-2.0
C#
1699a3178249cee656541bd3d885a30f519dec2c
Update grammar in StaticConstructorExceptionAnalyzer.cs #839
giggio/code-cracker,carloscds/code-cracker,code-cracker/code-cracker,code-cracker/code-cracker,jwooley/code-cracker,eriawan/code-cracker,carloscds/code-cracker
src/CSharp/CodeCracker/Design/StaticConstructorExceptionAnalyzer.cs
src/CSharp/CodeCracker/Design/StaticConstructorExceptionAnalyzer.cs
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Design { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer { internal const string Title = "Don't throw exceptions inside static constructors."; internal const string MessageFormat = "Don't throw exceptions inside static constructors."; internal const string Category = SupportedCategories.Design; const string Description = "Static constructors are called before a class is used for the first time. Exceptions thrown " + "in static constructors force the use of a try block and should be avoided."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.StaticConstructorException.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.StaticConstructorException)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var ctor = (ConstructorDeclarationSyntax)context.Node; if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return; if (ctor.Body == null) return; var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault(); if (@throw == null) return; context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text)); } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; using System.Linq; namespace CodeCracker.CSharp.Design { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class StaticConstructorExceptionAnalyzer : DiagnosticAnalyzer { internal const string Title = "Don't throw exception inside static constructors."; internal const string MessageFormat = "Don't throw exception inside static constructors."; internal const string Category = SupportedCategories.Design; const string Description = "Static constructor are called before the first time a class is used but the " + "caller doesn't control when exactly.\r\n" + "Exception thrown in this context force callers to use 'try' block around any useage of the class " + "and should be avoided."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.StaticConstructorException.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, true, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.StaticConstructorException)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ConstructorDeclaration); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var ctor = (ConstructorDeclarationSyntax)context.Node; if (!ctor.Modifiers.Any(SyntaxKind.StaticKeyword)) return; if (ctor.Body == null) return; var @throw = ctor.Body.ChildNodes().OfType<ThrowStatementSyntax>().FirstOrDefault(); if (@throw == null) return; context.ReportDiagnostic(Diagnostic.Create(Rule, @throw.GetLocation(), ctor.Identifier.Text)); } } }
apache-2.0
C#
eedab747a8e778487f71de157912cea66749d4b5
Fix Authorization Behaviour
NickPolyder/FreeParkingSystem
src/Common/FreeParkingSystem.Common/Behaviors/AuthorizeBehaviour.cs
src/Common/FreeParkingSystem.Common/Behaviors/AuthorizeBehaviour.cs
using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Xml.Schema; using FreeParkingSystem.Common.Authorization; using FreeParkingSystem.Common.ExtensionMethods; using FreeParkingSystem.Common.Messages; using MediatR; namespace FreeParkingSystem.Common.Behaviors { public class AuthorizeBehaviour<TRequest> : IPipelineBehavior<TRequest, BaseResponse> where TRequest : BaseRequest { private readonly IUserContextAccessor _userContextAccessor; public AuthorizeBehaviour(IUserContextAccessor userContextAccessor) { _userContextAccessor = userContextAccessor; } public Task<BaseResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<BaseResponse> next) { var userContext = _userContextAccessor.GetUserContext(); var authorizedRoles = typeof(TRequest) .GetCustomAttributes<AuthorizeRequestAttribute>() .Select(attr => attr.ProtectedBy) .ToArray(); var hasAuthorizeAttribute = authorizedRoles.Any(); if (hasAuthorizeAttribute && !userContext.IsAuthenticated()) { return request.ToUnauthenticatedResponse().AsTask(); } var rolesToAuthenticateTo = authorizedRoles .Where(role => role.HasValue) .Select(role => role.Value).ToArray(); if (hasAuthorizeAttribute && rolesToAuthenticateTo.Any(role => !userContext.HasRole(role))) { return request.ToUnauthorizedResponse(rolesToAuthenticateTo).AsTask(); } return next(); } } }
using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Xml.Schema; using FreeParkingSystem.Common.Authorization; using FreeParkingSystem.Common.ExtensionMethods; using FreeParkingSystem.Common.Messages; using MediatR; namespace FreeParkingSystem.Common.Behaviors { public class AuthorizeBehaviour<TRequest> : IPipelineBehavior<TRequest, BaseResponse> where TRequest : BaseRequest { private readonly IUserContextAccessor _userContextAccessor; public AuthorizeBehaviour(IUserContextAccessor userContextAccessor) { _userContextAccessor = userContextAccessor; } public Task<BaseResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<BaseResponse> next) { var userContext = _userContextAccessor.GetUserContext(); var authorizedRoles = typeof(TRequest) .GetCustomAttributes<AuthorizeRequestAttribute>() .Select(attr => attr.ProtectedBy) .ToArray(); var hasAuthorizeAttribute = authorizedRoles.Any(); if (hasAuthorizeAttribute && !userContext.IsAuthenticated()) { return request.ToUnauthenticatedResponse().AsTask(); } if (hasAuthorizeAttribute && !authorizedRoles.Any(role => role.HasValue && userContext.HasRole(role.Value))) { var roles = authorizedRoles.Where(attr => attr.HasValue) .Select(attr => attr.Value); return request.ToUnauthorizedResponse(roles).AsTask(); } return next(); } } }
mit
C#
3636ecd6a2110324abe68c7162d2499b891251bd
Update src/OmniSharp.Abstractions/Models/v1/InlayHints/InlayHintRequest.cs
OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.Abstractions/Models/v1/InlayHints/InlayHintRequest.cs
src/OmniSharp.Abstractions/Models/v1/InlayHints/InlayHintRequest.cs
using OmniSharp.Mef; using OmniSharp.Models.V2; #nullable enable annotations namespace OmniSharp.Models.v1.InlayHints; [OmniSharpEndpoint(OmniSharpEndpoints.InlayHint, typeof(InlayHintRequest), typeof(InlayHintResponse))] public record InlayHintRequest : IRequest { public Location Location { get; set; } }
using OmniSharp.Mef; using OmniSharp.Models.V2; #nullable enable annotations namespace OmniSharp.Models.v1.InlayHints; [OmniSharpEndpoint(OmniSharpEndpoints.InlayHint, typeof(InlayHintRequest), typeof(InlayHintResponse))] public record InlayHintRequest : IRequest { public Location Location { get; set; } }
mit
C#
2fa773bfa13014cd7535cdc0182b98aa2614e8e3
Fix a bug in Generator
PerfDotNet/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,redknightlois/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,redknightlois/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,redknightlois/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet
BenchmarkDotNet/Extensions/ConfigurationExtensions.cs
BenchmarkDotNet/Extensions/ConfigurationExtensions.cs
using System; using System.Linq; using System.Reflection; using BenchmarkDotNet.Jobs; namespace BenchmarkDotNet.Extensions { internal static class ConfigurationExtensions { public static string ToConfig(this Platform platform) { switch (platform) { case Platform.AnyCpu: return "AnyCPU"; case Platform.X86: return "x86"; case Platform.X64: return "x64"; case Platform.Host: return IntPtr.Size == 4 ? "x86" : "x64"; default: return "AnyCPU"; } } public static string ToConfig(this Framework framework, Type benchmarkType) { if (framework == Framework.Host) return DetectCurrentFramework(benchmarkType); var number = framework.ToString().Substring(1); var numberArray = number.ToCharArray().Select(c => c.ToString()).ToArray(); return "v" + string.Join(".", numberArray); } private static string DetectCurrentFramework(Type benchmarkType) { var attributes = benchmarkType.Assembly.GetCustomAttributes(false).OfType<Attribute>(); var frameworkAttribute = attributes.FirstOrDefault(a => a.ToString() == @"System.Runtime.Versioning.TargetFrameworkAttribute"); if (frameworkAttribute == null) return "v4.0"; var frameworkName = frameworkAttribute.GetType() .GetProperty("FrameworkName", BindingFlags.Public | BindingFlags.Instance) .GetValue(frameworkAttribute, null)?.ToString(); if (frameworkName != null) frameworkName = frameworkName.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).FirstOrDefault() ?? ""; return frameworkName; } public static string ToConfig(this Jit jit) { return jit == Jit.LegacyJit ? "1" : "0"; } } }
using System; using System.Linq; using System.Reflection; using BenchmarkDotNet.Jobs; namespace BenchmarkDotNet.Extensions { internal static class ConfigurationExtensions { public static string ToConfig(this Platform platform) { switch (platform) { case Platform.AnyCpu: return "AnyCPU"; case Platform.X86: return "x86"; case Platform.X64: return "x64"; case Platform.Host: return IntPtr.Size == 4 ? "x86" : "x64"; default: return "AnyCPU"; } } public static string ToConfig(this Framework framework, Type benchmarkType) { if (framework == Framework.Host) return DetectCurrentFramework(benchmarkType); var number = framework.ToString().Substring(1); var numberArray = number.ToCharArray().Select(c => c.ToString()).ToArray(); return "v" + string.Join(".", numberArray); } private static string DetectCurrentFramework(Type benchmarkType) { var attributes = benchmarkType.Assembly.GetCustomAttributes(false).OfType<Attribute>(); var frameworkAttribute = attributes.FirstOrDefault(a => a.ToString() == @"System.Runtime.Versioning.TargetFrameworkAttribute"); if (frameworkAttribute == null) return "v3.5"; var frameworkName = frameworkAttribute.GetType() .GetProperty("FrameworkName", BindingFlags.Public | BindingFlags.Instance) .GetValue(frameworkAttribute, null)?.ToString(); if (frameworkName != null) frameworkName = frameworkName.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries).Skip(1).FirstOrDefault() ?? ""; return frameworkName; } public static string ToConfig(this Jit jit) { return jit == Jit.LegacyJit ? "1" : "0"; } } }
mit
C#
3f500131d483b5ebbdc60fb4c905de2e754965d7
Add basic xmldoc
johnneijzen/osu,ZLima12/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,johnneijzen/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,ppy/osu,ZLima12/osu,UselessToucan/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Screens/Edit/EditorWorkingBeatmap.cs
osu.Game/Screens/Edit/EditorWorkingBeatmap.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.Collections.Generic; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Screens.Edit { /// <summary> /// Encapsulates a <see cref="WorkingBeatmap"/> while providing an overridden <see cref="Beatmap{TObject}"/>. /// </summary> /// <typeparam name="TObject"></typeparam> public class EditorWorkingBeatmap<TObject> : IWorkingBeatmap where TObject : HitObject { private readonly Beatmap<TObject> playableBeatmap; private readonly WorkingBeatmap workingBeatmap; public EditorWorkingBeatmap(Beatmap<TObject> playableBeatmap, WorkingBeatmap workingBeatmap) { this.playableBeatmap = playableBeatmap; this.workingBeatmap = workingBeatmap; } public IBeatmap Beatmap => workingBeatmap.Beatmap; public Texture Background => workingBeatmap.Background; public Track Track => workingBeatmap.Track; public Waveform Waveform => workingBeatmap.Waveform; public Storyboard Storyboard => workingBeatmap.Storyboard; public Skin Skin => workingBeatmap.Skin; public IBeatmap GetPlayableBeatmap(RulesetInfo ruleset, IReadOnlyList<Mod> mods) => playableBeatmap; } }
// 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.Collections.Generic; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Rulesets; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Screens.Edit { public class EditorWorkingBeatmap<TObject> : IWorkingBeatmap where TObject : HitObject { private readonly Beatmap<TObject> playableBeatmap; private readonly WorkingBeatmap workingBeatmap; public EditorWorkingBeatmap(Beatmap<TObject> playableBeatmap, WorkingBeatmap workingBeatmap) { this.playableBeatmap = playableBeatmap; this.workingBeatmap = workingBeatmap; } public IBeatmap Beatmap => workingBeatmap.Beatmap; public Texture Background => workingBeatmap.Background; public Track Track => workingBeatmap.Track; public Waveform Waveform => workingBeatmap.Waveform; public Storyboard Storyboard => workingBeatmap.Storyboard; public Skin Skin => workingBeatmap.Skin; public IBeatmap GetPlayableBeatmap(RulesetInfo ruleset, IReadOnlyList<Mod> mods) => playableBeatmap; } }
mit
C#
a7242920231fb05cef3d987569fb6fc6b2a24fe4
Fix AME parts being rotated
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Server/AME/Components/AMEPartComponent.cs
Content.Server/AME/Components/AMEPartComponent.cs
using System.Linq; using System.Threading.Tasks; using Content.Server.Hands.Components; using Content.Server.Tools; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; namespace Content.Server.AME.Components { [RegisterComponent] [ComponentReference(typeof(IInteractUsing))] public class AMEPartComponent : Component, IInteractUsing { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IServerEntityManager _serverEntityManager = default!; public override string Name => "AMEPart"; [DataField("unwrapSound")] private SoundSpecifier _unwrapSound = new SoundPathSpecifier("/Audio/Effects/unwrap.ogg"); [DataField("qualityNeeded", customTypeSerializer:typeof(PrototypeIdSerializer<EntityPrototype>))] private string _qualityNeeded = "Pulsing"; async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs args) { if (!args.User.HasComponent<HandsComponent>()) { Owner.PopupMessage(args.User, Loc.GetString("ame-part-component-interact-using-no-hands")); return false; } if (!EntitySystem.Get<ToolSystem>().HasQuality(args.Using.Uid, _qualityNeeded)) return false; if (!_mapManager.TryGetGrid(args.ClickLocation.GetGridId(_serverEntityManager), out var mapGrid)) return false; // No AME in space. var snapPos = mapGrid.TileIndicesFor(args.ClickLocation); if (mapGrid.GetAnchoredEntities(snapPos).Any(sc => _serverEntityManager.HasComponent<AMEShieldComponent>(sc))) { Owner.PopupMessage(args.User, Loc.GetString("ame-part-component-shielding-already-present")); return true; } var ent = _serverEntityManager.SpawnEntity("AMEShielding", mapGrid.GridTileToLocal(snapPos)); SoundSystem.Play(Filter.Pvs(Owner), _unwrapSound.GetSound(), Owner); Owner.QueueDelete(); return true; } } }
using System.Linq; using System.Threading.Tasks; using Content.Server.Hands.Components; using Content.Server.Tools; using Content.Shared.Interaction; using Content.Shared.Popups; using Content.Shared.Sound; using Robust.Server.GameObjects; using Robust.Shared.Audio; using Robust.Shared.GameObjects; using Robust.Shared.IoC; using Robust.Shared.Localization; using Robust.Shared.Map; using Robust.Shared.Player; using Robust.Shared.Prototypes; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype; namespace Content.Server.AME.Components { [RegisterComponent] [ComponentReference(typeof(IInteractUsing))] public class AMEPartComponent : Component, IInteractUsing { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IServerEntityManager _serverEntityManager = default!; public override string Name => "AMEPart"; [DataField("unwrapSound")] private SoundSpecifier _unwrapSound = new SoundPathSpecifier("/Audio/Effects/unwrap.ogg"); [DataField("qualityNeeded", customTypeSerializer:typeof(PrototypeIdSerializer<EntityPrototype>))] private string _qualityNeeded = "Pulsing"; async Task<bool> IInteractUsing.InteractUsing(InteractUsingEventArgs args) { if (!args.User.HasComponent<HandsComponent>()) { Owner.PopupMessage(args.User, Loc.GetString("ame-part-component-interact-using-no-hands")); return false; } if (!EntitySystem.Get<ToolSystem>().HasQuality(args.Using.Uid, _qualityNeeded)) return false; if (!_mapManager.TryGetGrid(args.ClickLocation.GetGridId(_serverEntityManager), out var mapGrid)) return false; // No AME in space. var snapPos = mapGrid.TileIndicesFor(args.ClickLocation); if (mapGrid.GetAnchoredEntities(snapPos).Any(sc => _serverEntityManager.HasComponent<AMEShieldComponent>(sc))) { Owner.PopupMessage(args.User, Loc.GetString("ame-part-component-shielding-already-present")); return true; } var ent = _serverEntityManager.SpawnEntity("AMEShielding", mapGrid.GridTileToLocal(snapPos)); ent.Transform.LocalRotation = Owner.Transform.LocalRotation; SoundSystem.Play(Filter.Pvs(Owner), _unwrapSound.GetSound(), Owner); Owner.QueueDelete(); return true; } } }
mit
C#
034db5430974b5ee6cd7ef857a8ae9cc60f5d90a
fix refresh popup
kyoryo/test
Grabacr07.KanColleViewer/Views/MainWindow.xaml.cs
Grabacr07.KanColleViewer/Views/MainWindow.xaml.cs
using System.ComponentModel; namespace Grabacr07.KanColleViewer.Views { /// <summary> /// KanColleViewer のメイン ウィンドウを表します。 /// </summary> partial class MainWindow { public static MainWindow Current { get; private set; } public MainWindow() { InitializeComponent(); Current = this; } protected override void OnClosing(CancelEventArgs e) { // ToDo: 確認ダイアログを実装したかった… //e.Cancel = true; //var dialog = new ExitDialog { Owner = this, }; //dialog.Show(); base.OnClosing(e); } public void RefreshNavigator() { App.ViewModelRoot.Navigator.ReNavigate(); } } }
using System.ComponentModel; namespace Grabacr07.KanColleViewer.Views { /// <summary> /// KanColleViewer のメイン ウィンドウを表します。 /// </summary> partial class MainWindow { public static MainWindow Current { get; private set; } public MainWindow() { InitializeComponent(); Current = this; } protected override void OnClosing(CancelEventArgs e) { // ToDo: 確認ダイアログを実装したかった… //e.Cancel = true; //var dialog = new ExitDialog { Owner = this, }; //dialog.Show(); base.OnClosing(e); } public void RefreshNavigator() { App.ViewModelRoot.Navigator.Refresh(); } } }
mit
C#
fe38f180ec6c23cce48c5e35a26845416b6269af
Add docs for HC595 shift register
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
NET/API/Treehopper.Libraries/IO/PortExpander/Hc595.cs
NET/API/Treehopper.Libraries/IO/PortExpander/Hc595.cs
namespace Treehopper.Libraries.IO.PortExpander { /// This class supports all standard 8-bit serial-input, parallel-output shift registers similar to the 74HC595. /// /// Once constructed, this object provides a list of Pins that can be used just as any other digital output pins. /// By default, changing the value of one of these pins will immediately flush to the shift register: /// \code /// var shift1 = new Hc595(board.Spi, board.Pins[7]); /// shift1.Pins[3].DigitalValue = true; // immediately sets the output high /// shift1.Pins[2].DigitalValue = true; // performs a second SPI transaction to immediately set the output high /// \endcode /// If you plan on updating many pins at once, set the ChainableShiftRegisterOutput.AutoFlush property to false and then call FlushAsync() whenever you wish your pin changes to be written to the shift register: /// \code /// var shift1 = new Hc595(board.Spi, board.Pins[7]); /// shift1.AutoFlush = false; // disable automatically flushing changes to the shift register /// shift1.Pins[3].DigitalValue = true; // nothing happens (yet) /// shift1.Pins[2].DigitalValue = true; // nothing happens (yet) /// await shift1.FlushAsync(); // both pins are updated in a single transaction /// \endcode /// Note that you can chain multiple shift registers together by using the second constructor listed. /// \code /// var shift1 = new Hc595(board.Spi, board.Pins[7]); // construct a shift register attached to our SPI interface /// var shift2 = new Hc595(shift1); // we have a second shift register attached to the output of the first. /// \endcode [Supports("Generic", "74HC595")] public class Hc595 : ShiftOut { /// <summary> /// Construct a new 74HC595-type shift register that is directly connected to a Treehopper's SPI port /// </summary> public Hc595(Spi spiModule, SpiChipSelectPin latchPin, double speedMhz = 6) : base(spiModule, latchPin, 8, SpiMode.Mode00, ChipSelectMode.PulseHighAtEnd, speedMhz) { } /// <summary> /// Construct a 595-type shift register connected to the output of another 595-type shift register. /// </summary> /// <param name="UpstreamDevice"></param> public Hc595(ShiftOut UpstreamDevice) : base(UpstreamDevice, 8) { } } }
namespace Treehopper.Libraries.IO.PortExpander { /// <summary> /// 74HC595 serial-in, parallel-out shift register. /// </summary> [Supports("Generic", "74HC595")] public class Hc595 : ShiftOut { /// <summary> /// Construct a new 74HC595-type shift register that is directly connected to a Treehopper's SPI port /// </summary> /// <remarks> /// This class supports all 74HC595 shift registers. The name of the class comes from the widely-available TI part. /// </remarks> public Hc595(Spi spiModule, SpiChipSelectPin latchPin, double speedMhz = 6) : base(spiModule, latchPin, 8, SpiMode.Mode00, ChipSelectMode.PulseHighAtEnd, speedMhz) { } /// <summary> /// Construct a 595-type shift register connected to the output of another 595-type shift register. /// </summary> /// <param name="UpstreamDevice"></param> public Hc595(ShiftOut UpstreamDevice) : base(UpstreamDevice, 8) { } } }
mit
C#
28647f02a5cf584443b1c1dd8724b6a1e618ae41
Add direction checking for translation ports
Voxelgon/Voxelgon,Voxelgon/Voxelgon
Assets/Plugins/Voxelgon/Spacecraft/ShipManager.cs
Assets/Plugins/Voxelgon/Spacecraft/ShipManager.cs
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Voxelgon; [RequireComponent (typeof (Rigidbody))] public class ShipManager : MonoBehaviour { public float portYawCutoff = 15; //input Variables public float linAxis; public float latAxis; public float yawAxis; //Setup Variables for gathering Ports public enum YawState { YawLeft, YawRight } public enum TransState { TransLeft, TransRight, TransForw, TransBack } //dictionaries of ports public Dictionary<YawState, List<GameObject> > yawPorts = new Dictionary<YawState, List<GameObject> > (); public Dictionary<TransState, List<GameObject> > transPorts = new Dictionary<TransState, List<GameObject> > (); public void SetupPorts(){ //Yaw port lists yawPorts.Add(YawState.YawLeft, new List<GameObject>()); yawPorts.Add(YawState.YawRight,new List<GameObject>()); //Translation port lists transPorts.Add(TransState.TransLeft, new List<GameObject>()); transPorts.Add(TransState.TransRight,new List<GameObject>()); transPorts.Add(TransState.TransForw, new List<GameObject>()); transPorts.Add(TransState.TransBack, new List<GameObject>()); Vector3 origin = transform.rigidbody.centerOfMass; //Debug.Log(origin); Component[] PortScripts = gameObject.GetComponentsInChildren(typeof(RCSport)); foreach(Component port in PortScripts) { float angle = Voxelgon.Math.RelativeAngle(origin, port.transform); float childAngle = port.transform.localEulerAngles.y; //Debug.Log(angle); if(angle > portYawCutoff){ yawPorts[YawState.YawLeft].Add(port.gameObject); //Debug.Log("This port is for turning Left!"); } else if(angle < (-1 * portYawCutoff)){ yawPorts[YawState.YawRight].Add(port.gameObject); //Debug.Log("This port is for turning right!"); } else { if((childAngle >= 315) && (childAngle < 45)) { //0 degrees transPorts[TransState.TransForw].Add(port.gameObject); } else if((childAngle >= 45) && (childAngle < 135)) { //90 degrees transPorts[TransState.TransRight].Add(port.gameObject); } else if((childAngle >= 135) && (childAngle < 225)) { //180 degrees transPorts[TransState.TransBack].Add(port.gameObject); } else if((childAngle >= 225) && (childAngle < 315)) { //270 degrees transPorts[TransState.TransLeft].Add(port.gameObject); } } } } //updates input variables public void UpdateInputs() { linAxis = Input.GetAxis("Thrust"); latAxis = Input.GetAxis("Strafe"); yawAxis = Input.GetAxis("Yaw"); } //Called every frame public void Update() { UpdateInputs(); } //Startup Script public void Start() { SetupPorts(); } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using Voxelgon; [RequireComponent (typeof (Rigidbody))] public class ShipManager : MonoBehaviour { public float portTransCutoff = 5; //input Variables public float linAxis; public float latAxis; public float yawAxis; //Setup Variables for gathering Ports public enum Direction{ YawLeft, YawRight, TransLeft, TransRight, TransForw, TransBack } //dictionary of ports public Dictionary<Direction, List<GameObject> > portGroups = new Dictionary<Direction, List<GameObject> > (); public void SetupPorts(){ portGroups.Add( Direction.YawLeft, new List<GameObject>() ); portGroups.Add( Direction.YawRight, new List<GameObject>() ); portGroups.Add( Direction.TransLeft, new List<GameObject>() ); portGroups.Add( Direction.TransRight, new List<GameObject>() ); portGroups.Add( Direction.TransForw, new List<GameObject>() ); portGroups.Add( Direction.TransBack, new List<GameObject>() ); Vector3 origin = transform.rigidbody.centerOfMass; //Debug.Log(origin); Component[] PortScripts = gameObject.GetComponentsInChildren(typeof(RCSport)); foreach(Component i in PortScripts) { float angle = Voxelgon.Math.RelativeAngle(origin, i.transform); //Debug.Log(angle); if(angle > portTransCutoff){ portGroups[Direction.YawLeft].Add(i.gameObject); //Debug.Log("This port is for turning Left!"); } else if(angle < (-1 * portTransCutoff)){ portGroups[Direction.YawRight].Add(i.gameObject); //Debug.Log("This port is for turning right!"); } } } //updates input variables public void UpdateInputs() { linAxis = Input.GetAxis("Thrust"); latAxis = Input.GetAxis("Strafe"); yawAxis = Input.GetAxis("Yaw"); } //Called every frame public void Update() { UpdateInputs(); } //Startup Script public void Start() { SetupPorts(); } }
apache-2.0
C#
e456da414533dd4a3bbafddf737f3f44188569b1
Make RemoteService a Duplex Service
c0nnex/SPAD.neXt,c0nnex/SPAD.neXt
SPAD.Interfaces/ServiceContract/IRemoteService.cs
SPAD.Interfaces/ServiceContract/IRemoteService.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.ServiceContract { public static class RemoteServiceContract { public static readonly Uri ServiceUrl = new Uri("net.pipe://localhost/SPAD.neXt"); public static readonly string ServiceEndpoint = "RemoteService"; } public sealed class RemoteServiceResponse { public bool HasError { get; set; } public string Error { get; set; } public double Value { get; set; } } public sealed class RemoteEventTarget { public string Name { get; set; } public HashSet<string> EventNames { get; set; } } [ServiceContract( Namespace = Constants.Namespace , CallbackContract = typeof(IRemoteServiceCallback))] [ServiceKnownType(typeof(RemoteServiceResponse))] [ServiceKnownType(typeof(RemoteEventTarget))] public interface IRemoteService { [OperationContract] RemoteServiceResponse GetValue(string variableName); [OperationContract] RemoteServiceResponse SetValue(string variableName, double newValue); [OperationContract] RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter); [OperationContract] List<RemoteEventTarget> GetEventTargets(); [OperationContract] string GetVersion(); } public interface IRemoteServiceCallback { [OperationContract(IsOneWay = true)] void RemoteEvent(string eventName); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel; using System.Text; using System.Threading.Tasks; namespace SPAD.neXt.Interfaces.ServiceContract { public sealed class RemoteServiceResponse { public bool HasError { get; set; } public string Error { get; set; } public double Value { get; set; } } [ServiceContract] [ServiceKnownType(typeof(RemoteServiceResponse))] public interface IRemoteService { [OperationContract] RemoteServiceResponse GetValue(string variableName); [OperationContract] RemoteServiceResponse SetValue(string variableName, double newValue); [OperationContract] RemoteServiceResponse EmulateEvent(string eventTarget, string eventName, string eventParameter); } }
mit
C#
22b215b8e80518b20208dbc1d77e2cd8f3489eb6
Update usage message
aersh/ctlg
Ctlg/Program.cs
Ctlg/Program.cs
using System; using Autofac; using Ctlg.Data.Service; using Ctlg.Db.Migrations; using Ctlg.Filesystem.Service; using Ctlg.Service; namespace Ctlg { class Program { static int Main(string[] args) { var parser = new ArgsParser(); var command = parser.Parse(args); if (command != null) { var container = BuildIocContainer(); using (var scope = container.BeginLifetimeScope()) { var svc = scope.Resolve<ICtlgService>(); svc.ApplyDbMigrations(); svc.Execute(command); } } else { ShowUsageInfo(); return 1; } return 0; } private static IContainer BuildIocContainer() { var builder = new ContainerBuilder(); builder.RegisterType<DataService>().As<IDataService>(); builder.RegisterType<MigrationService>().As<IMigrationService>(); builder.RegisterType<FilesystemService>().As<IFilesystemService>(); builder.RegisterType<CtlgContext>().As<ICtlgContext>(); builder.RegisterType<CtlgService>().As<ICtlgService>(); builder.RegisterType<ConsoleOutput>().As<IOutput>(); return builder.Build(); } private static void ShowUsageInfo() { Console.WriteLine("Usage:"); Console.WriteLine("\tctlg.exe add <path to directory>"); Console.WriteLine("\tctlg.exe list"); } } }
using System; using Autofac; using Ctlg.Data.Service; using Ctlg.Db.Migrations; using Ctlg.Filesystem.Service; using Ctlg.Service; namespace Ctlg { class Program { static int Main(string[] args) { var parser = new ArgsParser(); var command = parser.Parse(args); if (command != null) { var container = BuildIocContainer(); using (var scope = container.BeginLifetimeScope()) { var svc = scope.Resolve<ICtlgService>(); svc.ApplyDbMigrations(); svc.Execute(command); } } else { ShowUsageInfo(); return 1; } return 0; } private static IContainer BuildIocContainer() { var builder = new ContainerBuilder(); builder.RegisterType<DataService>().As<IDataService>(); builder.RegisterType<MigrationService>().As<IMigrationService>(); builder.RegisterType<FilesystemService>().As<IFilesystemService>(); builder.RegisterType<CtlgContext>().As<ICtlgContext>(); builder.RegisterType<CtlgService>().As<ICtlgService>(); builder.RegisterType<ConsoleOutput>().As<IOutput>(); return builder.Build(); } private static void ShowUsageInfo() { Console.WriteLine("Usage: ctlg.exe add <path to directory>"); } } }
mit
C#
2211b64c1d13228192b719a92dfd477d44940321
fix ReportsClient
MehdyKarimpour/extensions,AlejandroCano/extensions,AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,signumsoftware/framework,signumsoftware/framework
Signum.Windows.Extensions/Reports/ReportClient.cs
Signum.Windows.Extensions/Reports/ReportClient.cs
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Windows.Reports; using Signum.Entities.Reports; using Signum.Services; using System.Reflection; namespace Signum.Windows.Reports { public class ReportClient { public static void Start(bool toExcel, bool excelReport) { if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod())) { if (excelReport) { if (toExcel) SearchControl.GetCustomMenuItems += (qn, type) => qn as Type == typeof(ExcelReportDN) ? null : new ReportMenuItem() { PlainExcelMenuItem = new PlainExcelMenuItem() }; else SearchControl.GetCustomMenuItems += (qn, type) => new ReportMenuItem(); QueryClient.Start(); Navigator.AddSetting(new EntitySettings<ExcelReportDN>(EntityType.Default) { View = e => new ExcelReport() }); } else { if (toExcel) { SearchControl.GetCustomMenuItems += (qn, type) => new PlainExcelMenuItem(); } } } } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Windows.Reports; using Signum.Entities.Reports; using Signum.Services; using System.Reflection; namespace Signum.Windows.Reports { public class ReportClient { public static void Start(bool toExcel, bool excelReport) { if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod())) { if (excelReport) { if (toExcel) SearchControl.GetCustomMenuItems += (qn, type) => qn as Type == typeof(ExcelReportDN) ? null : new ReportMenuItem() { PlainExcelMenuItem = new PlainExcelMenuItem() }; else SearchControl.GetCustomMenuItems += (qn, type) => new PlainExcelMenuItem(); QueryClient.Start(); Navigator.AddSetting(new EntitySettings<ExcelReportDN>(EntityType.Default) { View = e => new ExcelReport() }); } else { if (toExcel) { SearchControl.GetCustomMenuItems += (qn, type) => new PlainExcelMenuItem(); } } } } } }
mit
C#
db3f146b54ccce81d1e95cc0e15a02d42eda70b5
Update StreamWriter tests + Explicitly iterate IEnumerable method
samcragg/Crest,samcragg/Crest,samcragg/Crest
test/Host.UnitTests/Serialization/MethodsTests.cs
test/Host.UnitTests/Serialization/MethodsTests.cs
namespace Host.UnitTests.Serialization { using System.Collections; using System.Linq; using Crest.Host.Serialization; using FluentAssertions; using Xunit; public class MethodsTests { private readonly Methods methods = new Methods(typeof(FakeSerializerBase)); public sealed class StreamWriter : MethodsTests { private const int StreamWriterWriteMethods = 17; [Fact] public void ShouldEnumerateAllTheWriteMethods() { int count = this.methods.StreamWriter.Count(); count.Should().Be(StreamWriterWriteMethods); } [Fact] public void ShouldProvideANonGenericEnumerateMethod() { var enumerable = (IEnumerable)this.methods.StreamWriter; int count = 0; foreach (object x in enumerable) { count++; } count.Should().Be(StreamWriterWriteMethods); } } } }
namespace Host.UnitTests.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using Crest.Host.Serialization; using FluentAssertions; using Xunit; public class MethodsTests { private readonly Methods methods = new Methods(typeof(FakeSerializerBase)); public sealed class StreamWriter : MethodsTests { private const int StreamWriterWriteMethods = 17; [Fact] public void ShouldEnumerateAllTheWriteMethods() { int count = this.methods.StreamWriter.Count(); count.Should().Be(StreamWriterWriteMethods); } [Fact] public void ShouldProvideANonGenericEnumerateMethod() { int count = ((IEnumerable)this.methods.StreamWriter) .Cast<KeyValuePair<Type, MethodInfo>>() .Count(); count.Should().Be(StreamWriterWriteMethods); } } } }
mit
C#
6199353b03acd3b1534a47e3a9d5377f37e843a9
use streamutil replace CopyTo
fengyhack/csharp-sdk,qiniu/csharp-sdk
QBox/Auth/DigestAuthClient.cs
QBox/Auth/DigestAuthClient.cs
using System; using System.Text; using System.Net; using System.IO; using System.Security.Cryptography; using QBox.RS; using QBox.Util; namespace QBox.Auth { public class DigestAuthClient : Client { public override void SetAuth(HttpWebRequest request, Stream body) { byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY); using (HMACSHA1 hmac = new HMACSHA1(secretKey)) { string pathAndQuery = request.Address.PathAndQuery; byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery); using (MemoryStream buffer = new MemoryStream()) { buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length); buffer.WriteByte((byte)'\n'); if (request.ContentType == "application/x-www-form-urlencoded" && body != null) { if (!body.CanSeek) { throw new Exception("stream can not seek"); } StreamUtil.Copy(body, buffer); body.Seek(0, SeekOrigin.Begin); } byte[] digest = hmac.ComputeHash(buffer.ToArray()); string digestBase64 = Base64UrlSafe.Encode(digest); string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64; request.Headers.Add("Authorization", authHead); } } } } }
using System; using System.Text; using System.Net; using System.IO; using System.Security.Cryptography; using QBox.RS; using QBox.Util; namespace QBox.Auth { public class DigestAuthClient : Client { public override void SetAuth(HttpWebRequest request, Stream body) { byte[] secretKey = Encoding.ASCII.GetBytes(Config.SECRET_KEY); using (HMACSHA1 hmac = new HMACSHA1(secretKey)) { string pathAndQuery = request.Address.PathAndQuery; byte[] pathAndQueryBytes = Encoding.ASCII.GetBytes(pathAndQuery); using (MemoryStream buffer = new MemoryStream()) { buffer.Write(pathAndQueryBytes, 0, pathAndQueryBytes.Length); buffer.WriteByte((byte)'\n'); if (request.ContentType == "application/x-www-form-urlencoded" && body != null) { if (!body.CanSeek) { throw new Exception("stream can not seek"); } body.CopyTo(buffer); body.Seek(0, SeekOrigin.Begin); } byte[] digest = hmac.ComputeHash(buffer.ToArray()); string digestBase64 = Base64UrlSafe.Encode(digest); string authHead = "QBox " + Config.ACCESS_KEY + ":" + digestBase64; request.Headers.Add("Authorization", authHead); } } } } }
mit
C#
f0f0c2ff3858087ea501725029efbee171ebd4c6
Add turn-ending functionality, game-ending functionality
makerslocal/LudumDare38
bees-in-the-trap/Assets/Scripts/GameController.cs
bees-in-the-trap/Assets/Scripts/GameController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameController : MonoBehaviour { public static int STARTING_BEES = 30; public static int STARTING_POLLEN = 100; public static int TURN_COUNT = 20; private int turn = 1; private int bees; private int usableBees; private int pollen; private float bPressTimeStamp; public GameObject cursorObject; private Cursor cursor; private BoardGeneration b; public Text beeText; public Text pollenText; // Use this for initialization void Start () { b = GameObject.FindGameObjectWithTag ("GameController").GetComponent<BoardGeneration> (); cursor = cursorObject.GetComponent<Cursor> (); bees = usableBees = STARTING_BEES; pollen = STARTING_POLLEN; beeText.text = usableBees + " / " + bees; pollenText.text = "" + pollen; bPressTimeStamp = 0f; } // Update is called once per frame void Update () { if (Input.GetKeyUp ("b")) { if (Time.time - bPressTimeStamp > 0.5f) { EndTurn (); bPressTimeStamp = 0f; } else { Buy (); bPressTimeStamp = 0f; } } if (Input.GetKeyDown ("b")) { bPressTimeStamp = Time.time; } } void Buy () { Hex h = cursor.GetSelectedHex (); if (usableBees >= h.beeCost && pollen >= h.pollenCost && !h.isActive && b.isHexPurchasable(h)) { h.ActivateHex (); b.AddPurchasableHexesAdjacentTo (b.GetIndexOfHex(h)); GameObject bee = h.transform.GetChild (0).gameObject; bee.GetComponent<Animator> ().SetBool ("IsPurchased", true); bee.GetComponent<SpriteRenderer> ().color = h.GetComponent<SpriteRenderer> ().color; bees += h.beeReward; usableBees -= h.beeCost; pollen -= h.pollenCost; beeText.text = usableBees + " / " + bees; pollenText.text = "" + pollen; } } void EndTurn () { while (usableBees-- > 0) { int r = Random.Range (1, 4); pollen += r; } usableBees = bees; beeText.text = usableBees + " / " + bees; pollenText.text = "" + pollen; if (++turn > TURN_COUNT) { Application.LoadLevel (0); // end the game } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameController : MonoBehaviour { public static int STARTING_BEES = 3; public static int STARTING_POLLEN = 10; private int bees; private int usableBees; private int pollen; public GameObject cursorObject; private Cursor cursor; private BoardGeneration b; public Text beeText; public Text pollenText; // Use this for initialization void Start () { b = GameObject.FindGameObjectWithTag ("GameController").GetComponent<BoardGeneration> (); cursor = cursorObject.GetComponent<Cursor> (); bees = usableBees = STARTING_BEES; pollen = STARTING_POLLEN; beeText.text = usableBees + " / " + bees; pollenText.text = "" + pollen; } // Update is called once per frame void Update () { if (Input.GetKeyUp ("b")) { Buy (); } } void Buy () { Hex h = cursor.GetSelectedHex (); if (usableBees >= h.beeCost && pollen >= h.pollenCost && !h.isActive && b.isHexPurchasable(h)) { h.ActivateHex (); b.AddPurchasableHexesAdjacentTo (b.GetIndexOfHex(h)); GameObject bee = h.transform.GetChild (0).gameObject; bee.GetComponent<Animator> ().SetBool ("IsPurchased", true); bee.GetComponent<SpriteRenderer> ().color = h.GetComponent<SpriteRenderer> ().color; bees += h.beeReward; usableBees -= h.beeCost; pollen -= h.pollenCost; beeText.text = usableBees + " / " + bees; pollenText.text = "" + pollen; } } }
mit
C#
d6469aed58fb58abf09fbe272faed45c1db8e7ba
Remove migration code
ppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,johnneijzen/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,EVAST9919/osu,UselessToucan/osu,peppy/osu,2yangk23/osu,ZLima12/osu,NeoAdonis/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu
osu.Game.Tournament/Models/TournamentProgression.cs
osu.Game.Tournament/Models/TournamentProgression.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; namespace osu.Game.Tournament.Models { /// <summary> /// A mapping between two <see cref="TournamentMatch"/>es. /// Used for serialisation exclusively. /// </summary> [Serializable] public class TournamentProgression { public int SourceID; public int TargetID; public bool Losers; public TournamentProgression(int sourceID, int targetID, bool losers = false) { SourceID = sourceID; TargetID = targetID; Losers = losers; } } }
// 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; namespace osu.Game.Tournament.Models { /// <summary> /// A mapping between two <see cref="TournamentMatch"/>es. /// Used for serialisation exclusively. /// </summary> [Serializable] public class TournamentProgression { public int SourceID; public int TargetID; // migration public int Item1 { set => SourceID = value; } public int Item2 { set => TargetID = value; } public bool Losers; public TournamentProgression(int sourceID, int targetID, bool losers = false) { SourceID = sourceID; TargetID = targetID; Losers = losers; } } }
mit
C#
f12ad802793d3f1d5471596d23cc9a3829f97485
Add "HDR=YES" in connection string, but other error is thrown
Iliev88/QA-Automation
DesignPattern/Models/AccessExcelData.cs
DesignPattern/Models/AccessExcelData.cs
using Dapper; using SeleniumDesignPatternsDemo.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPattern.Models { public class AccessExcelData { public static string TestDataFileConnection() { var path = ConfigurationManager.AppSettings["TestDataSheetPath"]; var fileName = "UserData.xlsx"; var connection = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 12.0 Xml; HDR=YES", path + fileName); return connection; } public static RegistrateUser GetTestData(string keyName) { using (var connection = new OleDbConnection(TestDataFileConnection())) { connection.Open(); var query = string.Format("SELECT * FROM [DataSet$] WHERE KEY = '{0}'", keyName); var value = connection.Query<RegistrateUser>(query).First(); connection.Close(); return value; } } } }
using Dapper; using SeleniumDesignPatternsDemo.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data.OleDb; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DesignPattern.Models { public class AccessExcelData { public static string TestDataFileConnection() { var path = ConfigurationManager.AppSettings["TestDataSheetPath"]; var fileName = "UserData.xlsx"; var connection = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0; Data Source = {0}; Extended Properties=Excel 12.0;", path + fileName); return connection; } public static RegistrateUser GetTestData(string keyName) { using (var connection = new OleDbConnection(TestDataFileConnection())) { connection.Open(); var query = string.Format("SELECT * FROM [DataSet$] WHERE KEY = '{0}'", keyName); var value = connection.Query<RegistrateUser>(query).First(); connection.Close(); return value; } } } }
mit
C#
d3cac9bcf82192edf724a5e2c279b05553e7da09
check if badge exist before insert
Riges/simpleQRCodeSystem
SimpleQRCodeSystem/Repositories/BadgeRepository.cs
SimpleQRCodeSystem/Repositories/BadgeRepository.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using NodaTime; using SimpleQRCodeSystem.Models; namespace SimpleQRCodeSystem.Repositories { internal class BadgeRepository : IBadgeRepository { private readonly string _databasePath = "Database.json"; private readonly List<Badge> _badges; public BadgeRepository() { _badges = new List<Badge>(); if (File.Exists(_databasePath)) { _badges = JsonConvert.DeserializeObject<List<Badge>>(File.ReadAllText(_databasePath)); } } public Badge Find(string code) { var result = _badges.FirstOrDefault(x => x.Code == code) ?? new Badge(); return result; } public void Insert(List<string> codes) { foreach (var code in codes) { var result = _badges.FirstOrDefault(x => x.Code == code); if (result == null) { _badges.Add(new Badge { Code = code }); } } Save(); } public void SetUsedAt(string code) { var badge = _badges.FirstOrDefault(x => x.Code == code); if (badge != null) { badge.Used = true; badge.UsedAt = SystemClock.Instance.Now; } Save(); } private void Save() { File.WriteAllText(_databasePath, JsonConvert.SerializeObject(_badges)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Newtonsoft.Json; using NodaTime; using SimpleQRCodeSystem.Models; namespace SimpleQRCodeSystem.Repositories { internal class BadgeRepository : IBadgeRepository { private readonly string _databasePath = "Database.json"; private readonly List<Badge> _badges; public BadgeRepository() { _badges = new List<Badge>(); if (File.Exists(_databasePath)) { _badges = JsonConvert.DeserializeObject<List<Badge>>(File.ReadAllText(_databasePath)); } } public Badge Find(string code) { var result = _badges.FirstOrDefault(x => x.Code == code) ?? new Badge(); return result; } public void Insert(List<string> codes) { foreach (var code in codes) { _badges.Add(new Badge { Code = code }); } Save(); } public void SetUsedAt(string code) { var badge = _badges.FirstOrDefault(x => x.Code == code); if (badge != null) { badge.Used = true; badge.UsedAt = SystemClock.Instance.Now; } Save(); } private void Save() { File.WriteAllText(_databasePath, JsonConvert.SerializeObject(_badges)); } } }
mit
C#
6481375199354c8f2cb3e5eea0ee7ff44bf2fcea
Update ExchangeRate.cs
tiksn/TIKSN-Framework
TIKSN.Core/Finance/ForeignExchange/ExchangeRate.cs
TIKSN.Core/Finance/ForeignExchange/ExchangeRate.cs
using System; namespace TIKSN.Finance.ForeignExchange { public class ExchangeRate : IEquatable<ExchangeRate> { public ExchangeRate(CurrencyPair pair, DateTimeOffset asOn, decimal rate) { if (pair == null) { throw new ArgumentNullException(nameof(pair)); } if (rate <= decimal.Zero) { throw new ArgumentOutOfRangeException(nameof(rate), rate, "Rate must be a positive number."); } this.Pair = pair; this.AsOn = asOn; this.Rate = rate; } public DateTimeOffset AsOn { get; } public CurrencyPair Pair { get; } public decimal Rate { get; } public bool Equals(ExchangeRate other) { if (other == null) { return false; } return this.AsOn == other.AsOn && this.Pair == other.Pair && this.Rate == other.Rate; } public override bool Equals(object obj) => this.Equals(obj as ExchangeRate); public ExchangeRate Reverse() => new(this.Pair.Reverse(), this.AsOn, decimal.One / this.Rate); public override int GetHashCode() => this.AsOn.GetHashCode() ^ this.Pair.GetHashCode() ^ this.Rate.GetHashCode(); } }
using System; namespace TIKSN.Finance.ForeignExchange { public class ExchangeRate : IEquatable<ExchangeRate> { public ExchangeRate(CurrencyPair pair, DateTimeOffset asOn, decimal rate) { if (pair == null) throw new ArgumentNullException(nameof(pair)); if (rate <= decimal.Zero) throw new ArgumentOutOfRangeException(nameof(rate), rate, "Rate must be a positive number."); Pair = pair; AsOn = asOn; Rate = rate; } public DateTimeOffset AsOn { get; } public CurrencyPair Pair { get; } public decimal Rate { get; } public bool Equals(ExchangeRate other) { if (other == null) return false; return AsOn == other.AsOn && Pair == other.Pair && Rate == other.Rate; } public override bool Equals(object obj) { return Equals(obj as ExchangeRate); } public ExchangeRate Reverse() { return new ExchangeRate(Pair.Reverse(), AsOn, decimal.One / Rate); } public override int GetHashCode() { return AsOn.GetHashCode() ^ Pair.GetHashCode() ^ Rate.GetHashCode(); } } }
mit
C#
4c995b1ad38e0c62e40466713d2f04caabfa01af
Fix layout size calculation issue
sevoku/xwt,steffenWi/xwt,iainx/xwt,residuum/xwt,TheBrainTech/xwt,directhex/xwt,mono/xwt,cra0zy/xwt,antmicro/xwt,hwthomas/xwt,mminns/xwt,mminns/xwt,lytico/xwt,hamekoz/xwt,akrisiun/xwt
Xwt.Gtk/Xwt.GtkBackend/TextLayoutBackendHandler.cs
Xwt.Gtk/Xwt.GtkBackend/TextLayoutBackendHandler.cs
// // TextLayoutBackendHandler.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using Xwt.Engine; namespace Xwt.GtkBackend { public class TextLayoutBackendHandler: ITextLayoutBackendHandler { public object Create (Context context) { GtkContext c = (GtkContext) WidgetRegistry.GetBackend (context); return new Pango.Layout (c.Widget.PangoContext); } public void SetText (object backend, string text) { Pango.Layout tl = (Pango.Layout) backend; tl.SetText (text); } public void SetFont (object backend, Xwt.Drawing.Font font) { Pango.Layout tl = (Pango.Layout)backend; tl.FontDescription = (Pango.FontDescription)WidgetRegistry.GetBackend (font); } public void SetWidth (object backend, double value) { Pango.Layout tl = (Pango.Layout)backend; tl.Width = (int) (value * Pango.Scale.PangoScale); } public Size GetSize (object backend) { Pango.Layout tl = (Pango.Layout) backend; int w, h; tl.GetPixelSize (out w, out h); return new Size ((double)w, (double)h); } } }
// // TextLayoutBackendHandler.cs // // Author: // Lluis Sanchez <[email protected]> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; using Xwt.Drawing; using Xwt.Engine; namespace Xwt.GtkBackend { public class TextLayoutBackendHandler: ITextLayoutBackendHandler { public object Create (Context context) { GtkContext c = (GtkContext) WidgetRegistry.GetBackend (context); return new Pango.Layout (c.Widget.PangoContext); } public void SetText (object backend, string text) { Pango.Layout tl = (Pango.Layout) backend; tl.SetText (text); } public void SetFont (object backend, Xwt.Drawing.Font font) { Pango.Layout tl = (Pango.Layout)backend; tl.FontDescription = (Pango.FontDescription)WidgetRegistry.GetBackend (font); } public void SetWidth (object backend, double value) { Pango.Layout tl = (Pango.Layout)backend; tl.Width = (int) value; } public Size GetSize (object backend) { Pango.Layout tl = (Pango.Layout) backend; int w, h; tl.GetSize (out w, out h); return new Size ((double)w / (double)Pango.Scale.PangoScale, (double)h / (double)Pango.Scale.PangoScale); } } }
mit
C#
d4b1dc41fc1cd629fa46fccde51b06500419311e
remove unnecessary ToDo tag
concordion/concordion-net,ShaKaRee/concordion-net,concordion/concordion-net,ShaKaRee/concordion-net,concordion/concordion-net,ShaKaRee/concordion-net
Concordion/Internal/ClassNameBasedSpecificationLocator.cs
Concordion/Internal/ClassNameBasedSpecificationLocator.cs
// Copyright 2009 Jeffrey Cameron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Concordion.Api; namespace Concordion.Internal { public class ClassNameBasedSpecificationLocator : ISpecificationLocator { #region ISpecificationLocator Members private string m_SpecificationSuffix; public ClassNameBasedSpecificationLocator() : this("html") { } public ClassNameBasedSpecificationLocator(string mSpecificationSuffix) { this.m_SpecificationSuffix = mSpecificationSuffix; } public Resource LocateSpecification(object fixture) { var fixtureName = fixture.GetType().ToString(); fixtureName = fixtureName.Replace(".", "\\"); //Add Test und Fixture -> Case Sensitive fixtureName = Regex.Replace(fixtureName, "(Fixture|Test)$", ""); //Suffix from Concordion.Specification.config var path = fixtureName + "." + m_SpecificationSuffix; return new Resource(path); } #endregion } }
// Copyright 2009 Jeffrey Cameron // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Concordion.Api; namespace Concordion.Internal { public class ClassNameBasedSpecificationLocator : ISpecificationLocator { #region ISpecificationLocator Members private string m_SpecificationSuffix; public ClassNameBasedSpecificationLocator() : this("html") { } public ClassNameBasedSpecificationLocator(string mSpecificationSuffix) { this.m_SpecificationSuffix = mSpecificationSuffix; } public Resource LocateSpecification(object fixture) { var fixtureName = fixture.GetType().ToString(); fixtureName = fixtureName.Replace(".", "\\"); //Todo:in Config File aufnehemn //Add Test und Fixture -> Case Sensitive fixtureName = Regex.Replace(fixtureName, "(Fixture|Test)$", ""); //Suffix from Concordion.Specification.config var path = fixtureName + "." + m_SpecificationSuffix; return new Resource(path); } #endregion } }
apache-2.0
C#
d2cfec8756fccc9f48dfdc3840b6ef5ee8a03e4c
Rename variable
ishu3101/Wox.Plugin.ChangeCase
Wox.Plugin.ChangeCase/Main.cs
Wox.Plugin.ChangeCase/Main.cs
using System.Windows.Forms; using System.Collections.Generic; namespace Wox.Plugin.ChangeCase { public class Main : IPlugin { public void Init(PluginInitContext context) { } public List<Result> Query(Query query) { List<Result> results = new List<Result>(); var keyword = query.ActionParameters; // get the input entered by the user string input = ""; foreach (string param in keyword) { input += " " + param; } results.Add(new Result() { Title = input.ToLower(), SubTitle = "Convert to Lowercase", IcoPath = "Images\\lowercase.png", Action = e => { // copy to clipboard after user select the item Clipboard.SetText(input.ToLower()); // return false to tell Wox don't hide query window, otherwise Wox will hide it automatically return false; } }); results.Add(new Result() { Title = input.ToUpper(), SubTitle = "Convert to Uppercase", IcoPath = "Images\\uppercase.png", Action = e => { // copy to clipboard after user select the item Clipboard.SetText(input.ToUpper()); // return false to tell Wox don't hide query window, otherwise Wox will hide it automatically return false; } }); return results; } } }
using System.Windows.Forms; using System.Collections.Generic; namespace Wox.Plugin.ChangeCase { public class Main : IPlugin { public void Init(PluginInitContext context) { } public List<Result> Query(Query query) { List<Result> results = new List<Result>(); var keyword = query.ActionParameters; // get the query string key = ""; foreach (string param in keyword) { key += " " + param; } results.Add(new Result() { Title = key.ToLower(), SubTitle = "Convert to Lowercase", IcoPath = "Images\\lowercase.png", Action = e => { // copy to clipboard after user select the item Clipboard.SetText(key.ToLower()); // return false to tell Wox don't hide query window, otherwise Wox will hide it automatically return false; } }); results.Add(new Result() { Title = key.ToUpper(), SubTitle = "Convert to Uppercase", IcoPath = "Images\\uppercase.png", Action = e => { // copy to clipboard after user select the item Clipboard.SetText(key.ToUpper()); // return false to tell Wox don't hide query window, otherwise Wox will hide it automatically return false; } }); return results; } } }
mit
C#
7dd36a58d1603890db63dc8b64b42fa93d9e25c6
Fix voting functionality
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Web/Controllers/VoteController.cs
PhotoLife/PhotoLife.Web/Controllers/VoteController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PhotoLife.Authentication.Providers; using PhotoLife.Services.Contracts; namespace PhotoLife.Controllers { public class VoteController : Controller { private readonly IVotingService voteService; private readonly IAuthenticationProvider authenticationProvider; public VoteController(IVotingService voteService, IAuthenticationProvider authenticationProvider) { if (voteService == null) { throw new ArgumentNullException(nameof(voteService)); } if (authenticationProvider == null) { throw new ArgumentNullException(nameof(authenticationProvider)); } this.voteService = voteService; this.authenticationProvider = authenticationProvider; } [HttpPost] public ActionResult Vote(int postId, int currentVoteCount) { var userId = this.authenticationProvider.CurrentUserId; var rating = this.voteService.Vote(postId, userId); if (rating < 0) { rating = currentVoteCount; } return this.PartialView(rating); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using PhotoLife.Authentication.Providers; using PhotoLife.Services.Contracts; namespace PhotoLife.Controllers { public class VoteController : Controller { private readonly IVotingService voteService; private readonly IAuthenticationProvider authenticationProvider; public VoteController(IVotingService voteService, IAuthenticationProvider authenticationProvider) { if (voteService == null) { throw new ArgumentNullException(nameof(voteService)); } if (authenticationProvider == null) { throw new ArgumentNullException(nameof(authenticationProvider)); } this.voteService = voteService; this.authenticationProvider = authenticationProvider; } [HttpPost] public ActionResult Vote(int logId, int currentVoteCount) { var userId = this.authenticationProvider.CurrentUserId; var rating = this.voteService.Vote(logId, userId); if (rating < 0) { rating = currentVoteCount; } return this.PartialView(rating); } } }
mit
C#
c9b9bbbd4c887bc82d9a28fec07847dc7ab991d7
Bump version to 0.20
github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.20.0"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.19.0"; } }
mit
C#
98791f3a1f8ad5c4e360512fe29dea128892876f
Add more GuildLevelPermissions.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
MitternachtWeb/Models/PagePermission.cs
MitternachtWeb/Models/PagePermission.cs
using Discord; using System; namespace MitternachtWeb.Models { [Flags] public enum BotLevelPermission { None = 0b_0000_0000, ReadBotConfig = 0b_0000_0001, WriteBotConfig = 0b_0000_0011, ReadAllGuildConfigs = 0b_0000_0100, WriteAllGuildConfigs = 0b_0000_1100, ReadAllModerations = 0b_0001_0000, WriteAllMutes = 0b_0011_0000, All = 0b_1111_1111, } [Flags] public enum GuildLevelPermission { None = 0b_0000_0000, ReadGuildConfig = 0b_0000_0001, WriteGuildConfig = 0b_0000_0011, ReadModeration = 0b_0000_0100, WriteMutes = 0b_0000_1100, ReadAll = ReadGuildConfig | ReadModeration, All = 0b_1111_1111, } public static class PagePermissionExtensions { public static GuildLevelPermission GetGuildLevelPermissions(this GuildPermissions guildPerms) { var perms = GuildLevelPermission.None; if(guildPerms.ViewAuditLog) { perms |= GuildLevelPermission.ReadAll; } if(guildPerms.ManageMessages) { perms |= GuildLevelPermission.WriteMutes; } if(guildPerms.Administrator) { perms |= GuildLevelPermission.All; } return perms; } } }
using Discord; using System; namespace MitternachtWeb.Models { [Flags] public enum BotLevelPermission { None = 0b_0000_0000, ReadBotConfig = 0b_0000_0001, WriteBotConfig = 0b_0000_0011, ReadAllGuildConfigs = 0b_0000_0100, WriteAllGuildConfigs = 0b_0000_1100, ReadAllModerations = 0b_0001_0000, WriteAllMutes = 0b_0011_0000, All = 0b_1111_1111, } [Flags] public enum GuildLevelPermission { None = 0b_0000_0000, ReadGuildConfig = 0b_0000_0001, WriteGuildConfig = 0b_0000_0011, ReadModeration = 0b_0000_0100, WriteMutes = 0b_0000_1100, } public static class PagePermissionExtensions { public static GuildLevelPermission GetGuildLevelPermissions(this GuildPermissions guildPerms) { var perms = GuildLevelPermission.None; if(guildPerms.ViewAuditLog) { perms |= GuildLevelPermission.ReadGuildConfig | GuildLevelPermission.ReadModeration; } if(guildPerms.ManageMessages) { perms |= GuildLevelPermission.WriteMutes; } if(guildPerms.Administrator) { perms |= GuildLevelPermission.WriteGuildConfig | GuildLevelPermission.WriteMutes; } return perms; } } }
mit
C#
f265afc2f6ca5140dbc7e9b4c79777fbe3156189
Add more information to failed Hooks
Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder
Pathfinder/Internal/Patcher/Executor.cs
Pathfinder/Internal/Patcher/Executor.cs
using System; using Mono.Cecil; using Mono.Cecil.Inject; using Pathfinder.Attribute; using Pathfinder.Util; namespace Pathfinder.Internal.Patcher { internal static class Executor { internal static void Main(AssemblyDefinition gameAssembly) { // Retrieve the hook methods var hooks = typeof(PathfinderHooks); MethodDefinition method; PatchAttribute attrib; string sig; foreach (var meth in hooks.GetMethods()) { attrib = meth.GetFirstAttribute<PatchAttribute>(); if (attrib == null) continue; sig = attrib.MethodSig; if (sig == null) { Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method."); } method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1)); if(method == null) { Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'."); continue; } try { method.InjectWith( gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(), attrib.Offset, attrib.Tag, (InjectFlags) attrib.Flags, attrib.After ? InjectDirection.After : InjectDirection.Before, attrib.LocalIds); } catch (Exception ex) { throw new Exception($"Error applying patch for {sig}", ex); } } } } }
using System; using Mono.Cecil; using Mono.Cecil.Inject; using Pathfinder.Attribute; using Pathfinder.Util; namespace Pathfinder.Internal.Patcher { internal static class Executor { internal static void Main(AssemblyDefinition gameAssembly) { // Retrieve the hook methods var hooks = typeof(PathfinderHooks); MethodDefinition method; PatchAttribute attrib; string sig; foreach (var meth in hooks.GetMethods()) { attrib = meth.GetFirstAttribute<PatchAttribute>(); if (attrib == null) continue; sig = attrib.MethodSig; if (sig == null) { Console.WriteLine($"Null method signature found, skipping {nameof(PatchAttribute)} on method."); } method = gameAssembly.MainModule.GetType(sig.Remove(sig.LastIndexOf('.')))?.GetMethod(sig.Substring(sig.LastIndexOf('.') + 1)); if(method == null) { Console.WriteLine($"Method signature '{sig}' could not be found, method hook patching failed, skipping {nameof(PatchAttribute)} on '{sig}'."); continue; } method.InjectWith( gameAssembly.MainModule.ImportReference(hooks.GetMethod(meth.Name)).Resolve(), attrib.Offset, attrib.Tag, (InjectFlags)attrib.Flags, attrib.After ? InjectDirection.After : InjectDirection.Before, attrib.LocalIds); } } } }
mit
C#
ee22db6014b0ef59303621209f6241b8b877d481
include System.Globalization
sqlkata/querybuilder
QueryBuilder.Tests/ParameterTypeTest.cs
QueryBuilder.Tests/ParameterTypeTest.cs
using System; using System.Collections.Generic; using System.Globalization; using SqlKata.Execution; using SqlKata; using SqlKata.Compilers; using Xunit; using System.Collections; public enum EnumExample { First, Second, Third, } public class ParameterTypeTest { private readonly Compiler pgsql; private readonly MySqlCompiler mysql; private readonly FirebirdCompiler fbsql; public SqlServerCompiler mssql { get; private set; } public ParameterTypeTest() { mssql = new SqlServerCompiler(); mysql = new MySqlCompiler(); pgsql = new PostgresCompiler(); fbsql = new FirebirdCompiler(); } private string[] Compile(Query q) { return new[] { mssql.Compile(q.Clone()).ToString(), mysql.Compile(q.Clone()).ToString(), pgsql.Compile(q.Clone()).ToString(), fbsql.Compile(q.Clone()).ToString(), }; } public class ParameterTypeGenerator : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {"1", 1}, new object[] {Convert.ToSingle("10.5", CultureInfo.InvariantCulture).ToString(), 10.5}, new object[] {"-2", -2}, new object[] {Convert.ToSingle("-2.8", CultureInfo.InvariantCulture).ToString(), -2.8}, new object[] {"true", true}, new object[] {"false", false}, new object[] {"'2018-10-28 19:22:00'", new DateTime(2018, 10, 28, 19, 22, 0)}, new object[] {"0 /* First */", EnumExample.First}, new object[] {"1 /* Second */", EnumExample.Second}, new object[] {"'a string'", "a string"}, }; public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } [Theory] [ClassData(typeof(ParameterTypeGenerator))] public void CorrectParameterTypeOutput(string rendered, object input) { var query = new Query("Table").Where("Col", input); var c = Compile(query); Assert.Equal($"SELECT * FROM [Table] WHERE [Col] = {rendered}", c[0]); } }
using System; using System.Collections.Generic; using SqlKata.Execution; using SqlKata; using SqlKata.Compilers; using Xunit; using System.Collections; public enum EnumExample { First, Second, Third, } public class ParameterTypeTest { private readonly Compiler pgsql; private readonly MySqlCompiler mysql; private readonly FirebirdCompiler fbsql; public SqlServerCompiler mssql { get; private set; } public ParameterTypeTest() { mssql = new SqlServerCompiler(); mysql = new MySqlCompiler(); pgsql = new PostgresCompiler(); fbsql = new FirebirdCompiler(); } private string[] Compile(Query q) { return new[] { mssql.Compile(q.Clone()).ToString(), mysql.Compile(q.Clone()).ToString(), pgsql.Compile(q.Clone()).ToString(), fbsql.Compile(q.Clone()).ToString(), }; } public class ParameterTypeGenerator : IEnumerable<object[]> { private readonly List<object[]> _data = new List<object[]> { new object[] {"1", 1}, new object[] {Convert.ToSingle("10.5", CultureInfo.InvariantCulture).ToString(), 10.5}, new object[] {"-2", -2}, new object[] {Convert.ToSingle("-2.8", CultureInfo.InvariantCulture).ToString(), -2.8}, new object[] {"true", true}, new object[] {"false", false}, new object[] {"'2018-10-28 19:22:00'", new DateTime(2018, 10, 28, 19, 22, 0)}, new object[] {"0 /* First */", EnumExample.First}, new object[] {"1 /* Second */", EnumExample.Second}, new object[] {"'a string'", "a string"}, }; public IEnumerator<object[]> GetEnumerator() => _data.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } [Theory] [ClassData(typeof(ParameterTypeGenerator))] public void CorrectParameterTypeOutput(string rendered, object input) { var query = new Query("Table").Where("Col", input); var c = Compile(query); Assert.Equal($"SELECT * FROM [Table] WHERE [Col] = {rendered}", c[0]); } }
mit
C#
2cd2b56a634923a9fa19e3c65c36d6c8fa3f279f
Update Aluno_Context.cs
mamprin/Escola_Cadastro_de_Alunos,mamprin/Escola_Cadastro_de_Alunos,mamprin/Escola_Cadastro_de_Alunos
Cadastro_Alunos/Cadastro_Alunos/Models/Aluno_Context.cs
Cadastro_Alunos/Cadastro_Alunos/Models/Aluno_Context.cs
 using System.Data.Entity; namespace Cadastro_Alunos.Models { public class Aluno_Context : DbContext { public Aluno_Context() : base("Cadastro_Escola") { } public DbSet<Alunos> alunos { get; set; } } }
 using System.Data.Entity; namespace Cadastro_Alunos.Models { public class Aluno_Context : DbContext { public Aluno_Context() : base("Escola") { } public DbSet<Alunos> alunos { get; set; } } }
mit
C#
8b32fafa6bc9ff7a6d4cda294317ac1d487343ae
Make AliasMatcher#GetMatchedType virtual
appharbor/appharbor-cli
src/AppHarbor/AliasMatcher.cs
src/AppHarbor/AliasMatcher.cs
using System; using System.Linq; using System.Collections.Generic; namespace AppHarbor { public class AliasMatcher : IAliasMatcher { private readonly IEnumerable<Type> _candidateTypes; public AliasMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !x.GetCustomAttributes(true).OfType<CommandHelpAttribute>().Any())) { throw new ArgumentException("All candidate types must be decorated with CommandHelpAttribute"); } _candidateTypes = candidateTypes; } public virtual Type GetMatchedType(string commandArgument) { try { return _candidateTypes.Single( x => x.GetCustomAttributes(true).OfType<CommandHelpAttribute>().Single().Alias.ToLower() == commandArgument.ToLower()); } catch (InvalidOperationException) { throw new ArgumentException("Command doesn't match any command alias"); } } public bool IsSatisfiedBy(string commandArgument) { throw new NotImplementedException(); } } }
using System; using System.Linq; using System.Collections.Generic; namespace AppHarbor { public class AliasMatcher : IAliasMatcher { private readonly IEnumerable<Type> _candidateTypes; public AliasMatcher(IEnumerable<Type> candidateTypes) { if (candidateTypes.Any(x => !x.GetCustomAttributes(true).OfType<CommandHelpAttribute>().Any())) { throw new ArgumentException("All candidate types must be decorated with CommandHelpAttribute"); } _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandArgument) { try { return _candidateTypes.Single( x => x.GetCustomAttributes(true).OfType<CommandHelpAttribute>().Single().Alias.ToLower() == commandArgument.ToLower()); } catch (InvalidOperationException) { throw new ArgumentException("Command doesn't match any command alias"); } } public bool IsSatisfiedBy(string commandArgument) { throw new NotImplementedException(); } } }
mit
C#
7f3fe7b9d4fe32c9d2086c9e374cfd9b0a4c79a0
Make GPodBase implement IDisposable for better .NET-like bindings
hyperair/libgpod,neuschaefer/libgpod,hyperair/libgpod,neuschaefer/libgpod,neuschaefer/libgpod,neuschaefer/libgpod,hyperair/libgpod,neuschaefer/libgpod,hyperair/libgpod,hyperair/libgpod
bindings/mono/libgpod-sharp/GPodBase.cs
bindings/mono/libgpod-sharp/GPodBase.cs
/* * Copyright (c) 2010 Nathaniel McCallum <[email protected]> * * The code contained in this file is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This file 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace GPod { using System; using System.Collections.Generic; using System.Runtime.InteropServices; /* internal class RefCounter { private Dictionary<IntPtr, int> counter = new Dictionary<IntPtr, int>(); public void Ref(HandleRef hr) { Ref(HandleRef.ToIntPtr(hr)); } public void Ref(IntPtr p) { if (counter.ContainsKey(p)) counter[p] += 1; else counter[p] = 1; } public void Unref(HandleRef hr) { Unref(HandleRef.ToIntPtr(hr)); } public void Unref(IntPtr p) { if (counter.ContainsKey(p)) counter[p] -= 1; } public int Get(HandleRef hr) { Get(HandleRef.ToIntPtr(hr)); } public int Get(HandleRef hr) { if (counter.ContainsKey(p)) return counter[p]; return -1; } }*/ interface IGPodBase { void SetBorrowed(bool borrowed); } public abstract class GPodBase<T> : IGPodBase, IDisposable { //protected static Dictionary<IntPtr, int> RefCounter = new RefCounter(); protected static IntPtr DateTimeTotime_t (DateTime time) { DateTime epoch = new DateTime (1970, 1, 1, 0, 0, 0); return new IntPtr (((int) time.ToUniversalTime().Subtract(epoch).TotalSeconds)); } protected static DateTime time_tToDateTime (IntPtr time_t) { DateTime epoch = new DateTime (1970, 1, 1, 0, 0, 0); int utc_offset = (int)(TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now)).TotalSeconds; return epoch.AddSeconds((int)time_t + utc_offset); } public HandleRef Handle; protected T Struct; protected bool Borrowed; public GPodBase(IntPtr handle) : this(handle, true) {} public GPodBase(IntPtr handle, bool borrowed) { Borrowed = borrowed; Handle = new HandleRef (this, handle); Struct = (T) Marshal.PtrToStructure(HandleRef.ToIntPtr(Handle), typeof(T)); } ~GPodBase() { if (!Borrowed) Destroy(); } public void SetBorrowed(bool borrowed) { Borrowed = borrowed; } protected abstract void Destroy(); public void Dispose () { if (!Borrowed) Destroy (); } } }
/* * Copyright (c) 2010 Nathaniel McCallum <[email protected]> * * The code contained in this file is free software; you can redistribute * it and/or modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either version * 2.1 of the License, or (at your option) any later version. * * This file 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this code; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace GPod { using System; using System.Collections.Generic; using System.Runtime.InteropServices; /* internal class RefCounter { private Dictionary<IntPtr, int> counter = new Dictionary<IntPtr, int>(); public void Ref(HandleRef hr) { Ref(HandleRef.ToIntPtr(hr)); } public void Ref(IntPtr p) { if (counter.ContainsKey(p)) counter[p] += 1; else counter[p] = 1; } public void Unref(HandleRef hr) { Unref(HandleRef.ToIntPtr(hr)); } public void Unref(IntPtr p) { if (counter.ContainsKey(p)) counter[p] -= 1; } public int Get(HandleRef hr) { Get(HandleRef.ToIntPtr(hr)); } public int Get(HandleRef hr) { if (counter.ContainsKey(p)) return counter[p]; return -1; } }*/ interface IGPodBase { void SetBorrowed(bool borrowed); } public abstract class GPodBase<T> : IGPodBase { //protected static Dictionary<IntPtr, int> RefCounter = new RefCounter(); protected static IntPtr DateTimeTotime_t (DateTime time) { DateTime epoch = new DateTime (1970, 1, 1, 0, 0, 0); return new IntPtr (((int) time.ToUniversalTime().Subtract(epoch).TotalSeconds)); } protected static DateTime time_tToDateTime (IntPtr time_t) { DateTime epoch = new DateTime (1970, 1, 1, 0, 0, 0); int utc_offset = (int)(TimeZone.CurrentTimeZone.GetUtcOffset (DateTime.Now)).TotalSeconds; return epoch.AddSeconds((int)time_t + utc_offset); } public HandleRef Handle; protected T Struct; protected bool Borrowed; public GPodBase(IntPtr handle) : this(handle, true) {} public GPodBase(IntPtr handle, bool borrowed) { Borrowed = borrowed; Handle = new HandleRef (this, handle); Struct = (T) Marshal.PtrToStructure(HandleRef.ToIntPtr(Handle), typeof(T)); } ~GPodBase() { if (!Borrowed) Destroy(); } public void SetBorrowed(bool borrowed) { Borrowed = borrowed; } protected abstract void Destroy(); } }
lgpl-2.1
C#
8c55f17a1fa7a9b5f52d3ba5fc00c2040b60ca40
Add Active property to Effect Improve INotifyPropertyChanged implementation
batstyx/Shamanic
Shamanic/Effect.cs
Shamanic/Effect.cs
using Hearthstone_Deck_Tracker.Annotations; using Hearthstone_Deck_Tracker.Utility.Logging; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Shamanic { public class Effect : INotifyPropertyChanged { public string Name { get; } public int Count { get => _Count; private set => SetProperty(ref _Count, value); } private int _Count; public bool Active { get => _Active; set => SetProperty(ref _Active, value); } private bool _Active; public Effect(string name) { Name = name; Count = 0; Log.Debug($"Shamanic Effect Create {Name}: {Count}"); } public int Increment(int byAmount = 1) { Log.Debug($"Shamanic Effect Increment {Name}: {Count}+{byAmount}"); Count += byAmount; return Count; } public void Reset() { Count = 0; Log.Debug($"Shamanic Effect Reset {Name}: {Count}"); } public bool HasCount { get { return Count > 0; } } #region INotifyPropertyChanged protected bool SetProperty<T>(ref T backingStore, T value, [CallerMemberName] string propertyName = "", Action onChanged = null) { if (EqualityComparer<T>.Default.Equals(backingStore, value)) return false; backingStore = value; onChanged?.Invoke(); OnPropertyChanged(propertyName); return true; } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var changed = PropertyChanged; if (changed == null) return; changed.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
using Hearthstone_Deck_Tracker.Annotations; using Hearthstone_Deck_Tracker.Hearthstone; using System; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; namespace Shamanic { public class Effect : INotifyPropertyChanged { public string Name { get; } public int Count { get; private set; } public Effect(string name) { Name = name; Count = 0; Debug.WriteLine("Shamanic Effect Create {0}: {1}", Name, Count); } public int Increment(int byAmount = 1) { Count += byAmount; Debug.WriteLine("Shamanic Effect Increment {0}: {1}", Name, Count); OnPropertyChanged(nameof(Count)); return Count; } public void Reset() { Count = 0; Debug.WriteLine("Shamanic Effect Reset {0}: {1}", Name, Count); OnPropertyChanged(nameof(Count)); } public bool HasCount { get { return Count > 0; } } public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
mit
C#
416719422eddbc4367e58e97e48cb2140693ded5
Fix json serialization when the destination type is equal to the value type (fixes net40 for boolean conversions)
PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1
Source/Eto.Serialization.Json/TypeConverterConverter.cs
Source/Eto.Serialization.Json/TypeConverterConverter.cs
using System; using Newtonsoft.Json; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; namespace Eto.Serialization.Json { public class TypeConverterConverter : JsonConverter { readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>(); public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { TypeConverter converter; if (objectType == reader.ValueType) return reader.Value; if (converters.TryGetValue(objectType, out converter)) { return converter.ConvertFrom(reader.Value); } return existingValue; } public override bool CanConvert(Type objectType) { if (converters.ContainsKey(objectType)) return true; var converter = TypeDescriptor.GetConverter(objectType); if (converter != null && converter.CanConvertFrom(typeof(string))) { converters.Add(objectType, converter); return true; } return false; } } }
using System; using Newtonsoft.Json; using System.Reflection; using System.Collections.Generic; using System.ComponentModel; namespace Eto.Serialization.Json { public class TypeConverterConverter : JsonConverter { readonly Dictionary<Type, TypeConverter> converters = new Dictionary<Type, TypeConverter>(); public override bool CanRead { get { return true; } } public override bool CanWrite { get { return false; } } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { } public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { TypeConverter converter; if (converters.TryGetValue(objectType, out converter)) { return converter.ConvertFrom(reader.Value); } return existingValue; } public override bool CanConvert(Type objectType) { if (converters.ContainsKey(objectType)) return true; var converter = TypeDescriptor.GetConverter(objectType); if (converter != null && converter.CanConvertFrom(typeof(string))) { converters.Add(objectType, converter); return true; } return false; } } }
bsd-3-clause
C#
45f5a1e9358de403434be9c5d9a6e7b6e139dd36
Fix null ExitTile
urbanyeti/sbad-floorplan-service
Map/DoorTile.cs
Map/DoorTile.cs
using System; using System.Collections.Generic; using System.Text; namespace SBad.Map { public class DoorTile : FloorTile { public DoorTile(int x, int y, ITile exitTile = null, int? cost = null, string notes = "") : base(x, y, cost, notes) { ExitTile = exitTile; } public ITile ExitTile { get; set; } public override ITile Shift(Point origin) { return new DoorTile(X + origin.X, Y + origin.Y, ExitTile?.Shift(origin), Cost, Notes); } } }
using System; using System.Collections.Generic; using System.Text; namespace SBad.Map { public class DoorTile : FloorTile { public DoorTile(int x, int y, ITile exitTile = null, int? cost = null, string notes = "") : base(x, y, cost, notes) { ExitTile = exitTile; } public ITile ExitTile { get; set; } public override ITile Shift(Point origin) { return new DoorTile(X + origin.X, Y + origin.Y, ExitTile.Shift(origin), Cost, Notes); } } }
mit
C#
50cf4f5132ca8247406b6dc92ae3e80408d67c80
Support for zhima.credit.score.brief.get method
JoyMoe/ZmopSharp
src/ZmopSharp.Score/Score.cs
src/ZmopSharp.Score/Score.cs
using System; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using ZmopSharp.Core; using ScoreConstants = ZmopSharp.Constants.Score; namespace ZmopSharp.Score { public class Score { private const string BriefGetMethod= "zhima.credit.score.brief.get"; private const string GetMethod = "zhima.credit.score.get"; private readonly Client _client; public Score(Client client) { _client = client; } public Score(string appId,string appKey, string zmopCert) { _client = new Client(appId, appKey, zmopCert); } public async Task<int> GetAsync(string transactionId, string openId) { var result = await _client.SendAsync(new Request { Method = GetMethod, Params = new { transaction_id = transactionId, product_code = ScoreConstants.ProductCode.Score, open_id = openId } }); if (!result["biz_response"]["success"].Value<bool>()) { throw new ZmopException(result["biz_response"]["errorMessage"].Value<string>()); } return string.Equals("N/A", result["biz_response"]["zmScore"].Value<string>()) ? 0 : result["biz_response"]["zmScore"].Value<int>(); } public async Task<bool> GetAsync(string transactionId, string certType, string certNo, string name, int admittanceScore) { if (!string.Equals(Constants.Score.CertType.AlipayUserId, certType) && !string.Equals(Constants.Score.CertType.IdentityCard, certType) && !string.Equals(Constants.Score.CertType.Passport, certType)) { throw new ArgumentOutOfRangeException(nameof(certType)); } var result = await _client.SendAsync(new Request { Method = BriefGetMethod, Params = new { transaction_id = transactionId, product_code = ScoreConstants.ProductCode.ScoreBrief, cert_type = certType, cert_no = certNo, name = name, admittance_score = admittanceScore } }); if (!result["biz_response"]["success"].Value<bool>()) { throw new ZmopException(result["biz_response"]["errorMessage"].Value<string>()); } return string.Equals("Y", result["biz_response"]["is_admittance"].Value<string>()); } } }
using System.Threading.Tasks; using Newtonsoft.Json.Linq; using ZmopSharp.Core; using ScoreConstants = ZmopSharp.Constants.Score; namespace ZmopSharp.Score { public class Score { private const string GetMethod = "zhima.credit.score.get"; private readonly Client _client; public Score(Client client) { _client = client; } public Score(string appId,string appKey, string zmopCert) { _client = new Client(appId, appKey, zmopCert); } public async Task<int> GetAsync(string transactionId, string openId) { var result = await _client.SendAsync(new Request { Method = GetMethod, Params = new { transaction_id = transactionId, product_code = ScoreConstants.ProductCode.Score, open_id = openId } }); if (!result["biz_response"]["success"].Value<bool>()) { throw new ZmopException(result["biz_response"]["errorMessage"].Value<string>()); } return string.Equals("N/A", result["biz_response"]["zmScore"].Value<string>()) ? 0 : result["biz_response"]["zmScore"].Value<int>(); } } }
mit
C#
a5abacd1e7e8fd33927c522f7335884ef25bee36
Change assembly watcher after notification changes
godotengine/godot,Valentactive/godot,sanikoyes/godot,Shockblast/godot,Valentactive/godot,Faless/godot,DmitriySalnikov/godot,pkowal1982/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,guilhermefelipecgs/godot,akien-mga/godot,pkowal1982/godot,Faless/godot,Zylann/godot,MarianoGnu/godot,Shockblast/godot,Shockblast/godot,BastiaanOlij/godot,vkbsb/godot,guilhermefelipecgs/godot,josempans/godot,firefly2442/godot,pkowal1982/godot,pkowal1982/godot,josempans/godot,Valentactive/godot,ZuBsPaCe/godot,guilhermefelipecgs/godot,vnen/godot,Zylann/godot,pkowal1982/godot,guilhermefelipecgs/godot,MarianoGnu/godot,vkbsb/godot,godotengine/godot,Faless/godot,godotengine/godot,Shockblast/godot,Paulloz/godot,vkbsb/godot,MarianoGnu/godot,DmitriySalnikov/godot,sanikoyes/godot,Zylann/godot,MarianoGnu/godot,vkbsb/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,firefly2442/godot,Faless/godot,honix/godot,honix/godot,BastiaanOlij/godot,MarianoGnu/godot,Shockblast/godot,DmitriySalnikov/godot,Shockblast/godot,sanikoyes/godot,ZuBsPaCe/godot,sanikoyes/godot,guilhermefelipecgs/godot,akien-mga/godot,firefly2442/godot,pkowal1982/godot,vkbsb/godot,firefly2442/godot,vnen/godot,josempans/godot,josempans/godot,Zylann/godot,akien-mga/godot,BastiaanOlij/godot,guilhermefelipecgs/godot,Paulloz/godot,godotengine/godot,vnen/godot,Valentactive/godot,MarianoGnu/godot,Zylann/godot,vkbsb/godot,josempans/godot,josempans/godot,vnen/godot,BastiaanOlij/godot,josempans/godot,Valentactive/godot,firefly2442/godot,vkbsb/godot,guilhermefelipecgs/godot,Faless/godot,godotengine/godot,Faless/godot,Valentactive/godot,firefly2442/godot,Zylann/godot,Valentactive/godot,DmitriySalnikov/godot,Faless/godot,vnen/godot,MarianoGnu/godot,Paulloz/godot,firefly2442/godot,BastiaanOlij/godot,honix/godot,DmitriySalnikov/godot,honix/godot,BastiaanOlij/godot,ZuBsPaCe/godot,MarianoGnu/godot,sanikoyes/godot,pkowal1982/godot,akien-mga/godot,Paulloz/godot,Faless/godot,godotengine/godot,vnen/godot,pkowal1982/godot,honix/godot,BastiaanOlij/godot,ZuBsPaCe/godot,sanikoyes/godot,akien-mga/godot,Shockblast/godot,honix/godot,sanikoyes/godot,Zylann/godot,sanikoyes/godot,vnen/godot,godotengine/godot,godotengine/godot,DmitriySalnikov/godot,Valentactive/godot,akien-mga/godot,Paulloz/godot,josempans/godot,vkbsb/godot,ZuBsPaCe/godot,akien-mga/godot,Zylann/godot,ZuBsPaCe/godot,vnen/godot,Paulloz/godot,BastiaanOlij/godot,akien-mga/godot,firefly2442/godot,Paulloz/godot,Shockblast/godot
modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
modules/mono/editor/GodotTools/GodotTools/HotReloadAssemblyWatcher.cs
using Godot; using GodotTools.Internals; using static GodotTools.Internals.Globals; namespace GodotTools { public class HotReloadAssemblyWatcher : Node { private Timer watchTimer; public override void _Notification(int what) { if (what == Node.NotificationWmWindowFocusIn) { RestartTimer(); if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } } private void TimerTimeout() { if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } public void RestartTimer() { watchTimer.Stop(); watchTimer.Start(); } public override void _Ready() { base._Ready(); watchTimer = new Timer { OneShot = false, WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5) }; watchTimer.Timeout += TimerTimeout; AddChild(watchTimer); watchTimer.Start(); } } }
using Godot; using GodotTools.Internals; using static GodotTools.Internals.Globals; namespace GodotTools { public class HotReloadAssemblyWatcher : Node { private Timer watchTimer; public override void _Notification(int what) { if (what == Node.NotificationWmFocusIn) { RestartTimer(); if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } } private void TimerTimeout() { if (Internal.IsAssembliesReloadingNeeded()) Internal.ReloadAssemblies(softReload: false); } public void RestartTimer() { watchTimer.Stop(); watchTimer.Start(); } public override void _Ready() { base._Ready(); watchTimer = new Timer { OneShot = false, WaitTime = (float)EditorDef("mono/assembly_watch_interval_sec", 0.5) }; watchTimer.Timeout += TimerTimeout; AddChild(watchTimer); watchTimer.Start(); } } }
mit
C#
31aeab6cc7a30297a8ae7a511b061b892c5e9d4c
fix isMatching as nullable
commercetools/commercetools-dotnet-sdk
commercetools.NET/ShippingMethods/ShippingRate.cs
commercetools.NET/ShippingMethods/ShippingRate.cs
using System; using System.Collections.Generic; using commercetools.Common; using commercetools.ShippingMethods.Tiers; using Newtonsoft.Json; namespace commercetools.ShippingMethods { /// <summary> /// ShippingRate /// </summary> /// <see href="https://dev.commercetools.com/http-api-projects-shippingMethods.html#shippingrate"/> public class ShippingRate { #region Properties [JsonProperty(PropertyName = "price")] public Money Price { get; set; } [JsonProperty(PropertyName = "freeAbove")] public Money FreeAbove { get; set; } [JsonProperty(PropertyName = "tiers")] public List<Tier> Tiers { get; set; } [JsonProperty(PropertyName = "isMatching")] public Boolean? IsMatching { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public ShippingRate() { } /// <summary> /// Initializes this instance with JSON data from an API response. /// </summary> /// <param name="data">JSON object</param> public ShippingRate(dynamic data) { if (data == null) { return; } this.Price = Helper.GetMoneyBasedOnType(data.price); this.FreeAbove = Helper.GetMoneyBasedOnType(data.freeAbove); // We do not use Helper.GetListFromJsonArray here, due to the JsonConverter property on Tier class. // Using GetListFromJsonArray ignores the JsonConverter property and fails to deserialize properly. this.Tiers = JsonConvert.DeserializeObject<List<Tier>>(data.tiers.ToString()); this.IsMatching = data.isMatching; } #endregion } }
using System; using System.Collections.Generic; using commercetools.Common; using commercetools.ShippingMethods.Tiers; using Newtonsoft.Json; namespace commercetools.ShippingMethods { /// <summary> /// ShippingRate /// </summary> /// <see href="https://dev.commercetools.com/http-api-projects-shippingMethods.html#shippingrate"/> public class ShippingRate { #region Properties [JsonProperty(PropertyName = "price")] public Money Price { get; set; } [JsonProperty(PropertyName = "freeAbove")] public Money FreeAbove { get; set; } [JsonProperty(PropertyName = "tiers")] public List<Tier> Tiers { get; set; } [JsonProperty(PropertyName = "isMatching")] public Boolean IsMatching { get; set; } #endregion #region Constructors /// <summary> /// Constructor. /// </summary> public ShippingRate() { } /// <summary> /// Initializes this instance with JSON data from an API response. /// </summary> /// <param name="data">JSON object</param> public ShippingRate(dynamic data) { if (data == null) { return; } this.Price = Helper.GetMoneyBasedOnType(data.price); this.FreeAbove = Helper.GetMoneyBasedOnType(data.freeAbove); // We do not use Helper.GetListFromJsonArray here, due to the JsonConverter property on Tier class. // Using GetListFromJsonArray ignores the JsonConverter property and fails to deserialize properly. this.Tiers = JsonConvert.DeserializeObject<List<Tier>>(data.tiers.ToString()); this.IsMatching = data.isMatching; } #endregion } }
mit
C#