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
2a76d81f27dcbfb27667de4c4239e7c46000dde6
Fix to convert paragraph tag with single carriage return
mysticmind/reversemarkdown-net
src/ReverseMarkdown/Converters/P.cs
src/ReverseMarkdown/Converters/P.cs
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine; } } }
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine + Environment.NewLine; } } }
mit
C#
846f6d174e9eec002c75ca5f505a33bc3036462a
Add some fields, I will use some of them (IsServer, IsOwnerClient) when serialize /deserialize some field at client
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/GameApi/LiteNetLibElement.cs
Scripts/GameApi/LiteNetLibElement.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct LiteNetLibElementInfo { public uint objectId; public int elementId; public LiteNetLibElementInfo(uint objectId, int elementId) { this.objectId = objectId; this.elementId = elementId; } public static void SerializeInfo(LiteNetLibElementInfo info, NetDataWriter writer) { writer.PutPackedUInt(info.objectId); writer.PutPackedUInt((uint)info.elementId); } public static LiteNetLibElementInfo DeserializeInfo(NetDataReader reader) { return new LiteNetLibElementInfo(reader.GetPackedUInt(), (int)reader.GetPackedUInt()); } } public abstract class LiteNetLibElement { [LiteNetLibReadOnly, SerializeField] protected LiteNetLibBehaviour behaviour; public LiteNetLibBehaviour Behaviour { get { return behaviour; } } public LiteNetLibIdentity Identity { get { return Behaviour.Identity; } } public long ConnectionId { get { return Behaviour.ConnectionId; } } public uint ObjectId { get { return Behaviour.ObjectId; } } public LiteNetLibGameManager Manager { get { return Behaviour.Manager; } } public bool IsServer { get { return Behaviour.IsServer; } } public bool IsClient { get { return Behaviour.IsClient; } } public bool IsOwnerClient { get { return Behaviour.IsOwnerClient; } } [LiteNetLibReadOnly, SerializeField] protected int elementId; public int ElementId { get { return elementId; } } public LiteNetLibElementInfo GetInfo() { return new LiteNetLibElementInfo(Behaviour.ObjectId, ElementId); } internal virtual void Setup(LiteNetLibBehaviour behaviour, int elementId) { this.behaviour = behaviour; this.elementId = elementId; } protected virtual bool ValidateBeforeAccess() { return Behaviour != null; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct LiteNetLibElementInfo { public uint objectId; public int elementId; public LiteNetLibElementInfo(uint objectId, int elementId) { this.objectId = objectId; this.elementId = elementId; } public static void SerializeInfo(LiteNetLibElementInfo info, NetDataWriter writer) { writer.PutPackedUInt(info.objectId); writer.PutPackedUInt((uint)info.elementId); } public static LiteNetLibElementInfo DeserializeInfo(NetDataReader reader) { return new LiteNetLibElementInfo(reader.GetPackedUInt(), (int)reader.GetPackedUInt()); } } public abstract class LiteNetLibElement { [LiteNetLibReadOnly, SerializeField] protected LiteNetLibBehaviour behaviour; public LiteNetLibBehaviour Behaviour { get { return behaviour; } } [LiteNetLibReadOnly, SerializeField] protected int elementId; public int ElementId { get { return elementId; } } public LiteNetLibGameManager Manager { get { return behaviour.Manager; } } public LiteNetLibElementInfo GetInfo() { return new LiteNetLibElementInfo(Behaviour.ObjectId, ElementId); } internal virtual void Setup(LiteNetLibBehaviour behaviour, int elementId) { this.behaviour = behaviour; this.elementId = elementId; } protected virtual bool ValidateBeforeAccess() { return Behaviour != null; } } }
mit
C#
f14be4d336f0e466f1cf7ebefbe12f7b0ed6f9f5
Remove done TODO.
DanTup/SimpleSlackBot
SimpleSlackBot/TestBot/Program.cs
SimpleSlackBot/TestBot/Program.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using SimpleSlackBot; using TestBot.Commands; namespace TestBot { class Program { static void Main(string[] args) { Debug.Listeners.Add(new ConsoleTraceListener()); MainAsync(args).Wait(); } static async Task MainAsync(string[] args) { var token = Environment.GetEnvironmentVariable("SLACK_BOT", EnvironmentVariableTarget.User); using (var bot = await Bot.Connect(token)) { bot.RegisterCommand(new EchoCommand()); bot.RegisterCommand(new CountdownCommand()); Console.WriteLine("Press a key to disconnect..."); Console.ReadKey(); Console.WriteLine(); } } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using SimpleSlackBot; using TestBot.Commands; namespace TestBot { class Program { static void Main(string[] args) { Debug.Listeners.Add(new ConsoleTraceListener()); MainAsync(args).Wait(); } static async Task MainAsync(string[] args) { var token = Environment.GetEnvironmentVariable("SLACK_BOT", EnvironmentVariableTarget.User); using (var bot = await Bot.Connect(token)) { // TODO: Commands. bot.RegisterCommand(new EchoCommand()); bot.RegisterCommand(new CountdownCommand()); Console.WriteLine("Press a key to disconnect..."); Console.ReadKey(); Console.WriteLine(); } } } }
mit
C#
fa711cbb9caa99c52016f57bdf1303caa0223870
make cookie valid cross sessions. (#85)
gyrosworkshop/Wukong,gyrosworkshop/Wukong
Wukong/Controllers/AuthController.cs
Wukong/Controllers/AuthController.cs
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Wukong.Models; namespace Wukong.Controllers { [Route("oauth")] public class AuthController : Controller { [HttpGet("all")] public IEnumerable<OAuthMethod> AllSchemes() { return new List<OAuthMethod>{ new OAuthMethod() { Scheme = "Microsoft", DisplayName = "Microsoft", Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}" }}; } [HttpGet("go/{any}")] public async Task SignIn(string any, string redirectUri = "/") { await HttpContext.ChallengeAsync( OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = redirectUri, IsPersistent = true }); } [HttpGet("signout")] public SignOutResult SignOut(string redirectUrl = "/") { return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } } }
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Wukong.Models; namespace Wukong.Controllers { [Route("oauth")] public class AuthController : Controller { [HttpGet("all")] public IEnumerable<OAuthMethod> AllSchemes() { return new List<OAuthMethod>{ new OAuthMethod() { Scheme = "Microsoft", DisplayName = "Microsoft", Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}" }}; } [HttpGet("go/{any}")] public async Task SignIn(string any, string redirectUri = "/") { await HttpContext.ChallengeAsync( OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = redirectUri }); } [HttpGet("signout")] public SignOutResult SignOut(string redirectUrl = "/") { return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } } }
mit
C#
8a503a1cdbdba2a32c378f3d51801ee60f1f4205
Refactor block constructor
ajlopez/BlockchainSharp
Src/BlockchainSharp/Core/Block.cs
Src/BlockchainSharp/Core/Block.cs
namespace BlockchainSharp.Core { using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Linq; using System.Text; using BlockchainSharp.Encoding; using Org.BouncyCastle.Crypto.Digests; public class Block { private static Transaction[] emptyTxs = new Transaction[0]; BlockHeader header; private Hash hash; private IList<Transaction> transactions; public Block(long number, Hash parentHash) : this(number, parentHash, emptyTxs) { } public Block(long number, Hash parentHash, IEnumerable<Transaction> transactions) { if (number == 0 && parentHash != null) throw new InvalidOperationException("Genesis block should have no parent"); this.header = new BlockHeader(number, parentHash); this.hash = new Hash(); this.transactions = new List<Transaction>(transactions); } public IEnumerable<Transaction> Transactions { get { return this.transactions; } } public long Number { get { return this.header.Number; } } public Hash Hash { get { return this.hash; } } public Hash ParentHash { get { return this.header.ParentHash; } } public bool IsGenesis { get { return this.header.Number == 0 && this.header.ParentHash == null; } } public bool HasParent(Block parent) { if (parent == null && this.header.ParentHash == null) return true; if (parent == null) return false; return parent.Number == this.header.Number - 1 && parent.Hash.Equals(this.header.ParentHash); } private Hash CalculateHash() { Sha3Digest digest = new Sha3Digest(256); byte[] bytes = BlockEncoder.Instance.Encode(this); digest.BlockUpdate(bytes, 0, bytes.Length); byte[] result = new byte[32]; digest.DoFinal(result, 0); return new Hash(result); } } }
namespace BlockchainSharp.Core { using System; using System.Collections.Generic; using System.Security.Cryptography; using System.Linq; using System.Text; using BlockchainSharp.Encoding; using Org.BouncyCastle.Crypto.Digests; public class Block { BlockHeader header; private Hash hash; private IList<Transaction> transactions; public Block(long number, Hash parentHash) { if (number == 0 && parentHash != null) throw new InvalidOperationException("Genesis block should have no parent"); this.header = new BlockHeader(number, parentHash); this.hash = new Hash(); if (parentHash != null) this.hash = this.CalculateHash(); } public Block(long number, Hash parentHash, IEnumerable<Transaction> transactions) : this(number, parentHash) { this.transactions = new List<Transaction>(transactions); } public IEnumerable<Transaction> Transactions { get { return this.transactions; } } public long Number { get { return this.header.Number; } } public Hash Hash { get { return this.hash; } } public Hash ParentHash { get { return this.header.ParentHash; } } public bool IsGenesis { get { return this.header.Number == 0 && this.header.ParentHash == null; } } public bool HasParent(Block parent) { if (parent == null && this.header.ParentHash == null) return true; if (parent == null) return false; return parent.Number == this.header.Number - 1 && parent.Hash.Equals(this.header.ParentHash); } private Hash CalculateHash() { Sha3Digest digest = new Sha3Digest(256); byte[] bytes = BlockEncoder.Instance.Encode(this); digest.BlockUpdate(bytes, 0, bytes.Length); byte[] result = new byte[32]; digest.DoFinal(result, 0); return new Hash(result); } } }
mit
C#
24ad06ada22d162c631a98ebcfc3ae7d530e494b
Add XmlnsPrefix attribute
canton7/Stylet,canton7/Stylet
Stylet/Properties/AssemblyInfo.cs
Stylet/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows.Markup; // 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("Stylet")] [assembly: AssemblyDescription("A very lightweight but powerful ViewModel-First MVVM framework for WPF, inspired by Caliburn.Micro. Comes with its own IoC container.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Antony Male")] [assembly: AssemblyProduct("Stylet")] [assembly: AssemblyCopyright("Copyright © Antony Male 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a557a739-6b61-44d2-a431-889bc11aac9e")] [assembly: XmlnsDefinition("https://github.com/canton7/Stylet", "Stylet.Xaml")] [assembly: XmlnsPrefix("https://github.com/canton7/Stylet", "s")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows.Markup; // 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("Stylet")] [assembly: AssemblyDescription("A very lightweight but powerful ViewModel-First MVVM framework for WPF, inspired by Caliburn.Micro. Comes with its own IoC container.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Antony Male")] [assembly: AssemblyProduct("Stylet")] [assembly: AssemblyCopyright("Copyright © Antony Male 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a557a739-6b61-44d2-a431-889bc11aac9e")] [assembly: XmlnsDefinition("https://github.com/canton7/Stylet", "Stylet.Xaml")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")]
mit
C#
f501ca1bb6b2c369f80e383db7b519fe7bcdcc3c
Correct Vector Test
alesliehughes/monoDX,alesliehughes/monoDX
Test.Microsoft.DirectX/Vector3.cs
Test.Microsoft.DirectX/Vector3.cs
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using NUnit.Framework; using Microsoft.DirectX; namespace Test.Microsoft.DirectX { [TestFixture()] public class TestVector3 { [Test()] public void TestEmpty () { Vector3 v3 = Vector3.Empty; Assert.AreEqual(0.0f, v3.X); Assert.AreEqual(0.0f, v3.Y); Assert.AreEqual(0.0f, v3.Z); } [Test()] public void TestDot () { Vector3 rhs = new Vector3(2.0f, 2.0f, 2.0f); Vector3 lhs = new Vector3(2.0f, 2.0f, 2.0f); float result; result = Vector3.Dot(lhs, rhs); Assert.AreEqual(12.0f, result); } [Test()] public void TestCross () { Vector3 rhs = new Vector3(3.0f, 3.0f, 3.0f); Vector3 lhs = new Vector3(2.0f, 2.0f, 2.0f); Vector3 result; result = Vector3.Cross(lhs, rhs); Assert.AreEqual(0.0f, result.X); Assert.AreEqual(0.0f, result.Y); Assert.AreEqual(0.0f, result.Z); } } }
/* * The MIT License (MIT) * * Copyright (c) 2013 Alistair Leslie-Hughes * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using NUnit.Framework; using Microsoft.DirectX; namespace Test.Microsoft.DirectX { [TestFixture()] public class TestVector3 { [Test()] public void TestEmpty () { Vector3 v3 = Vector3.Empty; Assert.AreEqual(0.0f, v3.X); Assert.AreEqual(0.0f, v3.X); Assert.AreEqual(0.0f, v3.X); } [Test()] public void TestDot () { Vector3 rhs = new Vector3(2.0f, 2.0f, 2.0f); Vector3 lhs = new Vector3(2.0f, 2.0f, 2.0f); float result; result = Vector3.Dot(lhs, rhs); Assert.AreEqual(12.0f, result); } [Test()] public void TestCross () { Vector3 rhs = new Vector3(3.0f, 3.0f, 3.0f); Vector3 lhs = new Vector3(2.0f, 2.0f, 2.0f); Vector3 result; result = Vector3.Cross(lhs, rhs); Assert.AreEqual(0.0f, result.X); Assert.AreEqual(0.0f, result.Y); Assert.AreEqual(0.0f, result.Z); } } }
mit
C#
c5bdf02db3149a62e55e59715ff76488c3aabfad
Add test to verify overwriting of values.
Alan-Lun/git-p3
Test/ConfigurationTests.cs
Test/ConfigurationTests.cs
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } [TestMethod] public void ParseGitConfig_OverwritesValues() { // http://thedailywtf.com/articles/What_Is_Truth_0x3f_ const string input = @" [core] autocrlf = true autocrlf = FileNotFound autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
mit
C#
ae95b0ebe59ad45fd60f0b2f36a4af2d4ae7c520
Update to test
RagtimeWilly/Astro.CQRS
src/Astro.CQRS.Tests/Messaging/CommandQueueSubscriberTests.cs
src/Astro.CQRS.Tests/Messaging/CommandQueueSubscriberTests.cs
 namespace Astro.CQRS.Tests { using System.Collections.Generic; using System.Configuration; using System.Threading; using Astro.CQRS.Messaging; using Moq; using NUnit.Framework; using Serilog; [TestFixture] public class CommandQueueSubscriberTests { [Test, Explicit] public void Start_SubscribesAndReceivesMessages() { var connectionString = ConfigurationManager.AppSettings["ServiceBus.ConnectionString"]; var queueName = ConfigurationManager.AppSettings["CommandsQueueName"]; var handlers = new List<ICommandHandler>(); var repo = new Mock<IEventSourcedAggregateRepository>(); var publisher = new Mock<IEventPublisher>(); var logger = new Mock<ILogger>(); var dispatcher = new CommandDispatcher(handlers, repo.Object, publisher.Object); var subscriber = new CommandQueueSubscriber(connectionString, queueName, dispatcher, logger.Object); subscriber.StartAsync(); Thread.Sleep(60 * 1000); subscriber.Stop(); } } }
 namespace Astro.CQRS.Tests { using System.Collections.Generic; using System.Configuration; using System.Threading; using Astro.CQRS.Messaging; using Moq; using NUnit.Framework; using Serilog; [TestFixture] public class CommandQueueSubscriberTests { [Test, Explicit] public void Start_SubscribesAndReceivesMessages() { var connectionString = ConfigurationManager.AppSettings["ServiceBus.ConnectionString"]; var queueName = ConfigurationManager.AppSettings["QueueName"]; var handlers = new List<ICommandHandler>(); var repo = new Mock<IEventSourcedAggregateRepository>(); var publisher = new Mock<IEventPublisher>(); var logger = new Mock<ILogger>(); var dispatcher = new CommandDispatcher(handlers, repo.Object, publisher.Object); var subscriber = new CommandQueueSubscriber(connectionString, queueName, dispatcher, logger.Object); subscriber.StartAsync(); Thread.Sleep(60 * 60 * 1000); } } }
mit
C#
21f5514fe11f4ee4c02661134bffbf700e24170d
Delete workaround for a long-fixed editor bug
MichalStrehovsky/roslyn,orthoxerox/roslyn,wvdd007/roslyn,davkean/roslyn,cston/roslyn,AnthonyDGreen/roslyn,weltkante/roslyn,tvand7093/roslyn,gafter/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,weltkante/roslyn,bartdesmet/roslyn,kelltrick/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,bartdesmet/roslyn,wvdd007/roslyn,AmadeusW/roslyn,dotnet/roslyn,jamesqo/roslyn,Giftednewt/roslyn,diryboy/roslyn,lorcanmooney/roslyn,agocke/roslyn,jkotas/roslyn,MattWindsor91/roslyn,tmeschter/roslyn,kelltrick/roslyn,genlu/roslyn,Hosch250/roslyn,eriawan/roslyn,abock/roslyn,agocke/roslyn,OmarTawfik/roslyn,tmat/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,genlu/roslyn,lorcanmooney/roslyn,bartdesmet/roslyn,agocke/roslyn,bkoelman/roslyn,TyOverby/roslyn,dpoeschl/roslyn,cston/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,srivatsn/roslyn,brettfo/roslyn,mattscheffer/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,tvand7093/roslyn,tannergooding/roslyn,aelij/roslyn,tmeschter/roslyn,khyperia/roslyn,gafter/roslyn,pdelvo/roslyn,dpoeschl/roslyn,jmarolf/roslyn,mavasani/roslyn,jkotas/roslyn,physhi/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,mattscheffer/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,khyperia/roslyn,mattscheffer/roslyn,tmeschter/roslyn,jcouv/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,DustinCampbell/roslyn,pdelvo/roslyn,kelltrick/roslyn,AlekseyTs/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,mmitche/roslyn,VSadov/roslyn,xasx/roslyn,Hosch250/roslyn,reaction1989/roslyn,AmadeusW/roslyn,TyOverby/roslyn,diryboy/roslyn,robinsedlaczek/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,MattWindsor91/roslyn,abock/roslyn,pdelvo/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mgoertz-msft/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,weltkante/roslyn,Giftednewt/roslyn,orthoxerox/roslyn,nguerrera/roslyn,jcouv/roslyn,Hosch250/roslyn,xasx/roslyn,AmadeusW/roslyn,dotnet/roslyn,VSadov/roslyn,genlu/roslyn,cston/roslyn,tvand7093/roslyn,AnthonyDGreen/roslyn,ErikSchierboom/roslyn,MattWindsor91/roslyn,panopticoncentral/roslyn,davkean/roslyn,Giftednewt/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,dpoeschl/roslyn,ErikSchierboom/roslyn,paulvanbrenk/roslyn,abock/roslyn,OmarTawfik/roslyn,mmitche/roslyn,tannergooding/roslyn,mavasani/roslyn,stephentoub/roslyn,reaction1989/roslyn,sharwell/roslyn,khyperia/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,reaction1989/roslyn,nguerrera/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,nguerrera/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,heejaechang/roslyn,tannergooding/roslyn,davkean/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,dotnet/roslyn,gafter/roslyn,tmat/roslyn,mmitche/roslyn,mavasani/roslyn,srivatsn/roslyn,KevinRansom/roslyn,DustinCampbell/roslyn,sharwell/roslyn,stephentoub/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,jamesqo/roslyn,aelij/roslyn,xasx/roslyn,bkoelman/roslyn,heejaechang/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,paulvanbrenk/roslyn,physhi/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,srivatsn/roslyn,aelij/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,brettfo/roslyn
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { if (exception is ArgumentOutOfRangeException && ((ArgumentOutOfRangeException)exception).ParamName == "span") { // TODO: this is known bug 655591, fixed by Jack in changeset 931906 // Remove this workaround once the fix reaches the DP branch and we all move over. return; } _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } }
mit
C#
aadcd60694f45e2f5d544a708455688667c437f7
Fix multithreaded test initialisation.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
tests/SideBySide/DatabaseFixture.cs
tests/SideBySide/DatabaseFixture.cs
using System; #if NETCOREAPP1_1_2 using System.Reflection; #endif using System.Threading; using MySql.Data.MySqlClient; namespace SideBySide { public class DatabaseFixture : IDisposable { public DatabaseFixture() { lock (s_lock) { if (!s_isInitialized) { // increase the number of worker threads to reduce number of spurious failures from threadpool starvation #if NETCOREAPP1_1_2 // from https://stackoverflow.com/a/42982698 typeof(ThreadPool).GetMethod("SetMinThreads", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { 64, 64 }); #else ThreadPool.SetMinThreads(64, 64); #endif var csb = AppConfig.CreateConnectionStringBuilder(); var database = csb.Database; csb.Database = ""; using (var db = new MySqlConnection(csb.ConnectionString)) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = $"create schema if not exists {database};"; cmd.ExecuteNonQuery(); if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase)) { cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } } db.Close(); } s_isInitialized = true; } } Connection = new MySqlConnection(AppConfig.ConnectionString); } public MySqlConnection Connection { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Connection.Dispose(); } } static object s_lock = new object(); static bool s_isInitialized; } }
using System; #if NETCOREAPP1_1_2 using System.Reflection; #endif using System.Threading; using MySql.Data.MySqlClient; namespace SideBySide { public class DatabaseFixture : IDisposable { public DatabaseFixture() { // increase the number of worker threads to reduce number of spurious failures from threadpool starvation #if NETCOREAPP1_1_2 // from https://stackoverflow.com/a/42982698 typeof(ThreadPool).GetMethod("SetMinThreads", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { 64, 64 }); #else ThreadPool.SetMinThreads(64, 64); #endif var csb = AppConfig.CreateConnectionStringBuilder(); var connectionString = csb.ConnectionString; var database = csb.Database; csb.Database = ""; using (var db = new MySqlConnection(csb.ConnectionString)) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = $"create schema if not exists {database};"; cmd.ExecuteNonQuery(); if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase)) { cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } } db.Close(); } Connection = new MySqlConnection(connectionString); } public MySqlConnection Connection { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Connection.Dispose(); } } } }
mit
C#
a26ce25c964205180d0b933e1e5d742b1b2dca22
Rename MemoryHandle PinnedPointer to Pointer and add property HasPointer. (#14604)
wtgodbe/corefx,ViktorHofer/corefx,ptoonen/corefx,mmitche/corefx,BrennanConroy/corefx,ptoonen/corefx,wtgodbe/corefx,ericstj/corefx,Ermiar/corefx,mmitche/corefx,mmitche/corefx,mmitche/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,Ermiar/corefx,shimingsg/corefx,zhenlan/corefx,ravimeda/corefx,ravimeda/corefx,shimingsg/corefx,zhenlan/corefx,wtgodbe/corefx,Jiayili1/corefx,Ermiar/corefx,zhenlan/corefx,ravimeda/corefx,Ermiar/corefx,wtgodbe/corefx,wtgodbe/corefx,Ermiar/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,BrennanConroy/corefx,zhenlan/corefx,BrennanConroy/corefx,mmitche/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,ptoonen/corefx,mmitche/corefx,ViktorHofer/corefx,ericstj/corefx,ravimeda/corefx,ravimeda/corefx,Jiayili1/corefx,ericstj/corefx,ViktorHofer/corefx,ravimeda/corefx,ericstj/corefx,zhenlan/corefx,Jiayili1/corefx,zhenlan/corefx,ericstj/corefx,shimingsg/corefx,zhenlan/corefx,mmitche/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,Jiayili1/corefx,shimingsg/corefx,Jiayili1/corefx,ptoonen/corefx,ptoonen/corefx,Ermiar/corefx,ravimeda/corefx,ViktorHofer/corefx,Ermiar/corefx
src/Common/src/CoreLib/System/Buffers/MemoryHandle.cs
src/Common/src/CoreLib/System/Buffers/MemoryHandle.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.Runtime; using System.Runtime.InteropServices; namespace System.Buffers { public unsafe struct MemoryHandle : IDisposable { private IRetainable _owner; private void* _pointer; private GCHandle _handle; [CLSCompliant(false)] public MemoryHandle(IRetainable owner, void* pointer = null, GCHandle handle = default(GCHandle)) { _owner = owner; _pointer = pointer; _handle = handle; } internal void AddOffset(int offset) { if (_pointer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pointer); } else { _pointer = (void*)((byte*)_pointer + offset); } } [CLSCompliant(false)] public void* Pointer => _pointer; public bool HasPointer => _pointer != null; public void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_owner != null) { _owner.Release(); _owner = null; } _pointer = null; } } }
// 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.Runtime; using System.Runtime.InteropServices; namespace System.Buffers { public unsafe struct MemoryHandle : IDisposable { private IRetainable _owner; private void* _pointer; private GCHandle _handle; [CLSCompliant(false)] public MemoryHandle(IRetainable owner, void* pinnedPointer = null, GCHandle handle = default(GCHandle)) { _owner = owner; _pointer = pinnedPointer; _handle = handle; } internal void AddOffset(int offset) { if (_pointer == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.pointer); } else { _pointer = (void*)((byte*)_pointer + offset); } } [CLSCompliant(false)] public void* PinnedPointer => _pointer; public void Dispose() { if (_handle.IsAllocated) { _handle.Free(); } if (_owner != null) { _owner.Release(); _owner = null; } _pointer = null; } } }
mit
C#
d4d0906459baa3e82c8025171595d8d200e8f977
remove useless member
pascalberger/docfx,hellosnow/docfx,LordZoltan/docfx,superyyrrzz/docfx,hellosnow/docfx,dotnet/docfx,pascalberger/docfx,superyyrrzz/docfx,928PJY/docfx,dotnet/docfx,pascalberger/docfx,hellosnow/docfx,LordZoltan/docfx,LordZoltan/docfx,DuncanmaMSFT/docfx,LordZoltan/docfx,dotnet/docfx,928PJY/docfx,928PJY/docfx,superyyrrzz/docfx,DuncanmaMSFT/docfx
src/Microsoft.DocAsCode.Plugins/ProcessingPriority.cs
src/Microsoft.DocAsCode.Plugins/ProcessingPriority.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Plugins { using System; using System.ComponentModel; public enum ProcessingPriority { NotSupported = -1, [EditorBrowsable(EditorBrowsableState.Never)] Lowest = 0, Low = 64, BelowNormal = 128, Normal = 256, AboveNormal = 512, High = 1024, [EditorBrowsable(EditorBrowsableState.Never)] Highest = int.MaxValue, } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Plugins { using System; using System.ComponentModel; public enum ProcessingPriority { NotSupported = -1, [Obsolete("NotSupported")] NotSupportted = -1, [EditorBrowsable(EditorBrowsableState.Never)] Lowest = 0, Low = 64, BelowNormal = 128, Normal = 256, AboveNormal = 512, High = 1024, [EditorBrowsable(EditorBrowsableState.Never)] Highest = int.MaxValue, } }
mit
C#
a5c592d903e9e1767c0f4dd8adfc1a37c0790f2d
Add missing EOF whitespace
tgstation/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Host/System/IProcessSuspender.cs
src/Tgstation.Server.Host/System/IProcessSuspender.cs
namespace Tgstation.Server.Host.System { /// <summary> /// Abstraction for suspending and resuming processes. /// </summary> interface IProcessSuspender { /// <summary> /// Suspend a given <see cref="Process"/>. /// </summary> /// <param name="process">The <see cref="Process"/> to suspend.</param> void SuspendProcess(global::System.Diagnostics.Process process); /// <summary> /// Resume a given suspended <see cref="Process"/>. /// </summary> /// <param name="process">The <see cref="Process"/> to susperesumend.</param> void ResumeProcess(global::System.Diagnostics.Process process); } }
namespace Tgstation.Server.Host.System { /// <summary> /// Abstraction for suspending and resuming processes. /// </summary> interface IProcessSuspender { /// <summary> /// Suspend a given <see cref="Process"/>. /// </summary> /// <param name="process">The <see cref="Process"/> to suspend.</param> void SuspendProcess(global::System.Diagnostics.Process process); /// <summary> /// Resume a given suspended <see cref="Process"/>. /// </summary> /// <param name="process">The <see cref="Process"/> to susperesumend.</param> void ResumeProcess(global::System.Diagnostics.Process process); } }
agpl-3.0
C#
a4d52ab0963b29d62d4d5374fc05cd58e1211260
Add function to get deductions from a payrun for a specific employee
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
src/keypay-dotnet/ApiFunctions/V2/PayRunDeductionFunction.cs
src/keypay-dotnet/ApiFunctions/V2/PayRunDeductionFunction.cs
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionsResponse List(int businessId, int payRunId, int employeeId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions/" + employeeId); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
mit
C#
a91253a4fa1a0cdca2720d159da5d49f2392d783
add comments
reaction1989/roslyn,dotnet/roslyn,tannergooding/roslyn,AmadeusW/roslyn,heejaechang/roslyn,dotnet/roslyn,weltkante/roslyn,stephentoub/roslyn,diryboy/roslyn,bartdesmet/roslyn,sharwell/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,MichalStrehovsky/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,agocke/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,brettfo/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,abock/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,diryboy/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,physhi/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,genlu/roslyn,tannergooding/roslyn,brettfo/roslyn,heejaechang/roslyn,bartdesmet/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,tmat/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,tannergooding/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,mavasani/roslyn,weltkante/roslyn,reaction1989/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,weltkante/roslyn,physhi/roslyn,aelij/roslyn,dotnet/roslyn,agocke/roslyn,genlu/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,davkean/roslyn,tmat/roslyn,aelij/roslyn,stephentoub/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,mavasani/roslyn,abock/roslyn,swaroop-sridhar/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,physhi/roslyn,eriawan/roslyn,abock/roslyn,brettfo/roslyn,ErikSchierboom/roslyn,genlu/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,tmat/roslyn,diryboy/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,nguerrera/roslyn,aelij/roslyn,bartdesmet/roslyn,eriawan/roslyn,stephentoub/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,MichalStrehovsky/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn
src/Features/CSharp/Portable/Completion/KeywordRecommenders/AssemblyKeywordRecommender.cs
src/Features/CSharp/Portable/Completion/KeywordRecommenders/AssemblyKeywordRecommender.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() != SyntaxKind.OpenBracketToken) { return false; } if (token.Parent.Kind() == SyntaxKind.AttributeList) { var attributeList = token.Parent; var parentSyntax = attributeList.Parent; switch (parentSyntax) { case CompilationUnitSyntax _: // There are some case the parente of attributeList is (Class/Interface/Enum/Struct)DeclarationSyntax, like: // [$$ // class Goo { // for these cases is necessary check if they Parent is CompilationUnitSyntax case BaseTypeDeclarationSyntax baseType when baseType.Parent is CompilationUnitSyntax: // There is some case the parente of attributeList is IncompleteMemberSyntax(See test: TestInOuterAttribute), like: // [$$ // for that case is necessary check if they Parent is CompilationUnitSyntax case IncompleteMemberSyntax incompleteMember when incompleteMember.Parent is CompilationUnitSyntax: return true; default: return false; } // TODO: Remove before merge //return compilationUnitSyntax is CompilationUnitSyntax || compilationUnitSyntax.Parent is CompilationUnitSyntax; } var skippedTokensTriviaSyntax = token.Parent; // This case happens when: // [$$ // namespace Goo { return skippedTokensTriviaSyntax is SkippedTokensTriviaSyntax; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class AssemblyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public AssemblyKeywordRecommender() : base(SyntaxKind.AssemblyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var token = context.TargetToken; if (token.Kind() != SyntaxKind.OpenBracketToken) { return false; } if (token.Parent.Kind() == SyntaxKind.AttributeList) { var attributeList = token.Parent; var compilationUnitSyntax = attributeList.Parent; return compilationUnitSyntax is CompilationUnitSyntax || compilationUnitSyntax.Parent is CompilationUnitSyntax; } var skippedTokensTriviaSyntax = token.Parent; return skippedTokensTriviaSyntax is SkippedTokensTriviaSyntax; } } }
mit
C#
8aba727248e353d55895299b128774c4c9b2abd3
Use temp path for test
dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS
src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HostedServices/TempFileCleanupTests.cs
src/Umbraco.Tests.UnitTests/Umbraco.Infrastructure/HostedServices/TempFileCleanupTests.cs
using System; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Infrastructure.HostedServices; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices { [TestFixture] public class TempFileCleanupTests { private Mock<IIOHelper> _mockIOHelper; private string _testPath = Path.GetTempPath(); [Test] public async Task Does_Not_Execute_When_Not_Main_Dom() { var sut = CreateTempFileCleanup(isMainDom: false); await sut.PerformExecuteAsync(null); VerifyFilesNotCleaned(); } [Test] public async Task Executes_And_Cleans_Files() { var sut = CreateTempFileCleanup(); await sut.PerformExecuteAsync(null); VerifyFilesCleaned(); } private TempFileCleanup CreateTempFileCleanup(bool isMainDom = true) { var mockMainDom = new Mock<IMainDom>(); mockMainDom.SetupGet(x => x.IsMainDom).Returns(isMainDom); _mockIOHelper = new Mock<IIOHelper>(); _mockIOHelper.Setup(x => x.GetTempFolders()) .Returns(new DirectoryInfo[] { new DirectoryInfo(_testPath) }); _mockIOHelper.Setup(x => x.CleanFolder(It.IsAny<DirectoryInfo>(), It.IsAny<TimeSpan>())) .Returns(CleanFolderResult.Success()); var mockLogger = new Mock<ILogger<TempFileCleanup>>(); var mockProfilingLogger = new Mock<IProfilingLogger>(); return new TempFileCleanup(_mockIOHelper.Object, mockMainDom.Object, mockLogger.Object); } private void VerifyFilesNotCleaned() { VerifyFilesCleaned(Times.Never()); } private void VerifyFilesCleaned() { VerifyFilesCleaned(Times.Once()); } private void VerifyFilesCleaned(Times times) { _mockIOHelper.Verify(x => x.CleanFolder(It.Is<DirectoryInfo>(y => y.FullName == _testPath), It.IsAny<TimeSpan>()), times); } } }
using System; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.IO; using Umbraco.Core.Logging; using Umbraco.Infrastructure.HostedServices; namespace Umbraco.Tests.UnitTests.Umbraco.Infrastructure.HostedServices { [TestFixture] public class TempFileCleanupTests { private Mock<IIOHelper> _mockIOHelper; private string _testPath = @"c:\test\temp\path"; [Test] public async Task Does_Not_Execute_When_Not_Main_Dom() { var sut = CreateTempFileCleanup(isMainDom: false); await sut.PerformExecuteAsync(null); VerifyFilesNotCleaned(); } [Test] public async Task Executes_And_Cleans_Files() { var sut = CreateTempFileCleanup(); await sut.PerformExecuteAsync(null); VerifyFilesCleaned(); } private TempFileCleanup CreateTempFileCleanup(bool isMainDom = true) { var mockMainDom = new Mock<IMainDom>(); mockMainDom.SetupGet(x => x.IsMainDom).Returns(isMainDom); _mockIOHelper = new Mock<IIOHelper>(); _mockIOHelper.Setup(x => x.GetTempFolders()) .Returns(new DirectoryInfo[] { new DirectoryInfo(_testPath) }); _mockIOHelper.Setup(x => x.CleanFolder(It.IsAny<DirectoryInfo>(), It.IsAny<TimeSpan>())) .Returns(CleanFolderResult.Success()); var mockLogger = new Mock<ILogger<TempFileCleanup>>(); var mockProfilingLogger = new Mock<IProfilingLogger>(); return new TempFileCleanup(_mockIOHelper.Object, mockMainDom.Object, mockLogger.Object); } private void VerifyFilesNotCleaned() { VerifyFilesCleaned(Times.Never()); } private void VerifyFilesCleaned() { VerifyFilesCleaned(Times.Once()); } private void VerifyFilesCleaned(Times times) { _mockIOHelper.Verify(x => x.CleanFolder(It.Is<DirectoryInfo>(y => y.FullName == _testPath), It.IsAny<TimeSpan>()), times); } } }
mit
C#
6b93d9c10a9e05b0075af16fc9e68e51753bfe20
Verify proof
Fairlay/FairlayDotNetClient
Program.cs
Program.cs
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FairlaySampleClient { class Program { static void Main(string[] args) { TestClient tc = new TestClient(); Console.WriteLine("Your private and public key were saved in the config.txt file:\r\n" + tc.getPublicKey()); bool suc = tc.init(0); var _GetAPI = new GetAPI("\"Cat\":12 ,\"TypeOr\":[0],\"PeriodOr\":[1], \"OnlyActive\":true"); // call grab every 10 seconds to update your markets. bool suc_grab = _GetAPI.grab(); if(suc_grab) { //use _GetAPI.Markets; } if(!suc) { Console.WriteLine("\r\nPlease Enter your UserID"); string line = Console.ReadLine(); int id; bool valid = Int32.TryParse(line, out id); if(!valid) return; suc= tc.init(id); } var nextPresidentOrderbook2016 = tc.getOrderbook(72633292476); if(suc) { Console.WriteLine("\r\nConnected!"); } else return; var xf = tc.getBalance(); Console.WriteLine("\r\nYour balance is: " + JsonConvert.SerializeObject(xf)); string yourusernameoremail = null; bool verifiedProof = tc.VerifyProofOfReserves(xf.PrivReservedFunds, yourusernameoremail); Console.WriteLine("\r\nIs your balance verified? " + verifiedProof); while(true) { Console.WriteLine("\r\nEnter Command"); var read = Console.ReadLine(); } } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FairlaySampleClient { class Program { static void Main(string[] args) { TestClient tc = new TestClient(); Console.WriteLine("Your private and public key were saved in the config.txt file:\r\n" + tc.getPublicKey()); bool suc = tc.init(0); var _GetAPI = new GetAPI("\"Cat\":12 ,\"TypeOr\":[0],\"PeriodOr\":[1], \"OnlyActive\":true"); // call grab every 10 seconds to update your markets. bool suc_grab = _GetAPI.grab(); if(suc_grab) { //use _GetAPI.Markets; } if(!suc) { Console.WriteLine("\r\nPlease Enter your UserID"); string line = Console.ReadLine(); int id; bool valid = Int32.TryParse(line, out id); if(!valid) return; suc= tc.init(id); } var nextPresidentOrderbook2016 = tc.getOrderbook(72633292476); if(suc) { Console.WriteLine("\r\nConnected!"); } else return; var xf = tc.getBalance(); Console.WriteLine("\r\nYour balance is: " + JsonConvert.SerializeObject(xf)); string yourusernameoremail = null; bool verifiedProof = tc.VerifyProofOfReserves(xf.PrivReservedFunds, yourusernameoremail); while(true) { Console.WriteLine("\r\nEnter Command"); var read = Console.ReadLine(); } } } }
mit
C#
91fa532907fd5cf1270e64f9bfc16b6407536cd1
Clarify that tax status can apply to all entities
mattgwagner/CertiPay.Payroll.Common
CertiPay.Payroll.Common/SpecialTaxStatus.cs
CertiPay.Payroll.Common/SpecialTaxStatus.cs
using System; using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Applies a special tax status to an employee, company, earning, or other entity. Can be combined together /// i.e. SpecialTaxStatus.ExemptFromFICA | SpecialTaxStatus.ExemptFromMedicare /// </summary> [Flags] public enum SpecialTaxStatus : byte { // Note: This might need to get tweaked, since I'm not sure if we need to separate FICA from SS and Medicare? /// <summary> /// Entity has no special tax considerations /// </summary> None = 0, /// <summary> /// Entity is exempt from paying FICA taxes /// </summary> ExemptFromFICA = 1 << 1, /// <summary> /// Entity is exempt from paying Social Security taxes /// </summary> ExemptFromSocialSecurity = 1 << 2, /// <summary> /// Entity is empt from paying medicare taxes /// </summary> ExemptFromMedicare = 1 << 3, /// <summary> /// Entity is exempt from paying federal taxes /// </summary> ExemptFromFederalTax = 1 << 4, /// <summary> /// Entity is exempt from paying state taxes /// </summary> ExemptFromStateTax = 1 << 5, /// <summary> /// Entity is exempt from paying local taxes /// </summary> ExemptFromLocalTax = 1 << 6 } public class SpecialTaxStatuses { public static IEnumerable<SpecialTaxStatus> Values() { yield return SpecialTaxStatus.None; yield return SpecialTaxStatus.ExemptFromFICA; yield return SpecialTaxStatus.ExemptFromSocialSecurity; yield return SpecialTaxStatus.ExemptFromMedicare; yield return SpecialTaxStatus.ExemptFromFederalTax; yield return SpecialTaxStatus.ExemptFromStateTax; yield return SpecialTaxStatus.ExemptFromLocalTax; } } }
using System; using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Applies a special tax status to an employee or company, can be combined together /// i.e. SpecialTaxStatus.ExemptFromFICA | SpecialTaxStatus.ExemptFromMedicare /// </summary> [Flags] public enum SpecialTaxStatus : byte { // Note: This might need to get tweaked, since I'm not sure if we need to separate FICA from SS and Medicare? /// <summary> /// Employee has no special tax considerations /// </summary> None = 0, /// <summary> /// Employee is exempt from paying FICA taxes /// </summary> ExemptFromFICA = 1 << 1, /// <summary> /// Employee is exempt from paying Social Security taxes /// </summary> ExemptFromSocialSecurity = 1 << 2, /// <summary> /// Employee is empt from paying medicare taxes /// </summary> ExemptFromMedicare = 1 << 3, /// <summary> /// Employee is exempt from paying federal taxes /// </summary> ExemptFromFederalTax = 1 << 4, /// <summary> /// Employee is exempt from paying state taxes /// </summary> ExemptFromStateTax = 1 << 5, /// <summary> /// Employee is exempt from paying local taxes /// </summary> ExemptFromLocalTax = 1 << 6 } public class SpecialTaxStatuses { public static IEnumerable<SpecialTaxStatus> Values() { yield return SpecialTaxStatus.None; yield return SpecialTaxStatus.ExemptFromFICA; yield return SpecialTaxStatus.ExemptFromSocialSecurity; yield return SpecialTaxStatus.ExemptFromMedicare; yield return SpecialTaxStatus.ExemptFromFederalTax; yield return SpecialTaxStatus.ExemptFromStateTax; yield return SpecialTaxStatus.ExemptFromLocalTax; } } }
mit
C#
d4badac60f14148750d47f361a6fd831020b5375
Change app to use minified files
yyankov/club-challange,yyankov/club-challange,yyankov/club-challange
ClubChallengeBeta/App_Start/BundleConfig.cs
ClubChallengeBeta/App_Start/BundleConfig.cs
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.min.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js", "~/Scripts/respond.min.js", "~/Scripts/blueimp-gallery.min.js", "~/Scripts/bootstrap-image-gallery.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/blueimp-gallery.min.css", "~/Content/bootstrap-image-gallery.min.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.min.css", "~/Content/site.css")); } } }
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js", "~/Scripts/blueimp-gallery.js", "~/Scripts/bootstrap-image-gallery.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/blueimp-gallery.css", "~/Content/bootstrap-image-gallery.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.css", "~/Content/site.css")); } } }
mit
C#
67a99b580e37f6eb15f9d50873952d9f62868a4c
Update the label we use for issues that need the team's attention. (#621)
tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools,tg-msft/azure-sdk-tools
tools/github-issues/Azure.Sdk.Tools.GitHubIssues/Constants.cs
tools/github-issues/Azure.Sdk.Tools.GitHubIssues/Constants.cs
namespace GitHubIssues { internal static class Constants { public static class Labels { public static string NeedsAttention = "needs-team-attention"; public static string CustomerReported = "customer-reported"; public static string Bug = "bug"; public static string Feature = "feature-request"; public static string Question = "question"; public static string Client = "Client"; public static string Mgmt = "Mgmt"; public static string Service = "Service"; public static string ServiceAttention = "Service Attention"; public static string EngSys = "EngSys"; public static string MgmtEngSys = "Mgmt-EngSys"; } } }
namespace GitHubIssues { internal static class Constants { public static class Labels { public static string NeedsAttention = "needs-attention"; public static string CustomerReported = "customer-reported"; public static string Bug = "bug"; public static string Feature = "feature-request"; public static string Question = "question"; public static string Client = "Client"; public static string Mgmt = "Mgmt"; public static string Service = "Service"; public static string ServiceAttention = "Service Attention"; public static string EngSys = "EngSys"; public static string MgmtEngSys = "Mgmt-EngSys"; } } }
mit
C#
7bb58c56f41c4c185b6926f360301ae268c2b839
Add Genre model implementation.
TeamYAGNI/LibrarySystem
LibrarySystem/LibrarySystem.Models/Genre.cs
LibrarySystem/LibrarySystem.Models/Genre.cs
// <copyright file="Genre.cs" company="YAGNI"> // All rights reserved. // </copyright> // <summary>Holds implementation of Genre model.</summary> using System.Collections.Generic; namespace LibrarySystem.Models { /// <summary> /// Represent a <see cref="Genre"/> entity model. /// </summary> public class Genre { /// <summary> /// Books from the <see cref="Genre"/> entity. /// </summary> private ICollection<Book> books; /// <summary> /// Initializes a new instance of the <see cref="Genre"/> class. /// </summary> public Genre() { this.books = new HashSet<Book>(); } /// <summary> /// Gets or sets the primary key of the <see cref="Genre"/> entity. /// </summary> /// <value>Primary key of the <see cref="Genre"/> entity.</value> public int Id { get; set; } /// <summary> /// Gets or sets the name of the <see cref="Genre"/> entity. /// </summary> /// <value>Name of the <see cref="Genre"/> entity.</value> public string Name { get; set; } /// <summary> /// Gets or sets foreign key of the Genre to witch the <see cref="Genre"/> entity is sub-category. /// </summary> /// <value>Primary key of the sup-genre of the <see cref="Book"/> entity.</value> public int SuperGenreId { get; set; } /// <summary> /// Gets or sets the Genre to witch the <see cref="Genre"/> entity is sub-category. /// </summary> /// <value>Sup-genre of the <see cref="Book"/> entity.</value> public Genre SuperGenre { get; set; } /// <summary> /// Gets or sets the initial collection of books from the <see cref="Genre"/> entity. /// </summary> /// <value>Collection of books from the <see cref="Genre"/> entity.</value> public ICollection<Book> Books { get { return this.books; } set { this.books = value; } } } }
using System.ComponentModel.DataAnnotations; namespace LibrarySystem.Models { public class Genre { public int Id { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } } }
mit
C#
52ede6bb9212a153d1e1183672fe3b66e459a9b7
Add hashing code to bench
furesoft/cecil,joj/cecil,ttRevan/cecil,saynomoo/cecil,sailro/cecil,fnajera-rac-de/cecil,mono/cecil,xen2/cecil,SiliconStudio/Mono.Cecil,jbevain/cecil,gluck/cecil,kzu/cecil,cgourlay/cecil
Mono.Cecil.PE/ByteBufferEqualityComparer.cs
Mono.Cecil.PE/ByteBufferEqualityComparer.cs
// // ByteBufferEqualityComparer.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; namespace Mono.Cecil.PE { sealed class ByteBufferEqualityComparer : IEqualityComparer<ByteBuffer> { public bool Equals (ByteBuffer x, ByteBuffer y) { if (x.length != y.length) return false; var x_buffer = x.buffer; var y_buffer = y.buffer; for (int i = 0; i < x.length; i++) if (x_buffer [i] != y_buffer [i]) return false; return true; } public int GetHashCode (ByteBuffer buffer) { #if !BYTE_BUFFER_WELL_DISTRIBUTED_HASH var hash = 0; var bytes = buffer.buffer; for (int i = 0; i < buffer.length; i++) hash = (hash * 37) ^ bytes [i]; return hash; #else const uint p = 16777619; uint hash = 2166136261; var bytes = buffer.buffer; for (int i = 0; i < buffer.length; i++) hash = (hash ^ bytes [i]) * p; hash += hash << 13; hash ^= hash >> 7; hash += hash << 3; hash ^= hash >> 17; hash += hash << 5; return (int) hash; #endif } } }
// // ByteBufferEqualityComparer.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; namespace Mono.Cecil.PE { sealed class ByteBufferEqualityComparer : IEqualityComparer<ByteBuffer> { public bool Equals (ByteBuffer x, ByteBuffer y) { if (x.length != y.length) return false; var x_buffer = x.buffer; var y_buffer = y.buffer; for (int i = 0; i < x.length; i++) if (x_buffer [i] != y_buffer [i]) return false; return true; } public int GetHashCode (ByteBuffer buffer) { var hash = 0; var bytes = buffer.buffer; for (int i = 0; i < buffer.length; i++) hash = (hash * 37) ^ bytes [i]; return hash; } } }
mit
C#
aa1997e5e8c4fcbe16fb2fceb351563b58f126dc
Remove warning about hidden versus new
Seddryck/NBi,Seddryck/NBi
NBi.Core/Scalar/Resolver/IScalarResolver.cs
NBi.Core/Scalar/Resolver/IScalarResolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { new T Execute(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { T Execute(); } }
apache-2.0
C#
c13aec2bf681bcba6bf095c7e6c1767b2597f3e2
Update test case
wongjiahau/TTAP-UTAR,wongjiahau/TTAP-UTAR
NUnit.Tests2/Test_StartDateEndDateFinder.cs
NUnit.Tests2/Test_StartDateEndDateFinder.cs
using NUnit.Framework; using System; using System.IO; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; namespace NUnit.Tests2 { [TestFixture] public class Test_StartDateEndDateFinder { string input = Helper.RawStringOfTestFile("SampleData-FAM-2017-2ndSem.html"); [Test] public void Test_1() { var parser = new StartDateEndDateFinder(input); Assert.True(parser.GetStartDate() == new DateTime(2017 , 5 , 29 , 0 , 0 , 0)); Assert.True(parser.GetEndDate() == new DateTime(2017 , 9 , 3 , 0 , 0 , 0)); } } }
using NUnit.Framework; using System; using System.IO; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; namespace NUnit.Tests2 { [TestFixture] public class Test_StartDateEndDateFinder { private static string input = "Home\t\t\r\n Log Out \t\r\n \r\nWelcome, LOW KE LI (15UKB04769) User Guide\r\n\r\n Course Timetable Preview\r\n\r\n\tCourse Timetable Preview\t\tMy Course Registration\t\r\n\r\n\r\nSESSION\t201705\tCLASS TYPE\tFull-time\tFACULTY\tFAM\tCAMPUS\tSungai Long Campus\tDURATION (WEEKS)\t29/05/2017 - 03/09/2017 (14)\r\n\r\nCOURSE\t\r\n Search\r\nDAY\t"; [Test] public void Test_1() { var parser = new StartDateEndDateFinder(input); Assert.True(parser.GetStartDate() == new DateTime(2017 , 5 , 29 , 0 , 0 , 0)); Assert.True(parser.GetEndDate() == new DateTime(2017 , 9 , 3 , 0 , 0 , 0)); } [Test] public void Test_2() { string htmlText = Helper.RawStringOfTestFile("Sample HTML.txt"); string plain = ExtensionMethods.RemoveTags(htmlText); var parser = new StartDateEndDateFinder(plain); Assert.True(parser.GetStartDate() == new DateTime(2017 , 5 , 29 , 0 , 0 , 0)); Assert.True(parser.GetEndDate() == new DateTime(2017 , 9 , 3 , 0 , 0 , 0)); } } }
agpl-3.0
C#
b66b6c29ac7d87fbfa7651f7b9ec89b40a8c3b3d
Fix for relative paths not working.
BenPhegan/NuGet.Extensions
NuGet.Extensions.Tests/Commands/GetTests.cs
NuGet.Extensions.Tests/Commands/GetTests.cs
using System.Linq; using NUnit.Framework; using NuGet.Extensions.Tests.TestObjects; namespace NuGet.Extensions.Tests.Commands { public class RepositoryConfigExecuteTests : GetCommandTestsBase { protected override void SetUpTest() { } [TestCase(@"c:\TestSolution", 2)] public void InstallSampleRepository(string repository, int expectedCount) { GetCommand.Arguments.Add(repository); GetCommand.Latest = true; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@"c:\TestSolution\Project1\packages.config", 2)] [TestCase(@"c:\TestSolution\Project2\packages.config", 2)] public void ExpectedInstallCounts(string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@"c:\TestSolution\Project1\packages.config", 2)] public void ExcludeVersion(string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExcludeVersion = true; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@"c:\", @".\TestSolution\Project1\packages.config", 2)] [TestCase(@"c:\TestSolution", @".", 2)] [TestCase(@"c:\", @".\TestSolution", 2)] public void CanUseRelativePaths(string basePath, string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExcludeVersion = true; GetCommand.Latest = true; GetCommand.BaseDirectory = basePath; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } } }
using System.Linq; using NUnit.Framework; using NuGet.Extensions.Tests.TestObjects; namespace NuGet.Extensions.Tests.Commands { public class RepositoryConfigExecuteTests : GetCommandTestsBase { protected override void SetUpTest() { } [TestCase(@"c:\TestSolution", 2)] public void InstallSampleRepository(string repository, int expectedCount) { GetCommand.Arguments.Add(repository); GetCommand.Latest = true; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@"c:\TestSolution\Project1\packages.config", 2)] [TestCase(@"c:\TestSolution\Project2\packages.config", 2)] public void ExpectedInstallCounts(string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@"c:\TestSolution\Project1\packages.config", 2)] public void ExcludeVersion(string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExcludeVersion = true; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } [TestCase(@".\TestSolution\Project1\packages.config", 2)] [TestCase(@".\TestSolution", 2)] public void CanUseRelativePaths(string packageConfig, int expectedCount) { GetCommand.Arguments.Add(packageConfig); GetCommand.ExcludeVersion = true; GetCommand.ExecuteCommand(); var packageCount = FileSystem.Object.GetDirectories(@"c:\TestSolution\packages").Count(); Assert.AreEqual(expectedCount, packageCount); } } }
mit
C#
05d7112b5909732f1f7f1685a7381abbdd6d7262
Update required mono version
mono/mono-addins,mono/mono-addins
bot-provisioning/dependencies.csx
bot-provisioning/dependencies.csx
#r "_provisionator/provisionator.dll" using static Xamarin.Provisioning.ProvisioningScript; using System; using System.Linq; Item ("https://xamjenkinsartifact.azureedge.net/build-package-osx-mono/2020-02/99/620cf538206fe0f8cd63d76c502149b331f56f51/MonoFramework-MDK-6.12.0.93.macos10.xamarin.universal.pkg", kind: ItemDependencyKind.AtLeast);
#r "_provisionator/provisionator.dll" using static Xamarin.Provisioning.ProvisioningScript; using System; using System.Linq; Item ("https://xamjenkinsartifact.azureedge.net/build-package-osx-mono/2019-06/174/6b4b99e571b94331765170418d875416bf295a4e/MonoFramework-MDK-6.4.0.190.macos10.xamarin.universal.pkg", kind: ItemDependencyKind.AtLeast);
mit
C#
9100471b1d69dccfda3448a0c51da0ec422bfa9f
fix classifier condition
GeertBellekens/Enterprise-Architect-Toolpack,GeertBellekens/Enterprise-Architect-Toolpack,GeertBellekens/Enterprise-Architect-Toolpack
MagicdrawMigrator/Correctors/FixCallBehaviorActionCorrector.cs
MagicdrawMigrator/Correctors/FixCallBehaviorActionCorrector.cs
using System.Linq; using System; using EAAddinFramework.Utilities; using TSF_EA =TSF.UmlToolingFramework.Wrappers.EA; using UML = TSF.UmlToolingFramework.UML; namespace MagicdrawMigrator { /// <summary> /// Description of FixCallBehaviorActionCorrector. /// </summary> public class FixCallBehaviorActionCorrector:MagicDrawCorrector { public FixCallBehaviorActionCorrector(MagicDrawReader magicDrawReader, TSF_EA.Model model, TSF_EA.Package mdPackage):base(magicDrawReader,model,mdPackage) { } #region implemented abstract members of MagicDrawCorrector public override void correct() { //Log start EAOutputLogger.log(this.model,this.outputName ,string.Format("{0} Starting fixing the CallBehavior action'" ,DateTime.Now.ToLongTimeString()) ,0 ,LogTypeEnum.log); string packageString = mdPackage.getPackageTreeIDString(); this.model.executeSQL(@"delete from t_xref where [XrefID] in (select x.[XrefID] from (t_xref x inner join t_object o on o.[ea_guid] = x.[Client]) where x.name = 'CustomProperties' and o.[Classifier] = 0 and x.[Description] like '@PROP=@NAME=kind@ENDNAME;@TYPE=ActionKind@ENDTYPE;@VALU=CallBehavior@ENDVALU;@PRMT=@ENDPRMT;@ENDPROP;' and o.[Package_ID] in ("+ packageString +"))"); //Log Finished EAOutputLogger.log(this.model,this.outputName ,string.Format("{0} Finished fixing the CallBehavior action'" ,DateTime.Now.ToLongTimeString()) ,0 ,LogTypeEnum.log); } #endregion } }
using System.Linq; using System; using EAAddinFramework.Utilities; using TSF_EA =TSF.UmlToolingFramework.Wrappers.EA; using UML = TSF.UmlToolingFramework.UML; namespace MagicdrawMigrator { /// <summary> /// Description of FixCallBehaviorActionCorrector. /// </summary> public class FixCallBehaviorActionCorrector:MagicDrawCorrector { public FixCallBehaviorActionCorrector(MagicDrawReader magicDrawReader, TSF_EA.Model model, TSF_EA.Package mdPackage):base(magicDrawReader,model,mdPackage) { } #region implemented abstract members of MagicDrawCorrector public override void correct() { //Log start EAOutputLogger.log(this.model,this.outputName ,string.Format("{0} Starting fixing the CallBehavior action'" ,DateTime.Now.ToLongTimeString()) ,0 ,LogTypeEnum.log); string packageString = mdPackage.getPackageTreeIDString(); this.model.executeSQL(@"delete from t_xref where [XrefID] in (select x.[XrefID] from (t_xref x inner join t_object o on o.[ea_guid] = x.[Client]) where x.name = 'CustomProperties' and o.[Classifier] <> 0 and x.[Description] like '@PROP=@NAME=kind@ENDNAME;@TYPE=ActionKind@ENDTYPE;@VALU=CallBehavior@ENDVALU;@PRMT=@ENDPRMT;@ENDPROP;' and o.[Package_ID] in ("+ packageString +"))"); //Log Finished EAOutputLogger.log(this.model,this.outputName ,string.Format("{0} Finished fixing the CallBehavior action'" ,DateTime.Now.ToLongTimeString()) ,0 ,LogTypeEnum.log); } #endregion } }
bsd-2-clause
C#
26591b838aa62eafc225d96fb3fe598e40f7d6c0
Remove windows long filename prefix
Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server
src/Tgstation.Server.Host.Watchdog/WindowsActiveAssemblyDeleter.cs
src/Tgstation.Server.Host.Watchdog/WindowsActiveAssemblyDeleter.cs
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file var tmpLocation = String.Concat(assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file //Also append the long path prefix just in case we're running on .NET framework var tmpLocation = String.Concat(@"\\?\", assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
agpl-3.0
C#
b7ff96eb1f3bafc8f0039879a2ac77e473daf8a1
Add MonoDevelopGtk synchronization context as consumption of Roslyn in VS for Mac uses this context.
tannergooding/roslyn,dotnet/roslyn,Giftednewt/roslyn,CyrusNajmabadi/roslyn,cston/roslyn,ErikSchierboom/roslyn,physhi/roslyn,aelij/roslyn,stephentoub/roslyn,nguerrera/roslyn,bkoelman/roslyn,pdelvo/roslyn,mavasani/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,agocke/roslyn,Hosch250/roslyn,srivatsn/roslyn,gafter/roslyn,cston/roslyn,pdelvo/roslyn,orthoxerox/roslyn,lorcanmooney/roslyn,diryboy/roslyn,xasx/roslyn,VSadov/roslyn,orthoxerox/roslyn,bartdesmet/roslyn,aelij/roslyn,tmeschter/roslyn,srivatsn/roslyn,davkean/roslyn,mattscheffer/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,srivatsn/roslyn,lorcanmooney/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,abock/roslyn,tvand7093/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,tmat/roslyn,genlu/roslyn,jasonmalinowski/roslyn,jamesqo/roslyn,DustinCampbell/roslyn,dpoeschl/roslyn,jamesqo/roslyn,MattWindsor91/roslyn,dpoeschl/roslyn,sharwell/roslyn,panopticoncentral/roslyn,physhi/roslyn,jamesqo/roslyn,Hosch250/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,reaction1989/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,swaroop-sridhar/roslyn,heejaechang/roslyn,stephentoub/roslyn,mmitche/roslyn,mgoertz-msft/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,MichalStrehovsky/roslyn,reaction1989/roslyn,sharwell/roslyn,agocke/roslyn,Hosch250/roslyn,reaction1989/roslyn,Giftednewt/roslyn,physhi/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,weltkante/roslyn,Giftednewt/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,tmeschter/roslyn,nguerrera/roslyn,mattscheffer/roslyn,VSadov/roslyn,brettfo/roslyn,mattscheffer/roslyn,bartdesmet/roslyn,tannergooding/roslyn,mavasani/roslyn,diryboy/roslyn,OmarTawfik/roslyn,MattWindsor91/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,bkoelman/roslyn,OmarTawfik/roslyn,bkoelman/roslyn,DustinCampbell/roslyn,khyperia/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,CaptainHayashi/roslyn,OmarTawfik/roslyn,dotnet/roslyn,xasx/roslyn,heejaechang/roslyn,cston/roslyn,paulvanbrenk/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,tvand7093/roslyn,mmitche/roslyn,eriawan/roslyn,MattWindsor91/roslyn,eriawan/roslyn,weltkante/roslyn,genlu/roslyn,davkean/roslyn,mmitche/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,xasx/roslyn,tmat/roslyn,KirillOsenkov/roslyn,khyperia/roslyn,wvdd007/roslyn,genlu/roslyn,sharwell/roslyn,mavasani/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,paulvanbrenk/roslyn,dotnet/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,jmarolf/roslyn,jcouv/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jkotas/roslyn,gafter/roslyn,pdelvo/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,jcouv/roslyn,dpoeschl/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,AmadeusW/roslyn,VSadov/roslyn,wvdd007/roslyn,tmeschter/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,gafter/roslyn,bartdesmet/roslyn,khyperia/roslyn,abock/roslyn,ErikSchierboom/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,AlekseyTs/roslyn,orthoxerox/roslyn,KevinRansom/roslyn,nguerrera/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,tmat/roslyn
src/Workspaces/Core/Portable/Utilities/ForegroundThreadDataKind.cs
src/Workspaces/Core/Portable/Utilities/ForegroundThreadDataKind.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; namespace Microsoft.CodeAnalysis.Utilities { internal enum ForegroundThreadDataKind { Wpf, WinForms, StaUnitTest, JoinableTask, ForcedByPackageInitialize, MonoDevelopGtk, Unknown } internal static class ForegroundThreadDataInfo { private static readonly ForegroundThreadDataKind s_fallbackForegroundThreadDataKind; private static ForegroundThreadDataKind? s_currentForegroundThreadDataKind; static ForegroundThreadDataInfo() { s_fallbackForegroundThreadDataKind = CreateDefault(Unknown); } internal static ForegroundThreadDataKind CreateDefault(ForegroundThreadDataKind defaultKind) { var syncConextTypeName = SynchronizationContext.Current?.GetType().FullName; switch (syncConextTypeName) { case "System.Windows.Threading.DispatcherSynchronizationContext": return Wpf; case "Microsoft.VisualStudio.Threading.JoinableTask+JoinableTaskSynchronizationContext": return JoinableTask; case "System.Windows.Forms.WindowsFormsSynchronizationContext": return WinForms; case "MonoDevelop.Ide.DispatchService+GtkSynchronizationContext": return MonoDevelopGtk; default: return defaultKind; } } internal static ForegroundThreadDataKind CurrentForegroundThreadDataKind { get { return s_currentForegroundThreadDataKind ?? s_fallbackForegroundThreadDataKind; } } internal static void SetCurrentForegroundThreadDataKind(ForegroundThreadDataKind? kind) { s_currentForegroundThreadDataKind = kind; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading; using static Microsoft.CodeAnalysis.Utilities.ForegroundThreadDataKind; namespace Microsoft.CodeAnalysis.Utilities { internal enum ForegroundThreadDataKind { Wpf, WinForms, StaUnitTest, JoinableTask, ForcedByPackageInitialize, Unknown } internal static class ForegroundThreadDataInfo { private static readonly ForegroundThreadDataKind s_fallbackForegroundThreadDataKind; private static ForegroundThreadDataKind? s_currentForegroundThreadDataKind; static ForegroundThreadDataInfo() { s_fallbackForegroundThreadDataKind = CreateDefault(Unknown); } internal static ForegroundThreadDataKind CreateDefault(ForegroundThreadDataKind defaultKind) { var syncConextTypeName = SynchronizationContext.Current?.GetType().FullName; switch (syncConextTypeName) { case "System.Windows.Threading.DispatcherSynchronizationContext": return Wpf; case "Microsoft.VisualStudio.Threading.JoinableTask+JoinableTaskSynchronizationContext": return JoinableTask; case "System.Windows.Forms.WindowsFormsSynchronizationContext": return WinForms; default: return defaultKind; } } internal static ForegroundThreadDataKind CurrentForegroundThreadDataKind { get { return s_currentForegroundThreadDataKind ?? s_fallbackForegroundThreadDataKind; } } internal static void SetCurrentForegroundThreadDataKind(ForegroundThreadDataKind? kind) { s_currentForegroundThreadDataKind = kind; } } }
mit
C#
12394cacf66d8967388b1592da472f1f9200bb72
Add RGB property on MyColor
Verrickt/BsodSimulator
BsodSimulator/Model/MyColor.cs
BsodSimulator/Model/MyColor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Windows.UI; using Windows.UI.Xaml.Media; namespace BsodSimulator.Model { public class MyColor { public string Name { get; private set; } public Brush Brush { get; private set; } public byte R { get;private set; } public byte B { get; private set; } public byte G { get; private set; } public byte A { get; private set; } private static IReadOnlyList<MyColor> myColors; public static MyColor GetColorByName(string name) { return myColors.Single(c => c.Name == name); } public static IReadOnlyList<MyColor> GetColors() { if (myColors == null) { var propertyInfo = typeof(Colors).GetRuntimeProperties(); var solidBrushs = from info in propertyInfo let color = (Color)info.GetValue(null) select new MyColor { Name = info.Name, Brush = new SolidColorBrush(color), R = color.R, G = color.G, B = color.B, A = color.A }; myColors = solidBrushs.ToList(); } return myColors; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Windows.UI; using Windows.UI.Xaml.Media; namespace BsodSimulator.Model { public class MyColor { public string Name { get; set; } public Brush Brush { get; set; } private static IReadOnlyList<MyColor> myColors; public static MyColor GetColorByName(string name) { return myColors.Single(c => c.Name == name); } public static IReadOnlyList<MyColor> GetColors() { if (myColors == null) { var propertyInfo = typeof(Colors).GetRuntimeProperties(); var solidBrushs = from info in propertyInfo select new MyColor { Name = info.Name, Brush = new SolidColorBrush( (Color)info.GetValue(null)) }; myColors = solidBrushs.ToList(); } return myColors; } } }
mit
C#
a57443b86c1963b221533702d62dc309f9eab5e1
Add a function; turn pawns ghostly
MoyTW/MTW_AncestorSpirits
Source/MTW_AncestorSpirits/AncestorUtils.cs
Source/MTW_AncestorSpirits/AncestorUtils.cs
using Verse; using RimWorld; using UnityEngine; namespace MTW_AncestorSpirits { public static class AncestorUtils { public static readonly Color spiritColor = new Color(0.95f, 0.87f, 0.93f, .2f); public const int TicksPerInterval = GenDate.TicksPerHour / 10; public const int IntervalsPerDay = GenDate.TicksPerDay / TicksPerInterval; public const int IntervalsPerSeason = GenDate.TicksPerSeason / TicksPerInterval; public static bool IsIntervalTick() { return (Find.TickManager.TicksGame % TicksPerInterval == 0); } public static float DayValueToIntervalValue(float dayValue) { return dayValue / IntervalsPerDay; } public static float SeasonValueToIntervalValue(float seasonValue) { return seasonValue / IntervalsPerSeason; } public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } public static long EstStartOfSeasonAt(long ticks) { var currentDayTicks = (int)(GenDate.CurrentDayPercent * GenDate.TicksPerDay); var dayOfSeason = GenDate.DayOfSeasonZeroBasedAt(ticks); var currentSeasonDayTicks = DaysToTicks(dayOfSeason); return ticks - currentDayTicks - currentSeasonDayTicks; } public static bool IsAncestor(Pawn p) { return p.def.defName == "Spirit"; } public static bool SetAncestorGraphics(Pawn pawn) { if (pawn.Drawer == null || pawn.Drawer.renderer == null || pawn.Drawer.renderer.graphics == null) { return false; } if (!pawn.Drawer.renderer.graphics.AllResolved) { pawn.Drawer.renderer.graphics.ResolveAllGraphics(); } if (pawn.Drawer.renderer.graphics.headGraphic == null || pawn.Drawer.renderer.graphics.nakedGraphic == null || pawn.Drawer.renderer.graphics.headGraphic.path == null || pawn.Drawer.renderer.graphics.nakedGraphic.path == null) { return false; } Graphic nakedBodyGraphic = GraphicGetter_NakedHumanlike.GetNakedBodyGraphic(pawn.story.BodyType, ShaderDatabase.CutoutSkin, AncestorUtils.spiritColor); Graphic headGraphic = GraphicDatabase.Get<Graphic_Multi>(pawn.story.HeadGraphicPath, ShaderDatabase.CutoutSkin, Vector2.one, AncestorUtils.spiritColor); pawn.Drawer.renderer.graphics.headGraphic = headGraphic; pawn.Drawer.renderer.graphics.nakedGraphic = nakedBodyGraphic; return true; } } }
using Verse; using RimWorld; using UnityEngine; namespace MTW_AncestorSpirits { public static class AncestorUtils { public const int TicksPerInterval = GenDate.TicksPerHour / 10; public const int IntervalsPerDay = GenDate.TicksPerDay / TicksPerInterval; public const int IntervalsPerSeason = GenDate.TicksPerSeason / TicksPerInterval; public static bool IsIntervalTick() { return (Find.TickManager.TicksGame % TicksPerInterval == 0); } public static float DayValueToIntervalValue(float dayValue) { return dayValue / IntervalsPerDay; } public static float SeasonValueToIntervalValue(float seasonValue) { return seasonValue / IntervalsPerSeason; } public static int DaysToTicks(float days) { return Mathf.RoundToInt(days * GenDate.TicksPerDay); } public static int HoursToTicks(float hours) { return Mathf.RoundToInt(hours * GenDate.TicksPerHour); } public static long EstStartOfSeasonAt(long ticks) { var currentDayTicks = (int)(GenDate.CurrentDayPercent * GenDate.TicksPerDay); var dayOfSeason = GenDate.DayOfSeasonZeroBasedAt(ticks); var currentSeasonDayTicks = DaysToTicks(dayOfSeason); return ticks - currentDayTicks - currentSeasonDayTicks; } public static bool IsAncestor(Pawn p) { return p.def.defName == "Spirit"; } } }
mit
C#
cb409496ce0ae53741670f99fc78e75044f77e7b
bump version
shanselman/Fody,ColinDabritzViewpoint/Fody,PKRoma/Fody,distantcam/Fody,ichengzi/Fody,GeertvanHorrik/Fody,Fody/Fody,jasonholloway/Fody,shanselman/Fody,huoxudong125/Fody,shanselman/Fody,furesoft/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("1.6.3.0")] [assembly: AssemblyFileVersion("1.6.3.0")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("1.6.2.0")] [assembly: AssemblyFileVersion("1.6.2.0")]
mit
C#
10e8a95f714451c184e68b62374d3cfc5d611db4
fix linux
NickStrupat/ComputerInfo
ComputerInfo/Linux.cs
ComputerInfo/Linux.cs
using System; using System.IO; using System.Linq; namespace NickStrupat { internal static class Linux { public static UInt64 TotalPhysicalMemory => GetBytesFromLine(MemTotalToken); public static UInt64 AvailablePhysicalMemory => GetBytesFromLine(MemFreeToken); public static UInt64 TotalVirtualMemory => throw new NotImplementedException(); public static UInt64 AvailableVirtualMemory => throw new NotImplementedException(); private static string[] GetProcMemInfoLines() => File.ReadAllLines("/proc/meminfo"); private const string MemTotalToken = "MemTotal:"; private const string MemFreeToken = "MemFree:"; private const string KbToken = "kB"; private static UInt64 GetBytesFromLine(String token) { var memTotalLine = GetProcMemInfoLines().FirstOrDefault(x => x.StartsWith(token))?.Substring(token.Length); if (memTotalLine != null && memTotalLine.EndsWith(KbToken) && UInt64.TryParse(memTotalLine.Substring(0, memTotalLine.Length - KbToken.Length), out var memKb)) return memKb * 1024; throw new Exception(); } } }
using System; using System.IO; using System.Linq; namespace NickStrupat { internal static class Linux { public static UInt64 TotalPhysicalMemory => GetBytesFromLine(MemTotalToken); public static UInt64 AvailablePhysicalMemory => GetBytesFromLine(MemFreeToken); public static UInt64 TotalVirtualMemory => throw new NotImplementedException(); public static UInt64 AvailableVirtualMemory => throw new NotImplementedException(); private static string[] GetProcMemInfoLines() => File.ReadAllLines("/proc/meminfo"); private const string MemTotalToken = "MemTotal:"; private const string MemFreeToken = "MemFree:"; private const string KbToken = "kB"; private static UInt64 GetBytesFromLine(String token) { var memTotalLine = GetProcMemInfoLines().FirstOrDefault(x => x.StartsWith(token)); if (memTotalLine.EndsWith(KbToken) && UInt64.TryParse(memTotalLine.Substring(0, memTotalLine.Length - KbToken.Length), out var memKb)) return memKb * 1024; throw new Exception(); } } }
mit
C#
3746c9c5cf7f72ec1b8faa4c4e8ed12e80a04556
fix in schema generation
namics/TerrificNet,namics/TerrificNet,schaelle/TerrificNet,schaelle/TerrificNet,TerrificNet/TerrificNet,namics/TerrificNet,TerrificNet/TerrificNet,namics/TerrificNet,schaelle/TerrificNet,TerrificNet/TerrificNet,namics/TerrificNet,TerrificNet/TerrificNet,TerrificNet/TerrificNet,schaelle/TerrificNet,schaelle/TerrificNet
TerrificNet.ViewEngine/SchemaProviders/SchemaMergeProvider.cs
TerrificNet.ViewEngine/SchemaProviders/SchemaMergeProvider.cs
using System.Threading.Tasks; using Newtonsoft.Json.Schema; using TerrificNet.ViewEngine.Schema; namespace TerrificNet.ViewEngine.SchemaProviders { public class SchemaMergeProvider : ISchemaProvider { private readonly ISchemaProvider _schemaProvider; private readonly ISchemaProvider _schemaBaseProvider; public SchemaMergeProvider(ISchemaProvider schemaProvider, ISchemaProvider schemaBaseProvider) { _schemaProvider = schemaProvider; _schemaBaseProvider = schemaBaseProvider; } public async Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template) { var comparer = new SchemaComparer(); var schema1Task = _schemaProvider.GetSchemaFromTemplateAsync(template); var schema2Task = _schemaBaseProvider.GetSchemaFromTemplateAsync(template); if (schema1Task == null) return await schema2Task; if (schema2Task == null) return await schema1Task; await Task.WhenAll(schema1Task, schema2Task).ConfigureAwait(false); return comparer.Apply(schema1Task.Result, schema2Task.Result, new SchemaComparisionReport()); } } }
using System.Threading.Tasks; using Newtonsoft.Json.Schema; using TerrificNet.ViewEngine.Schema; namespace TerrificNet.ViewEngine.SchemaProviders { public class SchemaMergeProvider : ISchemaProvider { private readonly ISchemaProvider _schemaProvider; private readonly ISchemaProvider _schemaBaseProvider; public SchemaMergeProvider(ISchemaProvider schemaProvider, ISchemaProvider schemaBaseProvider) { _schemaProvider = schemaProvider; _schemaBaseProvider = schemaBaseProvider; } public async Task<JSchema> GetSchemaFromTemplateAsync(TemplateInfo template) { var comparer = new SchemaComparer(); var schema1Task = _schemaProvider.GetSchemaFromTemplateAsync(template); var schema2Task = _schemaBaseProvider.GetSchemaFromTemplateAsync(template); await Task.WhenAll(schema1Task, schema2Task).ConfigureAwait(false); return comparer.Apply(schema1Task.Result, schema2Task.Result, new SchemaComparisionReport()); } } }
mit
C#
1bfeebaacd8bb38cc0dd53b845f9b7aaf65923a1
fix Upgrade_20221012_ReplaceButtonClass
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20221012_ReplaceButtonClass.cs
Signum.Upgrade/Upgrades/Upgrade_20221012_ReplaceButtonClass.cs
using System; using System.IO; using System.Net; using System.Net.Http; namespace Signum.Upgrade.Upgrades; class Upgrade_20221012_ReplaceButtonClass : CodeUpgradeBase { public override string Description => "Replaces badge btn-primary -> badge bg-primary..."; public override void Execute(UpgradeContext uctx) { Regex regexButtonClass = new Regex(@"badge btn-(primary|secondary|success|warning|danger|info|light|dark)"); uctx.ForeachCodeFile($@"*.tsx", file => { file.Replace(regexButtonClass, m => m.ToString().Replace("btn-", "bg-")); }); } }
using System; using System.IO; using System.Net; using System.Net.Http; namespace Signum.Upgrade.Upgrades; class Upgrade_20221012_ReplaceButtonClass : CodeUpgradeBase { public override string Description => "Replaces btn-primary -> bg-primary and btn-... -> bg-..."; public override void Execute(UpgradeContext uctx) { Regex regexButtonClass = new Regex(@"btn-(primary|secondary|success|warning|danger|info|light|dark)"); uctx.ForeachCodeFile($@"*.tsx", file => { file.Replace(regexButtonClass, m => m.ToString().Replace("btn-", "bg-")); }); } }
mit
C#
f9710fbe55a11cac209df320be1cab3165b5ade7
test of moving a pawn up successful
MorganR/wizards-chess,MorganR/wizards-chess
WizardsChess/WizardsChessTest/Movement/MovementPlannerTest1.cs
WizardsChess/WizardsChessTest/Movement/MovementPlannerTest1.cs
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using WizardsChess.Chess; using WizardsChess.Chess.Pieces; using WizardsChess.Movement; namespace WizardsChessTest { [TestClass] public class MovementPlannerTest1 { [TestMethod] public void MovePlannerInitializationCheck() { ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); ChessPiece TestPiece = planner.board.PieceAt(4, 1); Assert.AreEqual(TestPiece.Type, PieceType.Pawn); } [TestMethod] public void SampleMoveChecking1() { //String correctPoints = "start move\n[12, 3]\n[12, 7]\nend move \n"; //Set moves //White King Pawn to E5 Point2D moveW1Start = new Point2D(4, 1); //start location of the first white move (0-7, 0-7) Point2D moveW1End = new Point2D(4, 3); List<List<Point2D>> paths = new List<List<Point2D>>(); String printString = ""; ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); paths = planner.Move(moveW1Start, moveW1End); printString = planner.PrintDebug(paths); //System.Diagnostics.Debug.Write(printString); Assert.AreEqual("[12, 3]", paths[0][0].ToString()); Assert.AreEqual("[12, 7]", paths[0][1].ToString()); //Assert.AreEqual(correctPoints, printString); } /* public void SampleMoveChecking2() { String correctPoints = "start move\n[16, 1]\n"; ///TODO: finish this long ass list //Set moves //White King Side Knight to F6 Point2D moveW1Start = new Point2D(6, 0); //start location of the first white move (0-7, 0-7) Point2D moveW1End = new Point2D(5, 2); //Black King Pawn to E4 Point2D moveB1Start = new Point2D(4, 6); Point2D moveB1End = new Point2D(4, 4); //White Knight takes Black Pawn at E4 Point2D moveW2Start = moveW1End; Point2D moveW2End = moveB1End; List<List<List<Point2D>>> listOfPaths = new List<List<List<Point2D>>>(); String printString = ""; ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); listOfPaths.Add(planner.Move(moveW1Start, moveW1End)); listOfPaths.Add(planner.Move(moveB1Start, moveB1End)); listOfPaths.Add(planner.Move(moveW2Start, moveW2End)); listOfPaths.ForEach((p) => { printString += planner.PrintDebug(p); }); Assert.AreEqual(correctPoints, printString); } */ } }
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using WizardsChess.Chess; using WizardsChess.Chess.Pieces; using WizardsChess.Movement; namespace WizardsChessTest { [TestClass] public class MovementPlannerTest1 { [TestMethod] public void MovePlannerInitializationCheck() { ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); ChessPiece TestPiece = planner.board.PieceAt(1, 4); Assert.AreEqual(TestPiece.Type, PieceType.Pawn); } /*public void SampleMoveChecking1() { String correctPoints = "start move\n[12, 3]\n[12,7\nend move \n"; //Set moves //White King Pawn to E5 Point2D moveW1Start = new Point2D(4, 1); //start location of the first white move (0-7, 0-7) Point2D moveW1End = new Point2D(4, 3); List<List<Point2D>> paths = new List<List<Point2D>>(); String printString = ""; ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); paths = planner.Move(moveW1Start, moveW1End); printString = planner.PrintDebug(paths); Assert.AreEqual(correctPoints, printString); }*/ /* public void SampleMoveChecking2() { String correctPoints = "start move\n[16, 1]\n"; ///TODO: finish this long ass list //Set moves //White King Side Knight to F6 Point2D moveW1Start = new Point2D(6, 0); //start location of the first white move (0-7, 0-7) Point2D moveW1End = new Point2D(5, 2); //Black King Pawn to E4 Point2D moveB1Start = new Point2D(4, 6); Point2D moveB1End = new Point2D(4, 4); //White Knight takes Black Pawn at E4 Point2D moveW2Start = moveW1End; Point2D moveW2End = moveB1End; List<List<List<Point2D>>> listOfPaths = new List<List<List<Point2D>>>(); String printString = ""; ChessBoard board = new ChessBoard(); MovementPlanner planner = new MovementPlanner(board); listOfPaths.Add(planner.Move(moveW1Start, moveW1End)); listOfPaths.Add(planner.Move(moveB1Start, moveB1End)); listOfPaths.Add(planner.Move(moveW2Start, moveW2End)); listOfPaths.ForEach((p) => { printString += planner.PrintDebug(p); }); Assert.AreEqual(correctPoints, printString); } */ } }
apache-2.0
C#
96f895650dc5eb2ef2e61760f1b7b7e829dca896
add missed _logger.IsEnabled
Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode,Ky7m/DemoCode
WorkWithTelemetryInDotNET/BillingService/OrderPlacedHandler.cs
WorkWithTelemetryInDotNET/BillingService/OrderPlacedHandler.cs
using JetBrains.Annotations; using NServiceBus; using NServiceBus.Extensions.Diagnostics; using Shared; namespace BillingService; [UsedImplicitly] public partial class OrderPlacedHandler : IHandleMessages<OrderPlaced> { private readonly ILogger<OrderPlacedHandler> _logger; public OrderPlacedHandler(ILogger<OrderPlacedHandler> logger) { _logger = logger; } [LoggerMessage( Level = LogLevel.Information, Message = "BillingService has received OrderPlaced, OrderId = {OrderId}")] public static partial void LogOrderReceivedEvent(ILogger logger, string orderId); public Task Handle(OrderPlaced message, IMessageHandlerContext context) { if (_logger.IsEnabled(LogLevel.Information)) { LogOrderReceivedEvent(_logger, message.OrderId); } var currentActivity = context.Extensions.Get<ICurrentActivity>(); currentActivity.Current?.AddTag("payment.transaction.id", Guid.NewGuid().ToString()); return Task.CompletedTask; } }
using JetBrains.Annotations; using NServiceBus; using NServiceBus.Extensions.Diagnostics; using Shared; namespace BillingService; [UsedImplicitly] public partial class OrderPlacedHandler : IHandleMessages<OrderPlaced> { private readonly ILogger<OrderPlacedHandler> _logger; public OrderPlacedHandler(ILogger<OrderPlacedHandler> logger) { _logger = logger; } [LoggerMessage( Level = LogLevel.Information, Message = "BillingService has received OrderPlaced, OrderId = {OrderId}")] public static partial void LogOrderReceivedEvent(ILogger logger, string orderId); public Task Handle(OrderPlaced message, IMessageHandlerContext context) { LogOrderReceivedEvent(_logger, message.OrderId); var currentActivity = context.Extensions.Get<ICurrentActivity>(); currentActivity.Current?.AddTag("payment.transaction.id", Guid.NewGuid().ToString()); return Task.CompletedTask; } }
mit
C#
37ab5cfb151d578e91f58320cd75e512d6da0d7c
Fix comment
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/Dialogs/TestDialogViewModel.cs
WalletWasabi.Fluent/ViewModels/Dialogs/TestDialogViewModel.cs
using System.Windows.Input; using ReactiveUI; namespace WalletWasabi.Fluent.ViewModels.Dialogs { public class TestDialogViewModel : DialogViewModelBase<bool> { private NavigationStateViewModel _navigationState; private string _message; public TestDialogViewModel(NavigationStateViewModel navigationState, string message) { _navigationState = navigationState; _message = message; CancelCommand = ReactiveCommand.Create(() => Close(false)); NextCommand = ReactiveCommand.Create(() => Close(true)); } public string Message { get => _message; set => this.RaiseAndSetIfChanged(ref _message, value); } public ICommand CancelCommand { get; } public ICommand NextCommand { get; } protected override void OnDialogClosed() { // TODO: Disable when using Dialog inside DialogScreenViewModel / Settings // _navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(new AddWalletPageViewModel(_navigationState)); } public void Close() { // TODO: Dialog.xaml back Button binding to Close() method on base class which is protected so exception is thrown. Close(false); } } }
using System.Windows.Input; using ReactiveUI; namespace WalletWasabi.Fluent.ViewModels.Dialogs { public class TestDialogViewModel : DialogViewModelBase<bool> { private NavigationStateViewModel _navigationState; private string _message; public TestDialogViewModel(NavigationStateViewModel navigationState, string message) { _navigationState = navigationState; _message = message; CancelCommand = ReactiveCommand.Create(() => Close(false)); NextCommand = ReactiveCommand.Create(() => Close(true)); } public string Message { get => _message; set => this.RaiseAndSetIfChanged(ref _message, value); } public ICommand CancelCommand { get; } public ICommand NextCommand { get; } protected override void OnDialogClosed() { // TODO: Disable when using Dialog inside DialogScreenViewModel / Settings //_navigationState.HomeScreen?.Invoke().Router.NavigateAndReset.Execute(new AddWalletPageViewModel(_navigationState)); } public void Close() { // TODO: Dialog.xaml back Button binding to Close() method on base class which is protected so exception is thrown. Close(false); } } }
mit
C#
2a9027cf72eec7f5b71fa34d202dab7fd312980a
Put the addresses in the BCC line
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Jobs/EvaluationDueReminderJob.cs
Battery-Commander.Web/Jobs/EvaluationDueReminderJob.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentScheduler; using Serilog; using System; using System.IO; using System.Linq; namespace BatteryCommander.Web.Jobs { public class EvaluationDueReminderJob : IJob { private static readonly ILogger Log = Serilog.Log.ForContext<EvaluationDueReminderJob>(); private readonly Database db; private readonly IFluentEmailFactory emailSvc; public EvaluationDueReminderJob(Database db, IFluentEmailFactory emailSvc) { this.db = db; this.emailSvc = emailSvc; } public void Execute() { var soon = DateTime.Today.AddDays(15); Log.Information("Building Evaluations Due email for evals due before {soon}", soon); var evaluations_due_soon = EvaluationService.Filter(db, new EvaluationService.Query { Complete = false }) .Where(evaluation => evaluation.ThruDate < soon) .OrderBy(evaluation => evaluation.ThruDate) .ToList(); var recipients = SoldierService.Filter(db, new SoldierService.Query { Ranks = new[] { Rank.E6, Rank.E7, Rank.E8, Rank.O1, Rank.O2, Rank.O3 } }) .GetAwaiter() .GetResult() .Where(soldier => soldier.CanLogin) .Select(soldier => soldier.GetEmails()) .SelectMany(email => email) .ToList(); emailSvc .Create() .BCC(recipients) .To(emailAddress: "Evaluations@RedLeg.app") .Subject("Past Due and Upcoming Evaluations") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/EvaluationsDue.cshtml", evaluations_due_soon) .SendWithErrorCheck(); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentScheduler; using Serilog; using System; using System.IO; using System.Linq; namespace BatteryCommander.Web.Jobs { public class EvaluationDueReminderJob : IJob { private static readonly ILogger Log = Serilog.Log.ForContext<EvaluationDueReminderJob>(); private readonly Database db; private readonly IFluentEmailFactory emailSvc; public EvaluationDueReminderJob(Database db, IFluentEmailFactory emailSvc) { this.db = db; this.emailSvc = emailSvc; } public void Execute() { var soon = DateTime.Today.AddDays(15); Log.Information("Building Evaluations Due email for evals due before {soon}", soon); var evaluations_due_soon = EvaluationService.Filter(db, new EvaluationService.Query { Complete = false }) .Where(evaluation => evaluation.ThruDate < soon) .OrderBy(evaluation => evaluation.ThruDate) .ToList(); var recipients = SoldierService.Filter(db, new SoldierService.Query { Ranks = new[] { Rank.E6, Rank.E7, Rank.E8, Rank.O1, Rank.O2, Rank.O3 } }) .GetAwaiter() .GetResult() .Where(soldier => soldier.CanLogin) .Select(soldier => soldier.GetEmails()) .SelectMany(email => email) .ToList(); emailSvc .Create() .To(recipients) .Subject("Past Due and Upcoming Evaluations") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/EvaluationsDue.cshtml", evaluations_due_soon) .SendWithErrorCheck(); } } }
mit
C#
014a30a92f27e89fa17e9006fb48718338bda918
Simplify the AutoSubscribe feature
RadicalFx/Radical.Windows
src/Radical.Windows/Presentation/Boot/Features/AutoSubscribe.cs
src/Radical.Windows/Presentation/Boot/Features/AutoSubscribe.cs
using Microsoft.Extensions.DependencyInjection; using Radical.ComponentModel.Messaging; using Radical.Linq; using Radical.Reflection; using System; using System.Collections.Generic; using System.Linq; namespace Radical.Windows.Presentation.Boot.Features { class AutoSubscribe : IFeature { readonly List<Entry> entries = new List<Entry>(); public void Setup(IServiceProvider serviceProvider, ApplicationSettings applicationSettings) { var broker = serviceProvider.GetRequiredService<IMessageBroker>(); foreach (var entry in entries) { entry.Subscribe(broker, serviceProvider); } } internal void Add(Type implementation, IEnumerable<Type> contracts) { entries.Add(new Entry() { Implementation = implementation }); } } class Entry { public Type Implementation { get; set; } public void Subscribe(IMessageBroker broker, IServiceProvider serviceProvider) { var invocationModel = Implementation.Is<INeedSafeSubscription>() ? InvocationModel.Safe : InvocationModel.Default; Implementation.GetInterfaces() .Where(i => i.Is<IHandleMessage>() && i.IsGenericType) .ForEach(genericHandler => { var messageType = genericHandler.GetGenericArguments().Single(); broker.Subscribe(this, messageType, invocationModel, (s, msg) => { var handler = serviceProvider.GetService(Implementation) as IHandleMessage; if (handler.ShouldHandle(s, msg)) { handler.Handle(s, msg); } }); }); } } }
using Microsoft.Extensions.DependencyInjection; using Radical.ComponentModel.Messaging; using Radical.Linq; using Radical.Reflection; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Radical.Windows.Presentation.Boot.Features { class AutoSubscribe : IFeature { List<Entry> entries { get; set; } = new List<Entry>(); public void Setup(IServiceProvider serviceProvider, ApplicationSettings applicationSettings) { var broker = serviceProvider.GetRequiredService<IMessageBroker>(); foreach (var entry in entries) { entry.Subscribe(broker, serviceProvider); } } internal void Add(Type implementation, IEnumerable<Type> contracts) { entries.Add(new Entry() { Implementation = implementation, Contracts = contracts }); } } class Entry { public Type Implementation { get; set; } public IEnumerable<Type> Contracts { get; set; } public void Subscribe(IMessageBroker broker, IServiceProvider serviceProvider) { var invocationModel = Implementation.Is<INeedSafeSubscription>() ? InvocationModel.Safe : InvocationModel.Default; Implementation.GetInterfaces() .Where(i => i.Is<IHandleMessage>() && i.IsGenericType) .ForEach(genericHandler => { var messageType = genericHandler.GetGenericArguments().Single(); broker.Subscribe(this, messageType, invocationModel, (s, msg) => { var handler = serviceProvider.GetService(Implementation) as IHandleMessage; if (handler.ShouldHandle(s, msg)) { handler.Handle(s, msg); } }); }); } } }
mit
C#
096925012cf2127f3f92c783342ee9bac1134fd4
Update BaseCommitmentOrchestrator.cs
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Orchestrators/BaseCommitmentOrchestrator.cs
src/SFA.DAS.ProviderApprenticeshipsService.Web/Orchestrators/BaseCommitmentOrchestrator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MediatR; using SFA.DAS.Commitments.Api.Types; using SFA.DAS.Commitments.Api.Types.Commitment; using SFA.DAS.Commitments.Api.Types.Commitment.Types; using SFA.DAS.Commitments.Api.Types.TrainingProgramme; using SFA.DAS.HashingService; using SFA.DAS.ProviderApprenticeshipsService.Application.Exceptions; using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces; using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators { public class BaseCommitmentOrchestrator { protected readonly IMediator Mediator; protected readonly IHashingService HashingService; protected readonly IProviderCommitmentsLogger Logger; public BaseCommitmentOrchestrator(IMediator mediator, IHashingService hashingService, IProviderCommitmentsLogger logger) { // we keep null checks here, as this is a base class Mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); HashingService = hashingService ?? throw new ArgumentNullException(nameof(hashingService)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using MediatR; using SFA.DAS.Commitments.Api.Types; using SFA.DAS.Commitments.Api.Types.Commitment; using SFA.DAS.Commitments.Api.Types.Commitment.Types; using SFA.DAS.Commitments.Api.Types.TrainingProgramme; using SFA.DAS.HashingService; using SFA.DAS.ProviderApprenticeshipsService.Application.Exceptions; using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces; using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse; namespace SFA.DAS.ProviderApprenticeshipsService.Web.Orchestrators { public class BaseCommitmentOrchestrator { protected readonly IMediator Mediator; protected readonly IHashingService HashingService; protected readonly IProviderCommitmentsLogger Logger; public BaseCommitmentOrchestrator(IMediator mediator, IHashingService hashingService, IProviderCommitmentsLogger logger) { // we keep null checks here, as this is a base class Mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); HashingService = hashingService ?? throw new ArgumentNullException(nameof(hashingService)); Logger = logger ?? throw new ArgumentNullException(nameof(logger)); } protected static void AssertCommitmentStatus(CommitmentView commitment) { AssertCommitmentStatus(commitment, EditStatus.ProviderOnly); AssertCommitmentStatus(commitment, AgreementStatus.EmployerAgreed, AgreementStatus.ProviderAgreed, AgreementStatus.NotAgreed); } protected static void AssertCommitmentStatus(CommitmentView commitment, params AgreementStatus[] allowedAgreementStatuses) { if (commitment == null) throw new InvalidStateException("Null commitment"); if (!allowedAgreementStatuses.Contains(commitment.AgreementStatus)) throw new InvalidStateException($"Invalid commitment state (agreement status is {commitment.AgreementStatus}, expected {string.Join(",", allowedAgreementStatuses)})"); } protected static void AssertCommitmentStatus(CommitmentView commitment, params EditStatus[] allowedEditStatuses) { if (commitment == null) throw new InvalidStateException("Null commitment"); if (!allowedEditStatuses.Contains(commitment.EditStatus)) throw new InvalidStateException($"Invalid commitment state (edit status is {commitment.EditStatus}, expected {string.Join(",", allowedEditStatuses)})"); } } }
mit
C#
1d0761b604ce0f5abafac03f919a0347f0349002
Add a random string to adminEmail when creating account during integration testing to make sure the new account is unique
Jericho/CakeMail.RestClient
Source/CakeMail.RestClient.IntegrationTests/Clients.cs
Source/CakeMail.RestClient.IntegrationTests/Clients.cs
using CakeMail.RestClient.Models; using System; using System.Linq; using System.Threading.Tasks; namespace CakeMail.RestClient.IntegrationTests { public static class ClientsTests { private const int UTC_TIMEZONE_ID = 542; public static async Task ExecuteAllMethods(CakeMailRestClient api, string userKey, long clientId) { Console.WriteLine(""); Console.WriteLine(new string('-', 25)); Console.WriteLine("Executing CLIENTS methods..."); var clientsCount = await api.Clients.GetCountAsync(userKey, null, null, clientId).ConfigureAwait(false); Console.WriteLine("Clients count = {0}", clientsCount); var adminEmail = string.Format("admin{0:00}+{1:0000}@integrationtesting.com", clientsCount, (new Random()).Next(9999)); var confirmation = await api.Clients.CreateAsync(clientId, "_Integration Testing", "123 1st Street", "Suite 123", "Atlanta", "GA", "12345", "us", "www.company.com", "1-888-myphone", "1-888myfax", adminEmail, "Admin", "Integration Testing", "Super Administrator", "1-888-AdminPhone", "1-888-AdminMobile", "en_US", UTC_TIMEZONE_ID, "adminpassword", true).ConfigureAwait(false); Console.WriteLine("New client created. Confirmation code: {0}", confirmation); var unconfirmedClient = await api.Clients.GetAsync(userKey, confirmation).ConfigureAwait(false); Console.WriteLine("Information about this unconfirmed client: Name = {0}", unconfirmedClient.Name); var registrationInfo = await api.Clients.ConfirmAsync(confirmation).ConfigureAwait(false); Console.WriteLine("Client has been confirmed. Id = {0}", registrationInfo.ClientId); var clients = await api.Clients.GetListAsync(userKey, null, null, ClientsSortBy.CompanyName, SortDirection.Ascending, null, null, clientId).ConfigureAwait(false); Console.WriteLine("All clients retrieved. Count = {0}", clients.Count()); var updated = await api.Clients.UpdateAsync(userKey, registrationInfo.ClientId, name: "Fictitious Company").ConfigureAwait(false); Console.WriteLine("Client updated: {0}", updated ? "success" : "failed"); var client = await api.Clients.GetAsync(userKey, registrationInfo.ClientId).ConfigureAwait(false); Console.WriteLine("Client retrieved: Name = {0}", client.Name); var suspended = await api.Clients.SuspendAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client suspended: {0}", suspended ? "success" : "failed"); var reactivated = await api.Clients.ActivateAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client re-activated: {0}", reactivated ? "success" : "failed"); var deleted = await api.Clients.DeleteAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client deleted: {0}", deleted ? "success" : "failed"); Console.WriteLine(new string('-', 25)); Console.WriteLine(""); } } }
using CakeMail.RestClient.Models; using System; using System.Linq; using System.Threading.Tasks; namespace CakeMail.RestClient.IntegrationTests { public static class ClientsTests { private const int UTC_TIMEZONE_ID = 542; public static async Task ExecuteAllMethods(CakeMailRestClient api, string userKey, long clientId) { Console.WriteLine(""); Console.WriteLine(new string('-', 25)); Console.WriteLine("Executing CLIENTS methods..."); var clientsCount = await api.Clients.GetCountAsync(userKey, null, null, clientId).ConfigureAwait(false); Console.WriteLine("Clients count = {0}", clientsCount); var adminEmail = string.Format("admin{0:00}@integrationtesting.com", clientsCount); var confirmation = await api.Clients.CreateAsync(clientId, "_Integration Testing", "123 1st Street", "Suite 123", "Atlanta", "GA", "12345", "us", "www.company.com", "1-888-myphone", "1-888myfax", adminEmail, "Admin", "Integration Testing", "Super Administrator", "1-888-AdminPhone", "1-888-AdminMobile", "en_US", UTC_TIMEZONE_ID, "adminpassword", true).ConfigureAwait(false); Console.WriteLine("New client created. Confirmation code: {0}", confirmation); var unconfirmedClient = await api.Clients.GetAsync(userKey, confirmation).ConfigureAwait(false); Console.WriteLine("Information about this unconfirmed client: Name = {0}", unconfirmedClient.Name); var registrationInfo = await api.Clients.ConfirmAsync(confirmation).ConfigureAwait(false); Console.WriteLine("Client has been confirmed. Id = {0}", registrationInfo.ClientId); var clients = await api.Clients.GetListAsync(userKey, null, null, ClientsSortBy.CompanyName, SortDirection.Ascending, null, null, clientId).ConfigureAwait(false); Console.WriteLine("All clients retrieved. Count = {0}", clients.Count()); var updated = await api.Clients.UpdateAsync(userKey, registrationInfo.ClientId, name: "Fictitious Company").ConfigureAwait(false); Console.WriteLine("Client updated: {0}", updated ? "success" : "failed"); var client = await api.Clients.GetAsync(userKey, registrationInfo.ClientId).ConfigureAwait(false); Console.WriteLine("Client retrieved: Name = {0}", client.Name); var suspended = await api.Clients.SuspendAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client suspended: {0}", suspended ? "success" : "failed"); var reactivated = await api.Clients.ActivateAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client re-activated: {0}", reactivated ? "success" : "failed"); var deleted = await api.Clients.DeleteAsync(userKey, client.Id).ConfigureAwait(false); Console.WriteLine("Client deleted: {0}", deleted ? "success" : "failed"); Console.WriteLine(new string('-', 25)); Console.WriteLine(""); } } }
mit
C#
a20806d3a8fa68155caef9ad7bb0d488270c667c
Fix namespace issue in uwp
markmeeus/MarcelloDB
MarcelloDB.uwp/Platform.cs
MarcelloDB.uwp/Platform.cs
using MarcelloDB.Collections; using MarcelloDB.Platform; using MarcelloDB.Storage; using MarcelloDB.uwp.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
using MarcelloDB.Collections; using MarcelloDB.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public Storage.IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
mit
C#
8a9ec4b34c83a45e83f0e34ca8c1e0b3a8d7f7cb
update version
IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates,IdentityServer/IdentityServer4.Templates
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.4.0"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var buildArtifacts = Directory("./artifacts/packages"); var packageVersion = "2.3.1"; /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts, Directory("./feed/content/UI") }); }); /////////////////////////////////////////////////////////////////////////////// // Copy /////////////////////////////////////////////////////////////////////////////// Task("Copy") .IsDependentOn("Clean") .Does(() => { CreateDirectory("./feed/content"); // copy the singel csproj templates var files = GetFiles("./src/**/*.*"); CopyFiles(files, "./feed/content", true); // copy the UI files files = GetFiles("./ui/**/*.*"); CopyFiles(files, "./feed/content/ui", true); }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Copy") .Does(() => { var settings = new NuGetPackSettings { Version = packageVersion, OutputDirectory = buildArtifacts }; if (AppVeyor.IsRunningOnAppVeyor) { settings.Version = packageVersion + "-b" + AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0'); } NuGetPack("./feed/IdentityServer4.Templates.nuspec", settings); }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
c2d968382df8cd07ac93cdddb65d1e6305760cea
Clean up usings.
sjp/Schematic,sjp/Schematic,sjp/SJP.Schema,sjp/Schematic,sjp/Schematic
src/SJP.Schematic.Oracle.Tests/Integration/OracleDatabaseIdentifierLengthValidationTests.cs
src/SJP.Schematic.Oracle.Tests/Integration/OracleDatabaseIdentifierLengthValidationTests.cs
using NUnit.Framework; using SJP.Schematic.Core; namespace SJP.Schematic.Oracle.Tests.Integration { [TestFixture] internal sealed class OracleDatabaseIdentifierLengthValidationTests : OracleTest { private IOracleDatabaseIdentifierValidation Validator => new OracleDatabaseIdentifierLengthValidation(Connection); [Test] public void IsValidIdentifier_GivenIdentifierWithShortName_ReturnsTrue() { Identifier identifier = "test"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsTrue(isValid); } [Test] public void IsValidIdentifier_GivenIdentifierWithNonAsciiName_ReturnsFalse() { Identifier identifier = "☃"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsFalse(isValid); } [Test] public void IsValidIdentifier_GivenIdentifierWithLongName_ReturnsFalse() { // really long, should exceed max length even for newer oracle databases Identifier identifier = "asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsFalse(isValid); } } }
using System; using NUnit.Framework; using System.Data; using Moq; using SJP.Schematic.Core; namespace SJP.Schematic.Oracle.Tests.Integration { [TestFixture] internal class OracleDatabaseIdentifierLengthValidationTests : OracleTest { private IOracleDatabaseIdentifierValidation Validator => new OracleDatabaseIdentifierLengthValidation(Connection); [Test] public void IsValidIdentifier_GivenIdentifierWithShortName_ReturnsTrue() { Identifier identifier = "test"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsTrue(isValid); } [Test] public void IsValidIdentifier_GivenIdentifierWithNonAsciiName_ReturnsFalse() { Identifier identifier = "☃"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsFalse(isValid); } [Test] public void IsValidIdentifier_GivenIdentifierWithLongName_ReturnsFalse() { // really long, should exceed max length even for newer oracle databases Identifier identifier = "asdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasdasd"; var isValid = Validator.IsValidIdentifier(identifier); Assert.IsFalse(isValid); } } }
mit
C#
0d2921222cbe9e7ed4fba19edb38254466cafcf7
Fix test appveyor
gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LMP.Tests/XmlConverterTests.cs
LMP.Tests/XmlConverterTests.cs
using LunaCommon.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace LMP.Tests { [TestClass] public class XmlConverterTests { private static readonly string XmlExamplePath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "XmlExampleFiles"); [TestMethod] public void TestConvertEvaToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "EVA.txt")); } [TestMethod] public void TestConvertVesselToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "Vessel.txt")); } [TestMethod] public void TestConvertBigVesselToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "BigVessel.txt")); } [TestMethod] public void TestSeveralVesselsToXml() { foreach (var file in Directory.GetFiles(Path.Combine(XmlExamplePath, "Others"))) { SwitchToXmlAndBack(file); } } private void SwitchToXmlAndBack(string filePath) { if (!File.Exists(filePath)) return; var configNode = File.ReadAllText(filePath); var xml = ConfigNodeXmlParser.ConvertToXml(configNode); var backToConfigNode = ConfigNodeXmlParser.ConvertToConfigNode(xml); Assert.IsTrue(configNode.Equals(backToConfigNode), $"Error serializing config node. File: {Path.GetFileName(filePath)}"); } } }
using LunaCommon.Xml; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.IO; namespace LMP.Tests { [TestClass] public class XmlConverterTests { private static readonly string XmlExamplePath = Path.Combine(Directory.GetCurrentDirectory(), "..", "..", "XmlExampleFiles"); [TestMethod] public void TestConvertEvaToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "EVA.txt")); } [TestMethod] public void TestConvertVesselToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "Vessel.txt")); } [TestMethod] public void TestConvertBigVesselToXml() { SwitchToXmlAndBack(Path.Combine(XmlExamplePath, "BigVessel.txt")); } [TestMethod] public void TestSeveralVesselsToXml() { foreach (var file in Directory.GetFiles(Path.Combine(XmlExamplePath, "Others"))) { SwitchToXmlAndBack(file); } } private void SwitchToXmlAndBack(string filePath) { var configNode = File.ReadAllText(filePath); var xml = ConfigNodeXmlParser.ConvertToXml(configNode); var backToConfigNode = ConfigNodeXmlParser.ConvertToConfigNode(xml); Assert.IsTrue(configNode.Equals(backToConfigNode), $"Error serializing config node. File: {Path.GetFileName(filePath)}"); } } }
mit
C#
7181548128339348eac72a8bb90b22c099d1d128
add message saying that all pictures in that category will be deleted too
SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery
AstroPhotoGallery/AstroPhotoGallery/Views/Category/Delete.cshtml
AstroPhotoGallery/AstroPhotoGallery/Views/Category/Delete.cshtml
@model AstroPhotoGallery.Models.Category @{ ViewBag.Title = "Delete Category"; } <div class="container"> <div class="well"> <h2>@ViewBag.Title</h2> <h3 style="color: #e74c3c; text-align: center"> Are you sure you want to delete the below category? <br /> <br /> All pictures in that category will be deleted too. </h3> <br /> @using (Html.BeginForm("Delete", "Category", FormMethod.Post, new { @class = "form-horizontal" })) { @Html.AntiForgeryToken() <div class="form-group"> @Html.LabelFor(m => m.Name, new { @class = "control-label col-sm-4" }) <div class="col-sm-4 "> @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @readonly = "readonly" }) </div> </div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-4"> @Html.ActionLink("Cancel", "Index", "Category", new { @class = "btn btn-default" }) <input type="submit" value="Delete" class="btn btn-danger" /> </div> </div> } </div> </div>
@model AstroPhotoGallery.Models.Category @{ ViewBag.Title = "Delete Category"; } <div class="container"> <div class="well"> <h2>@ViewBag.Title</h2> <h3 style="color: #e74c3c; text-align: center">Are you sure you want to delete the below category?</h3> <br /> @using (Html.BeginForm("Delete", "Category", FormMethod.Post, new { @class = "form-horizontal" })) { @Html.AntiForgeryToken() <div class="form-group"> @Html.LabelFor(m => m.Name, new { @class = "control-label col-sm-4" }) <div class="col-sm-4 "> @Html.TextBoxFor(m => m.Name, new { @class = "form-control", @readonly = "readonly" }) </div> </div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-4"> @Html.ActionLink("Cancel", "Index", "Category", new { @class = "btn btn-default" }) <input type="submit" value="Delete" class="btn btn-danger" /> </div> </div> } </div> </div>
mit
C#
eb26e3aaa9915ce72b4bceb62ab6bd40f1d53975
Make monster ignore enemy bullets
ianlav/EECS393IsaacGameThing,ianlav/EECS393IsaacGameThing,ianlav/EECS393IsaacGameThing
EECS393IsaacGameThing/Assets/Scripts/Characters/Enemy/Monster.cs
EECS393IsaacGameThing/Assets/Scripts/Characters/Enemy/Monster.cs
using UnityEngine; using System.Collections; [RequireComponent(typeof(Rigidbody2D))] public class Monster : MonoBehaviour { public float updatesToUpgrade; private float updateClock; public float maxVelocity; //Highest possible speed of monster. Increases as game progresses. public float acceleration; //Ability for monster to return to speed when hit. Increases. public float defense; //Modifier for the amount that damage slows down monster. Increases. private Rigidbody2D rigidMonster; private PlayerMovement player; private UIController ui; void Start () { rigidMonster = GetComponent<Rigidbody2D>(); gameObject.tag = "Monster"; player = FindObjectOfType<PlayerMovement>(); ui = FindObjectOfType<UIController>(); } public void takeDamage(int damage){ maxVelocity -= damage/defense; //slow the monster when hit by projectile } void Update () { if(rigidMonster.velocity.x<maxVelocity){ rigidMonster.velocity = new Vector2(rigidMonster.velocity.x+acceleration, rigidMonster.velocity.y); if(rigidMonster.velocity.x > maxVelocity){rigidMonster.velocity=new Vector2(maxVelocity, rigidMonster.velocity.y);} } rigidMonster.velocity = new Vector2(rigidMonster.velocity.x, player.transform.position.y - transform.position.y); //keeps the monster on the same y plane if (updateClock >= updatesToUpgrade) { updateClock = 0; UpgradeMonster (); } else { updateClock += Time.deltaTime; } } void UpgradeMonster(){ maxVelocity += 0.5f; acceleration += 0.1f; defense += 0.5f; } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet")) { Bullet bul = col.GetComponent<Bullet>(); if (!bul.enemyMode) { rigidMonster.velocity = new Vector2 (rigidMonster.velocity.x - bul.damage / (1 + defense), 0); ui.thingTookDamage (col.transform.position, (int)(bul.damage / (1 + defense))); } } if(!col.CompareTag("LevelTrigger")) Destroy(col.gameObject); } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(Rigidbody2D))] public class Monster : MonoBehaviour { public float updatesToUpgrade; private float updateClock; public float maxVelocity; //Highest possible speed of monster. Increases as game progresses. public float acceleration; //Ability for monster to return to speed when hit. Increases. public float defense; //Modifier for the amount that damage slows down monster. Increases. private Rigidbody2D rigidMonster; private PlayerMovement player; private UIController ui; void Start () { rigidMonster = GetComponent<Rigidbody2D>(); gameObject.tag = "Monster"; player = FindObjectOfType<PlayerMovement>(); ui = FindObjectOfType<UIController>(); } public void takeDamage(int damage){ maxVelocity -= damage/defense; //slow the monster when hit by projectile } void Update () { if(rigidMonster.velocity.x<maxVelocity){ rigidMonster.velocity = new Vector2(rigidMonster.velocity.x+acceleration, rigidMonster.velocity.y); if(rigidMonster.velocity.x > maxVelocity){rigidMonster.velocity=new Vector2(maxVelocity, rigidMonster.velocity.y);} } rigidMonster.velocity = new Vector2(rigidMonster.velocity.x, player.transform.position.y - transform.position.y); //keeps the monster on the same y plane if (updateClock >= updatesToUpgrade) { updateClock = 0; UpgradeMonster (); } else { updateClock += Time.deltaTime; } } void UpgradeMonster(){ maxVelocity += 0.5f; acceleration += 0.1f; defense += 0.5f; } void OnTriggerEnter2D(Collider2D col) { if (col.CompareTag("Bullet")) { Bullet bul = col.GetComponent<Bullet>(); rigidMonster.velocity = new Vector2(rigidMonster.velocity.x - bul.damage / (1 + defense), 0); ui.thingTookDamage(col.transform.position, (int)(bul.damage / (1 + defense))); } if(!col.CompareTag("LevelTrigger")) Destroy(col.gameObject); } }
apache-2.0
C#
7cb39f212eaa07ad8b45b65c1a733d510cf5275f
refactor interface
Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017,Borayvor/ASP.NET-MVC-CourseProject-2017
PhotoArtSystem/Data/PhotoArtSystem.Data/IApplicationDbContext.cs
PhotoArtSystem/Data/PhotoArtSystem.Data/IApplicationDbContext.cs
namespace PhotoArtSystem.Data { using System.Data.Entity; using System.Data.Entity.Infrastructure; public interface IApplicationDbContext { DbSet<TEntity> Set<TEntity>() where TEntity : class; DbEntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class; void Dispose(); int SaveChanges(); } }
namespace PhotoArtSystem.Data { public interface IApplicationDbContext { int SaveChanges(); } }
mit
C#
24803833ac008a506f650237ea6a1d36dc84712f
Add source documentation for history item.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/History/TraktHistoryItem.cs
Source/Lib/TraktApiSharp/Objects/Get/History/TraktHistoryItem.cs
namespace TraktApiSharp.Objects.Get.History { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using Shows.Seasons; using System; /// <summary>A Trakt history item, containing a movie, show, season and / or episode and information about it.</summary> public class TraktHistoryItem { /// <summary>Gets or sets the id of this history item.</summary> [JsonProperty(PropertyName = "id")] public int Id { get; set; } /// <summary>Gets or sets the UTC datetime, when the movie, show, season and / or episode was watched.</summary> [JsonProperty(PropertyName = "watched_at")] public DateTime? WatchedAt { get; set; } /// <summary> /// Gets or sets the type of action. See also <seealso cref="TraktHistoryActionType" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "action")] [JsonConverter(typeof(TraktEnumerationConverter<TraktHistoryActionType>))] [Nullable] public TraktHistoryActionType Action { get; set; } /// <summary> /// Gets or sets the object type, which this history item contains. /// See also <seealso cref="TraktSyncItemType" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncItemType>))] [Nullable] public TraktSyncItemType Type { get; set; } /// <summary> /// Gets or sets the movie, if <see cref="Type" /> is <see cref="TraktSyncItemType.Movie" />. /// See also <seealso cref="TraktMovie" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } /// <summary> /// Gets or sets the show, if <see cref="Type" /> is <see cref="TraktSyncItemType.Show" />. /// May also be set, if <see cref="Type" /> is <see cref="TraktSyncItemType.Episode" /> or /// <see cref="TraktSyncItemType.Season" />. /// <para>See also <seealso cref="TraktShow" />.</para> /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } /// <summary> /// Gets or sets the season, if <see cref="Type" /> is <see cref="TraktSyncItemType.Season" />. /// See also <seealso cref="TraktSeason" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "season")] [Nullable] public TraktSeason Season { get; set; } /// <summary> /// Gets or sets the episode, if <see cref="Type" /> is <see cref="TraktSyncItemType.Episode" />. /// See also <seealso cref="TraktEpisode" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } } }
namespace TraktApiSharp.Objects.Get.History { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using Shows.Seasons; using System; public class TraktHistoryItem { [JsonProperty(PropertyName = "id")] public int Id { get; set; } [JsonProperty(PropertyName = "watched_at")] public DateTime? WatchedAt { get; set; } [JsonProperty(PropertyName = "action")] [JsonConverter(typeof(TraktEnumerationConverter<TraktHistoryActionType>))] [Nullable] public TraktHistoryActionType Action { get; set; } [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncItemType>))] [Nullable] public TraktSyncItemType Type { get; set; } [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } [JsonProperty(PropertyName = "season")] [Nullable] public TraktSeason Season { get; set; } [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } } }
mit
C#
a32550a54c9027bc3e46f6f4942f1efd05627e62
Allow preempting queue in dispatcher
rit-sse-mycroft/core
Mycroft/Dispatcher.cs
Mycroft/Dispatcher.cs
using Mycroft.App; using Mycroft.Cmd; using Mycroft.Cmd.Msg; using Mycroft.Server; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Mycroft { public class Dispatcher : ICommandable { private ConcurrentQueue<Command> DispatchQueue; private ConcurrentStack<Command> DispatchStack; private TcpServer Server; private Registry Registry; private MessageArchive MessageArchive; public Dispatcher(TcpServer server, Registry registry, MessageArchive messageArchive) { Server = server; Registry = registry; MessageArchive = messageArchive; DispatchQueue = new ConcurrentQueue<Command>(); DispatchStack = new ConcurrentStack<Command>(); } public void Run() { Server.ClientConnected += HandleNewClientConnection; Server.Start(); Command currentCmd; while (true) { if (DispatchStack.TryPop(out currentCmd) || DispatchQueue.TryDequeue(out currentCmd)) { // Issue all the commands o/ Server.Issue(currentCmd); MessageArchive.Issue(currentCmd); Registry.Issue(currentCmd); this.Issue(currentCmd); } } } public void Enqueue(Command cmd) { DispatchQueue.Enqueue(cmd); } public void PreemptQueue(Command cmd) { DispatchStack.Push(cmd); } /// <summary> /// Put a newly connected app in its own thread in the app thread pool /// </summary> /// <param name="connection"></param> private void HandleNewClientConnection(TcpConnection connection) { var instance = new AppInstance(connection.Client, this); instance.Listen(); } /// <summary> /// Applies a command to the registry /// </summary> /// <param name="command"></param> public void Issue(Command command) { command.VisitDispatcher(this); } } }
using Mycroft.App; using Mycroft.Cmd; using Mycroft.Cmd.Msg; using Mycroft.Server; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Mycroft { public class Dispatcher : ICommandable { private ConcurrentQueue<Command> DispatchQueue; private TcpServer Server; private Registry Registry; private MessageArchive MessageArchive; public Dispatcher(TcpServer server, Registry registry, MessageArchive messageArchive) { Server = server; Registry = registry; MessageArchive = messageArchive; DispatchQueue = new ConcurrentQueue<Command>(); } public void Run() { Server.ClientConnected += HandleNewClientConnection; Server.Start(); Command currentCmd; while (true) { if (DispatchQueue.TryDequeue(out currentCmd)) { // Issue all the commands o/ Server.Issue(currentCmd); Registry.Issue(currentCmd); MessageArchive.Issue(currentCmd); this.Issue(currentCmd); } } } public void Enqueue(Command cmd) { DispatchQueue.Enqueue(cmd); } /// <summary> /// Put a newly connected app in its own thread in the app thread pool /// </summary> /// <param name="connection"></param> private void HandleNewClientConnection(TcpConnection connection) { var instance = new AppInstance(connection.Client, this); instance.Listen(); } /// <summary> /// Applies a command to the registry /// </summary> /// <param name="command"></param> public void Issue(Command command) { command.VisitDispatcher(this); } } }
bsd-3-clause
C#
b0bbcf51a2a44e515f563e6075cf0fa99207f66f
Add new method to overwrite TransactionDetail line with a new string.
kenwilcox/BankFileParsers
BankFileParsers/Classes/BaiDetail.cs
BankFileParsers/Classes/BaiDetail.cs
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } /// <summary> /// Overwrite the TransactionDetail line with a new string /// </summary> /// <param name="line">New string to overwrite with</param> public void SetTransactionDetail(string line) { TransactionDetail = line; } } }
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } } }
mit
C#
a685a36011ec8a6ece52e5400c09337d4e178737
Remove redundant SDL_SendAppEvent from IosSurfaceRenderer
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Forms/IosSurfaceRenderer.cs
Bindings/Forms/IosSurfaceRenderer.cs
using System; using System.Threading; using System.Threading.Tasks; using Urho.Forms; using System.Runtime.InteropServices; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using UIKit; [assembly: ExportRendererAttribute(typeof(UrhoSurface), typeof(IosSurfaceRenderer))] namespace Urho.Forms { public class IosSurfaceRenderer : ViewRenderer<UrhoSurface, IosUrhoSurface> { protected override void OnElementChanged(ElementChangedEventArgs<UrhoSurface> e) { if (e.NewElement != null) { var surface = new IosUrhoSurface(); surface.BackgroundColor = UIColor.Black; e.NewElement.UrhoApplicationLauncher = surface.Launcher; SetNativeControl(surface); } } } public class IosUrhoSurface : UIView { static TaskCompletionSource<Application> applicationTaskSource; static readonly SemaphoreSlim launcherSemaphore = new SemaphoreSlim(1); static Urho.iOS.UrhoSurface surface; static Urho.Application app; internal async Task<Urho.Application> Launcher(Type type, ApplicationOptions options) { await launcherSemaphore.WaitAsync(); if (app != null) { app.Engine.Exit(); Urho.Application.StopCurrent (); } applicationTaskSource = new TaskCompletionSource<Application>(); Urho.Application.Started += UrhoApplicationStarted; if (surface != null) { surface.RemoveFromSuperview (); //app.Graphics.Release (false, false); } this.Add(surface = new Urho.iOS.UrhoSurface(this.Bounds)); await surface.InitializeTask; app = Urho.Application.CreateInstance(type, options); app.Run(); return await applicationTaskSource.Task; } void UrhoApplicationStarted() { Urho.Application.Started -= UrhoApplicationStarted; applicationTaskSource?.TrySetResult(app); launcherSemaphore.Release(); } } }
using System; using System.Threading; using System.Threading.Tasks; using Urho.Forms; using System.Runtime.InteropServices; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using UIKit; [assembly: ExportRendererAttribute(typeof(UrhoSurface), typeof(IosSurfaceRenderer))] namespace Urho.Forms { public class IosSurfaceRenderer : ViewRenderer<UrhoSurface, IosUrhoSurface> { protected override void OnElementChanged(ElementChangedEventArgs<UrhoSurface> e) { if (e.NewElement != null) { var surface = new IosUrhoSurface(); surface.BackgroundColor = UIColor.Black; e.NewElement.UrhoApplicationLauncher = surface.Launcher; SetNativeControl(surface); } } } public class IosUrhoSurface : UIView { static TaskCompletionSource<Application> applicationTaskSource; static readonly SemaphoreSlim launcherSemaphore = new SemaphoreSlim(1); static Urho.iOS.UrhoSurface surface; static Urho.Application app; [DllImport(Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] public static extern void SDL_SendAppEvent(Urho.iOS.SdlEvent sdlEvent); internal async Task<Urho.Application> Launcher(Type type, ApplicationOptions options) { await launcherSemaphore.WaitAsync(); if (app != null) { app.Engine.Exit(); Urho.Application.StopCurrent (); } applicationTaskSource = new TaskCompletionSource<Application>(); Urho.Application.Started += UrhoApplicationStarted; if (surface != null) { surface.RemoveFromSuperview (); //app.Graphics.Release (false, false); } this.Add(surface = new Urho.iOS.UrhoSurface(this.Bounds)); await surface.InitializeTask; app = Urho.Application.CreateInstance(type, options); app.Run(); return await applicationTaskSource.Task; } void UrhoApplicationStarted() { Urho.Application.Started -= UrhoApplicationStarted; applicationTaskSource?.TrySetResult(app); launcherSemaphore.Release(); } } }
mit
C#
eb3f1b398788ac400dbaef518f08c4a57e4c7b72
Revert "Remove unused property"
mstrother/BmpListener
BmpListener/Bgp/OptionalParameter.cs
BmpListener/Bgp/OptionalParameter.cs
using System; using System.Linq; namespace BmpListener.Bgp { public abstract class OptionalParameter { public enum Type : byte { Capabilities = 2 } protected OptionalParameter(ArraySegment<byte> data) { ParameterType = (Type) data.First(); ParameterLength = data.ElementAt(1); } public Type ParameterType { get; } public byte ParameterLength { get; } public static OptionalParameter GetOptionalParameter(ArraySegment<byte> data) { if ((Type) data.First() == Type.Capabilities) return new OptionalParameterCapability(data); return new OptionParameterUnknown(data); } } }
using System; using System.Linq; namespace BmpListener.Bgp { public abstract class OptionalParameter { public enum Type { Capabilities = 2 } protected OptionalParameter(ref ArraySegment<byte> data) { ParameterType = (Type) data.First(); var length = data.ElementAt(1); data = new ArraySegment<byte>(data.Array, data.Offset + 2, length); } public Type ParameterType { get; } public static OptionalParameter GetOptionalParameter(ArraySegment<byte> data) { if ((Type) data.First() == Type.Capabilities) return new OptionalParameterCapability(data); return new OptionParameterUnknown(data); } } }
mit
C#
a90024252a1175dab27d99c7633b0123c285b768
fix exception documentation bug
OBeautifulCode/OBeautifulCode.AccountingTime
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
OBeautifulCode.AccountingTime/ReportingPeriod/ReportingPeriod{T}.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable CheckNamespace namespace OBeautifulCode.AccountingTime { using System; /// <summary> /// Represents a range of time over which to report. /// </summary> /// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam> public abstract class ReportingPeriod<T> where T : UnitOfTime { /// <summary> /// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class. /// </summary> /// <param name="start">The start of the reporting period.</param> /// <param name="end">The end of the reporting period.</param> /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception> /// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are different kinds of units-of-time.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> is greater than <paramref name="end"/>.</exception> protected ReportingPeriod(T start, T end) { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (end == null) { throw new ArgumentNullException(nameof(end)); } if (start.GetType() != end.GetType()) { throw new ArgumentException("start and end are different kinds of units-of-time"); } if ((dynamic)start > (dynamic)end) { throw new ArgumentOutOfRangeException(nameof(start), "start is great than end"); } this.Start = start; this.End = end; } /// <summary> /// Gets the start of the reporting period. /// </summary> public T Start { get; private set; } /// <summary> /// Gets the end of the reporting period. /// </summary> public T End { get; private set; } } } // ReSharper restore CheckNamespace
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ReportingPeriod{T}.cs" company="OBeautifulCode"> // Copyright (c) OBeautifulCode. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- // ReSharper disable CheckNamespace namespace OBeautifulCode.AccountingTime { using System; /// <summary> /// Represents a range of time over which to report. /// </summary> /// <typeparam name="T">The unit-of-time used to define the start and end of the reporting period.</typeparam> public abstract class ReportingPeriod<T> where T : UnitOfTime { /// <summary> /// Initializes a new instance of the <see cref="ReportingPeriod{T}"/> class. /// </summary> /// <param name="start">The start of the reporting period.</param> /// <param name="end">The end of the reporting period.</param> /// <exception cref="ArgumentNullException"><paramref name="start"/> or <paramref name="end"/> are null.</exception> /// <exception cref="ArgumentException"><paramref name="start"/> and <paramref name="end"/> are not of the same type.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="start"/> is greater than <paramref name="end"/>.</exception> protected ReportingPeriod(T start, T end) { if (start == null) { throw new ArgumentNullException(nameof(start)); } if (end == null) { throw new ArgumentNullException(nameof(end)); } if (start.GetType() != end.GetType()) { throw new ArgumentException("start and end are different kinds of units-of-time"); } if ((dynamic)start > (dynamic)end) { throw new ArgumentOutOfRangeException(nameof(start), "start is great than end"); } this.Start = start; this.End = end; } /// <summary> /// Gets the start of the reporting period. /// </summary> public T Start { get; private set; } /// <summary> /// Gets the end of the reporting period. /// </summary> public T End { get; private set; } } } // ReSharper restore CheckNamespace
mit
C#
cbd8d9a5523d3da21ee25267e7563673ffd04b27
Fix change Account Apply to public
oskardudycz/EventSourcing.NetCore
Sample/EventSourcing.Sample.Transactions/Domain/Accounts/Account.cs
Sample/EventSourcing.Sample.Transactions/Domain/Accounts/Account.cs
using Domain.Aggregates; using EventSourcing.Sample.Tasks.Contracts.Accounts.Events; using EventSourcing.Sample.Tasks.Contracts.Transactions; using EventSourcing.Sample.Tasks.Contracts.Transactions.Events; using EventSourcing.Sample.Transactions.Domain.Accounts; using System; namespace EventSourcing.Sample.Tasks.Domain.Accounts { public class Account : EventSource { public Guid ClientId { get; private set; } public decimal Balance { get; private set; } public string Number { get; private set; } public Account() { } public Account(Guid clientId, IAccountNumberGenerator accountNumberGenerator) { var @event = new NewAccountCreated { AccountId = Guid.NewGuid(), ClientId = clientId, Number = accountNumberGenerator.Generate() }; Apply(@event); Append(@event); } public void RecordInflow(Guid fromId, decimal ammount) { var @event = new NewInflowRecorded(fromId, Id, new Inflow(ammount, DateTime.Now)); Apply(@event); Append(@event); } public void RecordOutflow(Guid toId, decimal ammount) { var @event = new NewOutflowRecorded(Id, toId, new Outflow(ammount, DateTime.Now)); Apply(@event); Append(@event); } public void Apply(NewAccountCreated @event) { Id = @event.AccountId; ClientId = @event.ClientId; Number = @event.Number; } public void Apply(NewInflowRecorded @event) { Balance += @event.Inflow.Ammount; } public void Apply(NewOutflowRecorded @event) { Balance -= @event.Outflow.Ammount; } } }
using Domain.Aggregates; using EventSourcing.Sample.Tasks.Contracts.Accounts.Events; using EventSourcing.Sample.Tasks.Contracts.Transactions; using EventSourcing.Sample.Tasks.Contracts.Transactions.Events; using EventSourcing.Sample.Transactions.Domain.Accounts; using System; namespace EventSourcing.Sample.Tasks.Domain.Accounts { public class Account : EventSource { public Guid ClientId { get; private set; } public decimal Balance { get; private set; } public string Number { get; private set; } public Account() { } public Account(Guid clientId, IAccountNumberGenerator accountNumberGenerator) { var @event = new NewAccountCreated { AccountId = Guid.NewGuid(), ClientId = clientId, Number = accountNumberGenerator.Generate() }; Apply(@event); Append(@event); } public void RecordInflow(Guid fromId, decimal ammount) { var @event = new NewInflowRecorded(fromId, Id, new Inflow(ammount, DateTime.Now)); Apply(@event); Append(@event); } public void RecordOutflow(Guid toId, decimal ammount) { var @event = new NewOutflowRecorded(Id, toId, new Outflow(ammount, DateTime.Now)); Apply(@event); Append(@event); } private void Apply(NewAccountCreated @event) { Id = @event.AccountId; ClientId = @event.ClientId; Number = @event.Number; } public void Apply(NewInflowRecorded @event) { Balance += @event.Inflow.Ammount; } public void Apply(NewOutflowRecorded @event) { Balance -= @event.Outflow.Ammount; } } }
mit
C#
81c3c2274f736cbe86ccf258e9a85254368c3d7e
Replace obsolete NavMeshAgent interface fot he newer one
allmonty/BrokenShield,allmonty/BrokenShield
Assets/Scripts/Enemy/Action_Patrol.cs
Assets/Scripts/Enemy/Action_Patrol.cs
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.isStopped = false; if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.Resume (); if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
apache-2.0
C#
8cd0c39c400a211f4dd392a1bc3d816a38d86adb
fix LF to CRLF
GROWrepo/Santa_Inc
Assets/script/monoBehavior/testNPC.cs
Assets/script/monoBehavior/testNPC.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class testNPC : MonoBehaviour, I_NPC { public dialog[] dialogs; public dialog[] getDialogs(GameObject GO) { GO.SendMessage("setCurrent", dialogs, SendMessageOptions.DontRequireReceiver); return this.dialogs; } public int getDialogSize() { return dialogs.Length; } // Use this for initialization void Start () { dialogs = new dialog[9]; dialogs[0] = new dialog("1", 0); dialogs[1] = new dialog("2", 1); dialogs[2] = new dialog("3", 0); dialogs[3] = new dialog("4", 1); dialogs[4] = new dialog("5", 0); dialogs[5] = new dialog("6", 1); dialogs[6] = new dialog("7", 0); dialogs[7] = new dialog("8", 1); dialogs[8] = new dialog("9", 0); } // Update is called once per frame void Update () { } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class testNPC : MonoBehaviour, I_NPC { public dialog[] dialogs; public dialog[] getDialogs(GameObject GO) { GO.SendMessage("setCurrent", dialogs, SendMessageOptions.DontRequireReceiver); return this.dialogs; } public int getDialogSize() { return dialogs.Length; } // Use this for initialization void Start () { dialogs = new dialog[9]; dialogs[0] = new dialog("1", 0); dialogs[1] = new dialog("2", 1); dialogs[2] = new dialog("3", 0); dialogs[3] = new dialog("4", 1); dialogs[4] = new dialog("5", 0); dialogs[5] = new dialog("6", 1); dialogs[6] = new dialog("7", 0); dialogs[7] = new dialog("8", 1); dialogs[8] = new dialog("9", 0); } // Update is called once per frame void Update () { } }
mit
C#
af6741d412fdad6c154555963abb84472c6fe84f
Bump version
Yuisbean/WebMConverter,o11c/WebMConverter,nixxquality/WebMConverter
Properties/AssemblyInfo.cs
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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.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("WebM for Retards")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WebM for Retards")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.2.1")]
mit
C#
72f176b16f1d5027c614b1277c681bb04b7935cb
Bump version
transistor1/SQLFormatterPlugin
Properties/AssemblyInfo.cs
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("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("22247641-9910-4c24-9a9d-dd295a749d41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.10005.0")] [assembly: AssemblyFileVersion("1.0.10005.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("SQLFormatterPlugin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SQLFormatterPlugin")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("22247641-9910-4c24-9a9d-dd295a749d41")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.10004.0")] [assembly: AssemblyFileVersion("1.0.10004.0")]
bsd-3-clause
C#
703bd707cf3aeeb06010f2b6df9ab5ff846d5856
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
autofac/Autofac.Extras.AggregateService
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")] [assembly: AssemblyDescription("")]
mit
C#
a0026f2510fa861165a0ba610ef6829ecf04f40e
Fix capacity estiminate for StringBuilder
roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon
R7.Epsilon/Components/Utils.cs
R7.Epsilon/Components/Utils.cs
// // Utils.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014-2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Text; namespace R7.Epsilon.Components { public static class Utils { /// <summary> /// Formats the list of arguments, excluding empty /// </summary> /// <returns>Formatted list.</returns> /// <param name="separator">Separator.</param> /// <param name="args">Arguments.</param> public static string FormatList (string separator, params object[] args) { var sb = new StringBuilder (args.Length * 16); var i = 0; foreach (var a in args) { if (a != null && !string.IsNullOrWhiteSpace (a.ToString ())) { if (i++ > 0) sb.Append (separator); sb.Append (a); } } return sb.ToString (); } public static string FormatList<T> (string separator, IEnumerable<T> args) where T: struct { var sb = new StringBuilder (); var i = 0; foreach (var a in args) { if (!string.IsNullOrWhiteSpace (a.ToString ())) { if (i++ > 0) { sb.Append (separator); } sb.Append (a); } } return sb.ToString (); } } }
// // Utils.cs // // Author: // Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2014-2016 Roman M. Yagodin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System.Collections.Generic; using System.Text; namespace R7.Epsilon.Components { public static class Utils { /// <summary> /// Formats the list of arguments, excluding empty /// </summary> /// <returns>Formatted list.</returns> /// <param name="separator">Separator.</param> /// <param name="args">Arguments.</param> public static string FormatList (string separator, params object[] args) { var sb = new StringBuilder (args.Length); var i = 0; foreach (var a in args) { if (a != null && !string.IsNullOrWhiteSpace (a.ToString ())) { if (i++ > 0) sb.Append (separator); sb.Append (a); } } return sb.ToString (); } public static string FormatList<T> (string separator, IEnumerable<T> args) where T: struct { var sb = new StringBuilder (); var i = 0; foreach (var a in args) { if (!string.IsNullOrWhiteSpace (a.ToString ())) { if (i++ > 0) { sb.Append (separator); } sb.Append (a); } } return sb.ToString (); } } }
agpl-3.0
C#
b48def16275378e131ce2ed9157796a7c687eaab
Align SwellSymbolPiece better for rotation.
ZLima12/osu,2yangk23/osu,Drezi126/osu,johnneijzen/osu,ZLima12/osu,peppy/osu-new,DrabWeb/osu,osu-RP/osu-RP,Nabile-Rahmani/osu,peppy/osu,DrabWeb/osu,johnneijzen/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,Damnae/osu,smoogipooo/osu,ppy/osu,peppy/osu,nyaamara/osu,naoey/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,tacchinotacchi/osu,ppy/osu,RedNesto/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,EVAST9919/osu,naoey/osu,UselessToucan/osu,peppy/osu,Frontear/osuKyzer
osu.Game.Modes.Taiko/Objects/Drawable/Pieces/SwellSymbolPiece.cs
osu.Game.Modes.Taiko/Objects/Drawable/Pieces/SwellSymbolPiece.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Graphics; using osu.Framework.Graphics; namespace osu.Game.Modes.Taiko.Objects.Drawable.Pieces { /// <summary> /// The symbol used for swell pieces. /// </summary> public class SwellSymbolPiece : TextAwesome { public SwellSymbolPiece() { Anchor = Anchor.Centre; Origin = Anchor.Centre; UseFullGlyphHeight = true; TextSize = CirclePiece.SYMBOL_INNER_SIZE; Icon = FontAwesome.fa_asterisk; Shadow = false; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Graphics; using osu.Framework.Graphics; namespace osu.Game.Modes.Taiko.Objects.Drawable.Pieces { /// <summary> /// The symbol used for swell pieces. /// </summary> public class SwellSymbolPiece : TextAwesome { public SwellSymbolPiece() { Anchor = Anchor.Centre; Origin = Anchor.Centre; TextSize = CirclePiece.SYMBOL_INNER_SIZE; Icon = FontAwesome.fa_asterisk; Shadow = false; } } }
mit
C#
0253123bbcc0b5291683d2f7b5c2c325c1485c8f
Change Issue's ScheduleImpact, CostImpact, and DueAt properties nullable (#8)
plangrid/plangrid-api-net
PlanGrid.Api/Issue.cs
PlanGrid.Api/Issue.cs
// <copyright file="Issue.cs" company="PlanGrid, Inc."> // Copyright (c) 2016 PlanGrid, Inc. All rights reserved. // </copyright> using System; using Newtonsoft.Json; namespace PlanGrid.Api { public class Issue : Record { [JsonProperty("number")] public int Number { get; set; } [JsonProperty("current_annotation")] public IssueAnnotation CurrentAnnotation { get; set; } [JsonProperty("room")] public string Room { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("assigned_to")] public UserReference[] AssignedTo { get; set; } [JsonProperty("status")] public IssueStatus Status { get; set; } [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } [JsonProperty("created_by")] public UserReference CreatedBy { get; set; } [JsonProperty("updated_at")] public DateTime UpdatedAt { get; set; } [JsonProperty("updated_by")] public UserReference UpdatedBy { get; set; } [JsonProperty("photos")] public CollectionReference<Photo> Photos { get; set; } [JsonProperty("comments")] public CollectionReference<Comment> Comments { get; set; } [JsonProperty("deleted")] public bool IsDeleted { get; set; } [JsonProperty("due_at")] public DateTime? DueAt { get; set; } [JsonProperty("has_cost_impact")] public bool HasCostImpact { get; set; } /// <summary> /// The cost impact in dollars and cents. /// </summary> [JsonProperty("cost_impact")] public decimal? CostImpact { get; set; } [JsonProperty("currency_code")] public string CurrencyCode { get; set; } [JsonProperty("has_schedule_impact")] public bool HasScheduleImpact { get; set; } /// <summary> /// The schedule impact in seconds. /// </summary> [JsonProperty("schedule_impact")] public long? ScheduleImpact { get; set; } private const int DayInSeconds = 60 * 60 * 24; [JsonIgnore] public int ScheduleImpactDays { get { return (int)(ScheduleImpact / (DayInSeconds)); } set { ScheduleImpact = value * DayInSeconds; } } } }
// <copyright file="Issue.cs" company="PlanGrid, Inc."> // Copyright (c) 2016 PlanGrid, Inc. All rights reserved. // </copyright> using System; using Newtonsoft.Json; namespace PlanGrid.Api { public class Issue : Record { [JsonProperty("number")] public int Number { get; set; } [JsonProperty("current_annotation")] public IssueAnnotation CurrentAnnotation { get; set; } [JsonProperty("room")] public string Room { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("assigned_to")] public UserReference[] AssignedTo { get; set; } [JsonProperty("status")] public IssueStatus Status { get; set; } [JsonProperty("created_at")] public DateTime CreatedAt { get; set; } [JsonProperty("created_by")] public UserReference CreatedBy { get; set; } [JsonProperty("updated_at")] public DateTime UpdatedAt { get; set; } [JsonProperty("updated_by")] public UserReference UpdatedBy { get; set; } [JsonProperty("photos")] public CollectionReference<Photo> Photos { get; set; } [JsonProperty("comments")] public CollectionReference<Comment> Comments { get; set; } [JsonProperty("deleted")] public bool IsDeleted { get; set; } [JsonProperty("due_at")] public DateTime DueAt { get; set; } [JsonProperty("has_cost_impact")] public bool HasCostImpact { get; set; } /// <summary> /// The cost impact in dollars and cents. /// </summary> [JsonProperty("cost_impact")] public decimal CostImpact { get; set; } [JsonProperty("currency_code")] public string CurrencyCode { get; set; } [JsonProperty("has_schedule_impact")] public bool HasScheduleImpact { get; set; } /// <summary> /// The schedule impact in seconds. /// </summary> [JsonProperty("schedule_impact")] public long ScheduleImpact { get; set; } private const int DayInSeconds = 60 * 60 * 24; [JsonIgnore] public int ScheduleImpactDays { get { return (int)(ScheduleImpact / (DayInSeconds)); } set { ScheduleImpact = value * DayInSeconds; } } } }
mit
C#
5ebb7c03cd69b48456222549b6c0b5b603ab9bdc
Update documentation
ViveportSoftware/vita_core_csharp,ViveportSoftware/vita_core_csharp
source/Htc.Vita.Core/Net/FileTransfer.FileTransferProgress.cs
source/Htc.Vita.Core/Net/FileTransfer.FileTransferProgress.cs
namespace Htc.Vita.Core.Net { public abstract partial class FileTransfer { /// <summary> /// Class FileTransferProgress. /// </summary> public class FileTransferProgress { /// <summary> /// Gets or sets the total bytes. /// </summary> /// <value>The total bytes.</value> public ulong TotalBytes { get; set; } /// <summary> /// Gets or sets the total files. /// </summary> /// <value>The total files.</value> public uint TotalFiles { get; set; } /// <summary> /// Gets or sets the transferred bytes. /// </summary> /// <value>The transferred bytes.</value> public ulong TransferredBytes { get; set; } /// <summary> /// Gets or sets the transferred files. /// </summary> /// <value>The transferred files.</value> public uint TransferredFiles { get; set; } } } }
namespace Htc.Vita.Core.Net { public abstract partial class FileTransfer { public class FileTransferProgress { public ulong TotalBytes { get; set; } public uint TotalFiles { get; set; } public ulong TransferredBytes { get; set; } public uint TransferredFiles { get; set; } } } }
mit
C#
22e96843046c670e1263fc5146c9e3dbc577e982
Add HasClass extension method for IWebElement
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
src/Atata.WebDriverExtras/Extensions/IWebElementExtensions.cs
src/Atata.WebDriverExtras/Extensions/IWebElementExtensions.cs
using System; using System.Linq; using OpenQA.Selenium; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static bool HasClass(this IWebElement element, string className) { return element.GetAttribute("class").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains(className); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
using OpenQA.Selenium; using System; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
apache-2.0
C#
a99debc5b1db62366e3dbe49ab2655b65fbdc28c
Add CloseAllChannels to ObserverEventDispatcher
SaladbowlCreative/Akka.Interfaced.SlimSocket
core/Akka.Interfaced.SlimSocket.Client/Communicator/Communicator.cs
core/Akka.Interfaced.SlimSocket.Client/Communicator/Communicator.cs
using System.Collections.Generic; using System.Linq; namespace Akka.Interfaced.SlimSocket.Client { public class Communicator { public ChannelFactory ChannelFactory { get; } public IList<IChannel> Channels { get; } public IObserverRegistry ObserverRegistry { get; } public Communicator() { ChannelFactory = new ChannelFactory() { CreateObserverRegistry = () => ObserverRegistry, ChannelRouter = OnChannelRouting }; Channels = new List<IChannel>(); ObserverRegistry = new ObserverRegistry(); } public IChannel CreateChannel(string address = null) { var newChannel = ChannelFactory.Create(address); OnChannelCreated(newChannel); return newChannel; } public void CloseAllChannels() { foreach (var channel in Channels.ToList()) channel.Close(); } private IChannel OnChannelRouting(IChannel parentChannel, string address) { return CreateChannel(address); } private void OnChannelCreated(IChannel newChannel) { newChannel.StateChanged += (channel, state) => { if (state == ChannelStateType.Closed) OnChannelClosed(channel); }; lock (Channels) { Channels.Add(newChannel); } } private void OnChannelClosed(IChannel channel) { lock (Channels) { Channels.Remove(channel); } } } }
using System.Collections.Generic; namespace Akka.Interfaced.SlimSocket.Client { public class Communicator { public ChannelFactory ChannelFactory { get; } public IList<IChannel> Channels { get; } public IObserverRegistry ObserverRegistry { get; } public Communicator() { ChannelFactory = new ChannelFactory() { CreateObserverRegistry = () => ObserverRegistry, ChannelRouter = OnChannelRouting }; Channels = new List<IChannel>(); ObserverRegistry = new ObserverRegistry(); } public IChannel CreateChannel(string address = null) { var newChannel = ChannelFactory.Create(address); OnChannelCreated(newChannel); return newChannel; } private IChannel OnChannelRouting(IChannel parentChannel, string address) { return CreateChannel(address); } private void OnChannelCreated(IChannel newChannel) { newChannel.StateChanged += (channel, state) => { if (state == ChannelStateType.Closed) OnChannelClosed(channel); }; lock (Channels) { Channels.Add(newChannel); } } private void OnChannelClosed(IChannel channel) { lock (Channels) { Channels.Remove(channel); } } } }
mit
C#
be7628d496da9a3c1a4b02ba0cb77d2ca7ccd0f4
Remove obsolete code
Elders/VSE-FormatDocumentOnSave,segrived/VSE-FormatDocumentOnSave
src/NMSD.VSE-FormatDocumentOnSave/KeyBindingFilterProvider.cs
src/NMSD.VSE-FormatDocumentOnSave/KeyBindingFilterProvider.cs
using System.ComponentModel.Composition; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace KeyBindingTest { [Export(typeof(IVsTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Editable)] internal class KeyBindingCommandFilterProvider : IVsTextViewCreationListener { [Import(typeof(IVsEditorAdaptersFactoryService))] internal IVsEditorAdaptersFactoryService editorFactory = null; [Import(typeof(SVsServiceProvider))] internal SVsServiceProvider ServiceProvider = null; public void VsTextViewCreated(IVsTextView textViewAdapter) { var dte = (DTE)ServiceProvider.GetService(typeof(DTE)); AddCommandFilter(textViewAdapter, new KeyBindingCommandFilter(dte)); } void AddCommandFilter(IVsTextView viewAdapter, KeyBindingCommandFilter commandFilter) { if (commandFilter.m_added == false) { //get the view adapter from the editor factory IOleCommandTarget next; int hr = viewAdapter.AddCommandFilter(commandFilter, out next); if (hr == VSConstants.S_OK) { commandFilter.m_added = true; //you'll need the next target for Exec and QueryStatus if (next != null) commandFilter.m_nextTarget = next; } } } } }
using System.ComponentModel.Composition; using EnvDTE; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.VisualStudio.Utilities; namespace KeyBindingTest { [Export(typeof(IVsTextViewCreationListener))] [ContentType("text")] [TextViewRole(PredefinedTextViewRoles.Editable)] internal class KeyBindingCommandFilterProvider : IVsTextViewCreationListener { [Import(typeof(IVsEditorAdaptersFactoryService))] internal IVsEditorAdaptersFactoryService editorFactory = null; [Import(typeof(SVsServiceProvider))] internal SVsServiceProvider ServiceProvider = null; public void VsTextViewCreated(IVsTextView textViewAdapter) { IWpfTextView textView = editorFactory.GetWpfTextView(textViewAdapter); if (textView == null) return; var dte = (DTE)ServiceProvider.GetService(typeof(DTE)); AddCommandFilter(textViewAdapter, new KeyBindingCommandFilter(dte)); } void AddCommandFilter(IVsTextView viewAdapter, KeyBindingCommandFilter commandFilter) { if (commandFilter.m_added == false) { //get the view adapter from the editor factory IOleCommandTarget next; int hr = viewAdapter.AddCommandFilter(commandFilter, out next); if (hr == VSConstants.S_OK) { commandFilter.m_added = true; //you'll need the next target for Exec and QueryStatus if (next != null) commandFilter.m_nextTarget = next; } } } } }
apache-2.0
C#
20717bbff0616c70bcb003c5e3ba0e44cca1cdeb
Convert KeyInfoNodeTest.cs
ravimeda/corefx,ViktorHofer/corefx,gkhanna79/corefx,ptoonen/corefx,marksmeltzer/corefx,MaggieTsang/corefx,jlin177/corefx,rjxby/corefx,YoupHulsebos/corefx,dhoehna/corefx,elijah6/corefx,krytarowski/corefx,stone-li/corefx,wtgodbe/corefx,krk/corefx,fgreinacher/corefx,Ermiar/corefx,YoupHulsebos/corefx,seanshpark/corefx,elijah6/corefx,ericstj/corefx,jlin177/corefx,ptoonen/corefx,ericstj/corefx,axelheer/corefx,Jiayili1/corefx,shimingsg/corefx,stephenmichaelf/corefx,krk/corefx,krk/corefx,YoupHulsebos/corefx,billwert/corefx,richlander/corefx,ravimeda/corefx,Ermiar/corefx,ericstj/corefx,the-dwyer/corefx,dhoehna/corefx,the-dwyer/corefx,mmitche/corefx,dhoehna/corefx,JosephTremoulet/corefx,mazong1123/corefx,JosephTremoulet/corefx,alexperovich/corefx,weltkante/corefx,mazong1123/corefx,shimingsg/corefx,mmitche/corefx,jlin177/corefx,YoupHulsebos/corefx,cydhaselton/corefx,ViktorHofer/corefx,nbarbettini/corefx,rubo/corefx,tijoytom/corefx,stephenmichaelf/corefx,weltkante/corefx,Petermarcu/corefx,nbarbettini/corefx,tijoytom/corefx,dotnet-bot/corefx,rahku/corefx,ptoonen/corefx,Jiayili1/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,the-dwyer/corefx,alexperovich/corefx,ptoonen/corefx,ViktorHofer/corefx,billwert/corefx,cydhaselton/corefx,parjong/corefx,DnlHarvey/corefx,ericstj/corefx,tijoytom/corefx,ViktorHofer/corefx,rubo/corefx,JosephTremoulet/corefx,weltkante/corefx,Ermiar/corefx,stephenmichaelf/corefx,the-dwyer/corefx,DnlHarvey/corefx,mazong1123/corefx,ptoonen/corefx,Ermiar/corefx,YoupHulsebos/corefx,billwert/corefx,yizhang82/corefx,richlander/corefx,richlander/corefx,JosephTremoulet/corefx,Petermarcu/corefx,mazong1123/corefx,elijah6/corefx,billwert/corefx,wtgodbe/corefx,axelheer/corefx,mmitche/corefx,krytarowski/corefx,twsouthwick/corefx,weltkante/corefx,ravimeda/corefx,rjxby/corefx,nchikanov/corefx,dhoehna/corefx,cydhaselton/corefx,parjong/corefx,zhenlan/corefx,zhenlan/corefx,richlander/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,stephenmichaelf/corefx,axelheer/corefx,nbarbettini/corefx,zhenlan/corefx,yizhang82/corefx,seanshpark/corefx,cydhaselton/corefx,Ermiar/corefx,stone-li/corefx,nchikanov/corefx,weltkante/corefx,dhoehna/corefx,parjong/corefx,MaggieTsang/corefx,yizhang82/corefx,Jiayili1/corefx,twsouthwick/corefx,krk/corefx,dhoehna/corefx,zhenlan/corefx,elijah6/corefx,zhenlan/corefx,stone-li/corefx,cydhaselton/corefx,stone-li/corefx,nchikanov/corefx,tijoytom/corefx,billwert/corefx,rjxby/corefx,tijoytom/corefx,krk/corefx,jlin177/corefx,ViktorHofer/corefx,krytarowski/corefx,rahku/corefx,twsouthwick/corefx,alexperovich/corefx,twsouthwick/corefx,the-dwyer/corefx,mazong1123/corefx,DnlHarvey/corefx,alexperovich/corefx,jlin177/corefx,ravimeda/corefx,rjxby/corefx,ravimeda/corefx,Ermiar/corefx,krytarowski/corefx,rjxby/corefx,krytarowski/corefx,yizhang82/corefx,Ermiar/corefx,shimingsg/corefx,wtgodbe/corefx,Petermarcu/corefx,stone-li/corefx,axelheer/corefx,krk/corefx,ptoonen/corefx,MaggieTsang/corefx,MaggieTsang/corefx,mazong1123/corefx,mmitche/corefx,mmitche/corefx,elijah6/corefx,fgreinacher/corefx,rjxby/corefx,parjong/corefx,dotnet-bot/corefx,DnlHarvey/corefx,dotnet-bot/corefx,twsouthwick/corefx,seanshpark/corefx,marksmeltzer/corefx,fgreinacher/corefx,parjong/corefx,elijah6/corefx,shimingsg/corefx,nchikanov/corefx,MaggieTsang/corefx,krytarowski/corefx,the-dwyer/corefx,rahku/corefx,marksmeltzer/corefx,mmitche/corefx,wtgodbe/corefx,stephenmichaelf/corefx,billwert/corefx,wtgodbe/corefx,gkhanna79/corefx,seanshpark/corefx,BrennanConroy/corefx,marksmeltzer/corefx,seanshpark/corefx,stephenmichaelf/corefx,stephenmichaelf/corefx,the-dwyer/corefx,billwert/corefx,alexperovich/corefx,dotnet-bot/corefx,shimingsg/corefx,DnlHarvey/corefx,alexperovich/corefx,rjxby/corefx,alexperovich/corefx,Jiayili1/corefx,Jiayili1/corefx,MaggieTsang/corefx,seanshpark/corefx,krytarowski/corefx,DnlHarvey/corefx,mazong1123/corefx,dhoehna/corefx,shimingsg/corefx,yizhang82/corefx,ptoonen/corefx,Jiayili1/corefx,Jiayili1/corefx,axelheer/corefx,gkhanna79/corefx,rahku/corefx,cydhaselton/corefx,rahku/corefx,tijoytom/corefx,dotnet-bot/corefx,axelheer/corefx,tijoytom/corefx,gkhanna79/corefx,marksmeltzer/corefx,dotnet-bot/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,wtgodbe/corefx,richlander/corefx,zhenlan/corefx,yizhang82/corefx,richlander/corefx,BrennanConroy/corefx,JosephTremoulet/corefx,BrennanConroy/corefx,gkhanna79/corefx,nchikanov/corefx,zhenlan/corefx,ViktorHofer/corefx,twsouthwick/corefx,rahku/corefx,stone-li/corefx,twsouthwick/corefx,parjong/corefx,nbarbettini/corefx,jlin177/corefx,Petermarcu/corefx,ericstj/corefx,nbarbettini/corefx,gkhanna79/corefx,cydhaselton/corefx,shimingsg/corefx,ViktorHofer/corefx,marksmeltzer/corefx,MaggieTsang/corefx,ravimeda/corefx,Petermarcu/corefx,Petermarcu/corefx,ericstj/corefx,rubo/corefx,nchikanov/corefx,parjong/corefx,yizhang82/corefx,mmitche/corefx,gkhanna79/corefx,weltkante/corefx,rahku/corefx,jlin177/corefx,Petermarcu/corefx,krk/corefx,nbarbettini/corefx,ericstj/corefx,rubo/corefx,elijah6/corefx,seanshpark/corefx,nbarbettini/corefx,weltkante/corefx,nchikanov/corefx,fgreinacher/corefx,wtgodbe/corefx,stone-li/corefx,marksmeltzer/corefx,ravimeda/corefx,richlander/corefx,rubo/corefx
src/System.Security.Cryptography.Xml/tests/KeyInfoNodeTest.cs
src/System.Security.Cryptography.Xml/tests/KeyInfoNodeTest.cs
// // KeyInfoNodeTest.cs - NUnit Test Cases for KeyInfoNode // // Author: // Sebastien Pouliot (spouliot@motus.com) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // // 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.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { public class KeyInfoNodeTest { [Fact] public void NewKeyNode() { string test = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); KeyInfoNode node1 = new KeyInfoNode(); node1.Value = doc.DocumentElement; XmlElement xel = node1.GetXml(); KeyInfoNode node2 = new KeyInfoNode(node1.Value); node2.LoadXml(xel); Assert.Equal((node1.GetXml().OuterXml), (node2.GetXml().OuterXml)); } [Fact] public void ImportKeyNode() { // Note: KeyValue is a valid KeyNode string value = "<KeyName xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Mono::</KeyName>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(value); KeyInfoNode node1 = new KeyInfoNode(); node1.LoadXml(doc.DocumentElement); string s = (node1.GetXml().OuterXml); Assert.Equal(value, s); } // well there's no invalid value - unless you read the doc ;-) [Fact] public void InvalidKeyNode() { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(bad); KeyInfoNode node1 = new KeyInfoNode(); // LAMESPEC: No ArgumentNullException is thrown if value == null node1.LoadXml(null); Assert.Null(node1.Value); } } }
// // KeyInfoNodeTest.cs - NUnit Test Cases for KeyInfoNode // // Author: // Sebastien Pouliot (spouliot@motus.com) // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // // 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.Xml; using Xunit; namespace System.Security.Cryptography.Xml.Tests { [TestFixture] public class KeyInfoNodeTest { [Test] public void NewKeyNode() { string test = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(test); KeyInfoNode node1 = new KeyInfoNode(); node1.Value = doc.DocumentElement; XmlElement xel = node1.GetXml(); KeyInfoNode node2 = new KeyInfoNode(node1.Value); node2.LoadXml(xel); Assert.AreEqual((node1.GetXml().OuterXml), (node2.GetXml().OuterXml), "node1==node2"); } [Test] public void ImportKeyNode() { // Note: KeyValue is a valid KeyNode string value = "<KeyName xmlns=\"http://www.w3.org/2000/09/xmldsig#\">Mono::</KeyName>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(value); KeyInfoNode node1 = new KeyInfoNode(); node1.LoadXml(doc.DocumentElement); string s = (node1.GetXml().OuterXml); Assert.AreEqual(value, s, "Node"); } // well there's no invalid value - unless you read the doc ;-) [Test] public void InvalidKeyNode() { string bad = "<Test></Test>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(bad); KeyInfoNode node1 = new KeyInfoNode(); // LAMESPEC: No ArgumentNullException is thrown if value == null node1.LoadXml(null); Assert.IsNull(node1.Value, "Value==null"); } } }
mit
C#
05fefb25e89e2ba36336454624fc7ad98bfaf378
move to version 3.0
WebApiContrib/WebApiContrib.Formatting.Jsonp,WebApiContrib/WebApiContrib.Formatting.Jsonp,puco/WebApiContrib.Formatting.Jsonp,puco/WebApiContrib.Formatting.Jsonp
src/WebApiContrib.Formatting.Jsonp/Properties/AssemblyInfo.cs
src/WebApiContrib.Formatting.Jsonp/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("WebApiContrib.Formatting.Jsonp")] [assembly: AssemblyDescription("Provides a JSONP MediaTypeFormatter implementation for ASP.NET Web API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WebApiContrib")] [assembly: AssemblyProduct("WebApiContrib.Formatting.Jsonp")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ea85f1dd-2454-4b75-9953-f3291e9336f8")] // 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("3.0.0")] [assembly: AssemblyFileVersion("3.0.0")] [assembly: InternalsVisibleTo("WebApiContrib.Formatting.Jsonp.Tests")]
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("WebApiContrib.Formatting.Jsonp")] [assembly: AssemblyDescription("Provides a JSONP MediaTypeFormatter implementation for ASP.NET Web API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WebApiContrib")] [assembly: AssemblyProduct("WebApiContrib.Formatting.Jsonp")] [assembly: AssemblyCopyright("Copyright © 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("ea85f1dd-2454-4b75-9953-f3291e9336f8")] // 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("2.1.0")] [assembly: AssemblyFileVersion("2.1.0")] [assembly: InternalsVisibleTo("WebApiContrib.Formatting.Jsonp.Tests")]
mit
C#
3a27814b2447d3be17ab6111334c065b7cc17230
optimize FluentConfigInterceptorResolver
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Aspect/FluentConfigInterceptorResolver.cs
src/WeihanLi.Common/Aspect/FluentConfigInterceptorResolver.cs
using System; using System.Collections.Generic; using WeihanLi.Common.Helpers; namespace WeihanLi.Common.Aspect { public class FluentConfigInterceptorResolver : IInterceptorResolver { public static readonly IInterceptorResolver Instance = new FluentConfigInterceptorResolver(); private FluentConfigInterceptorResolver() { } public IReadOnlyCollection<IInterceptor> ResolveInterceptors(IInvocation invocation) { foreach (var func in FluentAspects.AspectOptions.NoInterceptionConfigurations) { if (func(invocation)) { return ArrayHelper.Empty<IInterceptor>(); } } var interceptorTypes = new HashSet<Type>(); var interceptors = new List<IInterceptor>(32); foreach (var configuration in FluentAspects.AspectOptions.InterceptionConfigurations) { if (configuration.Key.Invoke(invocation)) { foreach (var interceptor in configuration.Value.Interceptors) { if (interceptorTypes.Add(interceptor.GetType())) { interceptors.Add(interceptor); } } } } return interceptors; } } }
using System.Collections.Generic; using WeihanLi.Common.Helpers; namespace WeihanLi.Common.Aspect { public class FluentConfigInterceptorResolver : IInterceptorResolver { public static readonly IInterceptorResolver Instance = new FluentConfigInterceptorResolver(); private FluentConfigInterceptorResolver() { } public IReadOnlyCollection<IInterceptor> ResolveInterceptors(IInvocation invocation) { var interceptors = new List<IInterceptor>(32); foreach (var func in FluentAspects.AspectOptions.NoInterceptionConfigurations) { if (func(invocation)) { return ArrayHelper.Empty<IInterceptor>(); } } foreach (var configuration in FluentAspects.AspectOptions.InterceptionConfigurations) { if (configuration.Key.Invoke(invocation)) { foreach (var interceptor in configuration.Value.Interceptors) { if (!interceptors.Exists(x => x.GetType() == interceptor.GetType())) { interceptors.Add(interceptor); } } } } return interceptors; } } }
mit
C#
57e93464fa9b6623eb2a11b5e7f2ad3af9461228
use property instead of method
lukehoban/JabbR,AAPT/jean0226case1322,yadyn/JabbR,fuzeman/vox,e10/JabbR,SonOfSam/JabbR,yadyn/JabbR,LookLikeAPro/JabbR,M-Zuber/JabbR,lukehoban/JabbR,CrankyTRex/JabbRMirror,meebey/JabbR,e10/JabbR,yadyn/JabbR,huanglitest/JabbRTest2,LookLikeAPro/JabbR,SonOfSam/JabbR,ajayanandgit/JabbR,18098924759/JabbR,AAPT/jean0226case1322,meebey/JabbR,mzdv/JabbR,borisyankov/JabbR,borisyankov/JabbR,LookLikeAPro/JabbR,18098924759/JabbR,M-Zuber/JabbR,mzdv/JabbR,JabbR/JabbR,timgranstrom/JabbR,lukehoban/JabbR,ajayanandgit/JabbR,fuzeman/vox,fuzeman/vox,timgranstrom/JabbR,huanglitest/JabbRTest2,JabbR/JabbR,meebey/JabbR,huanglitest/JabbRTest2,CrankyTRex/JabbRMirror,CrankyTRex/JabbRMirror,borisyankov/JabbR
JabbR/Services/ChatNotificationService.cs
JabbR/Services/ChatNotificationService.cs
using System; using JabbR.Models; using JabbR.ViewModels; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Infrastructure; namespace JabbR.Services { public class ChatNotificationService : IChatNotificationService { private readonly IConnectionManager _connectionManager; public ChatNotificationService(IConnectionManager connectionManager) { _connectionManager = connectionManager; } public void OnUserNameChanged(ChatUser user, string oldUserName, string newUserName) { // Create the view model var userViewModel = new UserViewModel(user); // Tell the user's connected clients that the name changed foreach (var client in user.ConnectedClients) { HubContext.Clients.Client(client.Id).userNameChanged(userViewModel); } // Notify all users in the rooms foreach (var room in user.Rooms) { HubContext.Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name); } } private IHubContext _hubContext; private IHubContext HubContext { get { if (_hubContext == null) { _hubContext = _connectionManager.GetHubContext<Chat>(); } return _hubContext; } } } }
using System; using JabbR.Models; using JabbR.ViewModels; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Infrastructure; namespace JabbR.Services { public class ChatNotificationService : IChatNotificationService { private readonly IConnectionManager _connectionManager; public ChatNotificationService(IConnectionManager connectionManager) { _connectionManager = connectionManager; } public void OnUserNameChanged(ChatUser user, string oldUserName, string newUserName) { // Create the view model var userViewModel = new UserViewModel(user); // Tell the user's connected clients that the name changed foreach (var client in user.ConnectedClients) { GetHubContext().Clients.Client(client.Id).userNameChanged(userViewModel); } // Notify all users in the rooms foreach (var room in user.Rooms) { GetHubContext().Clients.Group(room.Name).changeUserName(oldUserName, userViewModel, room.Name); } } private IHubContext _hubContext; internal IHubContext GetHubContext() { if (_hubContext == null) { _hubContext = _connectionManager.GetHubContext<Chat>(); } return _hubContext; } } }
mit
C#
55a7fa76b7f384e395351b8c6dc1197b16ef9513
remove unused code
dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap
src/DotNetCore.CAP.AzureServiceBus/CAP.AzureServiceBusOptions.cs
src/DotNetCore.CAP.AzureServiceBus/CAP.AzureServiceBusOptions.cs
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Primitives; // ReSharper disable once CheckNamespace namespace DotNetCore.CAP { /// <summary> /// Provides programmatic configuration for the CAP Azure Service Bus project. /// </summary> public class AzureServiceBusOptions { /// <summary> /// TopicPath default value for CAP. /// </summary> public const string DefaultTopicPath = "cap"; /// <summary> /// Azure Service Bus Namespace connection string. Must not contain topic information. /// </summary> public string ConnectionString { get; set; } /// <summary> /// The name of the topic relative to the service namespace base address. /// </summary> public string TopicPath { get; set; } = DefaultTopicPath; /// <summary> /// Represents the Azure Active Directory token provider for Azure Managed Service Identity integration. /// </summary> public ITokenProvider ManagementTokenProvider { get; set; } } }
// Copyright (c) .NET Core Community. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.ServiceBus; using Microsoft.Azure.ServiceBus.Primitives; // ReSharper disable once CheckNamespace namespace DotNetCore.CAP { /// <summary> /// Provides programmatic configuration for the CAP Azure Service Bus project. /// </summary> public class AzureServiceBusOptions { /// <summary> /// TopicPath default value for CAP. /// </summary> public const string DefaultTopicPath = "cap"; /// <summary> /// Azure Service Bus Namespace connection string. Must not contain topic information. /// </summary> public string ConnectionString { get; set; } /// <summary> /// The name of the topic relative to the service namespace base address. /// </summary> public string TopicPath { get; set; } = DefaultTopicPath; /// <summary> /// Represents the Azure Active Directory token provider for Azure Managed Service Identity integration. /// </summary> public ITokenProvider ManagementTokenProvider { get; set; } /// <summary> /// Used to generate Service Bus connection strings /// </summary> public ServiceBusConnectionStringBuilder ConnectionStringBuilder { get; set; } } }
mit
C#
c4a21ba20f2b043fe2bf7a0af50b57cfccd9e25b
Fix tests
DigDes/SoapCore
src/SoapCore.Tests/ModelBindingFilter/ModelBindingFilterTests.cs
src/SoapCore.Tests/ModelBindingFilter/ModelBindingFilterTests.cs
using System; using System.Collections.Generic; using System.ServiceModel; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SoapCore.Tests.ModelBindingFilter { [TestClass] public class ModelBindingFilterTests { [ClassInitialize] public static void StartServer(TestContext testContext) { Task.Run(() => { var host = new WebHostBuilder() .UseKestrel() .UseUrls("http://localhost:5053") .UseStartup<Startup>() .Build(); host.Run(); }).Wait(1000); } public ITestService CreateClient(Dictionary<string, object> headers = null) { var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5053/Service.svc", "localhost"))); var channelFactory = new ChannelFactory<ITestService>(binding, endpoint); var serviceClient = channelFactory.CreateChannel(); return serviceClient; } [TestMethod] public void ModelWasAlteredInModelBindingFilter() { var inputModel = new ComplexModelInputForModelBindingFilter { StringProperty = "string property test value", IntProperty = 123, ListProperty = new List<string> { "test", "list", "of", "strings" }, DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1)) }; var client = CreateClient(); var result = client.ComplexParamWithModelBindingFilter(inputModel); Assert.AreNotEqual(inputModel.StringProperty, result.StringProperty); Assert.AreNotEqual(inputModel.IntProperty, result.IntProperty); } [TestMethod] public void ModelWasNotAlteredInModelBindingFilter() { var inputModel = new ComplexModelInput { StringProperty = "string property test value", IntProperty = 123, ListProperty = new List<string> { "test", "list", "of", "strings" }, DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1)) }; var client = CreateClient(); var result = client.ComplexParam(inputModel); Assert.AreEqual(inputModel.StringProperty, result.StringProperty); Assert.AreEqual(inputModel.IntProperty, result.IntProperty); } } }
using System; using System.Collections.Generic; using System.ServiceModel; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace SoapCore.Tests.ModelBindingFilter { [TestClass] public class ModelBindingFilterTests { [ClassInitialize] public static void StartServer(TestContext testContext) { Task.Run(() => { var host = new WebHostBuilder() .UseKestrel() .UseUrls("http://localhost:5051") .UseStartup<Startup>() .Build(); host.Run(); }).Wait(1000); } public ITestService CreateClient(Dictionary<string, object> headers = null) { var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress(new Uri(string.Format("http://{0}:5051/Service.svc", "localhost"))); var channelFactory = new ChannelFactory<ITestService>(binding, endpoint); var serviceClient = channelFactory.CreateChannel(); return serviceClient; } [TestMethod] public void ModelWasAlteredInModelBindingFilter() { var inputModel = new ComplexModelInputForModelBindingFilter { StringProperty = "string property test value", IntProperty = 123, ListProperty = new List<string> { "test", "list", "of", "strings" }, DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1)) }; var client = CreateClient(); var result = client.ComplexParamWithModelBindingFilter(inputModel); Assert.AreNotEqual(inputModel.StringProperty, result.StringProperty); Assert.AreNotEqual(inputModel.IntProperty, result.IntProperty); } [TestMethod] public void ModelWasNotAlteredInModelBindingFilter() { var inputModel = new ComplexModelInput { StringProperty = "string property test value", IntProperty = 123, ListProperty = new List<string> { "test", "list", "of", "strings" }, DateTimeOffsetProperty = new DateTimeOffset(2018, 12, 31, 13, 59, 59, TimeSpan.FromHours(1)) }; var client = CreateClient(); var result = client.ComplexParam(inputModel); Assert.AreEqual(inputModel.StringProperty, result.StringProperty); Assert.AreEqual(inputModel.IntProperty, result.IntProperty); } } }
mit
C#
7225558ecef5e012aa5291d92a988f55999b88bb
Clean up using statements
patridge/StackGeography,patridge/StackGeography,patridge/StackGeography
StackGeography/geocode.ashx.cs
StackGeography/geocode.ashx.cs
using System.Configuration; using System.Web; using Newtonsoft.Json; using StackGeography.Models; namespace StackGeography { public class geocode : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string location = context.Request.Params["loc"]; GeocodingResult result = this.GeocodingCache.Lookup(location); if (result == null) { result = this.GeocodingLookupService.Geocode(location); if (result == null) { result = new GeocodingResult() { Location = location, Coordinates = null }; } this.GeocodingCache.Store(result); } string jsonResult; if (result.Coordinates == null) { jsonResult = JsonConvert.SerializeObject(new { result = (object)null }); } else { jsonResult = JsonConvert.SerializeObject(new { result = new { lat = result.Coordinates.Latitude, lng = result.Coordinates.Longitude } }); } context.Response.Write(jsonResult); } public bool IsReusable { get { return false; } } public IGeocodingCache GeocodingCache { get; set; } public IGeocodingLookupService GeocodingLookupService { get; set; } public geocode(IGeocodingCache geocodingCache, IGeocodingLookupService geocodingLookupService) { this.GeocodingCache = geocodingCache; this.GeocodingLookupService = geocodingLookupService; } private static IGeocodingCache GetGeocodingCache() { string connectionString = ConfigurationManager.ConnectionStrings["StackGeography"].ConnectionString; IGeocodingCache geocodingCache = new SqlServerGeocodingCache(connectionString); #if DEBUG // Override with local SQLCE connection string in debug. connectionString = ConfigurationManager.ConnectionStrings["StackGeography_sqlce"].ConnectionString; geocodingCache = new SqlCeGeocodingCache(connectionString); #endif return geocodingCache; } public geocode() : this(GetGeocodingCache(), new GoogleMapsGeocodingLookupService()) { } } }
using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Net; using System.Web; using Newtonsoft.Json; using StackGeography.Models; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Data.SqlServerCe; namespace StackGeography { public class geocode : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; string location = context.Request.Params["loc"]; GeocodingResult result = this.GeocodingCache.Lookup(location); if (result == null) { result = this.GeocodingLookupService.Geocode(location); if (result == null) { result = new GeocodingResult() { Location = location, Coordinates = null }; } this.GeocodingCache.Store(result); } string jsonResult; if (result.Coordinates == null) { jsonResult = JsonConvert.SerializeObject(new { result = (object)null }); } else { jsonResult = JsonConvert.SerializeObject(new { result = new { lat = result.Coordinates.Latitude, lng = result.Coordinates.Longitude } }); } context.Response.Write(jsonResult); } public bool IsReusable { get { return false; } } public IGeocodingCache GeocodingCache { get; set; } public IGeocodingLookupService GeocodingLookupService { get; set; } public geocode(IGeocodingCache geocodingCache, IGeocodingLookupService geocodingLookupService) { this.GeocodingCache = geocodingCache; this.GeocodingLookupService = geocodingLookupService; } private static IGeocodingCache GetGeocodingCache() { string connectionString = ConfigurationManager.ConnectionStrings["StackGeography"].ConnectionString; IGeocodingCache geocodingCache = new SqlServerGeocodingCache(connectionString); #if DEBUG // Override with local SQLCE connection string in debug. connectionString = ConfigurationManager.ConnectionStrings["StackGeography_sqlce"].ConnectionString; geocodingCache = new SqlCeGeocodingCache(connectionString); #endif return geocodingCache; } public geocode() : this(GetGeocodingCache(), new GoogleMapsGeocodingLookupService()) { } } }
mit
C#
e70dcf5178508ee9559c2eddf4aa7750caf5f5f7
fix bool logic when case testing
picoe/Eto.Parse,picoe/Eto.Parse
Eto.Parse/Parsers/CharSetTerminal.cs
Eto.Parse/Parsers/CharSetTerminal.cs
using System; using System.Linq; using Eto.Parse.Parsers; using System.Collections.Generic; namespace Eto.Parse.Parsers { public class CharSetTerminal : CharTerminal { char[] lookupCharacters; HashSet<char> characterLookup; /// <summary> /// Gets or sets the minimum count of characters before a lookup hash table is created /// </summary> /// <value>The minimum lookup count.</value> public int MinLookupCount { get; set; } public char[] Characters { get; set; } protected CharSetTerminal(CharSetTerminal other, ParserCloneArgs args) : base(other, args) { this.Characters = other.Characters != null ? (char[])other.Characters.Clone() : null; this.MinLookupCount = other.MinLookupCount; } public CharSetTerminal(params char[] chars) { this.Characters = (char[])chars.Clone(); this.MinLookupCount = 100; } class LowerCharComparer : IEqualityComparer<char> { public bool Equals(char c1, char c2) { return char.ToLowerInvariant(c1) == char.ToLowerInvariant(c2); } public int GetHashCode(char c1) { return char.ToLowerInvariant(c1).GetHashCode(); } } protected override void InnerInitialize(ParserInitializeArgs args) { base.InnerInitialize(args); if (TestCaseSensitive) { lookupCharacters = Characters; if (lookupCharacters.Length >= MinLookupCount) characterLookup = new HashSet<char>(lookupCharacters); } else { lookupCharacters = new char[Characters.Length]; for (int i = 0; i < Characters.Length; i++) { lookupCharacters[i] = char.ToLowerInvariant(Characters[i]); } if (lookupCharacters.Length >= MinLookupCount) characterLookup = new HashSet<char>(lookupCharacters, new LowerCharComparer()); } } protected override bool Test(char ch) { if (characterLookup != null) return characterLookup.Contains(ch); ch = TestCaseSensitive ? ch : char.ToLowerInvariant(ch); for (int i = 0; i < Characters.Length; i++) { if (lookupCharacters[i] == ch) return true; } return false; } protected override string CharName { get { var chars = string.Join(",", Characters.Select(CharToString)); return string.Format("{0}", chars); } } public override Parser Clone(ParserCloneArgs args) { return new CharSetTerminal(this, args); } } }
using System; using System.Linq; using Eto.Parse.Parsers; using System.Collections.Generic; namespace Eto.Parse.Parsers { public class CharSetTerminal : CharTerminal { char[] lookupCharacters; HashSet<char> characterLookup; /// <summary> /// Gets or sets the minimum count of characters before a lookup hash table is created /// </summary> /// <value>The minimum lookup count.</value> public int MinLookupCount { get; set; } public char[] Characters { get; set; } protected CharSetTerminal(CharSetTerminal other, ParserCloneArgs args) : base(other, args) { this.Characters = other.Characters != null ? (char[])other.Characters.Clone() : null; this.MinLookupCount = other.MinLookupCount; } public CharSetTerminal(params char[] chars) { this.Characters = (char[])chars.Clone(); this.MinLookupCount = 100; } class LowerCharComparer : IEqualityComparer<char> { public bool Equals(char c1, char c2) { return char.ToLowerInvariant(c1) == char.ToLowerInvariant(c2); } public int GetHashCode(char c1) { return char.ToLowerInvariant(c1).GetHashCode(); } } protected override void InnerInitialize(ParserInitializeArgs args) { base.InnerInitialize(args); if (TestCaseSensitive) { lookupCharacters = Characters; if (lookupCharacters.Length >= MinLookupCount) characterLookup = new HashSet<char>(lookupCharacters); } else { lookupCharacters = new char[Characters.Length]; for (int i = 0; i < Characters.Length; i++) { lookupCharacters[i] = char.ToLowerInvariant(Characters[i]); } if (lookupCharacters.Length >= MinLookupCount) characterLookup = new HashSet<char>(lookupCharacters, new LowerCharComparer()); } } protected override bool Test(char ch) { if (characterLookup != null) return characterLookup.Contains(ch); ch = TestCaseSensitive ? char.ToLowerInvariant(ch) : ch; for (int i = 0; i < Characters.Length; i++) { if (lookupCharacters[i] == ch) return true; } return false; } protected override string CharName { get { var chars = string.Join(",", Characters.Select(CharToString)); return string.Format("{0}", chars); } } public override Parser Clone(ParserCloneArgs args) { return new CharSetTerminal(this, args); } } }
mit
C#
668f2e5f1a2a9c605b07f539fd3727f8f32229de
Increment to v1.1.0.0
austins/PasswordHasher
PasswordHasher/Properties/AssemblyInfo.cs
PasswordHasher/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Password Hasher")] [assembly: AssemblyDescription( "Lets you hash a string through a variety of algorithms and see how long each method takes and the length of the resulting hashes." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Austin S.")] [assembly: AssemblyProduct("Password Hasher")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("Austin S.")] [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("1146a36c-4303-4059-a6b6-bb5ab5580c56")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Password Hasher")] [assembly: AssemblyDescription( "Lets you hash a string through a variety of algorithms and see how long each method takes and the length of the resulting hashes." )] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Austin S.")] [assembly: AssemblyProduct("Password Hasher")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("Austin S.")] [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("1146a36c-4303-4059-a6b6-bb5ab5580c56")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
1b27f38c463b8149ee1f3edd1d655a2fca0de71a
fix copy paste
Fody/Scalpel
Tests/ConfigReaderTests.cs
Tests/ConfigReaderTests.cs
using System.Xml.Linq; using NUnit.Framework; [TestFixture] public class ConfigReaderTests { [Test] public void RemoveReferencesNode() { var xElement = XElement.Parse(@" <Scalpel> <RemoveReferences> Foo Bar </RemoveReferences> </Scalpel>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } [Test] public void RemoveReferencesAttribute() { var xElement = XElement.Parse(@" <Scalpel RemoveReferences='Foo|Bar'/>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } [Test] public void RemoveReferencesCombined() { var xElement = XElement.Parse(@" <Scalpel RemoveReferences='Foo'> <RemoveReferences> Bar </RemoveReferences> </Scalpel>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } }
using System.Xml.Linq; using NUnit.Framework; [TestFixture] public class ConfigReaderTests { [Test] public void IncludeAssembliesNode() { var xElement = XElement.Parse(@" <Costura> <RemoveReferences> Foo Bar </RemoveReferences> </Costura>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } [Test] public void IncludeAssembliesAttribute() { var xElement = XElement.Parse(@" <Costura RemoveReferences='Foo|Bar'/>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } [Test] public void IncludeAssembliesCombined() { var xElement = XElement.Parse(@" <Costura RemoveReferences='Foo'> <RemoveReferences> Bar </RemoveReferences> </Costura>"); var moduleWeaver = new ModuleWeaver { Config = xElement }; moduleWeaver.ReadConfig(); Assert.AreEqual("Foo", moduleWeaver.RemoveReferences[0]); Assert.AreEqual("Bar", moduleWeaver.RemoveReferences[1]); } }
mit
C#
a48d1d235edf663d0cb378f5ae396abe4dd1dce5
Add comments too Live.cd
jappi00/Mittelalter-2D-Game
Assets/Scripts/Player/Live.cs
Assets/Scripts/Player/Live.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Live : MonoBehaviour { public Slider healthbar; //Lebens anzeige public int currentLife; //Anfangs Leben public int minLive; // Minimales Leben Standard = 0 public int maxLive; // Maximales Leben Standard = 100 // Überprüfen von den eingegebenen Daten void Start () { if (minLive >= maxLive) //wenn das maximale Leben kleiner oder gleich dem minimalem Leben ist wird wie unten geschrieben die Werte gesetzt { Debug.LogError("Das minimale Leben ist grösser oder gleich zum maximalen Leben, das Maximale wird zu 100 und das minimale zu 0 gesetzt"); minLive = 0; maxLive = 100; } if (minLive >= currentLife)//wenn das minimale Leben größer oder Gleich dem jetzigen Leben ist wird ein Fehler ausgegeben { Debug.LogError("Das momentane Leben ist gleich dem minimalen Leben also ist man sofort tot!"); } //Einrichten des Lebensbalken healthbar.minValue = minLive; healthbar.maxValue = maxLive; healthbar.value = currentLife; } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Live : MonoBehaviour { public Slider healthbar; //Lebens anzeige public int currentLife; //Anfangs Leben public int minLive; // Minimales Leben Standard = 0 public int maxLive; // Maximales Leben Standard = 100 // Use this for initialization void Start () { if (minLive >= maxLive) { Debug.LogError("Das minimale Leben ist grösser oder gleich zum maximalen Leben, das Maximale wird zu 100 und das minimale zu 0 gesetzt"); minLive = 0; maxLive = 100; } if (minLive == currentLife) { Debug.LogError("Das momentane Leben ist gleich dem minimalen Leben also ist man sofort tot!"); } healthbar.minValue = minLive; healthbar.maxValue = maxLive; healthbar.value = currentLife; } }
apache-2.0
C#
6e28ffd23fc99c0e6b91645e3174034693b50f06
Fix Clean target in default build to use 'SourceDirectory'.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
bootstrapping/Build.cs
bootstrapping/Build.cs
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.IO.FileSystemTasks; using static Nuke.Core.IO.PathConstruction; using static Nuke.Core.EnvironmentInfo; class Build : NukeBuild { //[GitVersion] readonly GitVersion GitVersion; //[GitRepository] readonly GitRepository GitRepository; // This is the application entry point for the build. // It also defines the default target to execute. public static int Main () => Execute<Build>(x => x.Compile); Target Clean => _ => _ // Disabled for safety. .OnlyWhen(() => false) .Executes(() => DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj"))) .Executes(() => EnsureCleanDirectory(OutputDirectory)); Target Restore => _ => _ .DependsOn(Clean) .Executes(() => { // Remove tasks as needed. They exist for compatibility. DotNetRestore(SolutionDirectory); if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild(s => DefaultSettings.MSBuildRestore); NuGetRestore(SolutionFile); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile .SetMSBuildVersion(MSBuildVersion))); // When having xproj-based projects, using VS2015 is necessary. MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles(SolutionDirectory, "*.xproj").Any() ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default(MSBuildVersion?); }
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.IO.FileSystemTasks; using static Nuke.Core.IO.PathConstruction; using static Nuke.Core.EnvironmentInfo; class Build : NukeBuild { //[GitVersion] readonly GitVersion GitVersion; //[GitRepository] readonly GitRepository GitRepository; // This is the application entry point for the build. // It also defines the default target to execute. public static int Main () => Execute<Build>(x => x.Compile); Target Clean => _ => _ // Disabled for safety. .OnlyWhen(() => false) .Executes(() => DeleteDirectories(GlobDirectories(SolutionDirectory, "**/bin", "**/obj"))) .Executes(() => EnsureCleanDirectory(OutputDirectory)); Target Restore => _ => _ .DependsOn(Clean) .Executes(() => { // Remove tasks as needed. They exist for compatibility. DotNetRestore(SolutionDirectory); if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild(s => DefaultSettings.MSBuildRestore); NuGetRestore(SolutionFile); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile .SetMSBuildVersion(MSBuildVersion))); // When having xproj-based projects, using VS2015 is necessary. MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles(SolutionDirectory, "*.xproj").Any() ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default(MSBuildVersion?); }
mit
C#
4bee952aabf537ba99e5ea310a93735de8f38f2a
Add id for register button
leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
Joinrpg/Views/Account/Register.cshtml
Joinrpg/Views/Account/Register.cshtml
@using JoinRpg.Web.App_Code; @model JoinRpg.Web.Models.RegisterViewModel @{ ViewBag.Title = "Регистрация"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("Register", "Account", FormMethod.Post, new {@class = "form-horizontal", role = "form"})) { @Html.AntiForgeryToken() <h4>Создать аккаунт</h4> <div class="alert alert-info"> @Html.Partial("_RegistrationRules") </div> <p>@Html.HelpLink("register", "Подробнее о регистрации")</p> <hr/> @Html.ValidationSummary("", new {@class = "text-danger"}) <div class="form-group"> @Html.LabelFor(m => m.Email, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.ConfirmPassword, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.PasswordFor(m => m.ConfirmPassword, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.RulesApproved, new {@class = "col-md-2 control-label"}) <div class="col-md-2"> @Html.EditorFor(m => m.RulesApproved) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" id="btnRegister" value="Зарегистрироваться"/> </div> </div> }
@using JoinRpg.Web.App_Code; @model JoinRpg.Web.Models.RegisterViewModel @{ ViewBag.Title = "Регистрация"; } <h2>@ViewBag.Title</h2> @using (Html.BeginForm("Register", "Account", FormMethod.Post, new {@class = "form-horizontal", role = "form"})) { @Html.AntiForgeryToken() <h4>Создать аккаунт</h4> <div class="alert alert-info"> @Html.Partial("_RegistrationRules") </div> <p>@Html.HelpLink("register", "Подробнее о регистрации")</p> <hr/> @Html.ValidationSummary("", new {@class = "text-danger"}) <div class="form-group"> @Html.LabelFor(m => m.Email, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.TextBoxFor(m => m.Email, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.Password, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.PasswordFor(m => m.Password, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.ConfirmPassword, new {@class = "col-md-2 control-label"}) <div class="col-md-10"> @Html.PasswordFor(m => m.ConfirmPassword, new {@class = "form-control"}) </div> </div> <div class="form-group"> @Html.LabelFor(m => m.RulesApproved, new {@class = "col-md-2 control-label"}) <div class="col-md-2"> @Html.EditorFor(m => m.RulesApproved) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-default" value="Зарегистрироваться"/> </div> </div> }
mit
C#
e21a3afd0bb02a9fe5a5b01599638d80827219d7
Allow overriding page heading, render()
kamsar/Kamsar.WebConsole,kamsar/Kamsar.WebConsole
Kamsar.WebConsole/Html5WebConsole.cs
Kamsar.WebConsole/Html5WebConsole.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; namespace Kamsar.WebConsole { /// <summary> /// Implements a WebConsole that has a basic HTML5 page wrapper on it. /// </summary> public class Html5WebConsole : WebConsole { HttpResponseBase _response; public Html5WebConsole(HttpResponseBase response) : base(response) { _response = response; Title = string.Empty; } public Html5WebConsole(HttpResponse response) : this(new HttpResponseWrapper(response)) { } public string Title { get; set; } /// <summary> /// Renders content into the <head> /// </summary> protected virtual void RenderHead() { if (!string.IsNullOrEmpty(Title)) { _response.Write(string.Format("<title>{0}</title>", Title)); } RenderResources(); } /// <summary> /// Renders heading content into the page (e.g. a <h1> of the title, etc) /// </summary> protected virtual void RenderPageHead() { if (!string.IsNullOrEmpty(Title)) { _response.Write(string.Format("<h1>{0}</h1>", Title)); } } public override void Render() { throw new NotImplementedException("Use the overload with the process action to place your console output at a proper location in the markup."); } public virtual void Render(Action<WebConsole> processAction) { _response.Write("<!DOCTYPE html>"); _response.Write("<html>"); _response.Write("<head>"); RenderHead(); _response.Write("</head>"); _response.Write("<body>"); _response.Write("<div class=\"wrapper\">"); RenderPageHead(); base.Render(); _response.Write("</div>"); _response.Flush(); processAction(this); _response.Write("</body>"); _response.Write("</html>"); _response.Flush(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.UI; namespace Kamsar.WebConsole { /// <summary> /// Implements a WebConsole that has a basic HTML5 page wrapper on it. /// </summary> public class Html5WebConsole : WebConsole { HttpResponseBase _response; public Html5WebConsole(HttpResponseBase response) : base(response) { _response = response; Title = string.Empty; } public Html5WebConsole(HttpResponse response) : this(new HttpResponseWrapper(response)) { } public string Title { get; set; } protected virtual void RenderHead() { if (!string.IsNullOrEmpty(Title)) { _response.Write(string.Format("<title>{0}</title>", Title)); } RenderResources(); } public override void Render() { throw new NotImplementedException("Use the overload with the process action to place your console output at a proper location in the page."); } public void Render(Action<WebConsole> processAction) { _response.Write("<!DOCTYPE html>"); _response.Write("<html>"); _response.Write("<head>"); RenderHead(); _response.Write("</head>"); _response.Write("<body>"); _response.Write("<div class=\"wrapper\">"); if (!string.IsNullOrEmpty(Title)) { _response.Write(string.Format("<h1>{0}</h1>", Title)); } base.Render(); _response.Write("</div>"); _response.Flush(); processAction(this); _response.Write("</body>"); _response.Write("</html>"); _response.Flush(); } } }
mit
C#
09b1a40f3cce0d9c31bb7d06e4743bf5eaae2019
Use public interface in test app
Microsoft/ApplicationInsights-Xamarin
XamarinTest/XamarinTest.cs
XamarinTest/XamarinTest.cs
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); ApplicationInsights.RenewSessionWithId ("MySession"); ApplicationInsights.SetUserId ("Christoph"); TelemetryManager.TrackMetric ("My custom metric", 2.2); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
mit
C#
b71c2e15c0fb16f589a88fc4857e84ecac7a2d4f
Bump version
kamil-mrzyglod/Oxygenize
Oxygenize/Properties/AssemblyInfo.cs
Oxygenize/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("Oxygenize")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Oxygenize")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("78a5cd71-2e0f-47a3-b553-d7109704dfe5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: InternalsVisibleTo("Oxygenize.Test")]
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("Oxygenize")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Oxygenize")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("78a5cd71-2e0f-47a3-b553-d7109704dfe5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Oxygenize.Test")]
mit
C#
bdfd7ee5520b1d603b40d150dbef5db44802eeab
Teste de Envio Secundário
gsmgabriela/Vai-Fundos
VaiFundos/VaiFundos/Program.cs
VaiFundos/VaiFundos/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VaiFundos { class Program { static void Main(string[] args) { //Olá Mundo! } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VaiFundos { class Program { static void Main(string[] args) { } } }
mit
C#
2bc1711b4817c160cdb14cba113a277a8bb436d6
Update AssemblyInfo.cs
DrunkyBard/AnalyzeMe
src/AnalyzeMe/AnalyzeMe.Design.Analyzers/Properties/AssemblyInfo.cs
src/AnalyzeMe/AnalyzeMe.Design.Analyzers/Properties/AssemblyInfo.cs
using System.Resources; 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("AnalyzeMe.Style.Analyzers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AnalyzeMe.Style.Analyzers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("AnalyzeMe.Tests")]
using System.Resources; 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("AnalyzeMe.Style.Analyzers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AnalyzeMe.Style.Analyzers")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("AnalyzeMe.Tests")]
mit
C#
9de19027ec1b842fbef2114f0529cf78583a3e67
use internal metrics in sample
DeonHeyns/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,ntent-ad/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,ntent-ad/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,alhardy/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET
Samples/Metrics.SamplesConsole/Program.cs
Samples/Metrics.SamplesConsole/Program.cs
using System; using Metrics.Samples; using Metrics.Utils; namespace Metrics.SamplesConsole { class Program { static void Main(string[] args) { //Metric.CompletelyDisableMetrics(); Metric.Config .WithHttpEndpoint("http://localhost:1234/") .WithAllCounters() .WithInternalMetrics() .WithReporting(config => config //.WithNLogCSVReports(TimeSpan.FromSeconds(5)) //.WithNLogTextReports(TimeSpan.FromSeconds(5)) //.WithReporter("CSV Reports", () => new CSVReporter(new RollingCSVFileAppender(@"c:\temp\csv")), TimeSpan.FromSeconds(10)) .WithConsoleReport(TimeSpan.FromSeconds(30)) //.WithCSVReports(@"c:\temp\reports\", TimeSpan.FromSeconds(10)) //.WithTextFileReport(@"C:\temp\reports\metrics.txt", TimeSpan.FromSeconds(10)) ); using (var scheduler = new ActionScheduler()) { SampleMetrics.RunSomeRequests(); scheduler.Start(TimeSpan.FromMilliseconds(500), () => SampleMetrics.RunSomeRequests()); //Metrics.Samples.FSharp.SampleMetrics.RunSomeRequests(); HealthChecksSample.RegisterHealthChecks(); //Metrics.Samples.FSharp.HealthChecksSample.RegisterHealthChecks(); Console.WriteLine("done setting things up"); Console.ReadKey(); } } } }
using System; using Metrics.Samples; using Metrics.Utils; namespace Metrics.SamplesConsole { class Program { static void Main(string[] args) { //Metric.CompletelyDisableMetrics(); Metric.Config .WithHttpEndpoint("http://localhost:1234/") .WithAllCounters() .WithReporting(config => config //.WithNLogCSVReports(TimeSpan.FromSeconds(5)) //.WithNLogTextReports(TimeSpan.FromSeconds(5)) //.WithReporter("CSV Reports", () => new CSVReporter(new RollingCSVFileAppender(@"c:\temp\csv")), TimeSpan.FromSeconds(10)) .WithConsoleReport(TimeSpan.FromSeconds(30)) //.WithCSVReports(@"c:\temp\reports\", TimeSpan.FromSeconds(10)) //.WithTextFileReport(@"C:\temp\reports\metrics.txt", TimeSpan.FromSeconds(10)) ); using (var scheduler = new ActionScheduler()) { SampleMetrics.RunSomeRequests(); scheduler.Start(TimeSpan.FromMilliseconds(500), () => SampleMetrics.RunSomeRequests()); //Metrics.Samples.FSharp.SampleMetrics.RunSomeRequests(); HealthChecksSample.RegisterHealthChecks(); //Metrics.Samples.FSharp.HealthChecksSample.RegisterHealthChecks(); Console.WriteLine("done setting things up"); Console.ReadKey(); } } } }
apache-2.0
C#
4f8daaba1293c01b94e46dd9abb7e5be00b19861
Fix ExcelViewModel
Zjazure/Joinzjazure,Zjazure/Joinzjazure
Joinzjazure/Models/ExcelViewModel.cs
Joinzjazure/Models/ExcelViewModel.cs
using Joinzjazure.Data; using System; using System.Linq; using System.Runtime.Serialization; namespace Joinzjazure.Models { [DataContract] public class ExcelViewModel { public ExcelViewModel(FormEntity entity) { Gender = entity.Gender; Email = entity.Email; Phone = entity.Phone; QQ = entity.QQ; Weibo = entity.Weibo; Description = entity.Description; Name = entity.RowKey; Class = int.Parse(entity.PartitionKey) % 100; Grade = int.Parse(entity.PartitionKey) / 100; Groups = string.Join(",", (from g in GroupXmlStore.GetAll() where (g.Value & entity.Groups) != 0 select g.Name).ToArray()); } [DataMember] public int Class { get; set; } [DataMember] public string Description { get; set; } [DataMember] public string Email { get; set; } [DataMember] public bool Gender { get; set; } [DataMember] public int Grade { get; set; } [DataMember] public string Groups { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Phone { get; set; } [DataMember] public string QQ { get; set; } [DataMember] public string Weibo { get; set; } } }
using Joinzjazure.Data; using System; using System.Linq; using System.Runtime.Serialization; namespace Joinzjazure.Models { [DataContract] public class ExcelViewModel { public ExcelViewModel(FormEntity entity) { Gender = entity.Gender; Email = entity.Email; Phone = entity.Phone; QQ = entity.QQ; Weibo = entity.Weibo; Description = entity.Description; Timestamp = entity.Timestamp.DateTime; Name = entity.RowKey; Class = int.Parse(entity.PartitionKey) % 100; Grade = int.Parse(entity.PartitionKey) / 100; Groups = string.Join(",", (from g in GroupXmlStore.GetAll() where (g.Value & entity.Groups) != 0 select g.Name).ToArray()); } [DataMember] public int Class { get; set; } [DataMember] public string Description { get; set; } [DataMember] public string Email { get; set; } [DataMember] public bool Gender { get; set; } [DataMember] public int Grade { get; set; } [DataMember] public string Groups { get; set; } [DataMember] public string Name { get; set; } [DataMember] public string Phone { get; set; } [DataMember] public string QQ { get; set; } [DataMember] public DateTime Timestamp { get; set; } [DataMember] public string Weibo { get; set; } } }
mit
C#
1d9024dff2bf4b7b0ba46b6f862f0717877e0770
add CurrentUserChanged
AlejandroCano/framework,signumsoftware/framework,avifatal/framework,AlejandroCano/framework,signumsoftware/framework,avifatal/framework
Signum.Entities/Basics/IUserEntity.cs
Signum.Entities/Basics/IUserEntity.cs
using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Signum.Entities.Basics { public interface IUserEntity : IEntity { } public static class UserHolder { public static readonly string UserSessionKey = "user"; public static event Action CurrentUserChanged; public static readonly SessionVariable<IUserEntity> CurrentUserVariable = Statics.SessionVariable<IUserEntity>(UserSessionKey); public static IUserEntity Current { get { return CurrentUserVariable.Value; } set { CurrentUserVariable.Value = value; if (CurrentUserChanged != null) CurrentUserChanged(); } } public static IDisposable UserSession(IUserEntity user) { var result = ScopeSessionFactory.OverrideSession(); UserHolder.Current = user; return result; } } }
using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Signum.Entities.Basics { public interface IUserEntity : IEntity { } public static class UserHolder { public static readonly string UserSessionKey = "user"; public static readonly SessionVariable<IUserEntity> CurrentUserVariable = Statics.SessionVariable<IUserEntity>(UserSessionKey); public static IUserEntity Current { get { return CurrentUserVariable.Value; } set { CurrentUserVariable.Value = value; } } public static IDisposable UserSession(IUserEntity user) { var result = ScopeSessionFactory.OverrideSession(); UserHolder.Current = user; return result; } } }
mit
C#
fd4b49e0d5ab086d24225ce69b1a2a267ab4a4d5
Fix remote API load order
TorchAPI/Torch
Torch.Server/Managers/RemoteAPIManager.cs
Torch.Server/Managers/RemoteAPIManager.cs
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { Torch.GameStateChanged += TorchOnGameStateChanged; base.Attach(); } /// <inheritdoc /> public override void Detach() { Torch.GameStateChanged -= TorchOnGameStateChanged; base.Detach(); } private void TorchOnGameStateChanged(MySandboxGame game, TorchGameState newstate) { if (newstate == TorchGameState.Loading && MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } } } }
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { if (MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } base.Attach(); } } }
apache-2.0
C#
cf60639e6a5b1909208b0011d628e66e97b2df6e
Complete missing documentation
evilz/sc2replay-csharp,ascendedguard/sc2replay-csharp
Starcraft2.ReplayParser/Difficulty.cs
Starcraft2.ReplayParser/Difficulty.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Difficulty.cs" company="SC2ReplayParser"> // Copyright © 2011 All Rights Reserved // </copyright> // <summary> // Describes the difficulty of a computer AI opponent. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Starcraft2.ReplayParser { /// <summary> /// Describes the difficulty of a computer AI opponent. /// </summary> public enum Difficulty { /// <summary> /// Unknown AI difficulty /// </summary> Unknown, /// <summary> /// Very Easy AI difficulty /// </summary> VeryEasy, /// <summary> /// Easy AI difficulty /// </summary> Easy, /// <summary> /// Medium AI difficulty /// </summary> Medium, /// <summary> /// Hard AI difficulty /// </summary> Hard, /// <summary> /// Very Hard AI difficulty /// </summary> VeryHard, /// <summary> /// Insane AI difficulty /// </summary> Insane, } }
namespace Starcraft2.ReplayParser { /// <summary> /// Enumeration of available difficulties for computer players. /// </summary> public enum Difficulty { Unknown, VeryEasy, Easy, Medium, Hard, VeryHard, Insane, } }
mit
C#
f09c2c6ab2134813b4161e743abca3da648a36a0
Fix test failure when BasicAuth tests were first to run
iamjasonp/wcf,imcarolwang/wcf,ericstj/wcf,imcarolwang/wcf,MattGal/wcf,dotnet/wcf,dotnet/wcf,mconnew/wcf,iamjasonp/wcf,StephenBonikowsky/wcf,khdang/wcf,shmao/wcf,imcarolwang/wcf,MattGal/wcf,mconnew/wcf,shmao/wcf,ElJerry/wcf,khdang/wcf,ElJerry/wcf,hongdai/wcf,KKhurin/wcf,hongdai/wcf,StephenBonikowsky/wcf,zhenlan/wcf,mconnew/wcf,zhenlan/wcf,dotnet/wcf,ericstj/wcf,KKhurin/wcf
src/System.Private.ServiceModel/tools/test/SelfHostWcfService/TestResources/BasicAuthResource.cs
src/System.Private.ServiceModel/tools/test/SelfHostWcfService/TestResources/BasicAuthResource.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfService.CertificateResources; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } protected override void ModifyHost(ServiceHost serviceHost, ResourceRequestContext context) { // Ensure the https certificate is installed before this endpoint resource is used CertificateResourceHelpers.EnsureSslPortCertificateInstalled(context.BridgeConfiguration); base.ModifyHost(serviceHost, context); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } } }
mit
C#
5285c807f70cdc9b17a08df8891f60ca6d7d4258
Add guard methods for Enum Argument OutOfRange check
jnyrup/fluentassertions,jnyrup/fluentassertions,dennisdoomen/fluentassertions,fluentassertions/fluentassertions,fluentassertions/fluentassertions,dennisdoomen/fluentassertions
Src/FluentAssertions/Common/Guard.cs
Src/FluentAssertions/Common/Guard.cs
using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName, string message) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } }
using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } }
apache-2.0
C#
5d77002f9c3c997d76ffe0c19ed41a5b7f78533d
Add XInput "A" button for jumping
danbolt/ggj-jan-2017
Pumpkin/Assets/Scripts/PlayerJump.cs
Pumpkin/Assets/Scripts/PlayerJump.cs
 using System; using UnityEngine; public class PlayerJump : MonoBehaviour { public Vector3 Force = new Vector3(0f, 2f, 0f); public string Button = "Jump"; public AudioClip[] JumpSounds; private Rigidbody _Rigidbody; private CapsuleCollider _Collider; private AudioSource _AudioSource; private float ColliderHeight; private System.Random _Random = new System.Random(); private int LastUsedSoundIndex = -1; private bool inAir; private void Start() { _Rigidbody = GetComponent<Rigidbody>(); _Collider = GetComponent<CapsuleCollider>(); _AudioSource = GetComponent<AudioSource>(); ColliderHeight = _Collider.bounds.extents.y; inAir = false; } private void FixedUpdate() { inAir = !IsGrounded; if ((Input.GetButtonDown(Button) || Input.GetButtonDown("Fire2")) && !inAir) { Jump(); PlayJumpSound(); } if (inAir) { Vector3 vel = _Rigidbody.velocity; vel.y -= 20.8f * Time.deltaTime; _Rigidbody.velocity = vel; } } private bool IsGrounded { get { //Physics.CheckCapsule(collider.bounds.center,new Vector3(collider.bounds.center.x,collider.bounds.min.y-0.1f,collider.bounds.center.z),0.18f)); return Physics.Raycast(transform.position, -Vector3.up, ColliderHeight + 0.02f); } } private void Jump() { _Rigidbody.velocity = Vector3.zero; _Rigidbody.angularVelocity = Vector3.zero; _Rigidbody.AddForce(Force, ForceMode.Impulse); } private void PlayJumpSound() { int soundCount = JumpSounds.Length; if (soundCount > 0) { int randIndex = _Random.Next(0, soundCount); if (randIndex == LastUsedSoundIndex) { randIndex = (randIndex + 1) % soundCount; } var sound = JumpSounds[randIndex]; _AudioSource.PlayOneShot(sound); } } }
 using System; using UnityEngine; public class PlayerJump : MonoBehaviour { public Vector3 Force = new Vector3(0f, 2f, 0f); public string Button = "Jump"; public AudioClip[] JumpSounds; private Rigidbody _Rigidbody; private CapsuleCollider _Collider; private AudioSource _AudioSource; private float ColliderHeight; private System.Random _Random = new System.Random(); private int LastUsedSoundIndex = -1; private bool inAir; private void Start() { _Rigidbody = GetComponent<Rigidbody>(); _Collider = GetComponent<CapsuleCollider>(); _AudioSource = GetComponent<AudioSource>(); ColliderHeight = _Collider.bounds.extents.y; inAir = false; } private void FixedUpdate() { inAir = !IsGrounded; if (Input.GetButtonDown(Button) && !inAir) { Jump(); PlayJumpSound(); } if (inAir) { Vector3 vel = _Rigidbody.velocity; vel.y -= 20.8f * Time.deltaTime; _Rigidbody.velocity = vel; } } private bool IsGrounded { get { //Physics.CheckCapsule(collider.bounds.center,new Vector3(collider.bounds.center.x,collider.bounds.min.y-0.1f,collider.bounds.center.z),0.18f)); return Physics.Raycast(transform.position, -Vector3.up, ColliderHeight + 0.02f); } } private void Jump() { _Rigidbody.velocity = Vector3.zero; _Rigidbody.angularVelocity = Vector3.zero; _Rigidbody.AddForce(Force, ForceMode.Impulse); } private void PlayJumpSound() { int soundCount = JumpSounds.Length; if (soundCount > 0) { int randIndex = _Random.Next(0, soundCount); if (randIndex == LastUsedSoundIndex) { randIndex = (randIndex + 1) % soundCount; } var sound = JumpSounds[randIndex]; _AudioSource.PlayOneShot(sound); } } }
mit
C#
a952a2b3cfb17f38f506109b95bd3177eda09e47
Add fake pour buttons in admin
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
RightpointLabs.Pourcast.Web/Areas/Admin/Views/Tap/Index.cshtml
RightpointLabs.Pourcast.Web/Areas/Admin/Views/Tap/Index.cshtml
@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}, new { @class = "btn"}) @if (null != tap.Keg) { <a class="btn btn-pour" data-tap-id="@tap.Id" href="#">Pour</a> } </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p> @section scripts { <script type="text/javascript"> $(function () { $(".btn-pour").each(function() { var $t = $(this); var tapId = $t.attr("data-tap-id"); var timer = null; var start = null; $t.mousedown(function () { $.getJSON("/api/tap/" + tapId + "/StartPour"); start = new Date().getTime(); timer = setInterval(function () { $.getJSON("/api/tap/" + tapId + "/Pouring?volume=" + ((new Date().getTime() - start) / 500)); }, 250); }); $t.mouseup(function () { clearInterval(timer); $.getJSON("/api/tap/" + tapId + "/StopPour?volume=" + ((new Date().getTime() - start) / 500)); }); }); }); </script> }
@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}) </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p>
mit
C#
f0b3a761ebe0a1eb6e39080eea248b03105adf02
Increase copyright year to 2017 in CommonAssemblyInfo.cs
atata-framework/atata-sample-app-tests
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.11.0")] [assembly: AssemblyFileVersion("0.11.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2016")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.11.0")] [assembly: AssemblyFileVersion("0.11.0")]
apache-2.0
C#
98afd73c04339993652abff4aebb0dcacf456c11
Update project scope in GlobalAssemblyInfo
michael-wolfenden/Polly
src/GlobalAssemblyInfo.cs
src/GlobalAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("Polly")] [assembly: AssemblyCompany("App vNext")] [assembly: AssemblyDescription("Polly is a library that allows developers to express resilience and transient fault handling policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation and Fallback in a fluent and thread-safe manner.")] [assembly: AssemblyCopyright("Copyright (c) 2016, App vNext")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
using System.Reflection; [assembly: AssemblyProduct("Polly")] [assembly: AssemblyCompany("App vNext")] [assembly: AssemblyDescription("Polly is a library that allows developers to express transient exception handling policies such as Retry, Retry Forever, Wait and Retry or Circuit Breaker in a fluent manner.")] [assembly: AssemblyCopyright("Copyright (c) 2016, App vNext")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif
bsd-3-clause
C#
294e744002660ef99b99de95ea81a81d99d78629
Fix regex pattern in removing emotes.
Ervie/Homunculus
Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs
Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-]+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-\']+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
mit
C#
704121a21c81e0cecad802a750c5c437acb801e3
add new stripe Hue settings
kubdotnet/LedControllerEngine
LedControllerEngine/Assets/Effects/Stripes/HueShift/HueShift.cs
LedControllerEngine/Assets/Effects/Stripes/HueShift/HueShift.cs
using System; using System.Collections.Generic; namespace LedControllerEngine.Assets.Effects.Stripes { public class HueShift : IEffect { public string Name { get => "HUE Shift"; } public int ModeNumber { get => 0; } public Guid Id { get => new Guid("46B5B727-0B0A-4ADD-A28A-2B578F1A48F9"); } public Type SettingsControl { get => typeof(HueShiftSettings); } private HueShiftSettingsModel _settingsModel = new HueShiftSettingsModel(); public object SettingsModel { get { return _settingsModel; } set { if (!(value is HueShiftSettingsModel)) { throw new ArgumentException("Wrong type, HueShiftSettingsModel expected"); } _settingsModel = (HueShiftSettingsModel)value; } } public Type EffectType => typeof(HueShift); public DeviceType Compatiblity { get => DeviceType.Stripe; } /// <summary> /// Gets the settings values. /// </summary> /// <returns> /// List of EffectSetting /// </returns> public List<EffectSetting> GetSettingsValues() { var settings = new List<EffectSetting>(); settings.Add(new EffectSetting() { Code = 0, Value = ModeNumber }); // effect mode number settings.Add(new EffectSetting() { Code = 1, Value = _settingsModel.StartingHue.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 2, Value = _settingsModel.EndingHue.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 3, Value = _settingsModel.HueOffset.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 4, Value = _settingsModel.StartingSaturation.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 5, Value = _settingsModel.PhaseOffset.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 7, Value = _settingsModel.Speed.GetValueOrDefault() }); return settings; } } }
using System; using System.Collections.Generic; namespace LedControllerEngine.Assets.Effects.Stripes { public class HueShift : IEffect { public string Name { get => "HUE Shift"; } public int ModeNumber { get => 0; } public Guid Id { get => new Guid("46B5B727-0B0A-4ADD-A28A-2B578F1A48F9"); } public Type SettingsControl { get => typeof(HueShiftSettings); } private HueShiftSettingsModel _settingsModel = new HueShiftSettingsModel(); public object SettingsModel { get { return _settingsModel; } set { if (!(value is HueShiftSettingsModel)) { throw new ArgumentException("Wrong type, HueShiftSettingsModel expected"); } _settingsModel = (HueShiftSettingsModel)value; } } public Type EffectType => typeof(HueShift); public DeviceType Compatiblity { get => DeviceType.Stripe; } /// <summary> /// Gets the settings values. /// </summary> /// <returns> /// List of EffectSetting /// </returns> public List<EffectSetting> GetSettingsValues() { var settings = new List<EffectSetting>(); settings.Add(new EffectSetting() { Code = 0, Value = ModeNumber }); // effect mode number settings.Add(new EffectSetting() { Code = 1, Value = _settingsModel.StartingHue.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 2, Value = _settingsModel.EndingHue.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 3, Value = _settingsModel.HueOffset.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 5, Value = _settingsModel.PhaseOffset.GetValueOrDefault() }); settings.Add(new EffectSetting() { Code = 7, Value = _settingsModel.Speed.GetValueOrDefault() }); return settings; } } }
mit
C#