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
675a405cdbcc7856632b7a72ae91ccd97a6154f2
Add virtual pre/post build methods.
Chaser324/unity-build,thaumazo/unity-build
Editor/Settings/BuildSettings.cs
Editor/Settings/BuildSettings.cs
using UnityEngine; using UnityEditor; namespace UnityBuild { public abstract class BuildSettings { public abstract string binName { get; } public abstract string binPath { get; } public abstract string[] scenesInBuild { get; } public abstract string[] copyToBuild { get; } public virtual void PreBuild() { } public virtual void PostBuild() { } } }
using UnityEngine; using UnityEditor; namespace UnityBuild { public abstract class BuildSettings { public abstract string binName { get; } public abstract string binPath { get; } public abstract string[] scenesInBuild { get; } public abstract string[] copyToBuild { get; } //// The name of executable file (e.g. mygame.exe, mygame.app) //public const string BIN_NAME = "mygame"; //// The base path where builds are output. //// Path is relative to the Unity project's base folder unless an absolute path is given. //public const string BIN_PATH = "bin"; //// A list of scenes to include in the build. The first listed scene will be loaded first. //public static string[] scenesInBuild = new string[] { // // "Assets/Scenes/scene1.unity", // // "Assets/Scenes/scene2.unity", // // ... //}; //// A list of files/directories to include with the build. //// Paths are relative to Unity project's base folder unless an absolute path is given. //public static string[] copyToBuild = new string[] { // // "DirectoryToInclude/", // // "FileToInclude.txt", // // ... //}; } }
mit
C#
87c8a449ed6c888a55f6c0ccac405dc884fce1d0
fix max upload file size
yar229/Mail.Ru-.net-cloud-client
MailRuCloudApi/AccountInfo.cs
MailRuCloudApi/AccountInfo.cs
namespace MailRuCloudApi { public class AccountInfo { private long _fileSizeLimit; public long FileSizeLimit { get { return _fileSizeLimit <= 0 ? long.MaxValue : _fileSizeLimit; } set { _fileSizeLimit = value; } } } }
namespace MailRuCloudApi { public class AccountInfo { public long FileSizeLimit { get; set; } } }
mit
C#
11e54199bad2339570dd3213abb2b987cc35eb94
Add GLACIER storage class
carbon/Amazon
src/Amazon.S3/Models/StorageClass.cs
src/Amazon.S3/Models/StorageClass.cs
namespace Amazon.S3 { public class StorageClass { private StorageClass(string name) { Name = name; } public string Name { get; } public override string ToString() => Name; public static readonly StorageClass Standard = new StorageClass("STANDARD"); public static readonly StorageClass StandardInfrequentAccess = new StorageClass("STANDARD_IA"); public static readonly StorageClass ReducedRedundancy = new StorageClass("REDUCED_REDUNDANCY"); public static readonly StorageClass Glacier = new StorageClass("GLACIER"); } // STANDARD | STANDARD_IA | REDUCED_REDUNDANCY }
namespace Amazon.S3 { public class StorageClass { internal StorageClass(string name) { Name = name; } public string Name { get; } public override string ToString() { return Name; } public static readonly StorageClass Standard = new StorageClass("STANDARD"); public static readonly StorageClass StandardInfrequentAccess = new StorageClass("STANDARD_IA"); public static readonly StorageClass ReducedRedundancy = new StorageClass("REDUCED_REDUNDANCY"); } // STANDARD | STANDARD_IA | REDUCED_REDUNDANCY }
mit
C#
79612cff89f184dbe0efa2ee33bfd914471a8c59
Make Reference a struct
RogueException/Discord.Net,Joe4evr/Discord.Net,AntiTcb/Discord.Net,LassieME/Discord.Net,Confruggy/Discord.Net
src/Discord.Net/Helpers/Reference.cs
src/Discord.Net/Helpers/Reference.cs
using System; namespace Discord { internal struct Reference<T> where T : CachedObject { private Action<T> _onCache, _onUncache; private Func<string, T> _getItem; private string _id; public string Id { get { return _id; } set { _id = value; _value = null; } } private T _value; public T Value { get { var v = _value; //A little trickery to make this threadsafe if (v != null && !_value.IsCached) { v = null; _value = null; } if (v == null && _id != null) { v = _getItem(_id); if (v != null && _onCache != null) _onCache(v); _value = v; } return v; } } public T Load() { return Value; //Used for precaching } public void Unload() { if (_onUncache != null) { var v = _value; if (v != null && _onUncache != null) _onUncache(v); } } public Reference(Func<string, T> onUpdate, Action<T> onCache = null, Action<T> onUncache = null) : this(null, onUpdate, onCache, onUncache) { } public Reference(string id, Func<string, T> getItem, Action<T> onCache = null, Action<T> onUncache = null) { _id = id; _getItem = getItem; _onCache = onCache; _onUncache = onUncache; _value = null; } } }
using System; namespace Discord { internal class Reference<T> where T : CachedObject { private Action<T> _onCache, _onUncache; private Func<string, T> _getItem; private string _id; public string Id { get { return _id; } set { _id = value; _value = null; } } private T _value; public T Value { get { var v = _value; //A little trickery to make this threadsafe if (v != null && !_value.IsCached) { v = null; _value = null; } if (v == null && _id != null) { v = _getItem(_id); if (v != null && _onCache != null) _onCache(v); _value = v; } return v; } } public T Load() { return Value; //Used for precaching } public void Unload() { if (_onUncache != null) { var v = _value; if (v != null && _onUncache != null) _onUncache(v); } } public Reference(Func<string, T> onUpdate, Action<T> onCache = null, Action<T> onUncache = null) : this(null, onUpdate, onCache, onUncache) { } public Reference(string id, Func<string, T> getItem, Action<T> onCache = null, Action<T> onUncache = null) { _id = id; _getItem = getItem; _onCache = onCache; _onUncache = onUncache; } } }
mit
C#
ea2b79f3c1a74c7809603730c2e21031dae0d67c
Change mask variables to const values, remove from constructor
Figglewatts/LBD2OBJ
LBD2OBJLib/Types/FixedPoint.cs
LBD2OBJLib/Types/FixedPoint.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LBD2OBJLib.Types { class FixedPoint { public int IntegralPart { get; set; } public int DecimalPart { get; set; } const byte SIGN_MASK = 128; const byte INTEGRAL_MASK = 112; const byte MANTISSA_MASK = 15; public FixedPoint(byte[] data) { if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); } byte[] _data = new byte[2]; data.CopyTo(_data, 0); bool isNegative = (_data[0] & SIGN_MASK) == 128; int integralPart = (_data[0] & INTEGRAL_MASK) * (isNegative ? -1 : 1); int decimalPart = (_data[0] & MANTISSA_MASK); decimalPart <<= 8; decimalPart += data[1]; IntegralPart = integralPart; DecimalPart = decimalPart; } public override string ToString() { return IntegralPart + "." + DecimalPart; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LBD2OBJLib.Types { class FixedPoint { public int IntegralPart { get; set; } public int DecimalPart { get; set; } public FixedPoint(byte[] data) { if (data.Length != 2) { throw new ArgumentException("data must be 2 bytes", "data"); } byte[] _data = new byte[2]; data.CopyTo(_data, 0); var signMask = (byte)128; var integralMask = (byte)112; var firstPartOfDecimalMask = (byte)15; bool isNegative = (_data[0] & signMask) == 128; int integralPart = (_data[0] & integralMask) * (isNegative ? -1 : 1); int decimalPart = (_data[0] & firstPartOfDecimalMask); decimalPart <<= 8; decimalPart += data[1]; IntegralPart = integralPart; DecimalPart = decimalPart; } public override string ToString() { return IntegralPart + "." + DecimalPart; } } }
mit
C#
9e8a1cea150669e6bed23e966d5fa29a31d2b8d7
fix for AddExperience method
yungtechboy1/MiNET
src/MiNET/MiNET/ExperienceManager.cs
src/MiNET/MiNET/ExperienceManager.cs
using MiNET.Net; using MiNET.Worlds; using System; namespace MiNET { public class ExperienceManager { public Player Player { get; set; } public float ExperienceLevel { get; set; } = 0f; public float Experience { get; set; } = 0f; public ExperienceManager(Player player) { Player = player; } public void AddExperience(float xp, bool send = true) { var xpToNextLevel = GetXpToNextLevel(); if (xp + Experience < xpToNextLevel) { Experience += xp; } else { var expDiff = Experience + xp - xpToNextLevel; ExperienceLevel++; Experience = 0; AddExperience(expDiff, false); } if (send) { SendAttributes(); } } public void RemoveExperienceLevels(float levels) { var currentXp = CalculateXp(); ExperienceLevel = Experience - Math.Abs(levels); Experience = GetXpToNextLevel() * currentXp; } protected virtual float GetXpToNextLevel() { float xpToNextLevel = 0; if (ExperienceLevel >= 0 && ExperienceLevel <= 15) { xpToNextLevel = 2 * ExperienceLevel + 7; } else if (ExperienceLevel > 15 && ExperienceLevel <= 30) { xpToNextLevel = 5 * ExperienceLevel - 38; } else if (ExperienceLevel > 30) { xpToNextLevel = 9 * ExperienceLevel - 158; } return xpToNextLevel; } protected virtual float CalculateXp() { return Experience / GetXpToNextLevel(); } public virtual PlayerAttributes AddExperienceAttributes(PlayerAttributes attributes) { attributes["minecraft:player.experience"] = new PlayerAttribute { Name = "minecraft:player.experience", MinValue = 0, MaxValue = 1, Value = CalculateXp(), Default = 0, }; attributes["minecraft:player.level"] = new PlayerAttribute { Name = "minecraft:player.level", MinValue = 0, MaxValue = 24791, Value = ExperienceLevel, Default = 0, }; return attributes; } public virtual void SendAttributes() { var attributes = new PlayerAttributes(); attributes = AddExperienceAttributes(attributes); McpeUpdateAttributes attributesPackate = McpeUpdateAttributes.CreateObject(); attributesPackate.runtimeEntityId = EntityManager.EntityIdSelf; attributesPackate.attributes = attributes; Player.SendPacket(attributesPackate); } } }
using MiNET.Net; using MiNET.Worlds; using System; namespace MiNET { public class ExperienceManager { public Player Player { get; set; } public float ExperienceLevel { get; set; } = 0f; public float Experience { get; set; } = 0f; public ExperienceManager(Player player) { Player = player; } public void AddExperience(float xp, bool send = true) { var xpToNextLevel = GetXpToNextLevel(); if (xp + Experience < xpToNextLevel) { Experience += xp; } else { ExperienceLevel++; AddExperience(Experience + xp - xpToNextLevel, false); } if (send) { SendAttributes(); // Player.SendUpdateAttributes(); } } public void RemoveExperienceLevels(float levels) { var currentXp = CalculateXp(); ExperienceLevel = Experience - Math.Abs(levels); Experience = GetXpToNextLevel() * currentXp; } protected virtual float GetXpToNextLevel() { float xpToNextLevel = 0; if (ExperienceLevel >= 0 && ExperienceLevel <= 15) { xpToNextLevel = 2 * ExperienceLevel + 7; } else if (ExperienceLevel > 15 && ExperienceLevel <= 30) { xpToNextLevel = 5 * ExperienceLevel - 38; } else if (ExperienceLevel > 30) { xpToNextLevel = 9 * ExperienceLevel - 158; } return xpToNextLevel; } protected virtual float CalculateXp() { return Experience / GetXpToNextLevel(); } public virtual PlayerAttributes AddExperienceAttributes(PlayerAttributes attributes) { attributes["minecraft:player.experience"] = new PlayerAttribute { Name = "minecraft:player.experience", MinValue = 0, MaxValue = 1, Value = CalculateXp(), Default = 0, }; attributes["minecraft:player.level"] = new PlayerAttribute { Name = "minecraft:player.level", MinValue = 0, MaxValue = 24791, Value = ExperienceLevel, Default = 0, }; return attributes; } public virtual void SendAttributes() { var attributes = new PlayerAttributes(); attributes = AddExperienceAttributes(attributes); McpeUpdateAttributes attributesPackate = McpeUpdateAttributes.CreateObject(); attributesPackate.runtimeEntityId = EntityManager.EntityIdSelf; attributesPackate.attributes = attributes; Player.SendPacket(attributesPackate); } } }
mpl-2.0
C#
fd8319419f4957b6ec4088cfe31bf8515aa5e888
Add SDL support to SampleGame
peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
SampleGame.Desktop/Program.cs
SampleGame.Desktop/Program.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework; using osu.Framework.Platform; namespace SampleGame.Desktop { public static class Program { [STAThread] public static void Main(string[] args) { bool useSdl = args.Contains(@"--sdl"); using (GameHost host = Host.GetSuitableHost(@"sample-game", useSdl: useSdl)) using (Game game = new SampleGameGame()) host.Run(game); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Platform; using osu.Framework; namespace SampleGame.Desktop { public static class Program { [STAThread] public static void Main() { using (GameHost host = Host.GetSuitableHost(@"sample-game")) using (Game game = new SampleGameGame()) host.Run(game); } } }
mit
C#
cc43e076ffbaba5161923b32df47f33e760db544
use an xmlReader and xmlWriter instead of XDocument
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
NuCache/Rewriters/XmlRewriter.cs
NuCache/Rewriters/XmlRewriter.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace NuCache.Rewriters { public class XmlRewriter { private readonly UriRewriter _uriRewriter; public XmlRewriter(UriRewriter uriRewriter) { _uriRewriter = uriRewriter; } private void ProcessReplacement(XElement node, Func<string, Uri> transform) { if (node.Name.LocalName == "link" && node.Attribute("rel").Value == "next") { var attribute = node.Attribute("href"); attribute.SetValue(transform(attribute.Value)); } /* on FEED root. node .Attributes() .Where(a => a.Name.LocalName == "base") .ForEach(a => a.SetValue(transform(a.Value))); //root // .Attributes() // .Where(a => a.Name.LocalName == "base") // .ForEach(a => a.SetValue(transform(a.Value))); */ if (node.Name.LocalName == "entry") { node .Elements() .Where(e => e.Name.LocalName == "content") .Attributes("src") .ForEach(a => a.SetValue(transform(a.Value))); node .Elements() .Where(e => e.Name.LocalName == "id") .ForEach(e => e.SetValue(transform(e.Value))); } if (node.Name.LocalName == "id") { node.SetValue(transform(node.Value)); } } public virtual void Rewrite(Uri targetUri, Stream inputStream, Stream outputStream) { Func<String, Uri> transform = url => _uriRewriter.TransformHost(targetUri, new Uri(url)); using (var reader = XmlReader.Create(inputStream)) using (var writer = XmlWriter.Create(outputStream)) { writer.WriteStartDocument(); reader.MoveToContent(); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { var element = (XElement)XNode.ReadFrom(reader); ProcessReplacement(element, transform); element.WriteTo(writer); } } writer.WriteEndElement(); } //var doc = XDocument.Load(inputStream); //var root = doc.Root; //var ns = root.Name.Namespace; //root // .Elements(ns + "link") // .Where(e => e.Attribute("rel").Value == "next") // .Attributes("href") // .ForEach(a => a.SetValue(transform(a.Value))); //root // .Attributes() // .Where(a => a.Name.LocalName == "base") // .ForEach(a => a.SetValue(transform(a.Value))); //root // .Elements("id") // .ForEach(a => a.SetValue(transform(a.Value))); //var entries = root // .Elements(ns + "entry") // .ToList(); //entries // .Elements(ns + "content") // .Attributes("src") // .ForEach(a => a.SetValue(transform(a.Value))); //entries // .Elements(ns + "id") // .ForEach(a => a.SetValue(transform(a.Value))); //doc.Save(outputStream); } } }
using System; using System.IO; using System.Linq; using System.Xml.Linq; namespace NuCache.Rewriters { public class XmlRewriter { private readonly UriRewriter _uriRewriter; public XmlRewriter(UriRewriter uriRewriter) { _uriRewriter = uriRewriter; } public virtual void Rewrite(Uri targetUri, Stream inputStream, Stream outputStream) { var doc = XDocument.Load(inputStream); var root = doc.Root; var ns = root.Name.Namespace; Func<String, Uri> transform = url => _uriRewriter.TransformHost(targetUri, new Uri(url)); root .Elements(ns + "link") .Where(e => e.Attribute("rel").Value == "next") .Attributes("href") .ForEach(a => a.SetValue(transform(a.Value))); root .Attributes() .Where(a => a.Name.LocalName == "base") .ForEach(a => a.SetValue(transform(a.Value))); root .Elements("id") .ForEach(a => a.SetValue(transform(a.Value))); var entries = root .Elements(ns + "entry") .ToList(); entries .Elements(ns + "content") .Attributes("src") .ForEach(a => a.SetValue(transform(a.Value))); entries .Elements(ns + "id") .ForEach(a => a.SetValue(transform(a.Value))); doc.Save(outputStream); } } }
lgpl-2.1
C#
d8c1479f46e4bb01131d9b2a69e8e21e8bec13e8
Add support for displaying NiceHash profitability from WhatToMine.com
nwoolls/MultiMiner,nwoolls/MultiMiner
MultiMiner.WhatToMine/Extensions/CoinInformationExtensions.cs
MultiMiner.WhatToMine/Extensions/CoinInformationExtensions.cs
using MultiMiner.CoinApi.Data; using MultiMiner.Xgminer.Data; using System; using System.Linq; namespace MultiMiner.WhatToMine.Extensions { static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, Data.ApiCoinInformation apiCoinInformation) { coinInformation.Symbol = FixSymbolName(apiCoinInformation.Tag, apiCoinInformation.Algorithm); coinInformation.Algorithm = FixAlgorithmName(apiCoinInformation.Algorithm); coinInformation.CurrentBlocks = apiCoinInformation.Last_Block; coinInformation.Difficulty = apiCoinInformation.Difficulty; coinInformation.Reward = apiCoinInformation.Block_Reward; coinInformation.NetworkHashRate = apiCoinInformation.Nethash; coinInformation.Profitability = apiCoinInformation.Profitability; coinInformation.AdjustedProfitability = apiCoinInformation.Profitability; coinInformation.AverageProfitability = apiCoinInformation.Profitability24; coinInformation.NetworkHashRate = apiCoinInformation.Nethash; if (coinInformation.Symbol.Equals("BTC", StringComparison.OrdinalIgnoreCase)) coinInformation.Price = 1; else coinInformation.Price = apiCoinInformation.Exchange_Rate; } private static string FixSymbolName(string symbol, string algorithm) { string result = symbol; if ("NICEHASH".Equals(result)) { result = "NiceHash:" + algorithm.Replace(AlgorithmFullNames.SHA256, AlgorithmNames.SHA256); } return result; } private static string FixAlgorithmName(string algorithm) { string result = algorithm; if (algorithm.Equals(ApiContext.ScryptNFactor, StringComparison.OrdinalIgnoreCase)) { result = AlgorithmFullNames.ScryptN; } else { KnownAlgorithm knownAlgorithm = KnownAlgorithms.Algorithms.SingleOrDefault(a => a.Name.Equals(algorithm, StringComparison.OrdinalIgnoreCase)); if (knownAlgorithm != null) result = knownAlgorithm.FullName; } return result; } } }
using MultiMiner.CoinApi.Data; using MultiMiner.Xgminer.Data; using System; using System.Linq; namespace MultiMiner.WhatToMine.Extensions { static class CoinInformationExtensions { public static void PopulateFromJson(this CoinInformation coinInformation, Data.ApiCoinInformation apiCoinInformation) { coinInformation.Symbol = apiCoinInformation.Tag; coinInformation.Algorithm = FixAlgorithmName(apiCoinInformation.Algorithm); coinInformation.CurrentBlocks = apiCoinInformation.Last_Block; coinInformation.Difficulty = apiCoinInformation.Difficulty; coinInformation.Reward = apiCoinInformation.Block_Reward; coinInformation.NetworkHashRate = apiCoinInformation.Nethash; coinInformation.Profitability = apiCoinInformation.Profitability; coinInformation.AdjustedProfitability = apiCoinInformation.Profitability; coinInformation.AverageProfitability = apiCoinInformation.Profitability24; coinInformation.NetworkHashRate = apiCoinInformation.Nethash; if (coinInformation.Symbol.Equals("BTC", StringComparison.OrdinalIgnoreCase)) coinInformation.Price = 1; else coinInformation.Price = apiCoinInformation.Exchange_Rate; } private static string FixAlgorithmName(string algorithm) { string result = algorithm; if (algorithm.Equals(ApiContext.ScryptNFactor, StringComparison.OrdinalIgnoreCase)) result = AlgorithmFullNames.ScryptN; else { KnownAlgorithm knownAlgorithm = KnownAlgorithms.Algorithms.SingleOrDefault(a => a.Name.Equals(algorithm, StringComparison.OrdinalIgnoreCase)); if (knownAlgorithm != null) result = knownAlgorithm.FullName; } return result; } } }
mit
C#
07baeda87898657f050010d112aad60a47b37888
Hide irrelevant tabs when the Writing System is a voice one.
ermshiperete/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,JohnThomson/libpalaso,JohnThomson/libpalaso,darcywong00/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,mccarthyrb/libpalaso,chrisvire/libpalaso,darcywong00/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,marksvc/libpalaso,tombogle/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,gmartin7/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,hatton/libpalaso,tombogle/libpalaso,sillsdev/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,hatton/libpalaso,hatton/libpalaso,marksvc/libpalaso,hatton/libpalaso
PalasoUIWindowsForms/WritingSystems/WSPropertiesTabControl.cs
PalasoUIWindowsForms/WritingSystems/WSPropertiesTabControl.cs
using System; using System.Windows.Forms; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSPropertiesTabControl : UserControl { private WritingSystemSetupModel _model; public WSPropertiesTabControl() { InitializeComponent(); } public void BindToModel(WritingSystemSetupModel model) { if (_model != null) { _model.SelectionChanged -= ModelChanged; _model.CurrentItemUpdated -= ModelChanged; } _model = model; _identifiersControl.BindToModel(_model); _fontControl.BindToModel(_model); _keyboardControl.BindToModel(_model); _sortControl.BindToModel(_model); _spellingControl.BindToModel(_model); if (_model != null) { _model.SelectionChanged+= ModelChanged; _model.CurrentItemUpdated += ModelChanged; } this.Disposed += OnDisposed; } private void ModelChanged(object sender, EventArgs e) { if( !_model.CurrentIsVoice && _tabControl.Controls.Contains(_spellingPage)) { return;// don't mess if we really don't need a change } _tabControl.Controls.Clear(); this._tabControl.Controls.Add(this._identifiersPage); if( !_model.CurrentIsVoice) { this._tabControl.Controls.Add(this._spellingPage); this._tabControl.Controls.Add(this._fontsPage); this._tabControl.Controls.Add(this._keyboardsPage); this._tabControl.Controls.Add(this._sortingPage); } } void OnDisposed(object sender, EventArgs e) { if (_model != null) _model.SelectionChanged -= ModelChanged; } } }
using System.Windows.Forms; namespace Palaso.UI.WindowsForms.WritingSystems { public partial class WSPropertiesTabControl : UserControl { private WritingSystemSetupModel _model; public WSPropertiesTabControl() { InitializeComponent(); } public void BindToModel(WritingSystemSetupModel model) { _model = model; _identifiersControl.BindToModel(_model); _fontControl.BindToModel(_model); _keyboardControl.BindToModel(_model); _sortControl.BindToModel(_model); _spellingControl.BindToModel(_model); } } }
mit
C#
bc72532c5ec9c747caa42bd236bc8d80a6d6694f
Refactor Multiply Integers Operation to use GetValues and CloneWithValues
ajlopez/TensorSharp
Src/TensorSharp/Operations/MultiplyIntegerIntegerOperation.cs
Src/TensorSharp/Operations/MultiplyIntegerIntegerOperation.cs
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { int[] values1 = tensor1.GetValues(); int l = values1.Length; int value2 = tensor2.GetValue(); int[] newvalues = new int[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] * value2; return tensor1.CloneWithNewValues(newvalues); } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class MultiplyIntegerIntegerOperation : IBinaryOperation<int, int, int> { public Tensor<int> Evaluate(Tensor<int> tensor1, Tensor<int> tensor2) { Tensor<int> result = new Tensor<int>(); result.SetValue(tensor1.GetValue() * tensor2.GetValue()); return result; } } }
mit
C#
dcdb662b497af5c796e37152307202f70fd2f419
Change Statement constructors
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Statement.cs
using NBitcoin.Secp256k1; using System.Collections.Generic; using System.Linq; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { public class Statement { public Statement(GroupElement publicPoint, IEnumerable<GroupElement> generators) : this(ToTable(generators.Prepend(publicPoint))) { } public Statement(params GroupElement[] equation) : this(ToTable(equation)) { } public Statement(GroupElement[,] equations) { var terms = equations.GetLength(1); Guard.True(nameof(terms), terms >= 2, $"Invalid {nameof(terms)}. It needs to have at least one generator and one public point."); foreach (var generator in equations) { Guard.NotNull(nameof(generator), generator); } // make an equation out of each row taking the first element of each row as the public point var rows = Enumerable.Range(0, equations.GetLength(0)); var cols = Enumerable.Range(1, terms - 1); Equations = rows.Select(i => new Equation(equations[i, 0], new GroupElementVector(cols.Select(j => equations[i, j])))); } public IEnumerable<Equation> Equations { get; } public IEnumerable<GroupElement> PublicPoints => Equations.Select(x => x.PublicPoint); public IEnumerable<GroupElement> Generators => Equations.SelectMany(x => x.Generators); public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, ScalarVector responses) { // The responses matrix should match the generators in the equations and // there should be once nonce per equation. Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count()); return Equations.Zip(publicNonces, (equation, r) => equation.Verify(r, challenge, responses)).All(x => x); } // Helper function for constructor private static GroupElement[,] ToTable (IEnumerable<GroupElement> equation) { var table = new GroupElement[1, equation.Count()]; foreach (var (g, i) in equation.Select((x, i) => (x, i))) { table[0, i] = g; } return table; } } }
using NBitcoin.Secp256k1; using System.Collections.Generic; using System.Linq; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { public class Statement { public Statement(GroupElement[,] equations) { var terms = equations.GetLength(1); Guard.True(nameof(terms), terms >= 2, $"Invalid {nameof(terms)}. It needs to have at least one generator and one public point."); foreach (var generator in equations) { Guard.NotNull(nameof(generator), generator); } // make an equation out of each row taking the first element of each row as the public point var rows = Enumerable.Range(0, equations.GetLength(0)); var cols = Enumerable.Range(1, terms - 1); Equations = rows.Select(i => new Equation(equations[i, 0], new GroupElementVector(cols.Select(j => equations[i, j])))); } public IEnumerable<Equation> Equations { get; } public IEnumerable<GroupElement> PublicPoints => Equations.Select(x => x.PublicPoint); public IEnumerable<GroupElement> Generators => Equations.SelectMany(x => x.Generators); public bool CheckVerificationEquation(GroupElementVector publicNonces, Scalar challenge, ScalarVector responses) { // The responses matrix should match the generators in the equations and // there should be once nonce per equation. Guard.True(nameof(publicNonces), Equations.Count() == publicNonces.Count()); return Equations.Zip(publicNonces, (equation, r) => equation.Verify(r, challenge, responses)).All(x => x); } } }
mit
C#
8a4db8460de6e49bb4cb6ef29c18c04690d1d982
rename type parameters to make them more explicit
Recognos/Metrics.NET,alhardy/Metrics.NET,mnadel/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,MetaG8/Metrics.NET,etishor/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,cvent/Metrics.NET,etishor/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,ntent-ad/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET
Src/Metrics/Meta/MetricMeta.cs
Src/Metrics/Meta/MetricMeta.cs
 namespace Metrics.Meta { public abstract class MetricMeta<TMetric, TMetricValue> where TMetric : Metric<TMetricValue> where TMetricValue : struct { private readonly TMetric metric; protected MetricMeta(string name, TMetric metric, Unit unit) { this.metric = metric; this.Name = name; this.Unit = unit; } public string Name { get; private set; } public TMetricValue Value { get { return this.metric.Value; } } public Unit Unit { get; private set; } internal TMetric Metric() { return this.metric; } } }
 namespace Metrics.Meta { public abstract class MetricMeta<T, V> where T : Metric<V> where V : struct { private readonly T metric; protected MetricMeta(string name, T metric, Unit unit) { this.metric = metric; this.Name = name; this.Unit = unit; } public string Name { get; private set; } public V Value { get { return this.metric.Value; } } public Unit Unit { get; private set; } internal T Metric() { return this.metric; } } }
apache-2.0
C#
585cded973c0d4db57a1d0adcecb7f9d694a8fda
Remove sending big data test.
shiftkey/SignalR,shiftkey/SignalR
SignalR.Tests/ConnectionFacts.cs
SignalR.Tests/ConnectionFacts.cs
using System; using System.Linq; using System.Threading; using Moq; using SignalR.Client.Transports; using SignalR.Hosting.Memory; using Xunit; namespace SignalR.Client.Tests { public class ConnectionFacts { public class Start { [Fact] public void FailsIfProtocolVersionIsNull() { var connection = new Connection("http://test"); var transport = new Mock<IClientTransport>(); transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = null })); var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(InvalidOperationException), ex); Assert.Equal("Incompatible protocol version.", ex.Message); } } } }
using System; using System.Linq; using System.Threading; using Moq; using SignalR.Client.Transports; using SignalR.Hosting.Memory; using Xunit; namespace SignalR.Client.Tests { public class ConnectionFacts { public class Start { [Fact] public void FailsIfProtocolVersionIsNull() { var connection = new Connection("http://test"); var transport = new Mock<IClientTransport>(); transport.Setup(m => m.Negotiate(connection)).Returns(TaskAsyncHelper.FromResult(new NegotiationResponse { ProtocolVersion = null })); var aggEx = Assert.Throws<AggregateException>(() => connection.Start(transport.Object).Wait()); var ex = aggEx.Unwrap(); Assert.IsType(typeof(InvalidOperationException), ex); Assert.Equal("Incompatible protocol version.", ex.Message); } } public class Received { [Fact] public void SendingBigData() { var host = new MemoryHost(); host.MapConnection<SampleConnection>("/echo"); var connection = new Connection("http://foo/echo"); var wh = new ManualResetEventSlim(); var n = 0; var target = 20; connection.Received += data => { n++; if (n == target) { wh.Set(); } }; connection.Start(host).Wait(); var conn = host.ConnectionManager.GetConnection<SampleConnection>(); for (int i = 0; i < target; ++i) { var node = new BigData(); conn.Broadcast(node).Wait(); Thread.Sleep(1000); } Assert.True(wh.Wait(TimeSpan.FromMinutes(1)), "Timed out"); } public class BigData { public string[] Dummy { get { return Enumerable.Range(0, 1000).Select(x => new String('*', 500)).ToArray(); } } } public class SampleConnection : PersistentConnection { } } } }
mit
C#
c8b71ecdbc8ad0e1ea6d90a0b660ce7a9a429931
Add a help function
wrightg42/todo-list,It423/todo-list
Todo-List/Todo-List/Program.cs
Todo-List/Todo-List/Program.cs
// Program.cs // <copyright file="Program.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Todo_List { /// <summary> /// An application entry point for a console-based hand of Whist. /// </summary> public class Program { /// <summary> /// The main entry point for the program. /// </summary> /// <param name="args"> Any arguments the program is run with. </param> public static void Main(string[] args) { Help(); Console.ReadKey(); } /// <summary> /// Displays help information about the program. /// </summary> public static void Help() { Console.WriteLine("Welcome to George Wright's todo list program!"); Console.WriteLine("To add a note use:\n\t/a [Name] [Category1, Catergory2...]\n"); Console.WriteLine("To view notes use:\n\t/v [Category1, Catergory2...]\n"); Console.WriteLine("To remove a note use:\n\t/r [Name]\n"); Console.WriteLine("To edit a note use:\n\t/e [Name] [New name] [New Category1, New Catergory2...]\n"); Console.WriteLine("Categories are not allways needed in the command. When adding/editing a note, it will add to the uncategorised list."); Console.WriteLine("When viewing a note it will display all categories.\n"); Console.WriteLine("To display this help again use:\n\t/h\n\n"); } } }
// Program.cs // <copyright file="Program.cs"> This code is protected under the MIT License. </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Todo_List { /// <summary> /// An application entry point for a console-based hand of Whist. /// </summary> public class Program { /// <summary> /// The main entry point for the program. /// </summary> /// <param name="args"> Any arguments the program is run with. </param> public static void Main(string[] args) { } } }
mit
C#
8118aba6a2c9befd85b36da4d9f6be7c4df96aa9
Update Track tests to use carrier and tracking number constants
goshippo/shippo-csharp-client
ShippoTesting/TrackTest.cs
ShippoTesting/TrackTest.cs
using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Shippo; namespace ShippoTesting { [TestFixture ()] public class TrackTest : ShippoTest { private static readonly String TRACKING_NO = "9205590164917337534322"; private static readonly String CARRIER = "usps"; [Test ()] public void TestValidGetStatus () { Track track = getAPIResource ().RetrieveTracking (CARRIER, TRACKING_NO); Assert.AreEqual (TRACKING_NO, track.TrackingNumber); Assert.IsNotNull (track.TrackingStatus); Assert.IsNotNull (track.TrackingHistory); } [Test ()] [ExpectedException (typeof (ShippoException))] public void TestInvalidGetStatus () { getAPIResource ().RetrieveTracking (CARRIER, "INVALID_ID"); } [Test ()] public void TestValidRegisterWebhook () { Track track = getAPIResource ().RetrieveTracking (CARRIER, TRACKING_NO); Hashtable parameters = new Hashtable (); parameters.Add ("carrier", CARRIER); parameters.Add ("tracking_number", track.TrackingNumber); Track register = getAPIResource ().RegisterTrackingWebhook (parameters); Assert.IsNotNull (register.TrackingNumber); Assert.IsNotNull (register.TrackingHistory); } [Test ()] [ExpectedException (typeof (ShippoException))] public void TestInvalidRegisterWebhook () { Hashtable parameters = new Hashtable (); parameters.Add ("carrier", CARRIER); parameters.Add ("tracking_number", "INVALID_ID"); getAPIResource ().RegisterTrackingWebhook (parameters); } } }
using System; using System.Collections; using System.Collections.Generic; using NUnit.Framework; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Shippo; namespace ShippoTesting { [TestFixture ()] public class TrackTest : ShippoTest { private const String TRACKING_NO = "9205590164917337534322"; private const String CARRIER = "usps"; [Test ()] public void TestValidGetStatus () { Track track = getAPIResource ().RetrieveTracking (CARRIER, TRACKING_NO); Assert.AreEqual (TRACKING_NO, track.TrackingNumber.ToString()); Assert.IsNotNull (track.TrackingStatus); Assert.IsNotNull (track.TrackingHistory); } [Test ()] [ExpectedException (typeof (ShippoException))] public void TestInvalidGetStatus () { getAPIResource ().RetrieveTracking (CARRIER, "INVALID_ID"); } [Test ()] public void TestValidRegisterWebhook () { Shipment shipment = ShipmentTest.getDefaultObject (); Track track = getAPIResource ().RetrieveTracking (CARRIER, shipment.ObjectId); Assert.IsNotNull (track.TrackingNumber); Assert.IsNotNull (track.TrackingHistory); Hashtable parameters = new Hashtable (); parameters.Add ("carrier", CARRIER); parameters.Add ("tracking_number", track.TrackingNumber); Track register = getAPIResource ().RegisterTrackingWebhook (parameters); Assert.IsNotNull (register.TrackingNumber); Assert.IsNotNull (register.TrackingHistory); } [Test ()] [ExpectedException (typeof (ShippoException))] public void TestInvalidRegisterWebhook () { Hashtable parameters = new Hashtable (); parameters.Add ("carrier", CARRIER); parameters.Add ("tracking_number", "INVALID_ID"); getAPIResource ().RegisterTrackingWebhook (parameters); } } }
apache-2.0
C#
57824b68472de45e7276ab1151152596d76c4e28
Update IUserMessage.cs
LassieME/Discord.Net,RogueException/Discord.Net,Confruggy/Discord.Net,AntiTcb/Discord.Net
src/Discord.Net.Core/Entities/Messages/IUserMessage.cs
src/Discord.Net.Core/Entities/Messages/IUserMessage.cs
using Discord.API.Rest; using System; using System.Threading.Tasks; namespace Discord { public interface IUserMessage : IMessage { /// <summary> Modifies this message. </summary> Task ModifyAsync(Action<ModifyMessageParams> func, RequestOptions options = null); /// <summary> Adds this message to its channel's pinned messages. </summary> Task PinAsync(RequestOptions options = null); /// <summary> Removes this message from its channel's pinned messages. </summary> Task UnpinAsync(RequestOptions options = null); /// <summary> Transforms this message's text into a human readable form by resolving its tags. </summary> string Resolve( TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name); } }
using Discord.API.Rest; using System; using System.Threading.Tasks; namespace Discord { public interface IUserMessage : IMessage, IDeletable { /// <summary> Modifies this message. </summary> Task ModifyAsync(Action<ModifyMessageParams> func, RequestOptions options = null); /// <summary> Adds this message to its channel's pinned messages. </summary> Task PinAsync(RequestOptions options = null); /// <summary> Removes this message from its channel's pinned messages. </summary> Task UnpinAsync(RequestOptions options = null); /// <summary> Transforms this message's text into a human readable form by resolving its tags. </summary> string Resolve( TagHandling userHandling = TagHandling.Name, TagHandling channelHandling = TagHandling.Name, TagHandling roleHandling = TagHandling.Name, TagHandling everyoneHandling = TagHandling.Ignore, TagHandling emojiHandling = TagHandling.Name); } }
mit
C#
b3b08e1130a6ef444a63d76b59e5a83b95c98daf
Fix return value
nikeee/HolzShots
src/HolzShots.Core/Composition/PluginUploaderSource.cs
src/HolzShots.Core/Composition/PluginUploaderSource.cs
using HolzShots.Net; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace HolzShots.Composition { public class PluginUploaderSource : PluginManager<Uploader>, IUploaderSource { public PluginUploaderSource(string pluginDirectory) : base(pluginDirectory) { } public (IPluginMetadata metadata, Uploader uploader)? GetUploaderByName(string name) { Debug.Assert(!string.IsNullOrEmpty(name)); Debug.Assert(Loaded); var pls = Plugins; Debug.Assert(pls != null); return pls .Where(p => CustomUploaderSource.HasEqualUploaderName(p.metadata.Name, name)) .Select(p => ((IPluginMetadata metadata, Uploader uploader)?)(new PluginMetadata(p.metadata), p.instance) /* cast is needed to make FirstOrDefault produce null instead of (null, null) */) .FirstOrDefault(); } public IReadOnlyList<string> GetUploaderNames() { var meta = GetMetadata(); Debug.Assert(meta != null); return meta.Select(i => i.Name).ToList(); } } }
using HolzShots.Net; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; namespace HolzShots.Composition { public class PluginUploaderSource : PluginManager<Uploader>, IUploaderSource { public PluginUploaderSource(string pluginDirectory) : base(pluginDirectory) { } public (IPluginMetadata metadata, Uploader uploader)? GetUploaderByName(string name) { Debug.Assert(!string.IsNullOrEmpty(name)); Debug.Assert(Loaded); var pls = Plugins; Debug.Assert(pls != null); return pls .Where(p => CustomUploaderSource.HasEqualUploaderName(p.metadata.Name, name)) .Select(p => (new PluginMetadata(p.metadata), p.instance)) .FirstOrDefault(); } public IReadOnlyList<string> GetUploaderNames() { var meta = GetMetadata(); Debug.Assert(meta != null); return meta.Select(i => i.Name).ToList(); } } }
agpl-3.0
C#
3fa153c94c729bf4a8231f36957658dde0ce7afe
Remove commented code and unused usings
JasperFx/jasper,JasperFx/jasper,JasperFx/jasper
src/Jasper.ConfluentKafka/Internal/KafkaTopicRouter.cs
src/Jasper.ConfluentKafka/Internal/KafkaTopicRouter.cs
using System; using Baseline; using Jasper.Configuration; using Jasper.Runtime.Routing; namespace Jasper.ConfluentKafka.Internal { public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration> { public override Uri BuildUriForTopic(string topicName) { var endpoint = new KafkaEndpoint { IsDurable = true, TopicName = topicName }; return endpoint.Uri; } public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName, IEndpoints endpoints) { var uri = BuildUriForTopic(topicName); var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri); return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint); } } }
using System; using System.Collections.Generic; using Baseline; using Confluent.Kafka; using Jasper.Configuration; using Jasper.Runtime.Routing; namespace Jasper.ConfluentKafka.Internal { public class KafkaTopicRouter : TopicRouter<KafkaSubscriberConfiguration> { //Dictionary<Uri, ProducerConfig> producerConfigs; //public KafkaTopicRouter(Dictionary<Uri, ProducerConfig> producerConfigs) //{ //} public override Uri BuildUriForTopic(string topicName) { var endpoint = new KafkaEndpoint { IsDurable = true, TopicName = topicName }; return endpoint.Uri; } public override KafkaSubscriberConfiguration FindConfigurationForTopic(string topicName, IEndpoints endpoints) { var uri = BuildUriForTopic(topicName); var endpoint = endpoints.As<TransportCollection>().GetOrCreateEndpoint(uri); return new KafkaSubscriberConfiguration((KafkaEndpoint) endpoint); } } }
mit
C#
de512f78b32927a06227240ddeabcf7760b85fbf
update document link
Microsoft/dotnet-apiport,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport,Microsoft/dotnet-apiport,mjrousos/dotnet-apiport
src/lib/Microsoft.Fx.Portability/DocumentationLinks.cs
src/lib/Microsoft.Fx.Portability/DocumentationLinks.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; namespace Microsoft.Fx.Portability { public static class DocumentationLinks { public static readonly Uri PrivacyPolicy = new Uri("https://privacy.microsoft.com/en-us/privacystatement"); public static readonly Uri About = new Uri("https://aka.ms/dotnet-portabilityanalyzer"); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Microsoft.Fx.Portability { public static class DocumentationLinks { public static readonly Uri PrivacyPolicy = new Uri("https://privacy.microsoft.com/en-us/privacystatement"); public static readonly Uri About = new Uri("https://go.microsoft.com/fwlink/?LinkId=506955"); } }
mit
C#
429016ac43223e76a7971075a6f0df9684dd3530
Fix circular dependency
agc93/Cake.BuildSystems.Module,agc93/Cake.BuildSystems.Module
src/Cake.TFBuild.Module/TFBuildLog.cs
src/Cake.TFBuild.Module/TFBuildLog.cs
using System; using System.Reflection; using Cake.Common.Build; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Diagnostics; namespace Cake.TFBuild.Module { public class TFBuildLog : ICakeLog { public TFBuildLog(IConsole console, Verbosity verbosity = Verbosity.Normal) { _cakeLogImplementation = new CakeBuildLog(console, verbosity); } private readonly ICakeLog _cakeLogImplementation; public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("TF_BUILD"))) { switch (level) { case LogLevel.Fatal: case LogLevel.Error: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##vso[task.logissue type=error;]{0}", string.Format(format, args)); break; case LogLevel.Warning: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##vso[task.logissue type=warning;]{0}", string.Format(format, args)); break; case LogLevel.Information: case LogLevel.Verbose: case LogLevel.Debug: break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } } _cakeLogImplementation.Write(verbosity, level, format, args); } public Verbosity Verbosity { get { return _cakeLogImplementation.Verbosity; } set { _cakeLogImplementation.Verbosity = value; } } } }
using System; using System.Reflection; using Cake.Common.Build; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Diagnostics; namespace Cake.TFBuild.Module { public class TFBuildLog : ICakeLog { public TFBuildLog(IConsole console, ICakeContext context, Verbosity verbosity = Verbosity.Normal) { _cakeLogImplementation = new CakeBuildLog(console, verbosity); _context = context; } private readonly ICakeLog _cakeLogImplementation; private readonly ICakeContext _context; public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { var b = _context.BuildSystem(); if (b.IsRunningOnVSTS || b.IsRunningOnTFS) { switch (level) { case LogLevel.Fatal: case LogLevel.Error: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##vso[task.logissue type=error;]{0}", string.Format(format, args)); break; case LogLevel.Warning: _cakeLogImplementation.Write(Verbosity.Quiet, LogLevel.Information, "##vso[task.logissue type=warning;]{0}", string.Format(format, args)); break; case LogLevel.Information: case LogLevel.Verbose: case LogLevel.Debug: break; default: throw new ArgumentOutOfRangeException(nameof(level), level, null); } } _cakeLogImplementation.Write(verbosity, level, format, args); } public Verbosity Verbosity { get { return _cakeLogImplementation.Verbosity; } set { _cakeLogImplementation.Verbosity = value; } } } }
mit
C#
e03212134d8f0886b8ecc436029037f5e278495a
use id + key in http auth
x4d3/maestrano-dotnet,maestrano/maestrano-dotnet,prosser/maestrano-dotnet,maestrano/maestrano-dotnet,alachaum/maestrano-dotnet,alachaum/maestrano-dotnet,x4d3/maestrano-dotnet
src/Maestrano/Api/MnoAuthenticator.cs
src/Maestrano/Api/MnoAuthenticator.cs
using System; using System.Linq; using RestSharp; using System.Net; namespace Maestrano.Api { public class MnoAuthenticator : IAuthenticator { private readonly string _apiKey; private readonly string _apiId; public MnoAuthenticator(string apiId, string apiKey) { _apiId = apiId; _apiKey = apiKey; } public void Authenticate(IRestClient client, IRestRequest request) { request.Credentials = new NetworkCredential(_apiId,_apiKey); } } }
using System; using System.Linq; using RestSharp; using System.Net; namespace Maestrano.Api { public class MnoAuthenticator : IAuthenticator { private readonly string _apiKey; public MnoAuthenticator(string apiKey) { _apiKey = apiKey; } public void Authenticate(IRestClient client, IRestRequest request) { request.Credentials = new NetworkCredential(_apiKey, ""); } } }
mit
C#
7888382751584c4ba933dfd517feb78d02877e68
Fix NotifyDone override in MinigameDemo
haavardlian/tdt4240
tdt4240/tdt4240/Minigames/MinigameDemo/MinigameDemo.cs
tdt4240/tdt4240/Minigames/MinigameDemo/MinigameDemo.cs
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tdt4240.Minigames.MinigameDemo { class MinigameDemo : MiniGame { private int numberOfPlayers; private SpriteFont font; private Vector2[] textPosition = new Vector2[4]; public MinigameDemo(Board board) : base(board) { this.supportedPlayers = SupportedPlayers.All; this.numberOfPlayers = PlayerManager.Instance.NumberOfPlayers; //DO stuff based on the amount of players playing } public override void Activate(bool instancePreserved) { base.Activate(instancePreserved); if (!instancePreserved) { font = content.Load<SpriteFont>("fonts/menufont"); } } public override void HandleInput(GameTime gameTime, InputState input) { foreach(Player player in PlayerManager.Instance.Players) { textPosition[(int)player.playerIndex] += player.Input.GetThumbstickVector(); if (player.Input.IsButtonPressed(GameButtons.X)) { //DO stuff } } } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); } public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); foreach (Player player in PlayerManager.Instance.Players) { spriteBatch.DrawString(font, player.TestString, textPosition[(int)player.playerIndex], player.color); } spriteBatch.End(); } public override void NotifyDone(PlayerIndex winningPlayerIndex) { base.NotifyDone(winningPlayerIndex); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tdt4240.Minigames.MinigameDemo { class MinigameDemo : MiniGame { private int numberOfPlayers; private SpriteFont font; private Vector2[] textPosition = new Vector2[4]; public MinigameDemo(Board board) : base(board) { this.supportedPlayers = SupportedPlayers.All; this.numberOfPlayers = PlayerManager.Instance.NumberOfPlayers; //DO stuff based on the amount of players playing } public override void Activate(bool instancePreserved) { base.Activate(instancePreserved); if (!instancePreserved) { font = content.Load<SpriteFont>("fonts/menufont"); } } public override void HandleInput(GameTime gameTime, InputState input) { foreach(Player player in PlayerManager.Instance.Players) { textPosition[(int)player.playerIndex] += player.Input.GetThumbstickVector(); if (player.Input.IsButtonPressed(GameButtons.X)) { //DO stuff } } } public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); } public override void Draw(GameTime gameTime) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); foreach (Player player in PlayerManager.Instance.Players) { spriteBatch.DrawString(font, player.TestString, textPosition[(int)player.playerIndex], player.color); } spriteBatch.End(); } public override void NotifyDone(int winnerIndex) { base.NotifyDone(winnerIndex); } } }
apache-2.0
C#
cecd990db5b223a0907e8e348b43cee6b2a105f5
fix tests
assaframan/MoviesRestForAppHarbor,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,assaframan/MoviesRestForAppHarbor,zhaokunfay/ServiceStack.Examples
tests/ServiceStack.Examples.Tests/StoreNewUserTests.cs
tests/ServiceStack.Examples.Tests/StoreNewUserTests.cs
using NUnit.Framework; using ServiceStack.Examples.ServiceInterface; using ServiceStack.Examples.ServiceModel.Operations; using ServiceStack.Examples.ServiceModel.Types; using ServiceStack.OrmLite; namespace ServiceStack.Examples.Tests { [TestFixture] public class StoreNewUserTests : TestHostBase { readonly StoreNewUser request = new StoreNewUser { UserName = "Test", Email = "[email protected]", Password = "password" }; [Test] public void StoreNewUser_Test() { using (var dbConn = ConnectionFactory.OpenDbConnection()) using (var dbCmd = dbConn.CreateCommand()) { var service = new StoreNewUserService { ConnectionFactory = ConnectionFactory }; var newUserRequest = new StoreNewUser { UserName = "StoreNewUser_Test", Email = "[email protected]", Password = "password" }; var response = (StoreNewUserResponse)service.Execute(newUserRequest); var storedUser = dbCmd.First<User>("UserName = {0}", newUserRequest.UserName); Assert.That(storedUser.Id, Is.EqualTo(response.UserId)); Assert.That(storedUser.Email, Is.EqualTo(newUserRequest.Email)); Assert.That(storedUser.Password, Is.EqualTo(newUserRequest.Password)); } } [Test] public void Existing_user_returns_error_response() { using (var dbConn = ConnectionFactory.OpenDbConnection()) using (var dbCmd = dbConn.CreateCommand()) { dbCmd.Insert(new User { UserName = request.UserName }); var service = new StoreNewUserService { ConnectionFactory = ConnectionFactory }; var response = (StoreNewUserResponse)service.Execute(request); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("UserNameMustBeUnique")); } } } }
using NUnit.Framework; using ServiceStack.Examples.ServiceInterface; using ServiceStack.Examples.ServiceModel.Operations; using ServiceStack.Examples.ServiceModel.Types; using ServiceStack.OrmLite; namespace ServiceStack.Examples.Tests { [TestFixture] public class StoreNewUserTests : TestHostBase { readonly StoreNewUser request = new StoreNewUser { UserName = "Test", Email = "[email protected]", Password = "password" }; [Test] public void StoreNewUser_Test() { using (var dbConn = ConnectionFactory.OpenDbConnection()) using (var dbCmd = dbConn.CreateCommand()) { var service = new StoreNewUserService { ConnectionFactory = ConnectionFactory }; var response = (StoreNewUserResponse)service.Execute(request); Assert.That(response.UserId, Is.EqualTo(1)); var storedUser = dbCmd.First<User>("UserName = {0}", request.UserName); Assert.That(storedUser.Email, Is.EqualTo(request.Email)); Assert.That(storedUser.Password, Is.EqualTo(request.Password)); } } [Test] public void Existing_user_returns_error_response() { using (var dbConn = ConnectionFactory.OpenDbConnection()) using (var dbCmd = dbConn.CreateCommand()) { dbCmd.Insert(new User { UserName = request.UserName }); var service = new StoreNewUserService { ConnectionFactory = ConnectionFactory }; var response = (StoreNewUserResponse)service.Execute(request); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo("UserNameMustBeUnique")); } } } }
bsd-3-clause
C#
19ec841d463655d386b891c96a3461eda9ee6c55
Bump version to 0.30.8
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.8"; } }
#pragma warning disable 436 using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017-2018")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("TaskSystemIntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.30.7"; } }
mit
C#
0e976cf64d6af26eae80dd99ddf384f4069d0f4a
Add StorageLocations for Outlining and Structure-Guide options.
physhi/roslyn,a-ctor/roslyn,zooba/roslyn,genlu/roslyn,xoofx/roslyn,MichalStrehovsky/roslyn,mattscheffer/roslyn,kelltrick/roslyn,mgoertz-msft/roslyn,bbarry/roslyn,mattscheffer/roslyn,AmadeusW/roslyn,CaptainHayashi/roslyn,KirillOsenkov/roslyn,lorcanmooney/roslyn,davkean/roslyn,TyOverby/roslyn,AlekseyTs/roslyn,dotnet/roslyn,akrisiun/roslyn,yeaicc/roslyn,agocke/roslyn,panopticoncentral/roslyn,xasx/roslyn,dotnet/roslyn,kelltrick/roslyn,cston/roslyn,robinsedlaczek/roslyn,heejaechang/roslyn,mmitche/roslyn,sharwell/roslyn,CaptainHayashi/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jeffanders/roslyn,cston/roslyn,aelij/roslyn,lorcanmooney/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,CaptainHayashi/roslyn,bartdesmet/roslyn,sharwell/roslyn,jkotas/roslyn,kelltrick/roslyn,khyperia/roslyn,amcasey/roslyn,gafter/roslyn,orthoxerox/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,Hosch250/roslyn,CyrusNajmabadi/roslyn,jamesqo/roslyn,pdelvo/roslyn,mmitche/roslyn,Giftednewt/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,xoofx/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,akrisiun/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,jamesqo/roslyn,Hosch250/roslyn,AArnott/roslyn,jeffanders/roslyn,dpoeschl/roslyn,jkotas/roslyn,dpoeschl/roslyn,mattwar/roslyn,MattWindsor91/roslyn,bbarry/roslyn,eriawan/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,Giftednewt/roslyn,nguerrera/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,davkean/roslyn,stephentoub/roslyn,bkoelman/roslyn,jkotas/roslyn,ErikSchierboom/roslyn,tvand7093/roslyn,brettfo/roslyn,reaction1989/roslyn,AArnott/roslyn,VSadov/roslyn,lorcanmooney/roslyn,srivatsn/roslyn,srivatsn/roslyn,bbarry/roslyn,khyperia/roslyn,tmat/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,weltkante/roslyn,KevinRansom/roslyn,tmat/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,tmeschter/roslyn,KevinRansom/roslyn,a-ctor/roslyn,eriawan/roslyn,tvand7093/roslyn,OmarTawfik/roslyn,AmadeusW/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,mattwar/roslyn,genlu/roslyn,xoofx/roslyn,tmeschter/roslyn,akrisiun/roslyn,xasx/roslyn,panopticoncentral/roslyn,yeaicc/roslyn,yeaicc/roslyn,mavasani/roslyn,agocke/roslyn,brettfo/roslyn,DustinCampbell/roslyn,paulvanbrenk/roslyn,paulvanbrenk/roslyn,reaction1989/roslyn,jcouv/roslyn,zooba/roslyn,abock/roslyn,MichalStrehovsky/roslyn,srivatsn/roslyn,Giftednewt/roslyn,heejaechang/roslyn,mmitche/roslyn,swaroop-sridhar/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,tmeschter/roslyn,OmarTawfik/roslyn,jmarolf/roslyn,abock/roslyn,stephentoub/roslyn,abock/roslyn,OmarTawfik/roslyn,davkean/roslyn,Hosch250/roslyn,paulvanbrenk/roslyn,AnthonyDGreen/roslyn,DustinCampbell/roslyn,bkoelman/roslyn,robinsedlaczek/roslyn,mavasani/roslyn,jcouv/roslyn,VSadov/roslyn,dotnet/roslyn,orthoxerox/roslyn,tannergooding/roslyn,pdelvo/roslyn,AnthonyDGreen/roslyn,mgoertz-msft/roslyn,gafter/roslyn,drognanar/roslyn,amcasey/roslyn,khyperia/roslyn,wvdd007/roslyn,amcasey/roslyn,jmarolf/roslyn,zooba/roslyn,gafter/roslyn,bkoelman/roslyn,diryboy/roslyn,bartdesmet/roslyn,a-ctor/roslyn,xasx/roslyn,drognanar/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,aelij/roslyn,TyOverby/roslyn,aelij/roslyn,wvdd007/roslyn,KevinRansom/roslyn,agocke/roslyn,MattWindsor91/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,genlu/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,dpoeschl/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,drognanar/roslyn,jeffanders/roslyn,physhi/roslyn,robinsedlaczek/roslyn,VSadov/roslyn,mattscheffer/roslyn,stephentoub/roslyn,physhi/roslyn,jamesqo/roslyn,nguerrera/roslyn,DustinCampbell/roslyn,diryboy/roslyn,eriawan/roslyn,pdelvo/roslyn,bartdesmet/roslyn,orthoxerox/roslyn,mattwar/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,AArnott/roslyn
src/Features/Core/Portable/Structure/BlockStructureOptions.cs
src/Features/Core/Portable/Structure/BlockStructureOptions.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 Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Structure { internal static class BlockStructureOptions { public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForDeclarationLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCodeLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowBlockStructureGuidesForCodeLevelConstructs)}")); public static readonly PerLanguageOption<bool> ShowOutliningForCommentsAndPreprocessorRegions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForCommentsAndPreprocessorRegions), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCommentsAndPreprocessorRegions)}")); public static readonly PerLanguageOption<bool> ShowOutliningForDeclarationLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForDeclarationLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForDeclarationLevelConstructs)}")); public static readonly PerLanguageOption<bool> ShowOutliningForCodeLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForCodeLevelConstructs), defaultValue: true, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(ShowOutliningForCodeLevelConstructs)}")); public static readonly PerLanguageOption<bool> CollapseRegionsWhenCollapsingToDefinitions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(CollapseRegionsWhenCollapsingToDefinitions), defaultValue: false, storageLocations: new RoamingProfileStorageLocation($"TextEditor.%LANGUAGE%.Specific.{nameof(CollapseRegionsWhenCollapsingToDefinitions)}")); } }
// 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 Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.Structure { internal static class BlockStructureOptions { public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCommentsAndPreprocessorRegions), defaultValue: false); public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForDeclarationLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForDeclarationLevelConstructs), defaultValue: true); public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCodeLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowBlockStructureGuidesForCodeLevelConstructs), defaultValue: true); public static readonly PerLanguageOption<bool> ShowOutliningForCommentsAndPreprocessorRegions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForCommentsAndPreprocessorRegions), defaultValue: true); public static readonly PerLanguageOption<bool> ShowOutliningForDeclarationLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForDeclarationLevelConstructs), defaultValue: true); public static readonly PerLanguageOption<bool> ShowOutliningForCodeLevelConstructs = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(ShowOutliningForCodeLevelConstructs), defaultValue: true); public static readonly PerLanguageOption<bool> CollapseRegionsWhenCollapsingToDefinitions = new PerLanguageOption<bool>( nameof(BlockStructureOptions), nameof(CollapseRegionsWhenCollapsingToDefinitions), defaultValue: false); } }
apache-2.0
C#
433909078e6315aa9328d0313670f7ec694f68ea
Improve error message when coverage is not found
lucaslorentz/minicover,lucaslorentz/minicover,lucaslorentz/minicover
src/MiniCover/CommandLine/Options/CoverageLoadedFileOption.cs
src/MiniCover/CommandLine/Options/CoverageLoadedFileOption.cs
using System.IO; using MiniCover.Exceptions; using MiniCover.Model; using Newtonsoft.Json; namespace MiniCover.CommandLine.Options { class CoverageLoadedFileOption : CoverageFileOption { public InstrumentationResult Result { get; private set; } protected override FileInfo PrepareValue(string value) { var fileInfo = base.PrepareValue(value); if (!fileInfo.Exists) throw new ValidationException($"Coverage file does not exist '{fileInfo.FullName}'"); var coverageFileString = File.ReadAllText(fileInfo.FullName); Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString); return fileInfo; } } }
using System.IO; using MiniCover.Model; using Newtonsoft.Json; namespace MiniCover.CommandLine.Options { class CoverageLoadedFileOption : CoverageFileOption { public InstrumentationResult Result { get; private set; } protected override FileInfo PrepareValue(string value) { var fileInfo = base.PrepareValue(value); if (!fileInfo.Exists) throw new FileNotFoundException($"Coverage file does not exist '{fileInfo.FullName}'"); var coverageFileString = File.ReadAllText(fileInfo.FullName); Result = JsonConvert.DeserializeObject<InstrumentationResult>(coverageFileString); return fileInfo; } } }
mit
C#
e05d9184bd44952881498934122a7ec4e43405a8
Fix and fully implement paging of enqueued job ids
dersia/Hangfire.Azure.ServiceBusQueue,barclayadam/Hangfire.Azure.ServiceBusQueue,HangfireIO/Hangfire.Azure.ServiceBusQueue
HangFire.Azure.ServiceBusQueue/ServiceBusQueueMonitoringApi.cs
HangFire.Azure.ServiceBusQueue/ServiceBusQueueMonitoringApi.cs
using System; using System.Collections.Generic; using System.Linq; using Hangfire.SqlServer; namespace Hangfire.Azure.ServiceBusQueue { internal class ServiceBusQueueMonitoringApi : IPersistentJobQueueMonitoringApi { private readonly ServiceBusManager _manager; private readonly string[] _queues; public ServiceBusQueueMonitoringApi(ServiceBusManager manager, string[] queues) { if (manager == null) throw new ArgumentNullException("manager"); if (queues == null) throw new ArgumentNullException("queues"); _manager = manager; _queues = queues; } public IEnumerable<string> GetQueues() { return _queues; } public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage) { var client = _manager.GetClient(queue); var jobIds = new List<int>(); // We have to overfetch to retrieve enough messages for paging. // e.g. @from = 10 and page size = 20 we need 30 messages from the start var messages = client.PeekBatch(0, @from + perPage).ToArray(); // We could use LINQ here but to avoid creating lots of garbage lists // through .Skip / .ToList etc. use a simple loop. for (var i = 0; i < messages.Length; i++) { var msg = messages[i]; // Only include the job id once we have skipped past the @from // number if (i >= @from) { jobIds.Add(int.Parse(msg.GetBody<string>())); } msg.Dispose(); } return jobIds; } public IEnumerable<int> GetFetchedJobIds(string queue, int @from, int perPage) { return Enumerable.Empty<int>(); } public EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue) { var queueDescriptor = _manager.GetDescription(queue); return new EnqueuedAndFetchedCountDto { EnqueuedCount = (int) queueDescriptor.MessageCount, FetchedCount = null }; } } }
using System; using System.Collections.Generic; using System.Linq; using Hangfire.SqlServer; namespace Hangfire.Azure.ServiceBusQueue { internal class ServiceBusQueueMonitoringApi : IPersistentJobQueueMonitoringApi { private readonly ServiceBusManager _manager; private readonly string[] _queues; public ServiceBusQueueMonitoringApi(ServiceBusManager manager, string[] queues) { if (manager == null) throw new ArgumentNullException("manager"); if (queues == null) throw new ArgumentNullException("queues"); _manager = manager; _queues = queues; } public IEnumerable<string> GetQueues() { return _queues; } public IEnumerable<int> GetEnqueuedJobIds(string queue, int @from, int perPage) { var client = _manager.GetClient(queue); var messages = client.PeekBatch(perPage).ToArray(); var jobIds = messages.Select(x => int.Parse(x.GetBody<string>())).ToList(); foreach (var message in messages) { message.Dispose(); } return jobIds; } public IEnumerable<int> GetFetchedJobIds(string queue, int @from, int perPage) { return Enumerable.Empty<int>(); } public EnqueuedAndFetchedCountDto GetEnqueuedAndFetchedCount(string queue) { var queueDescriptor = _manager.GetDescription(queue); return new EnqueuedAndFetchedCountDto { EnqueuedCount = (int) queueDescriptor.MessageCount, FetchedCount = null }; } } }
mit
C#
075253940b19314d7307e72f58621c91bc548f0f
test tweak
mprzybylak/CSharpConventionTests
minefieldtests/PackagesConfigAnalyse.cs
minefieldtests/PackagesConfigAnalyse.cs
using System; using System.Collections.Generic; using System.IO; using NUnit.Framework; using System.Linq; using System.Text.RegularExpressions; namespace minefieldtests { public class PackagesConfigAnalyse { [Test] public void AllowedVersionConstraintsIsNotViolated() { var count = GetFiles("minefieldtests") .Where(n => n.EndsWith("packages.config")) .Select(n => File.ReadAllText(n)) .Where(f => Regex.IsMatch(f, "id=\"NUnit\".*allowedVersions=\"\\[2,3\\)\"")) .Count(); Assert.AreEqual(1, count); } public List<string> GetFiles(string path) { var d = new DirectoryInfo(Directory.GetCurrentDirectory()); while (d.EnumerateFiles("*.sln").Any() == false) { d = d.Parent; } var fullPath = Path.Combine(d.FullName, path); return Directory.EnumerateFiles(fullPath) .ToList(); } } }
using System; using System.Collections.Generic; using System.IO; using NUnit.Framework; using System.Linq; using System.Text.RegularExpressions; namespace minefieldtests { public class PackagesConfigAnalyse { [Test] public void AllowedVersionConstraintsIsNotViolated() { var count = GetFiles("minefieldtests") .Where(n => n.EndsWith("packages.config")) .Select(n => File.ReadAllText(n)) .Where(f => Regex.IsMatch(f, "id=\"NUnit\".*allowedVersions=\".2,3.\"")) .Count(); Assert.AreEqual(1, count); } public List<string> GetFiles(string path) { var d = new DirectoryInfo(Directory.GetCurrentDirectory()); while (d.EnumerateFiles("*.sln").Any() == false) { d = d.Parent; } var fullPath = Path.Combine(d.FullName, path); return Directory.EnumerateFiles(fullPath) .ToList(); } } }
mit
C#
e0d10742fc455dfe50daf534fed11e22c1271a2c
Add no/unless-stopped restart policies
jterry75/Docker.DotNet,ahmetalpbalkan/Docker.DotNet,jterry75/Docker.DotNet
Docker.DotNet/Models/RestartPolicy.cs
Docker.DotNet/Models/RestartPolicy.cs
using System.Runtime.Serialization; namespace Docker.DotNet.Models { public enum RestartPolicyKind { [EnumMember(Value = "no")] No, [EnumMember(Value = "always")] Always, [EnumMember(Value = "on-failure")] OnFailure, [EnumMember(Value = "unless-stopped")] UnlessStopped } [DataContract] public class RestartPolicy { [DataMember(Name = "Name")] public RestartPolicyKind Name { get; set; } [DataMember(Name = "MaximumRetryCount")] public int MaximumRetryCount { get; set; } } }
using System.Runtime.Serialization; namespace Docker.DotNet.Models { public enum RestartPolicyKind { [EnumMember(Value = "always")] Always, [EnumMember(Value = "on-failure")] OnFailure } [DataContract] public class RestartPolicy { [DataMember(Name = "Name")] public RestartPolicyKind Name { get; set; } [DataMember(Name = "MaximumRetryCount")] public int MaximumRetryCount { get; set; } } }
apache-2.0
C#
1d00ca5f845587a3b6fbecd6edf8799854a4719c
Use ElementTheme.Default as default
zumicts/Audiotica
Windows/Audiotica.Core.Windows/Utilities/AppSettingsUtility.cs
Windows/Audiotica.Core.Windows/Utilities/AppSettingsUtility.cs
using Windows.Storage; using Windows.UI.Xaml; using Audiotica.Core.Common; using Audiotica.Core.Utilities.Interfaces; using Audiotica.Core.Windows.Helpers; namespace Audiotica.Core.Windows.Utilities { public class AppSettingsUtility : ObservableObject, IAppSettingsUtility { private readonly ISettingsUtility _settingsUtility; private int _theme; public AppSettingsUtility(ISettingsUtility settingsUtility) { _settingsUtility = settingsUtility; DownloadsPath = settingsUtility.Read("DownloadsPath", "virtual://Music/Audiotica/"); TempDownloadsPath = settingsUtility.Read("TempDownloadsPath", ApplicationData.Current.TemporaryFolder.Path); _theme = _settingsUtility.Read(ApplicationSettingsConstants.Theme, (int)ElementTheme.Default); } public string DownloadsPath { get; set; } public string TempDownloadsPath { get; } public int Theme { get { return _theme; } set { Set(ref _theme, value); _settingsUtility.Write(ApplicationSettingsConstants.Theme, value); } } } }
using Windows.Storage; using Windows.UI.Xaml; using Audiotica.Core.Common; using Audiotica.Core.Utilities.Interfaces; using Audiotica.Core.Windows.Helpers; namespace Audiotica.Core.Windows.Utilities { public class AppSettingsUtility : ObservableObject, IAppSettingsUtility { private readonly ISettingsUtility _settingsUtility; private int _theme; public AppSettingsUtility(ISettingsUtility settingsUtility) { _settingsUtility = settingsUtility; DownloadsPath = settingsUtility.Read("DownloadsPath", "virtual://Music/Audiotica/"); TempDownloadsPath = settingsUtility.Read("TempDownloadsPath", ApplicationData.Current.TemporaryFolder.Path); _theme = _settingsUtility.Read(ApplicationSettingsConstants.Theme, (int)ElementTheme.Light); } public string DownloadsPath { get; set; } public string TempDownloadsPath { get; } public int Theme { get { return _theme; } set { Set(ref _theme, value); _settingsUtility.Write(ApplicationSettingsConstants.Theme, value); } } } }
apache-2.0
C#
435910df6c3bbe16221a3b72bb3813f4d0913916
Add license disclaimer
dga711/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,windygu/CefSharp,illfang/CefSharp,wangzheng888520/CefSharp,ITGlobal/CefSharp,rlmcneary2/CefSharp,yoder/CefSharp,rover886/CefSharp,battewr/CefSharp,rover886/CefSharp,Livit/CefSharp,illfang/CefSharp,haozhouxu/CefSharp,dga711/CefSharp,Livit/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,ruisebastiao/CefSharp,NumbersInternational/CefSharp,Octopus-ITSM/CefSharp,yoder/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,ruisebastiao/CefSharp,VioletLife/CefSharp,ITGlobal/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,yoder/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,windygu/CefSharp,twxstar/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,yoder/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,VioletLife/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,twxstar/CefSharp,dga711/CefSharp,illfang/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,joshvera/CefSharp,windygu/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,AJDev77/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,Octopus-ITSM/CefSharp,jamespearce2006/CefSharp,twxstar/CefSharp,illfang/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,ITGlobal/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,wangzheng888520/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,rlmcneary2/CefSharp,rover886/CefSharp,joshvera/CefSharp,VioletLife/CefSharp,battewr/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp
CefSharp/CefFocusSource.cs
CefSharp/CefFocusSource.cs
// Copyright © 2010-2014 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp { /// <summary> /// Focus Source /// </summary> public enum CefFocusSource { /// // The source is explicit navigation via the API (LoadURL(), etc). /// FocusSourceNavigation = 0, /// // The source is a system-generated focus event. /// FocusSourceSystem } }
namespace CefSharp { /// <summary> /// Focus Source /// </summary> public enum CefFocusSource { /// // The source is explicit navigation via the API (LoadURL(), etc). /// FocusSourceNavigation = 0, /// // The source is a system-generated focus event. /// FocusSourceSystem } }
bsd-3-clause
C#
f2e3ac51c7717c1613307368551ea42b9989b9c0
Disable iText AGPL Warning
hclewk/MergePDF
MergePDF/Program.cs
MergePDF/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using iTextSharp.text.log; using Nancy.Hosting.Self; namespace MergePDF { class Program { static void Main(string[] args) { CounterFactory.getInstance().SetCounter(new AGPLWarningRemoverCounter()); var uri = "http://localhost:8888"; Console.WriteLine("Starting Nancy on " + uri); // initialize an instance of NancyHost var host = new NancyHost(new HostConfiguration() { UrlReservations = new UrlReservations() { CreateAutomatically = true }, RewriteLocalhost = true }, new Uri(uri)); host.Start(); // start hosting Console.ReadLine(); Console.WriteLine("Stopping Nancy"); host.Stop(); // stop hosting } } public class AGPLWarningRemoverCounter : ICounter { public AGPLWarningRemoverCounter() { } public ICounter GetCounter(Type klass) { return this; } public void Read(long l) { } public void Written(long l) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Nancy.Hosting.Self; namespace MergePDF { class Program { static void Main(string[] args) { var uri = "http://localhost:8888"; Console.WriteLine("Starting Nancy on " + uri); // initialize an instance of NancyHost var host = new NancyHost(new HostConfiguration() { UrlReservations = new UrlReservations() { CreateAutomatically = true }, RewriteLocalhost = true }, new Uri(uri)); host.Start(); // start hosting Console.ReadLine(); Console.WriteLine("Stopping Nancy"); host.Stop(); // stop hosting } } }
agpl-3.0
C#
4eaf39d3ac0be7d9328e54450e581c2085e3b2d7
Fix namespace.
cube-soft/Cube.Core,cube-soft/Cube.Core
Libraries/Sources/CommandExtension.cs
Libraries/Sources/CommandExtension.cs
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows.Input; namespace Cube.Xui.Mixin { /* --------------------------------------------------------------------- */ /// /// CommandExtension /// /// <summary> /// Provides functionality to execute against the ICommand object. /// </summary> /// /* --------------------------------------------------------------------- */ public static class CommandExtension { #region Methods /* ----------------------------------------------------------------- */ /// /// Execute /// /// <summary> /// Execute the command without any parameters. /// </summary> /// /// <param name="src">Command object.</param> /// /* ----------------------------------------------------------------- */ public static void Execute(this ICommand src) => src.Execute(null); /* ----------------------------------------------------------------- */ /// /// CanExecute /// /// <summary> /// Returns a value that determines the specified command /// can be executed with any parameters. /// </summary> /// /// <param name="src">Command object.</param> /// /* ----------------------------------------------------------------- */ public static bool CanExecute(this ICommand src) => src.CanExecute(null); #endregion } }
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System.Windows.Input; namespace Cube.Xui.Sources { /* --------------------------------------------------------------------- */ /// /// CommandExtension /// /// <summary> /// Provides functionality to execute against the ICommand object. /// </summary> /// /* --------------------------------------------------------------------- */ public static class CommandExtension { #region Methods /* ----------------------------------------------------------------- */ /// /// Execute /// /// <summary> /// Execute the command without any parameters. /// </summary> /// /// <param name="src">Command object.</param> /// /* ----------------------------------------------------------------- */ public static void Execute(this ICommand src) => src.Execute(null); /* ----------------------------------------------------------------- */ /// /// CanExecute /// /// <summary> /// Returns a value that determines the specified command /// can be executed with any parameters. /// </summary> /// /// <param name="src">Command object.</param> /// /* ----------------------------------------------------------------- */ public static bool CanExecute(this ICommand src) => src.CanExecute(null); #endregion } }
apache-2.0
C#
a69b1636be75e094a7323a0961a45a1703a878f1
Update tests
UselessToucan/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,peppy/osu
osu.Game.Tests/Visual/Editing/TestSceneEditorSamplePlayback.cs
osu.Game.Tests/Visual/Editing/TestSceneEditorSamplePlayback.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Audio; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSamplePlayback : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestSlidingSampleStopsOnSeek() { DrawableSlider slider = null; DrawableSample[] loopingSamples = null; DrawableSample[] onceOffSamples = null; AddStep("get first slider", () => { slider = Editor.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First(); onceOffSamples = slider.ChildrenOfType<DrawableSample>().Where(s => !s.Looping).ToArray(); loopingSamples = slider.ChildrenOfType<DrawableSample>().Where(s => s.Looping).ToArray(); }); AddStep("start playback", () => EditorClock.Start()); AddUntilStep("wait for slider sliding then seek", () => { if (!slider.Tracking.Value) return false; if (!loopingSamples.Any(s => s.Playing)) return false; EditorClock.Seek(20000); return true; }); AddAssert("non-looping samples are playing", () => onceOffSamples.Length == 4 && loopingSamples.All(s => s.Played || s.Playing)); AddAssert("looping samples are not playing", () => loopingSamples.Length == 1 && loopingSamples.All(s => s.Played && !s.Playing)); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using NUnit.Framework; using osu.Framework.Graphics.Audio; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Tests.Visual.Editing { public class TestSceneEditorSamplePlayback : EditorTestScene { protected override Ruleset CreateEditorRuleset() => new OsuRuleset(); [Test] public void TestSlidingSampleStopsOnSeek() { DrawableSlider slider = null; DrawableSample[] samples = null; AddStep("get first slider", () => { slider = Editor.ChildrenOfType<DrawableSlider>().OrderBy(s => s.HitObject.StartTime).First(); samples = slider.ChildrenOfType<DrawableSample>().ToArray(); }); AddStep("start playback", () => EditorClock.Start()); AddUntilStep("wait for slider sliding then seek", () => { if (!slider.Tracking.Value) return false; if (!samples.Any(s => s.Playing)) return false; EditorClock.Seek(20000); return true; }); AddAssert("slider samples are not playing", () => samples.Length == 5 && samples.All(s => s.Played && !s.Playing)); } } }
mit
C#
8f330bfdedc5644fede877a5aa2063210cdc12b5
Fix failing unit tests
afgbeveridge/Quorum,afgbeveridge/Quorum,afgbeveridge/Quorum
Quorum.Tests/BaseQuorumTestFixture.cs
Quorum.Tests/BaseQuorumTestFixture.cs
using FSM; using FluentAssertions; using Infra; using System.Threading.Tasks; namespace Quorum.Tests { public abstract class BaseQuorumTestFixture { protected IStateMachine<IExecutionContext> CreateMachine(Builder bldr) { var mc = bldr.Create(); bldr.Register<IMasterWorkAdapter, EmptyWorker>(); // Register any old nexus bldr.Resolve<IConfiguration>().LocalSet(Constants.Configuration.Nexus.Key, "A,B"); return mc; } protected async Task<IStateMachine<IExecutionContext>> CreateAndStartMachine(Builder bldr, bool checkOnce = true) { var mc = CreateMachine(bldr); return await StartMachine(mc, checkOnce); } protected async Task<IStateMachine<IExecutionContext>> StartMachine(IStateMachine<IExecutionContext> mc, bool checkOnce = true) { await mc.Start(); mc.CurrentState.Should().NotBeNull("Default machine should have a current state"); if (checkOnce) await mc.CheckQueuedEvents(); return mc; } protected async Task TriggerThenCheck(IStateMachine<IExecutionContext> mc, string eventName) { await mc.Trigger(EventInstance.Create(eventName)); await mc.CheckQueuedEvents(); } } }
using FSM; using FluentAssertions; using System.Threading.Tasks; namespace Quorum.Tests { public abstract class BaseQuorumTestFixture { protected IStateMachine<IExecutionContext> CreateMachine(Builder bldr) { var mc = bldr.Create(); bldr.Register<IMasterWorkAdapter, EmptyWorker>(); return mc; } protected async Task<IStateMachine<IExecutionContext>> CreateAndStartMachine(Builder bldr, bool checkOnce = true) { var mc = CreateMachine(bldr); return await StartMachine(mc, checkOnce); } protected async Task<IStateMachine<IExecutionContext>> StartMachine(IStateMachine<IExecutionContext> mc, bool checkOnce = true) { await mc.Start(); mc.CurrentState.Should().NotBeNull("Default machine should have a current state"); if (checkOnce) await mc.CheckQueuedEvents(); return mc; } protected async Task TriggerThenCheck(IStateMachine<IExecutionContext> mc, string eventName) { await mc.Trigger(EventInstance.Create(eventName)); await mc.CheckQueuedEvents(); } } }
mit
C#
e75179448af307fa478e614e2bf50d75d46bfa05
Update version
BinaryKits/ZPLUtility
ZPLUtility/Properties/AssemblyInfo.cs
ZPLUtility/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("ZPLUtility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Binary Kits Pte. Ltd.")] [assembly: AssemblyProduct("ZPLUtility")] [assembly: AssemblyCopyright("BinaryKits Pte. Ltd. 2021")] [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("a836ca9d-cf58-4289-85f7-781eff51e091")] // 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.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ZPLUtility")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Binary Kits Pte. Ltd.")] [assembly: AssemblyProduct("ZPLUtility")] [assembly: AssemblyCopyright("BinaryKits Pte. Ltd. 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a836ca9d-cf58-4289-85f7-781eff51e091")] // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
mit
C#
c3402230b1fde51ae52837a27469fc57d4f0509b
Update grammar in EmptyObjectInitializerAnalyzer.cs #839
code-cracker/code-cracker,jwooley/code-cracker,eriawan/code-cracker,code-cracker/code-cracker,carloscds/code-cracker,giggio/code-cracker,carloscds/code-cracker
src/CSharp/CodeCracker/Style/EmptyObjectInitializerAnalyzer.cs
src/CSharp/CodeCracker/Style/EmptyObjectInitializerAnalyzer.cs
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; namespace CodeCracker.CSharp.Style { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class EmptyObjectInitializerAnalyzer : DiagnosticAnalyzer { internal const string Title = "Empty Object Initializer"; internal const string MessageFormat = "{0}"; internal const string Category = SupportedCategories.Style; const string Description = "An object initializer without any arguments can be replaced with the standard constructor syntax."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.EmptyObjectInitializer.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.Unnecessary, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.EmptyObjectInitializer)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ObjectCreationExpression); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var objectCreation = context.Node as ObjectCreationExpressionSyntax; if (objectCreation.Initializer != null && !objectCreation.Initializer.Expressions.Any()) { var diagnostic = Diagnostic.Create(Rule, objectCreation.Initializer.OpenBraceToken.GetLocation(), "Remove the empty object initializer."); context.ReportDiagnostic(diagnostic); } } } }
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using System.Collections.Immutable; namespace CodeCracker.CSharp.Style { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class EmptyObjectInitializerAnalyzer : DiagnosticAnalyzer { internal const string Title = "Empty Object Initializer"; internal const string MessageFormat = "{0}"; internal const string Category = SupportedCategories.Style; const string Description = "An empty object initializer doesn't add any information and only clutter the code.\r\n" + "If there is no member to initialize, prefer using the standard constructor syntax."; internal static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( DiagnosticId.EmptyObjectInitializer.ToDiagnosticId(), Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, customTags: WellKnownDiagnosticTags.Unnecessary, description: Description, helpLinkUri: HelpLink.ForDiagnostic(DiagnosticId.EmptyObjectInitializer)); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(Analyzer, SyntaxKind.ObjectCreationExpression); private static void Analyzer(SyntaxNodeAnalysisContext context) { if (context.IsGenerated()) return; var objectCreation = context.Node as ObjectCreationExpressionSyntax; if (objectCreation.Initializer != null && !objectCreation.Initializer.Expressions.Any()) { var diagnostic = Diagnostic.Create(Rule, objectCreation.Initializer.OpenBraceToken.GetLocation(), "Remove empty object initializer."); context.ReportDiagnostic(diagnostic); } } } }
apache-2.0
C#
29931fb429e59ae00acdc5643f64d17409642a38
Update FizzBuzz.cs
michaeljwebb/Algorithm-Practice
LeetCode/FizzBuzz.cs
LeetCode/FizzBuzz.cs
//Output the string representation of numbers from 1 to n. //For multiples of three output "Fizz" //For multiples of five output "Buzz" //For multiples of both three and five output "FizzBuzz" using System; using System.Collections.Generic; using System.Linq; using System.Text; public class FizzBuzz { private static void Main(string[] args) { for (int i = 1; i < 16; i++) { if (i % 3 == 0 && i % 5 == 0) { Console.WriteLine("FizzBuzz"); } else if (i % 3 == 0) { Console.WriteLine("Fizz"); } else if (i % 5 == 0) { Console.WriteLine("Buzz"); } else { Console.WriteLine(i); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; public class FizzBuzz { private static void Main(string[] args) { for (int i = 1; i < 16; i++) { if (i % 3 == 0 && i % 5 == 0) { Console.WriteLine("FizzBuzz"); } else if (i % 3 == 0) { Console.WriteLine("Fizz"); } else if (i % 5 == 0) { Console.WriteLine("Buzz"); } else { Console.WriteLine(i); } } } }
mit
C#
51d79701ed2c0c96dbb16760f041e55626a1bd20
Fix wrong date representation
afisd/jovice,afisd/jovice
Aphysoft.Share/Extensions/DateTime.cs
Aphysoft.Share/Extensions/DateTime.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aphysoft.Share { /// <summary> /// DateTime Extensions /// </summary> public static class DateTimeExtensions { public static DateTime ConvertOffset(this DateTime value, TimeSpan offset) { if (value == DateTime.MinValue) return DateTime.MinValue; return value + offset; } public static DateTime ConvertOffset(this DateTime value, int hourOffset) { return value.ConvertOffset(new TimeSpan(hourOffset, 0, 0)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Aphysoft.Share { /// <summary> /// DateTime Extensions /// </summary> public static class DateTimeExtensions { public static DateTime ConvertOffset(this DateTime value, TimeSpan offset) { if (value == DateTime.MinValue) return DateTime.MinValue; DateTimeOffset d = new DateTimeOffset(value, offset); return d.UtcDateTime; } public static DateTime ConvertOffset(this DateTime value, int hourOffset) { return value.ConvertOffset(new TimeSpan(hourOffset, 0, 0)); } } }
mit
C#
8baf58aa1eb06d5811dabd33d79efaaee0070272
Fix force selector reset clipping error.
s-soltys/PoolVR
Assets/PoolVR/Scripts/FollowTarget.cs
Assets/PoolVR/Scripts/FollowTarget.cs
using System; using System.Collections; using System.Collections.Generic; using UniRx; using UnityEngine; using Zenject; public class FollowTarget : MonoBehaviour { [Inject] public ForceSelector ForceSelector { get; set; } public Rigidbody targetRb; public float velocityThresh; public float moveToTargetSpeed; public float distanceToResume; public float distanceToReset; private IDisposable sub; void Start() { sub = Observable .IntervalFrame(5) .Select(_ => Vector3.Distance(targetRb.transform.position, transform.position)) .Hysteresis((d, referenceDist) => d - referenceDist, distanceToResume, distanceToReset) .Subscribe(isMoving => { ForceSelector.IsRunning = !isMoving; }); } void OnDestroy() { if (sub != null) { sub.Dispose(); sub = null; } } void Update () { if (targetRb.velocity.magnitude < velocityThresh && !ForceSelector.IsRunning) { transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Zenject; public class FollowTarget : MonoBehaviour { [Inject] public ForceSelector ForceSelector { get; set; } public Rigidbody targetRb; public float distanceToReset = 0.1f; public float velocityThresh; public float moveToTargetSpeed; public bool isAtTarget; void Update () { isAtTarget = Vector3.Distance(targetRb.transform.position, transform.position) <= distanceToReset; if (targetRb.velocity.magnitude < velocityThresh && !isAtTarget) { transform.position = Vector3.Lerp(transform.position, targetRb.transform.position, moveToTargetSpeed); } ForceSelector.IsRunning = isAtTarget; } }
mit
C#
ca69034a99ef1e7f723598d80af8c99333f2bc23
Update anchor within help link (follow-up to r3671). Closes #3647.
walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,netjunki/trac-Pygit2,walty8/trac,walty8/trac,netjunki/trac-Pygit2,jun66j5/trac-ja,jun66j5/trac-ja,netjunki/trac-Pygit2,walty8/trac
templates/anydiff.cs
templates/anydiff.cs
<?cs include "header.cs"?> <div id="ctxtnav" class="nav"></div> <div id="content" class="changeset"> <div id="title"> <h1>Select Base and Target for Diff:</h1> </div> <div id="anydiff"> <form action="<?cs var:anydiff.changeset_href ?>" method="get"> <table> <tr> <th><label for="old_path">From:</label></th> <td> <input type="text" id="old_path" name="old_path" value="<?cs var:anydiff.old_path ?>" size="44" /> <label for="old_rev">at Revision:</label> <input type="text" id="old_rev" name="old" value="<?cs var:anydiff.old_rev ?>" size="4" /> </td> </tr> <tr> <th><label for="new_path">To:</label></th> <td> <input type="text" id="new_path" name="new_path" value="<?cs var:anydiff.new_path ?>" size="44" /> <label for="new_rev">at Revision:</label> <input type="text" id="new_rev" name="new" value="<?cs var:anydiff.new_rev ?>" size="4" /> </td> </tr> </table> <div class="buttons"> <input type="submit" value="View changes" /> </div> </form> </div> <div id="help"> <strong>Note:</strong> See <a href="<?cs var:trac.href.wiki ?>/TracChangeset#ExaminingDifferencesBetweenBranches">TracChangeset</a> for help on using the arbitrary diff feature. </div> </div> <?cs include "footer.cs"?>
<?cs include "header.cs"?> <div id="ctxtnav" class="nav"></div> <div id="content" class="changeset"> <div id="title"> <h1>Select Base and Target for Diff:</h1> </div> <div id="anydiff"> <form action="<?cs var:anydiff.changeset_href ?>" method="get"> <table> <tr> <th><label for="old_path">From:</label></th> <td> <input type="text" id="old_path" name="old_path" value="<?cs var:anydiff.old_path ?>" size="44" /> <label for="old_rev">at Revision:</label> <input type="text" id="old_rev" name="old" value="<?cs var:anydiff.old_rev ?>" size="4" /> </td> </tr> <tr> <th><label for="new_path">To:</label></th> <td> <input type="text" id="new_path" name="new_path" value="<?cs var:anydiff.new_path ?>" size="44" /> <label for="new_rev">at Revision:</label> <input type="text" id="new_rev" name="new" value="<?cs var:anydiff.new_rev ?>" size="4" /> </td> </tr> </table> <div class="buttons"> <input type="submit" value="View changes" /> </div> </form> </div> <div id="help"> <strong>Note:</strong> See <a href="<?cs var:trac.href.wiki ?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset</a> for help on using the arbitrary diff feature. </div> </div> <?cs include "footer.cs"?>
bsd-3-clause
C#
ed363f9f8fd25eb8168f3f1acc8f60566805e6db
make datetimes optional
MiXTelematics/MiX.Integrate.Api.Client
MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs
MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs
using System; using System.Collections.Generic; using System.Text; using MiX.Integrate.Shared.Entities.Communications; namespace MiX.Integrate.Shared.Entities.Messages { public class SendJobMessageCarrier { public SendJobMessageCarrier() { } public short VehicleId { get; set; } public string Description { get; set; } public string UserDescription { get; set; } public string Body { get; set; } public DateTime? StartDate { get; set; } public DateTime? ExpiryDate { get; set; } public bool RequiresAddress { get; set; } public bool AddAddressSummary { get; set; } public bool UseFirstAddressForSummary { get; set; } public JobMessageActionNotifications NotificationSettings { get; set; } public int[] AddressList { get; set; } public CommsTransports Transport { get; set; } public bool Urgent { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using MiX.Integrate.Shared.Entities.Communications; namespace MiX.Integrate.Shared.Entities.Messages { public class SendJobMessageCarrier { public SendJobMessageCarrier() { } public short VehicleId { get; set; } public string Description { get; set; } public string UserDescription { get; set; } public string Body { get; set; } public DateTime StartDate { get; set; } public DateTime ExpiryDate { get; set; } public bool RequiresAddress { get; set; } public bool AddAddressSummary { get; set; } public bool UseFirstAddressForSummary { get; set; } public JobMessageActionNotifications NotificationSettings { get; set; } public int[] AddressList { get; set; } public CommsTransports Transport { get; set; } public bool Urgent { get; set; } } }
mit
C#
e1f4299a57f05cb4ae333c5f6e78e00a56bc22d9
Fix login changes in WPF UI.
MonkAlex/MangaReader
MangaReader/ViewModel/LoginModel.cs
MangaReader/ViewModel/LoginModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using MangaReader.Core.Account; using MangaReader.Core.Manga; using MangaReader.Core.NHibernate; using MangaReader.ViewModel.Commands.AddManga; using MangaReader.ViewModel.Primitive; namespace MangaReader.ViewModel { public class LoginModel : BaseViewModel { private ILogin login; private bool isEnabled; public int LoginId { get; } public string Login { get { return login.Name; } set { login.Name = value; OnPropertyChanged(); } } public string Password { get { return login.Password; } set { login.Password = value; OnPropertyChanged(); } } public bool CanEdit { get { return IsEnabled && HasLogin && !login.IsLogined; } } public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanEdit)); } } public bool HasLogin { get; set; } public bool HasError { get { return !HasLogin; } } public ICommand LogInOutCommand { get; private set; } public async Task<List<IManga>> GetBookmarks() { if (login != null) return await login.GetBookmarks(); return new List<IManga>(); } public LoginModel(ILogin login) { if (login != null) { this.login = login; this.LoginId = login.Id; this.LogInOutCommand = new LogInOutCommand(this.login); this.login.LoginStateChanged += LoginOnLoginStateChanged; HasLogin = true; } else HasLogin = false; } private void LoginOnLoginStateChanged(object sender, bool b) { OnPropertyChanged(nameof(CanEdit)); OnPropertyChanged(nameof(Login)); OnPropertyChanged(nameof(Password)); } public void Save() { if (this.login != null) { using (var context = Repository.GetEntityContext($"Save settings for {LoginId}")) { var actualLogin = context.Get<ILogin>().Single(s => s.Id == LoginId); actualLogin.Name = this.Login; actualLogin.Password = this.Password; context.Save(actualLogin); this.login = actualLogin; } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Windows.Input; using MangaReader.Core.Account; using MangaReader.Core.Manga; using MangaReader.ViewModel.Commands.AddManga; using MangaReader.ViewModel.Primitive; namespace MangaReader.ViewModel { public class LoginModel : BaseViewModel { private ILogin login; private bool isEnabled; public int LoginId { get; } public string Login { get { return login.Name; } set { login.Name = value; OnPropertyChanged(); } } public string Password { get { return login.Password; } set { login.Password = value; OnPropertyChanged(); } } public bool CanEdit { get { return IsEnabled && HasLogin && !login.IsLogined; } } public bool IsEnabled { get { return isEnabled; } set { isEnabled = value; OnPropertyChanged(); OnPropertyChanged(nameof(CanEdit)); } } public bool HasLogin { get; set; } public bool HasError { get { return !HasLogin; } } public ICommand LogInOutCommand { get; private set; } public async Task<List<IManga>> GetBookmarks() { if (login != null) return await login.GetBookmarks(); return new List<IManga>(); } public LoginModel(ILogin login) { if (login != null) { this.login = login; this.LoginId = login.Id; this.LogInOutCommand = new LogInOutCommand(this.login); this.login.LoginStateChanged += LoginOnLoginStateChanged; HasLogin = true; } else HasLogin = false; } private void LoginOnLoginStateChanged(object sender, bool b) { OnPropertyChanged(nameof(CanEdit)); OnPropertyChanged(nameof(Login)); OnPropertyChanged(nameof(Password)); } public void Save() { if (this.login != null) { this.login.Name = this.Login; this.login.Password = this.Password; } } } }
mit
C#
51fb5fec89cc2eb18809c6e6aae9d7dc130b5b85
Update Class.cs
EduSource/QuickBooks.Net
QuickBooks.Net.Data/Models/Class.cs
QuickBooks.Net.Data/Models/Class.cs
using Newtonsoft.Json; using QuickBooks.Net.Data.Models.Fields; namespace QuickBooks.Net.Data.Models { public class Class : QuickBooksBaseModelString { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Name { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool SubClass { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Ref ParentRef { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string FullyQualifiedName { get; set; } public bool Active { get; set; } internal override QuickBooksBaseModelString CreateReturnObject() { return new Class { Id = Id, Name = Name, SubClass = SubClass, ParentRef = ParentRef, FullyQualifiedName = FullyQualifiedName, Active = Active }; } internal override QuickBooksBaseModelString UpdateReturnObject() { return this; } internal override QuickBooksBaseModelString DeleteReturnObject() { return new Class { Id = Id, SyncToken = SyncToken, Active = false, Name = Name }; } } }
using Newtonsoft.Json; using QuickBooks.Net.Data.Models.Fields; namespace QuickBooks.Net.Data.Models { public class Class : QuickBooksBaseModelString { [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string Name { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public bool SubClass { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public Ref ParentRef { get; set; } [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string FullyQualifiedName { get; set; } public bool Active { get; set; } internal override QuickBooksBaseModelString CreateReturnObject() { return new Class { Id = Id, Name = Name, SubClass = SubClass, ParentRef = ParentRef, FullyQualifiedName = FullyQualifiedName, Active = Active }; } internal override QuickBooksBaseModelString UpdateReturnObject() { return this; } internal override QuickBooksBaseModelString DeleteReturnObject() { return new Class { Id = Id, SyncToken = SyncToken, Active = false }; } } }
mit
C#
be326a7c4522ad4f40a612620b9c42c150ff9713
Fix typo in compiler directive
fringebits/NLog,ajayanandgit/NLog,RichiCoder1/NLog,rajk987/NLog,BrandonLegault/NLog,czema/NLog,ilya-g/NLog,vbfox/NLog,zbrad/NLog,RRUZ/NLog,kevindaub/NLog,bjornbouetsmith/NLog,zbrad/NLog,mikkelxn/NLog,thomkinson/NLog,ie-zero/NLog,AqlaSolutions/NLog-Unity3D,pwelter34/NLog,luigiberrettini/NLog,BrandonLegault/NLog,FeodorFitsner/NLog,ArsenShnurkov/NLog,RichiCoder1/NLog,ie-zero/NLog,tetrodoxin/NLog,MoaidHathot/NLog,ajayanandgit/NLog,UgurAldanmaz/NLog,Niklas-Peter/NLog,bhaeussermann/NLog,UgurAldanmaz/NLog,tmusico/NLog,nazim9214/NLog,matteobruni/NLog,AqlaSolutions/NLog-Unity3D,vladikk/NLog,BrandonLegault/NLog,BrandonLegault/NLog,fringebits/NLog,thomkinson/NLog,AndreGleichner/NLog,snakefoot/NLog,mikkelxn/NLog,thomkinson/NLog,kevindaub/NLog,AqlaSolutions/NLog-Unity3D,ArsenShnurkov/NLog,fringebits/NLog,czema/NLog,littlesmilelove/NLog,pwelter34/NLog,rajk987/NLog,BrutalCode/NLog,tmusico/NLog,matteobruni/NLog,czema/NLog,vbfox/NLog,michaeljbaird/NLog,luigiberrettini/NLog,vladikk/NLog,AndreGleichner/NLog,tetrodoxin/NLog,littlesmilelove/NLog,MartinTherriault/NLog,czema/NLog,michaeljbaird/NLog,fringebits/NLog,sean-gilliam/NLog,vladikk/NLog,rajk987/NLog,Niklas-Peter/NLog,campbeb/NLog,MoaidHathot/NLog,RRUZ/NLog,babymechanic/NLog,breyed/NLog,tohosnet/NLog,bhaeussermann/NLog,NLog/NLog,FeodorFitsner/NLog,hubo0831/NLog,rajeshgande/NLog,bryjamus/NLog,rajk987/NLog,BrutalCode/NLog,thomkinson/NLog,nazim9214/NLog,mikkelxn/NLog,bjornbouetsmith/NLog,AqlaSolutions/NLog-Unity3D,vladikk/NLog,304NotModified/NLog,tohosnet/NLog,mikkelxn/NLog,breyed/NLog,MartinTherriault/NLog,campbeb/NLog,hubo0831/NLog,ilya-g/NLog,rajeshgande/NLog,bryjamus/NLog,babymechanic/NLog
src/NLog/LayoutRenderers/AssemblyVersionLayoutRenderer.cs
src/NLog/LayoutRenderers/AssemblyVersionLayoutRenderer.cs
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT2 && !NET_CF namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using NLog.Config; using NLog.Internal; #if SILVERLIGHT using System.Windows; #else using System.Reflection; #endif /// <summary> /// Assembly version. /// </summary> [LayoutRenderer("assembly-version")] public class AssemblyVersionLayoutRenderer : LayoutRenderer { /// <summary> /// Renders assembly version and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { #if SILVERLIGHT var assembly = Application.Current.GetType().Assembly; #else var assembly = Assembly.GetEntryAssembly(); #endif var assemblyVersion = assembly == null ? "Could not find entry assembly" : assembly.GetName().Version.ToString(); builder.Append(assemblyVersion); } } } #endif
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <[email protected]> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT2 && !_NET_CF namespace NLog.LayoutRenderers { using System; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using NLog.Config; using NLog.Internal; #if SILVERLIGHT using System.Windows; #else using System.Reflection; #endif /// <summary> /// Assembly version. /// </summary> [LayoutRenderer("assembly-version")] public class AssemblyVersionLayoutRenderer : LayoutRenderer { /// <summary> /// Renders assembly version and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { #if SILVERLIGHT var assembly = Application.Current.GetType().Assembly; #else var assembly = Assembly.GetEntryAssembly(); #endif var assemblyVersion = assembly == null ? "Could not find entry assembly" : assembly.GetName().Version.ToString(); builder.Append(assemblyVersion); } } } #endif
bsd-3-clause
C#
65683d3e77cba40370f9b0e6e6cf13d0fb95e6bf
Rename the-admin to admin in Layout-Login (#9777)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2
src/OrchardCore.Themes/TheAdmin/Views/Layout-Login.cshtml
src/OrchardCore.Themes/TheAdmin/Views/Layout-Login.cshtml
@inject DarkModeService DarkModeService; @{ var darkMode = await DarkModeService.IsDarkModeAsync(); } <!DOCTYPE html> <html lang="@Orchard.CultureName()" dir="@Orchard.CultureDir()" data-theme="@DarkModeService.CurrentTheme"> <head> <title>@RenderTitleSegments(Site.SiteName, "before")</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link type="image/x-icon" rel="shortcut icon" href="~/TheAdmin/favicon.ico" /> <!-- Bootstrap CSS --> <style asp-name="admin" version="1"></style> <script asp-name="font-awesome" at="Foot" version="5"></script> <script asp-name="font-awesome-v4-shims" at="Foot" version="5"></script> <resources type="Header" /> </head> <body> <div class="ta-content ta-content-login"> @await RenderSectionAsync("Header", required: false) @await RenderSectionAsync("Messages", required: false) <div class="auth-wrapper"> @await RenderBodyAsync() </div> </div> @await RenderSectionAsync("Footer", required: false) <resources type="Footer" /> </body> </html>
@inject DarkModeService DarkModeService; @{ var darkMode = await DarkModeService.IsDarkModeAsync(); } <!DOCTYPE html> <html lang="@Orchard.CultureName()" dir="@Orchard.CultureDir()" data-theme="@DarkModeService.CurrentTheme"> <head> <title>@RenderTitleSegments(Site.SiteName, "before")</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link type="image/x-icon" rel="shortcut icon" href="~/TheAdmin/favicon.ico" /> <!-- Bootstrap CSS --> <style asp-name="the-admin" version="1"></style> <script asp-name="font-awesome" at="Foot" version="5"></script> <script asp-name="font-awesome-v4-shims" at="Foot" version="5"></script> <resources type="Header" /> </head> <body> <div class="ta-content ta-content-login"> @await RenderSectionAsync("Header", required: false) @await RenderSectionAsync("Messages", required: false) <div class="auth-wrapper"> @await RenderBodyAsync() </div> </div> @await RenderSectionAsync("Footer", required: false) <resources type="Footer" /> </body> </html>
bsd-3-clause
C#
c9a9b7e505d427b2cbea2cc6816c8b1681033407
Adjust method order
ludwigjossieaux/pickles,magicmonty/pickles,magicmonty/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,dirkrombauts/pickles,dirkrombauts/pickles,picklesdoc/pickles,dirkrombauts/pickles,dirkrombauts/pickles,magicmonty/pickles,magicmonty/pickles
src/Pickles/Pickles.TestFrameworks/NUnit2/NUnitResults.cs
src/Pickles/Pickles.TestFrameworks/NUnit2/NUnitResults.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NUnitResults.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO.Abstractions; using System.Linq; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.TestFrameworks.NUnit2 { public class NUnitResults : MultipleTestResults { private readonly NUnit2SingleResultLoader singleResultLoader = new NUnit2SingleResultLoader(); public NUnitResults(IConfiguration configuration, NUnitExampleSignatureBuilder exampleSignatureBuilder) : base(true, configuration) { this.SetExampleSignatureBuilder(exampleSignatureBuilder); } public void SetExampleSignatureBuilder(NUnitExampleSignatureBuilder exampleSignatureBuilder) { foreach (var testResult in TestResults.OfType<NUnitSingleResults>()) { testResult.ExampleSignatureBuilder = exampleSignatureBuilder; } } public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments) { var results = TestResults.OfType<NUnitSingleResults>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray(); return EvaluateTestResults(results); } protected override ITestResults ConstructSingleTestResult(FileInfoBase fileInfo) { return this.singleResultLoader.Load(fileInfo); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NUnitResults.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO.Abstractions; using System.Linq; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.TestFrameworks.NUnit2 { public class NUnitResults : MultipleTestResults { private readonly NUnit2SingleResultLoader singleResultLoader = new NUnit2SingleResultLoader(); public NUnitResults(IConfiguration configuration, NUnitExampleSignatureBuilder exampleSignatureBuilder) : base(true, configuration) { this.SetExampleSignatureBuilder(exampleSignatureBuilder); } public void SetExampleSignatureBuilder(NUnitExampleSignatureBuilder exampleSignatureBuilder) { foreach (var testResult in TestResults.OfType<NUnitSingleResults>()) { testResult.ExampleSignatureBuilder = exampleSignatureBuilder; } } protected override ITestResults ConstructSingleTestResult(FileInfoBase fileInfo) { return this.singleResultLoader.Load(fileInfo); } public override TestResult GetExampleResult(ScenarioOutline scenarioOutline, string[] arguments) { var results = TestResults.OfType<NUnitSingleResults>().Select(tr => tr.GetExampleResult(scenarioOutline, arguments)).ToArray(); return EvaluateTestResults(results); } } }
apache-2.0
C#
c0847c9becda6986e34f1f5852063fb7e422cd62
Change is ready accessibility, to allow other project able to set this value
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/GameApi/LiteNetLibPlayer.cs
Scripts/GameApi/LiteNetLibPlayer.cs
using System.Collections.Generic; namespace LiteNetLibManager { public class LiteNetLibPlayer { public LiteNetLibGameManager Manager { get; protected set; } public long ConnectionId { get; protected set; } public bool IsReady { get; set; } internal readonly HashSet<LiteNetLibIdentity> SubscribingObjects = new HashSet<LiteNetLibIdentity>(); internal readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>(); public LiteNetLibPlayer(LiteNetLibGameManager manager, long connectionId) { Manager = manager; ConnectionId = connectionId; } internal void AddSubscribing(LiteNetLibIdentity identity) { SubscribingObjects.Add(identity); Manager.SendServerSpawnObjectWithData(ConnectionId, identity); } internal void RemoveSubscribing(LiteNetLibIdentity identity, bool destroyObjectsOnPeer) { SubscribingObjects.Remove(identity); if (destroyObjectsOnPeer) Manager.SendServerDestroyObject(ConnectionId, identity.ObjectId, LiteNetLibGameManager.DestroyObjectReasons.RemovedFromSubscribing); } internal void ClearSubscribing(bool destroyObjectsOnPeer) { // Remove this from identities subscriber list foreach (LiteNetLibIdentity identity in SubscribingObjects) { // Don't call for remove subscribing // because it's going to clear in this function identity.RemoveSubscriber(this, false); if (destroyObjectsOnPeer) Manager.SendServerDestroyObject(ConnectionId, identity.ObjectId, LiteNetLibGameManager.DestroyObjectReasons.RemovedFromSubscribing); } SubscribingObjects.Clear(); } /// <summary> /// Call this function to destroy all objects that spawned by this player /// </summary> internal void DestroyAllObjects() { List<uint> objectIds = new List<uint>(SpawnedObjects.Keys); foreach (uint objectId in objectIds) Manager.Assets.NetworkDestroy(objectId, LiteNetLibGameManager.DestroyObjectReasons.RequestedToDestroy); SpawnedObjects.Clear(); } } }
using System.Collections; using System.Collections.Generic; using LiteNetLib; namespace LiteNetLibManager { public class LiteNetLibPlayer { public LiteNetLibGameManager Manager { get; protected set; } public long ConnectionId { get; protected set; } internal bool IsReady { get; set; } internal readonly HashSet<LiteNetLibIdentity> SubscribingObjects = new HashSet<LiteNetLibIdentity>(); internal readonly Dictionary<uint, LiteNetLibIdentity> SpawnedObjects = new Dictionary<uint, LiteNetLibIdentity>(); public LiteNetLibPlayer(LiteNetLibGameManager manager, long connectionId) { Manager = manager; ConnectionId = connectionId; } internal void AddSubscribing(LiteNetLibIdentity identity) { SubscribingObjects.Add(identity); Manager.SendServerSpawnObjectWithData(ConnectionId, identity); } internal void RemoveSubscribing(LiteNetLibIdentity identity, bool destroyObjectsOnPeer) { SubscribingObjects.Remove(identity); if (destroyObjectsOnPeer) Manager.SendServerDestroyObject(ConnectionId, identity.ObjectId, LiteNetLibGameManager.DestroyObjectReasons.RemovedFromSubscribing); } internal void ClearSubscribing(bool destroyObjectsOnPeer) { // Remove this from identities subscriber list foreach (LiteNetLibIdentity identity in SubscribingObjects) { // Don't call for remove subscribing // because it's going to clear in this function identity.RemoveSubscriber(this, false); if (destroyObjectsOnPeer) Manager.SendServerDestroyObject(ConnectionId, identity.ObjectId, LiteNetLibGameManager.DestroyObjectReasons.RemovedFromSubscribing); } SubscribingObjects.Clear(); } /// <summary> /// Call this function to destroy all objects that spawned by this player /// </summary> internal void DestroyAllObjects() { List<uint> objectIds = new List<uint>(SpawnedObjects.Keys); foreach (uint objectId in objectIds) Manager.Assets.NetworkDestroy(objectId, LiteNetLibGameManager.DestroyObjectReasons.RequestedToDestroy); SpawnedObjects.Clear(); } } }
mit
C#
fbd2a306069b2712dce3709aa09780a4e843f181
Update 'default value' title + description of CheckBox Configuration (#8421)
KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,tcmorris/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
src/Umbraco.Web/PropertyEditors/TrueFalseConfiguration.cs
src/Umbraco.Web/PropertyEditors/TrueFalseConfiguration.cs
using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// Represents the configuration for the boolean value editor. /// </summary> public class TrueFalseConfiguration { [ConfigurationField("default","Initial State", "boolean",Description = "The initial state for this checkbox, when it is displayed for the first time in the backoffice, eg. for a new content item.")] public string Default { get; set; } // TODO: well, true or false?! [ConfigurationField("labelOn", "Write a label text", "textstring")] public string Label { get; set; } } }
using Umbraco.Core.PropertyEditors; namespace Umbraco.Web.PropertyEditors { /// <summary> /// Represents the configuration for the boolean value editor. /// </summary> public class TrueFalseConfiguration { [ConfigurationField("default", "Default Value", "boolean")] public string Default { get; set; } // TODO: well, true or false?! [ConfigurationField("labelOn", "Write a label text", "textstring")] public string Label { get; set; } } }
mit
C#
382214e537a5716c3d21896862b8b64e1b81b6b1
Remove profanity - don't want to alienate folk
larrynburris/Bands
examples/Bands.GettingStarted/Program.cs
examples/Bands.GettingStarted/Program.cs
using Bands.Output; using System; namespace Bands.GettingStarted { class Program { static void Main(string[] args) { Console.WriteLine("Getting started with Bands!"); var payload = new CounterPayload(); var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo); var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand); var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand); outerConsoleBand.Enter(payload); Console.WriteLine("Kinda awesome, right?"); Console.Read(); } public static void CallAddTwo(CounterPayload payload) { Console.WriteLine("Calling payload.AddTwo()"); payload.AddTwo(); } } }
using Bands.Output; using System; namespace Bands.GettingStarted { class Program { static void Main(string[] args) { Console.WriteLine("Getting started with Bands!"); var payload = new CounterPayload(); var innerConsoleBand = new ConsoleWriterBand<CounterPayload>(CallAddTwo); var incrementableBand = new IncrementableBand<CounterPayload>(innerConsoleBand); var outerConsoleBand = new ConsoleWriterBand<CounterPayload>(incrementableBand); outerConsoleBand.Enter(payload); Console.WriteLine("Kinda badass, right?"); Console.Read(); } public static void CallAddTwo(CounterPayload payload) { Console.WriteLine("Calling payload.AddTwo()"); payload.AddTwo(); } } }
mit
C#
e8c7f5da19d4bbbf2b1da524c04d778ae9c8c928
Prepare release 4.5.4 - update file version. Work Item #1920
CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork,CslaGenFork/CslaGenFork
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
trunk/Solutions/CslaGenFork/Properties/AssemblyInfo.cs
using System; 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("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2015")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyVersion("4.5.3")] [assembly: AssemblyFileVersionAttribute("4.5.3")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
using System; 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("Csla Generator Fork")] [assembly: AssemblyDescription("CSLA.NET Business Objects and Data Access Layer code generation tool.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CslaGenFork Project")] [assembly: AssemblyProduct("Csla Generator Fork")] [assembly: AssemblyCopyright("Copyright CslaGen Project 2007, 2009\r\nCopyright Tiago Freitas Leal 2009, 2015")] [assembly: AssemblyTrademark("All Rights Reserved.")] [assembly: AssemblyCulture("")] [assembly: CLSCompliant(false)] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.3.*")] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyFile("")] [assembly: AssemblyKeyName("")] [assembly: AssemblyFileVersionAttribute("4.5.3")] [assembly: GuidAttribute("5c019c4f-d2ab-40dd-9860-70bd603b6017")] [assembly: ComVisibleAttribute(false)]
mit
C#
f6a35c5490f1d35db4a3c22bb60ec188a3f88ac4
Support for parsing inequality operator with integral operands.
TestStack/TestStack.FluentMVCTesting
TestStack.FluentMVCTesting.Tests/Internal/ExpressionInspectorTests.cs
TestStack.FluentMVCTesting.Tests/Internal/ExpressionInspectorTests.cs
using NUnit.Framework; using System; using System.Linq.Expressions; using TestStack.FluentMVCTesting.Internal; namespace TestStack.FluentMVCTesting.Tests.Internal { [TestFixture] public class ExpressionInspectorShould { [Test] public void Correctly_parse_equality_comparison_with_string_operands() { Expression<Func<string, bool>> func = text => text == "any"; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("text => text == \"any\"", actual); } [Test] public void Correctly_parse_equality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number == 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number == 5", actual); } [Test] public void Correctly_parse_inequality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number != 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number != 5", actual); } } }
using NUnit.Framework; using System; using System.Linq.Expressions; using TestStack.FluentMVCTesting.Internal; namespace TestStack.FluentMVCTesting.Tests.Internal { [TestFixture] public class ExpressionInspectorShould { [Test] public void Correctly_parse_equality_comparison_with_string_operands() { Expression<Func<string, bool>> func = text => text == "any"; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("text => text == \"any\"", actual); } [Test] public void Correctly_parse_equality_comparison_with_int_operands() { Expression<Func<int, bool>> func = number => number == 5; ExpressionInspector sut = new ExpressionInspector(); var actual = sut.Inspect(func); Assert.AreEqual("number => number == 5", actual); } } }
mit
C#
ce5f62aa6c8ee24ac1620d457b9ee7963ff84578
Fix failing test ORDRSP after change on Condition stacking behavior
indice-co/EDI.Net
test/indice.Edi.Tests/Models/EdiFact_ORDRSP_Conditions.cs
test/indice.Edi.Tests/Models/EdiFact_ORDRSP_Conditions.cs
using indice.Edi.Serialization; using System; using System.Collections.Generic; namespace indice.Edi.Tests.Models { public class Interchange_ORDRSP { public Message_ORDRSP Message { get; set; } } [EdiMessage] public class Message_ORDRSP { [EdiCondition("Z01", "Z10", Path = "IMD/1/0")] public List<IMD> IMD_List { get; set; } [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")] public IMD IMD_Other { get; set; } /// <summary> /// Item Description /// </summary> [EdiSegment, EdiPath("IMD")] public class IMD { [EdiValue(Path = "IMD/0")] public string FieldA { get; set; } [EdiValue(Path = "IMD/1")] public string FieldB { get; set; } [EdiValue(Path = "IMD/2")] public string FieldC { get; set; } } } }
using indice.Edi.Serialization; using System; using System.Collections.Generic; namespace indice.Edi.Tests.Models { public class Interchange_ORDRSP { public Message_ORDRSP Message { get; set; } } [EdiMessage] public class Message_ORDRSP { [EdiCondition("Z01", Path = "IMD/1/0")] [EdiCondition("Z10", Path = "IMD/1/0")] public List<IMD> IMD_List { get; set; } [EdiCondition("Z01", "Z10", CheckFor = EdiConditionCheckType.NotEqual, Path = "IMD/1/0")] public IMD IMD_Other { get; set; } /// <summary> /// Item Description /// </summary> [EdiSegment, EdiPath("IMD")] public class IMD { [EdiValue(Path = "IMD/0")] public string FieldA { get; set; } [EdiValue(Path = "IMD/1")] public string FieldB { get; set; } [EdiValue(Path = "IMD/2")] public string FieldC { get; set; } } } }
mit
C#
6aeec82b39f6b0cd2c785f23d8baca752c5b9651
throw if object not loaded
HarshPoint/HarshPoint,NaseUkolyCZ/HarshPoint,the-ress/HarshPoint
HarshPoint/Extensions/ClientObjectExtensions.cs
HarshPoint/Extensions/ClientObjectExtensions.cs
using Microsoft.SharePoint.Client; using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace HarshPoint { internal static class ClientObjectExtensions { public static Boolean IsNull(this ClientObject clientObject) { if (clientObject == null) { return true; } if (clientObject.ServerObjectIsNull.HasValue) { return clientObject.ServerObjectIsNull.Value; } throw new InvalidOperationException(SR.ClientObject_IsNullNotLoaded); } public static Boolean IsPropertyAvailable<T>(this T clientObject, Expression<Func<T, Object>> expression) where T : ClientObject { if (clientObject == null) { throw Error.ArgumentNull(nameof(clientObject)); } if (expression == null) { throw Error.ArgumentNull(nameof(expression)); } return clientObject.IsPropertyAvailable(expression.GetMemberName()); } public static async Task<TResult> EnsurePropertyAvailable<T, TResult>(this T clientObject, Expression<Func<T, TResult>> expression) where T : ClientObject { if (clientObject == null) { throw Error.ArgumentNull(nameof(clientObject)); } if (expression == null) { throw Error.ArgumentNull(nameof(expression)); } var objectExpression = expression.ConvertToObject(); var compiledExpression = expression.Compile(); if (!IsPropertyAvailable(clientObject, objectExpression)) { clientObject.Context.Load(clientObject, objectExpression); await clientObject.Context.ExecuteQueryAsync(); } return compiledExpression(clientObject); } } }
using Microsoft.SharePoint.Client; using System; using System.Linq.Expressions; using System.Threading.Tasks; namespace HarshPoint { internal static class ClientObjectExtensions { public static Boolean IsNull(this ClientObject clientObject) { if (clientObject == null) { return true; } if (clientObject.ServerObjectIsNull.HasValue) { return clientObject.ServerObjectIsNull.Value; } return false; } public static Boolean IsPropertyAvailable<T>(this T clientObject, Expression<Func<T, Object>> expression) where T : ClientObject { if (clientObject == null) { throw Error.ArgumentNull(nameof(clientObject)); } if (expression == null) { throw Error.ArgumentNull(nameof(expression)); } return clientObject.IsPropertyAvailable(expression.GetMemberName()); } public static async Task<TResult> EnsurePropertyAvailable<T, TResult>(this T clientObject, Expression<Func<T, TResult>> expression) where T : ClientObject { if (clientObject == null) { throw Error.ArgumentNull(nameof(clientObject)); } if (expression == null) { throw Error.ArgumentNull(nameof(expression)); } var objectExpression = expression.ConvertToObject(); var compiledExpression = expression.Compile(); if (!IsPropertyAvailable(clientObject, objectExpression)) { clientObject.Context.Load(clientObject, objectExpression); await clientObject.Context.ExecuteQueryAsync(); } return compiledExpression(clientObject); } } }
bsd-2-clause
C#
25913023561f76043e11ff0813b2c8ece57274b5
Make ResponseExceptions constructor public CTR
apache/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,robertdale/tinkerpop,krlohnes/tinkerpop,pluradj/incubator-tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,apache/incubator-tinkerpop,robertdale/tinkerpop,apache/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,robertdale/tinkerpop,pluradj/incubator-tinkerpop
gremlin-dotnet/src/Gremlin.Net/Driver/Exceptions/ResponseException.cs
gremlin-dotnet/src/Gremlin.Net/Driver/Exceptions/ResponseException.cs
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System; namespace Gremlin.Net.Driver.Exceptions { /// <summary> /// The exception that is thrown when a response is received from Gremlin Server that indicates that an error occurred. /// </summary> public class ResponseException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ResponseException" /> class. /// </summary> /// <param name="message">The error message string.</param> public ResponseException(string message) : base(message) { } } }
#region License /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #endregion using System; namespace Gremlin.Net.Driver.Exceptions { /// <summary> /// The exception that is thrown when a response is received from Gremlin Server that indicates that an error occurred. /// </summary> public class ResponseException : Exception { internal ResponseException(string message) : base(message) { } } }
apache-2.0
C#
429265a8fb11b4953974f2c8aaa0d4ac33c83796
add routing
jaredthirsk/Machine,jaredthirsk/Machine,jaredthirsk/Machine
LionFire.Machine.Api/Controllers/ProcessesController.cs
LionFire.Machine.Api/Controllers/ProcessesController.cs
using LionFire.Machine.Processes.Linux; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LionFire.Machine.Api.Controllers { [Route("[controller]")] public class ProcessesController : Controller { //[HttpGet("[action]")] [HttpGet] public LoadAvgFile LoadAvg() { return LoadAvgFile.Retrieve(); } } }
using LionFire.Machine.Processes.Linux; using Microsoft.AspNet.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LionFire.Machine.Api.Controllers { //[Route("machine/[controller]")] public class ProcessesController : Controller { //[HttpGet("[action]")] public LoadAvgFile LoadAvg() { return LoadAvgFile.Retrieve(); } } }
mit
C#
fdbe7f99800c0b88cac514a0bd08f5c000a47b74
reset if one player dies
Ross-Byrne/HistoryBeatDown
Assets/Scripts/CharacterStatus.cs
Assets/Scripts/CharacterStatus.cs
using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; public class CharacterStatus : MonoBehaviour { public int LivePoints = 100; public int DamagePerHit = 10; public AudioClip hitSFX; AudioSource _audio; // Use this for initialization void Start () { _audio = GetComponent<AudioSource> (); } // Update is called once per frame void Update () { } void OnTriggerEnter2D (Collider2D coll) { Debug.Log (coll); if (coll.gameObject.tag == "Projectile") { Destroy (coll.gameObject); HandleHit (); } } void HandleHit () { //todo //Debug.Log("Hit " + this.gameObject.tag); LivePoints -= DamagePerHit; _audio.PlayOneShot (hitSFX); if (LivePoints <= 0) HandleDeath (); } void HandleDeath() { Debug.Log("Died " + this.gameObject.tag); SceneManager.LoadScene(SceneManager.GetActiveScene().name); } }
using UnityEngine; using System.Collections; public class CharacterStatus : MonoBehaviour { public int LivePoints = 100; public int DamagePerHit = 10; public AudioClip hitSFX; AudioSource _audio; // Use this for initialization void Start () { _audio = GetComponent<AudioSource> (); } // Update is called once per frame void Update () { } void OnTriggerEnter2D (Collider2D coll) { Debug.Log (coll); if (coll.gameObject.tag == "Projectile") { Destroy (coll.gameObject); HandleHit (); } } void HandleHit () { //todo //Debug.Log("Hit " + this.gameObject.tag); LivePoints -= DamagePerHit; _audio.PlayOneShot (hitSFX); if (LivePoints <= 0) HandleDeath (); } void HandleDeath() { Debug.Log("Died " + this.gameObject.tag); } }
mit
C#
fd59da011c917a007dc9e2f120a16cfd29593e60
change tramp color
spencewenski/Vision
Assets/Scripts/ProjectileTramp.cs
Assets/Scripts/ProjectileTramp.cs
using UnityEngine; using System.Collections; public class ProjectileTramp : Projectile { void Awake() { rigidBody = GetComponent<Rigidbody>(); // SET EFFECT IN YOUR AWAKE FUNCTION effect = Cube.CubeEffect_e.TRAMP; outlineColor = (Color.green + Color.black)/2; accentColor = Color.green; } }
using UnityEngine; using System.Collections; public class ProjectileTramp : Projectile { void Awake() { rigidBody = GetComponent<Rigidbody>(); // SET EFFECT IN YOUR AWAKE FUNCTION effect = Cube.CubeEffect_e.TRAMP; outlineColor = Color.green; accentColor = (Color.green + Color.white)/2; } }
mit
C#
c67b00eca7ca3cb42e02b5a1a5ea56ba9f4d4bb8
Verify error checking
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
Snittlistan.Test/MatchController_EditDetails.cs
Snittlistan.Test/MatchController_EditDetails.cs
using System; using System.Web.Mvc; using MvcContrib.TestHelper; using Snittlistan.Controllers; using Snittlistan.Models; using Snittlistan.ViewModels; using Xunit; namespace Snittlistan.Test { public class MatchController_EditDetails : DbTest { [Fact] public void CanEditDetails() { // Arrange var then = DateTime.Now.AddDays(-1); Match originalMatch = new Match("Place", then, 1, new Team("Home", 13), new Team("Away", 6)); Session.Store(originalMatch); Session.SaveChanges(); WaitForNonStaleResults<Match>(); // Act var controller = new MatchController(Session); var now = DateTime.Now; var result = controller.EditDetails(new MatchViewModel.MatchDetails { Id = originalMatch.Id, Location = "NewPlace", Date = now, BitsMatchId = 2 }); // Assert result.AssertActionRedirect().ToAction("Details").WithParameter("id", originalMatch.Id); var match = Session.Load<Match>(originalMatch.Id); match.Location.ShouldBe("NewPlace"); match.Date.ShouldBe(now); match.BitsMatchId.ShouldBe(2); } [Fact] public void CannotEditNonExistingMatch() { var controller = new MatchController(Session); var result = controller.EditDetails(1); // Assert result.AssertResultIs<HttpNotFoundResult>(); } [Fact] public void CannotPostNonExistingMatch() { var controller = new MatchController(Session); var result = controller.EditDetails(new MatchViewModel.MatchDetails { Id = 1 }); // Assert result.AssertResultIs<HttpNotFoundResult>(); } [Fact] public void CorrectView() { // Arrange var match = DbSeed.CreateMatch(); Session.Store(match); // Act var controller = new MatchController(Session); var result = controller.EditDetails(match.Id); // Assert result.AssertViewRendered().ForView(string.Empty); } [Fact] public void WhenErrorReturnView() { // Arrange var controller = new MatchController(Session); controller.ModelState.AddModelError("key", "error"); // Act var result = controller.EditDetails(null); // Assert result.AssertViewRendered().ForView(string.Empty); } } }
using System; using System.Web.Mvc; using MvcContrib.TestHelper; using Snittlistan.Controllers; using Snittlistan.Models; using Snittlistan.ViewModels; using Xunit; namespace Snittlistan.Test { public class MatchController_EditDetails : DbTest { [Fact] public void CanEditDetails() { // Arrange var then = DateTime.Now.AddDays(-1); Match originalMatch = new Match("Place", then, 1, new Team("Home", 13), new Team("Away", 6)); Session.Store(originalMatch); Session.SaveChanges(); WaitForNonStaleResults<Match>(); // Act var controller = new MatchController(Session); var now = DateTime.Now; var result = controller.EditDetails(new MatchViewModel.MatchDetails { Id = originalMatch.Id, Location = "NewPlace", Date = now, BitsMatchId = 2 }); // Assert result.AssertActionRedirect().ToAction("Details").WithParameter("id", originalMatch.Id); var match = Session.Load<Match>(originalMatch.Id); match.Location.ShouldBe("NewPlace"); match.Date.ShouldBe(now); match.BitsMatchId.ShouldBe(2); } [Fact] public void CannotEditNonExistingMatch() { var controller = new MatchController(Session); var result = controller.EditDetails(1); // Assert result.AssertResultIs<HttpNotFoundResult>(); } [Fact] public void CannotPostNonExistingMatch() { var controller = new MatchController(Session); var result = controller.EditDetails(new MatchViewModel.MatchDetails { Id = 1 }); // Assert result.AssertResultIs<HttpNotFoundResult>(); } [Fact] public void CorrectView() { // Arrange var match = DbSeed.CreateMatch(); Session.Store(match); // Act var controller = new MatchController(Session); var result = controller.EditDetails(match.Id); // Assert result.AssertViewRendered().ForView(string.Empty); } } }
mit
C#
8d9a36e2c2211bc13be7b1d9ed997c88a76f5ebd
return name on ToString in GenericTypeInfo
tareq-s/Typewriter,coolkev/Typewriter,johannordin/Typewriter,frhagn/Typewriter,SeriousM/Typewriter
Typewriter/CodeModel/CodeDom/GenericTypeInfo.cs
Typewriter/CodeModel/CodeDom/GenericTypeInfo.cs
using System; using System.Collections.Generic; namespace Typewriter.CodeModel.CodeDom { internal class GenericTypeInfo : Type { private readonly string fullName; private readonly object parent; private readonly FileInfo file; public GenericTypeInfo(string fullName, object parent, FileInfo file) { this.fullName = fullName; this.parent = parent; this.file = file; } public ICollection<Attribute> Attributes => new Attribute[0]; public ICollection<Constant> Constants => new Constant[0]; public ICollection<Field> Fields => new Field[0]; public Class BaseClass => null; public string FullName => fullName; public IEnumerable<Type> GenericTypeArguments => new Type[0]; public ICollection<Interface> Interfaces => new Interface[0]; public bool IsEnum => false; public bool IsEnumerable => false; public bool IsGeneric => false; public bool IsNullable => false; public bool IsPrimitive => false; public ICollection<Method> Methods => new Method[0]; public string Name => fullName; public string Namespace => null; public object Parent => parent; public ICollection<Property> Properties => new Property[0]; public override string ToString() { return fullName; } } }
using System; using System.Collections.Generic; namespace Typewriter.CodeModel.CodeDom { internal class GenericTypeInfo : Type { private readonly string fullName; private readonly object parent; private readonly FileInfo file; public GenericTypeInfo(string fullName, object parent, FileInfo file) { this.fullName = fullName; this.parent = parent; this.file = file; } public ICollection<Attribute> Attributes => new Attribute[0]; public ICollection<Constant> Constants => new Constant[0]; public ICollection<Field> Fields => new Field[0]; public Class BaseClass => null; public string FullName => fullName; public IEnumerable<Type> GenericTypeArguments => new Type[0]; public ICollection<Interface> Interfaces => new Interface[0]; public bool IsEnum => false; public bool IsEnumerable => false; public bool IsGeneric => false; public bool IsNullable => false; public bool IsPrimitive => false; public ICollection<Method> Methods => new Method[0]; public string Name => fullName; public string Namespace => null; public object Parent => parent; public ICollection<Property> Properties => new Property[0]; } }
apache-2.0
C#
ab5459ac13606c020342b88623aa913979b60a17
Format file.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/NadekoBot/Services/Database/Repositories/ILevelModelRepository.cs
src/NadekoBot/Services/Database/Repositories/ILevelModelRepository.cs
using System; using System.Linq; using Mitternacht.Services.Database.Models; namespace Mitternacht.Services.Database.Repositories { public interface ILevelModelRepository : IRepository<LevelModel> { LevelModel GetOrCreate(ulong guildId, ulong userId); LevelModel Get(ulong guildId, ulong userId); void AddXp(ulong guildId, ulong userId, int xp, ulong? channelId = null); void SetXp(ulong guildId, ulong userId, int xp, ulong? channelId = null); void SetLevel(ulong guildId, ulong userId, int level, ulong? channelId = null); bool CanGetMessageXp(ulong guildId, ulong userId, DateTime time); void ReplaceTimestamp(ulong guildId, ulong userId, DateTime timestamp); IOrderedQueryable<LevelModel> GetAllSortedForRanks(ulong guildId, ulong[] guildUserIds); } public class LevelChangedArgs { public ulong GuildId { get; } public ulong UserId { get; } public int OldLevel { get; } public int NewLevel { get; } public ulong? ChannelId { get; } public ChangeTypes ChangeType => OldLevel < NewLevel ? ChangeTypes.Up : ChangeTypes.Down; public LevelChangedArgs(ulong guildId, ulong userId, int oldLevel, int newLevel, ulong? channelId = null) { GuildId = guildId; UserId = userId; OldLevel = oldLevel; NewLevel = newLevel; ChannelId = channelId; } public enum ChangeTypes { Up, Down } } }
using System; using System.Linq; using Mitternacht.Services.Database.Models; namespace Mitternacht.Services.Database.Repositories { public interface ILevelModelRepository : IRepository<LevelModel> { LevelModel GetOrCreate(ulong guildId, ulong userId); LevelModel Get(ulong guildId, ulong userId); void AddXp(ulong guildId, ulong userId, int xp, ulong? channelId = null); void SetXp(ulong guildId, ulong userId, int xp, ulong? channelId = null); void SetLevel(ulong guildId, ulong userId, int level, ulong? channelId = null); bool CanGetMessageXp(ulong guildId, ulong userId, DateTime time); void ReplaceTimestamp(ulong guildId, ulong userId, DateTime timestamp); IOrderedQueryable<LevelModel> GetAllSortedForRanks(ulong guildId, ulong[] guildUserIds); } public class LevelChangedArgs { public ulong GuildId { get; } public ulong UserId { get; } public int OldLevel { get; } public int NewLevel { get; } public ulong? ChannelId { get; } public ChangeTypes ChangeType => OldLevel < NewLevel ? ChangeTypes.Up : ChangeTypes.Down; public LevelChangedArgs(ulong guildId, ulong userId, int oldLevel, int newLevel, ulong? channelId = null) { GuildId = guildId; UserId = userId; OldLevel = oldLevel; NewLevel = newLevel; ChannelId = channelId; } public enum ChangeTypes { Up, Down } } }
mit
C#
92b13471b506b29341d0aef73c52d635e59a6220
Make sure that On-Premise Connector cleans up on Windows shutdown
thinktecture/relayserver,jasminsehic/relayserver,jasminsehic/relayserver,jasminsehic/relayserver,thinktecture/relayserver,thinktecture/relayserver
Thinktecture.Relay.OnPremiseConnectorService/Program.cs
Thinktecture.Relay.OnPremiseConnectorService/Program.cs
using System; using System.Diagnostics; using Serilog; using Topshelf; namespace Thinktecture.Relay.OnPremiseConnectorService { internal static class Program { private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); try { HostFactory.Run(config => { config.UseSerilog(); config.EnableShutdown(); config.Service<OnPremisesService>(settings => { settings.ConstructUsing(_ => new OnPremisesService()); settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false)); settings.WhenStopped(s => s.Stop()); settings.WhenShutdown(s => s.Stop()); }); config.RunAsNetworkService(); config.SetDescription("Thinktecture Relay OnPremises Service"); config.SetDisplayName("Thinktecture Relay OnPremises Service"); config.SetServiceName("TTRelayOnPremisesService"); }); } catch (Exception ex) { Log.Logger.Fatal(ex, "Service crashed"); } finally { Log.CloseAndFlush(); } Log.CloseAndFlush(); #if DEBUG if (Debugger.IsAttached) { // ReSharper disable once LocalizableElement Console.WriteLine("\nPress any key to close application window..."); Console.ReadKey(true); } #endif } } }
using System; using System.Diagnostics; using Serilog; using Topshelf; namespace Thinktecture.Relay.OnPremiseConnectorService { internal static class Program { private static void Main(string[] args) { Log.Logger = new LoggerConfiguration() .ReadFrom.AppSettings() .CreateLogger(); try { HostFactory.Run(config => { config.UseSerilog(); config.Service<OnPremisesService>(settings => { settings.ConstructUsing(_ => new OnPremisesService()); settings.WhenStarted(async s => await s.StartAsync().ConfigureAwait(false)); settings.WhenStopped(s => s.Stop()); }); config.RunAsNetworkService(); config.SetDescription("Thinktecture Relay OnPremises Service"); config.SetDisplayName("Thinktecture Relay OnPremises Service"); config.SetServiceName("TTRelayOnPremisesService"); }); } catch (Exception ex) { Log.Logger.Fatal(ex, "Service crashed"); } finally { Log.CloseAndFlush(); } Log.CloseAndFlush(); #if DEBUG if (Debugger.IsAttached) { // ReSharper disable once LocalizableElement Console.WriteLine("\nPress any key to close application window..."); Console.ReadKey(true); } #endif } } }
bsd-3-clause
C#
d1c44e95ae1dfbe3808962e4fb2be4fe6178d25a
Check scene name before PlayerList Reset
Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,krille90/unitystation
UnityProject/Assets/Scripts/PlayGroups/PlayerManager.cs
UnityProject/Assets/Scripts/PlayGroups/PlayerManager.cs
using UnityEngine; using UnityEngine.SceneManagement; //Handles control and spawn of player prefab namespace PlayGroup { public class PlayerManager : MonoBehaviour { private static PlayerManager playerManager; public static GameObject LocalPlayer { get; private set; } public static Equipment.Equipment Equipment { get; private set; } public static PlayerScript LocalPlayerScript { get; private set; } //For access via other parts of the game public static PlayerScript PlayerScript { get; private set; } public static bool HasSpawned { get; private set; } //To fix playername bug when running two instances on 1 machine public static string PlayerNameCache { get; set; } public static PlayerManager Instance { get { if (!playerManager) { playerManager = FindObjectOfType<PlayerManager>(); } return playerManager; } } private void OnEnable() { SceneManager.sceneLoaded += OnLevelFinishedLoading; } private void OnDisable() { SceneManager.sceneLoaded -= OnLevelFinishedLoading; } private void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) { Reset(); if (scene.name != "Lobby") { PlayerList.Instance.ResetSyncedState(); } } public static void Reset() { HasSpawned = false; } public static void SetPlayerForControl(GameObject playerObjToControl) { LocalPlayer = playerObjToControl; LocalPlayerScript = playerObjToControl.GetComponent<PlayerScript>(); PlayerScript = LocalPlayerScript; // Set this on the manager so it can be accessed by other components/managers Camera2DFollow.followControl.target = LocalPlayer.transform; HasSpawned = true; } public static bool PlayerInReach(Transform transform) { if (PlayerScript != null) { return PlayerScript.IsInReach(transform.position); } return false; } } }
using UnityEngine; using UnityEngine.SceneManagement; //Handles control and spawn of player prefab namespace PlayGroup { public class PlayerManager : MonoBehaviour { private static PlayerManager playerManager; public static GameObject LocalPlayer { get; private set; } public static Equipment.Equipment Equipment { get; private set; } public static PlayerScript LocalPlayerScript { get; private set; } //For access via other parts of the game public static PlayerScript PlayerScript { get; private set; } public static bool HasSpawned { get; private set; } //To fix playername bug when running two instances on 1 machine public static string PlayerNameCache { get; set; } public static PlayerManager Instance { get { if (!playerManager) { playerManager = FindObjectOfType<PlayerManager>(); } return playerManager; } } private void OnEnable() { SceneManager.sceneLoaded += OnLevelFinishedLoading; } private void OnDisable() { SceneManager.sceneLoaded -= OnLevelFinishedLoading; } private void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode) { Reset(); PlayerList.Instance.ResetSyncedState(); } public static void Reset() { HasSpawned = false; } public static void SetPlayerForControl(GameObject playerObjToControl) { LocalPlayer = playerObjToControl; LocalPlayerScript = playerObjToControl.GetComponent<PlayerScript>(); PlayerScript = LocalPlayerScript; // Set this on the manager so it can be accessed by other components/managers Camera2DFollow.followControl.target = LocalPlayer.transform; HasSpawned = true; } public static bool PlayerInReach(Transform transform) { if (PlayerScript != null) { return PlayerScript.IsInReach(transform.position); } return false; } } }
agpl-3.0
C#
5f72c8ad786932aa7aad187f19183f59a0ef18f2
Fix .netcore versions
adoconnection/AspNetDeploy,adoconnection/AspNetDeploy,adoconnection/AspNetDeploy
Packagers.VisualStudioProject/DotNetCoreProjectPackager.cs
Packagers.VisualStudioProject/DotNetCoreProjectPackager.cs
using System; using System.IO; using System.Linq; using System.Xml.Linq; using Ionic.Zip; namespace Packagers.VisualStudioProject { public class DotNetCoreProjectPackager : VisualStudioProjectPackager { protected override void PackageProjectContents(ZipFile zipFile, XDocument xDocument, XNamespace vsNamespace, string projectRootFolder) { XElement targetFramework = xDocument.Descendants("TargetFramework").FirstOrDefault(); if (targetFramework == null) { throw new VisualStudioPackagerException("targetFramework not set"); } if (!this.IsFrameworkSupported(targetFramework.Value)) { throw new VisualStudioPackagerException("targetFramework not supported: " + targetFramework.Value); } AddProjectDirectory( zipFile, projectRootFolder, Path.Combine("bin", "Release", targetFramework.Value, "publish"), "\\"); } private bool IsFrameworkSupported(string targetFramework) { if (targetFramework.Equals("netcoreapp2.0", StringComparison.InvariantCultureIgnoreCase)) { return true; } if (targetFramework.Equals("netcoreapp2.1", StringComparison.InvariantCultureIgnoreCase)) { return true; } if (targetFramework.Equals("netcoreapp2.2", StringComparison.InvariantCultureIgnoreCase)) { return true; } if (targetFramework.Equals("netcoreapp2.3", StringComparison.InvariantCultureIgnoreCase)) { return true; } return false; } } }
using System; using System.IO; using System.Linq; using System.Xml.Linq; using Ionic.Zip; namespace Packagers.VisualStudioProject { public class DotNetCoreProjectPackager : VisualStudioProjectPackager { protected override void PackageProjectContents(ZipFile zipFile, XDocument xDocument, XNamespace vsNamespace, string projectRootFolder) { XElement targetFramework = xDocument.Descendants("TargetFramework").FirstOrDefault(); if (targetFramework == null) { throw new VisualStudioPackagerException("targetFramework not set"); } if (!targetFramework.Value.Equals("netcoreapp2.0", StringComparison.InvariantCultureIgnoreCase)) { throw new VisualStudioPackagerException("targetFramework not supported: " + targetFramework.Value); } AddProjectDirectory( zipFile, projectRootFolder, Path.Combine("bin", "Release", targetFramework.Value, "publish"), "\\"); } } }
apache-2.0
C#
878ea878713a98a1058897b5a6d50d49130cea74
Comment added
codeforgebelgrade/Diablo3-API-Library
Diablo3APIDemo/MainWindow.xaml.cs
Diablo3APIDemo/MainWindow.xaml.cs
using System.Windows; using Codeforge.Diablo3InfoClasses; using Codeforge.Diablo3Info; using Newtonsoft.Json; namespace Diablo3APIDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// This project serves simply as a demo project - an example showing how to use the library /// The values used below are set to EU region and en_GB as locale /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnSendProfileRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); ProfileInfo profileInfoResponse = DiabloService.GetProfileInfo(RequestParameters.REGIONS.EU, tbBattleTag.Text, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(profileInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendCharacterRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); CharacterInfo charInfoResponse = DiabloService.GetCharacterInfo(RequestParameters.REGIONS.EU, tbBattleTag.Text, tbHeroId.Text, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(charInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendArtisanRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); ArtisanInfo artisanInfoResponse = DiabloService.GetArtisanInfo(RequestParameters.REGIONS.EU, RequestParameters.ARTISANS.BLACKSMITH, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(artisanInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendFollowerRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); FollowerInfo followerInfoResponse = DiabloService.GetFollowerInfo(RequestParameters.REGIONS.EU, RequestParameters.FOLLOWERS.TEMPLAR, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(followerInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } } }
using System.Windows; using Codeforge.Diablo3InfoClasses; using Codeforge.Diablo3Info; using Newtonsoft.Json; namespace Diablo3APIDemo { /// <summary> /// Interaction logic for MainWindow.xaml /// This project serves simply as a demo project - an example showing how to use the library /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void btnSendProfileRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); ProfileInfo profileInfoResponse = DiabloService.GetProfileInfo(RequestParameters.REGIONS.EU, tbBattleTag.Text, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(profileInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendCharacterRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); CharacterInfo charInfoResponse = DiabloService.GetCharacterInfo(RequestParameters.REGIONS.EU, tbBattleTag.Text, tbHeroId.Text, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(charInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendArtisanRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); ArtisanInfo artisanInfoResponse = DiabloService.GetArtisanInfo(RequestParameters.REGIONS.EU, RequestParameters.ARTISANS.BLACKSMITH, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(artisanInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } private void btnSendFollowerRequest_Click(object sender, RoutedEventArgs e) { tbJsonResponse.Clear(); FollowerInfo followerInfoResponse = DiabloService.GetFollowerInfo(RequestParameters.REGIONS.EU, RequestParameters.FOLLOWERS.TEMPLAR, "en_GB", tbApiKey.Text); string output = JsonConvert.SerializeObject(followerInfoResponse, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); tbJsonResponse.Text = output; } } }
mit
C#
2a2b4c1e3ba985759a44a22201159ae734b3db0f
Update CompositeMetricTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/CompositeMetricTelemeter.cs
TIKSN.Core/Analytics/Telemetry/CompositeMetricTelemeter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeMetricTelemeter : IMetricTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<IMetricTelemeter> metricTelemeters; public CompositeMetricTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<IMetricTelemeter> metricTelemeters) { this.commonConfiguration = commonConfiguration; this.metricTelemeters = metricTelemeters; } public async Task TrackMetric(string metricName, decimal metricValue) { if (this.commonConfiguration.GetConfiguration().IsMetricTrackingEnabled) { foreach (var metricTelemeter in this.metricTelemeters) { try { await metricTelemeter.TrackMetric(metricName, metricValue); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeMetricTelemeter : IMetricTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<IMetricTelemeter> metricTelemeters; public CompositeMetricTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<IMetricTelemeter> metricTelemeters) { this.commonConfiguration = commonConfiguration; this.metricTelemeters = metricTelemeters; } public async Task TrackMetric(string metricName, decimal metricValue) { if (commonConfiguration.GetConfiguration().IsMetricTrackingEnabled) { foreach (var metricTelemeter in metricTelemeters) { try { await metricTelemeter.TrackMetric(metricName, metricValue); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
mit
C#
6ac2130398389751ecda91bd69adf0ef5666c274
Use better terminology
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework
osu.Framework/Screens/ScreenExitEvent.cs
osu.Framework/Screens/ScreenExitEvent.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Screens { public class ScreenExitEvent : ScreenEvent { /// <summary> /// The <see cref="IScreen"/> that will be resumed next. /// </summary> public IScreen Next; /// <summary> /// The final <see cref="IScreen"/> of this exit operation. /// </summary> public IScreen Destination; public ScreenExitEvent(IScreen next, IScreen destination) { Next = next; Destination = destination; } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Framework.Screens { public class ScreenExitEvent : ScreenEvent { /// <summary> /// The <see cref="IScreen"/> that will be resumed next. /// </summary> public IScreen Next; /// <summary> /// The final <see cref="IScreen"/> of an exit operation. /// </summary> public IScreen Destination; public ScreenExitEvent(IScreen next, IScreen destination) { Next = next; Destination = destination; } } }
mit
C#
54de1ce949994cad98a77d07cd909f72b213712f
Set message id by official's highest
insthync/suriyun-unity-iap
Assets/SuriyunUnityIAP/Scripts/Network/Messages/IAPNetworkMessageId.cs
Assets/SuriyunUnityIAP/Scripts/Network/Messages/IAPNetworkMessageId.cs
using UnityEngine.Networking; namespace Suriyun.UnityIAP { public class IAPNetworkMessageId { // Developer can changes these Ids to avoid hacking while hosting public const short ToServerBuyProductMsgId = MsgType.Highest + 201; public const short ToServerRequestProducts = MsgType.Highest + 202; public const short ToClientResponseProducts = MsgType.Highest + 203; } }
namespace Suriyun.UnityIAP { public class IAPNetworkMessageId { public const short ToServerBuyProductMsgId = 3000; public const short ToServerRequestProducts = 3001; public const short ToClientResponseProducts = 3002; } }
mit
C#
4f0bfe4b62d70b9aed73a45d52751a6bb937bfec
Add Obsolete attribute to AssetEx.Throws helper method
magoswiat/octokit.net,shana/octokit.net,shiftkey/octokit.net,octokit/octokit.net,takumikub/octokit.net,cH40z-Lord/octokit.net,eriawan/octokit.net,gdziadkiewicz/octokit.net,fake-organization/octokit.net,rlugojr/octokit.net,hahmed/octokit.net,thedillonb/octokit.net,dlsteuer/octokit.net,michaKFromParis/octokit.net,Red-Folder/octokit.net,Sarmad93/octokit.net,mminns/octokit.net,SLdragon1989/octokit.net,devkhan/octokit.net,gabrielweyer/octokit.net,dampir/octokit.net,shiftkey-tester/octokit.net,octokit-net-test-org/octokit.net,fffej/octokit.net,daukantas/octokit.net,darrelmiller/octokit.net,editor-tools/octokit.net,SamTheDev/octokit.net,ivandrofly/octokit.net,thedillonb/octokit.net,shiftkey/octokit.net,geek0r/octokit.net,chunkychode/octokit.net,nsrnnnnn/octokit.net,SamTheDev/octokit.net,brramos/octokit.net,gabrielweyer/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,hahmed/octokit.net,kolbasov/octokit.net,eriawan/octokit.net,bslliw/octokit.net,SmithAndr/octokit.net,adamralph/octokit.net,ivandrofly/octokit.net,shana/octokit.net,rlugojr/octokit.net,nsnnnnrn/octokit.net,kdolan/octokit.net,forki/octokit.net,naveensrinivasan/octokit.net,TattsGroup/octokit.net,octokit/octokit.net,chunkychode/octokit.net,M-Zuber/octokit.net,Sarmad93/octokit.net,octokit-net-test-org/octokit.net,editor-tools/octokit.net,devkhan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,hitesh97/octokit.net,M-Zuber/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,ChrisMissal/octokit.net,khellang/octokit.net,octokit-net-test/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester/octokit.net,khellang/octokit.net,alfhenrik/octokit.net,alfhenrik/octokit.net,dampir/octokit.net,mminns/octokit.net
Octokit.Tests/Helpers/AssertEx.cs
Octokit.Tests/Helpers/AssertEx.cs
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace Octokit.Tests.Helpers { public static class AssertEx { public static void WithMessage(Action assert, string message) { // TODO: we should just :fire: this to the ground assert(); } public static TAttribute HasAttribute<TAttribute>(MemberInfo memberInfo, bool inherit = false) where TAttribute : Attribute { var attribute = memberInfo.GetCustomAttribute<TAttribute>(inherit); Assert.NotNull(attribute); return attribute; } [Obsolete("This was written before the support for testing asynchronous tasks was added in xUnit 2.0 (because we pre-dated it). Use Assert.ThrowsAsync")] public async static Task<T> Throws<T>(Func<Task> testCode) where T : Exception { try { await testCode(); Assert.Throws<T>(() => { }); // Use xUnit's default behavior. } catch (T exception) { return exception; } // We should never reach this line. It's here because the compiler doesn't know that // Assert.Throws above will always throw. return null; } static readonly string[] whitespaceArguments = { " ", "\t", "\n", "\n\r", " " }; public static async Task ThrowsWhenGivenWhitespaceArgument(Func<string, Task> action) { foreach (var argument in whitespaceArguments) { await Throws<ArgumentException>(async () => await action(argument)); } } public static void IsReadOnlyCollection<T>(object instance) { var collection = instance as ICollection<T>; // The collection == null case is for .NET 4.0 Assert.True(instance is IReadOnlyList<T> && (collection == null || collection.IsReadOnly)); } public static void IsReadOnlyCollection(Type type) { var isReadOnlyList = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>); var isReadOnlyDictionary = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>); Assert.True(isReadOnlyList || isReadOnlyDictionary); } } }
using System; using System.Collections.Generic; using System.Reflection; using System.Threading.Tasks; using Xunit; namespace Octokit.Tests.Helpers { public static class AssertEx { public static void WithMessage(Action assert, string message) { // TODO: we should just :fire: this to the ground assert(); } public static TAttribute HasAttribute<TAttribute>(MemberInfo memberInfo, bool inherit = false) where TAttribute : Attribute { var attribute = memberInfo.GetCustomAttribute<TAttribute>(inherit); Assert.NotNull(attribute); return attribute; } public async static Task<T> Throws<T>(Func<Task> testCode) where T : Exception { try { await testCode(); Assert.Throws<T>(() => { }); // Use xUnit's default behavior. } catch (T exception) { return exception; } // We should never reach this line. It's here because the compiler doesn't know that // Assert.Throws above will always throw. return null; } static readonly string[] whitespaceArguments = { " ", "\t", "\n", "\n\r", " " }; public static async Task ThrowsWhenGivenWhitespaceArgument(Func<string, Task> action) { foreach (var argument in whitespaceArguments) { await Throws<ArgumentException>(async () => await action(argument)); } } public static void IsReadOnlyCollection<T>(object instance) { var collection = instance as ICollection<T>; // The collection == null case is for .NET 4.0 Assert.True(instance is IReadOnlyList<T> && (collection == null || collection.IsReadOnly)); } public static void IsReadOnlyCollection(Type type) { var isReadOnlyList = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyList<>); var isReadOnlyDictionary = type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IReadOnlyDictionary<,>); Assert.True(isReadOnlyList || isReadOnlyDictionary); } } }
mit
C#
ff93f81f7d90bd494811acfd42016dbfdbe64bc4
Add missing using statement from merge
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Controllers/ApprenticesController.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api/Controllers/ApprenticesController.cs
using System; using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SFA.DAS.CommitmentsV2.Application.Queries.GetApprovedApprentices; using SFA.DAS.CommitmentsV2.Application.Queries.GetApprovedApprenticesFilterValues; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class ApprenticesController : ControllerBase { private readonly IMediator _mediator; private readonly ILogger<ApprenticesController> _logger; public ApprenticesController(IMediator mediator, ILogger<ApprenticesController> logger) { _mediator = mediator; _logger = logger; } [HttpGet] [Route("{providerId}")] public async Task<IActionResult> GetApprovedApprentices(uint providerId) { try { var response = await _mediator.Send(new GetApprovedApprenticesRequest {ProviderId = providerId}); if (response == null) { return NotFound(); } return Ok(response.Apprenticeships); } catch (Exception e) { _logger.LogError(e, e.Message); throw; } } [HttpGet] [Route("filters/{providerId}")] public async Task<IActionResult> GetApprovedApprenticesFilterValues(uint providerId) { var response = await _mediator.Send(new GetApprovedApprenticesFilterValuesQuery { ProviderId = providerId }); if (response == null) { return NotFound(); } return Ok(response); } } }
using System.Threading.Tasks; using MediatR; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using SFA.DAS.CommitmentsV2.Application.Queries.GetApprovedApprentices; using SFA.DAS.CommitmentsV2.Application.Queries.GetApprovedApprenticesFilterValues; namespace SFA.DAS.CommitmentsV2.Api.Controllers { [Route("api/[controller]")] [ApiController] [Authorize] public class ApprenticesController : ControllerBase { private readonly IMediator _mediator; private readonly ILogger<ApprenticesController> _logger; public ApprenticesController(IMediator mediator, ILogger<ApprenticesController> logger) { _mediator = mediator; _logger = logger; } [HttpGet] [Route("{providerId}")] public async Task<IActionResult> GetApprovedApprentices(uint providerId) { try { var response = await _mediator.Send(new GetApprovedApprenticesRequest {ProviderId = providerId}); if (response == null) { return NotFound(); } return Ok(response.Apprenticeships); } catch (Exception e) { _logger.LogError(e, e.Message); throw; } } [HttpGet] [Route("filters/{providerId}")] public async Task<IActionResult> GetApprovedApprenticesFilterValues(uint providerId) { var response = await _mediator.Send(new GetApprovedApprenticesFilterValuesQuery { ProviderId = providerId }); if (response == null) { return NotFound(); } return Ok(response); } } }
mit
C#
d34c609d3626d3b4722b71486b3b2727207a6057
Update ConsumeFuelEvent.cs
Notulp/Pluton,Notulp/Pluton
Pluton/Events/ConsumeFuelEvent.cs
Pluton/Events/ConsumeFuelEvent.cs
using System; namespace Pluton.Events { public class ConsumeFuelEvent : CountedInstance { private BaseOven _baseOven; private InvItem _item; private ItemModBurnable _burn; public ConsumeFuelEvent(BaseOven bo, Item fuel, ItemModBurnable burn) { this._baseOven = bo; this._item = new InvItem(fuel); this._burn = burn; } public BaseOven BaseOven { get { return this._baseOven; } } public InvItem Item { get { return this._item; } } public ItemModBurnable Burnable { get { return this._burn; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Policy; using System.Text; namespace Pluton.Events { public class ConsumeFuelEvent { private BaseOven _baseOven; private InvItem _item; private ItemModBurnable _burn; public ConsumeFuelEvent(BaseOven bo, Item fuel, ItemModBurnable burn) { this._baseOven = bo; this._item = new InvItem(fuel); this._burn = burn; } public BaseOven BaseOven { get { return this._baseOven; } } public InvItem Item { get { return this._item; } } public ItemModBurnable Burnable { get { return this._burn; } } } }
mit
C#
94a7368b49b961068635c3f37dccd716701b60db
Upgrade 02 Editing Project
JetBrains/resharper-workshop,JetBrains/resharper-workshop,JetBrains/resharper-workshop
01-Navigation/4-Contextual_navigation/4.7-Navigate_To_menu_related_files_forms.cs
01-Navigation/4-Contextual_navigation/4.7-Navigate_To_menu_related_files_forms.cs
using System.Windows.Forms; namespace JetBrains.ReSharper.Koans.Navigation { // Navigate To menu // // Displays a contextual menu of options you can use to navigate to from // your current location // // Very useful way of navigating without having to learn ALL of the shortcuts! // // Alt+` (VS) // Ctrl+Shift+G (IntelliJ) // 1. Navigate to related files. E.g. related designer files // Put text caret here → // Navigate to Related Files shows list of other files containing definitions of Form1 public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace JetBrains.ReSharper.Koans.Navigation { // Navigate To menu // // Displays a contextual menu of options you can use to navigate to from // your current location // // Very useful way of navigating without having to learn ALL of the shortcuts! // // Alt+` (VS) // Ctrl+Shift+G (IntelliJ) // 1. Navigate to related files. E.g. related designer files // Put text caret here → // Navigate to Related Files shows list of other files containing definitions of Form1 public partial class Form1 : Form { public Form1() { InitializeComponent(); } } }
apache-2.0
C#
24b314b51f9c5c28be61b09fa6f56558c03c8100
Fix hold note masks not working
ZLima12/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,NeoAdonis/osu,NeoAdonis/osu,ZLima12/osu,naoey/osu,UselessToucan/osu,peppy/osu-new,naoey/osu,naoey/osu,DrabWeb/osu,peppy/osu,ppy/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu
osu.Game.Rulesets.Mania/Edit/Layers/Selection/Overlays/HoldNoteMask.cs
osu.Game.Rulesets.Mania/Edit/Layers/Selection/Overlays/HoldNoteMask.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class HoldNoteMask : HitObjectMask { private readonly BodyPiece body; public HoldNoteMask(DrawableHoldNote hold) : base(hold) { var holdObject = hold.HitObject; InternalChildren = new Drawable[] { new HoldNoteNoteMask(hold.Head), new HoldNoteNoteMask(hold.Tail), body = new BodyPiece { AccentColour = Color4.Transparent }, }; holdObject.ColumnChanged += _ => Position = hold.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; } protected override void Update() { base.Update(); Size = HitObject.DrawSize; Position = Parent.ToLocalSpace(HitObject.ScreenSpaceDrawQuad.TopLeft); } private class HoldNoteNoteMask : NoteMask { public HoldNoteNoteMask(DrawableNote note) : base(note) { Select(); } protected override void Update() { base.Update(); Position = HitObject.DrawPosition; } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Objects.Drawables.Pieces; using OpenTK.Graphics; namespace osu.Game.Rulesets.Mania.Edit.Layers.Selection.Overlays { public class HoldNoteMask : HitObjectMask { private readonly BodyPiece body; public HoldNoteMask(DrawableHoldNote hold) : base(hold) { Position = hold.Position; var holdObject = hold.HitObject; InternalChildren = new Drawable[] { new NoteMask(hold.Head), new NoteMask(hold.Tail), body = new BodyPiece { AccentColour = Color4.Transparent }, }; holdObject.ColumnChanged += _ => Position = hold.Position; } [BackgroundDependencyLoader] private void load(OsuColour colours) { body.BorderColour = colours.Yellow; } } }
mit
C#
d39de969c06f189b85428194a002bd42720faa0c
test resize
lnl122/Solver2
Solver2/Solver2/Form1.Designer.cs
Solver2/Solver2/Form1.Designer.cs
namespace Solver2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(926, 362); this.Name = "Form1"; this.Text = "name of app"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion } }
namespace Solver2 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 262); this.Name = "Form1"; this.Text = "name of app"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion } }
mit
C#
6a5a224c87ebef5fab31e345cae88a5de882c632
Update SimpleProoperty.cs
maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt
CSharp/Class/SimpleProoperty.cs
CSharp/Class/SimpleProoperty.cs
using System; public class Program { public static void Main() {} } public class Pessoa { public string Nome { get; set; } public string Endereço { get; set; } public int Ano_nascimento { get; set; } public int Idade { get; set; } public string Telefone { get; set; } public Pessoa(string nome, string endereço, int ano_nascimento, string telefone) { Nome = nome; Endereço = endereço; Ano_nascimento = ano_nascimento; Telefone = telefone; Idade = DateTime.Now.Year - ano_nascimento; } } public class Fisica : Pessoa { public string NmmCPF { get; private set; } public Fisica(string nome, string endereço, int ano_nascimento, string telefone, string nCPF) : base(nome, endereço, ano_nascimento, telefone) { this.NmmCPF = nCPF; } } public class Juridica : Pessoa { public string NumCnpj { get; private set; } public Juridica(string nome, string endereço, int ano_nascimento, string telefone, string nCNPJ) : base(nome, endereço, ano_nascimento, telefone) { NumCnpj = nCNPJ; } } //http://pt.stackoverflow.com/q/187631/101
using System; public class Program { public static void Main() {} } public class Pessoa { public string Nome { get; set; } public string Endereço { get; set; } public int Ano_nascimento { get; set; } public int Idade { get; set; } public string Telefone { get; set; } public Pessoa(string nome, string endereço, int ano_nascimento, string telefone) { Nome = nome; Endereço = endereço; Ano_nascimento = ano_nascimento; Telefone = telefone; Idade = DateTime.Now.Year - ano_nascimento; } } public class Fisica : Pessoa { public string NmmCPF { get; set; } public Fisica(string nome, string endereço, int ano_nascimento, string telefone, string nCPF) : base(nome, endereço, ano_nascimento, telefone) { this.NmmCPF = nCPF; } } public class Juridica : Pessoa { public string NumCnpj { get; set; } public Juridica(string nome, string endereço, int ano_nascimento, string telefone, string nCNPJ) : base(nome, endereço, ano_nascimento, telefone) { NumCnpj = nCNPJ; } } //http://pt.stackoverflow.com/q/187631/101
mit
C#
5dca9bf0c115eeb39a4495a4209c0027689dc158
Update IShellCommand.cs
tiksn/TIKSN-Framework
TIKSN.Core/Shell/IShellCommand.cs
TIKSN.Core/Shell/IShellCommand.cs
using System.Threading; using System.Threading.Tasks; namespace TIKSN.Shell { public interface IShellCommand { Task ExecuteAsync(CancellationToken cancellationToken); } }
using System.Threading; using System.Threading.Tasks; namespace TIKSN.Shell { public interface IShellCommand { Task ExecuteAsync(CancellationToken cancellationToken); } }
mit
C#
15491c099cb667d208a603a3b1c4d4322b1087cb
implement new contract requirements: EnsureLocalDataFolder()
zmira/abremir.AllMyBricks
abremir.AllMyBricks.DatabaseFeeder/Implementations/FileSystemService.cs
abremir.AllMyBricks.DatabaseFeeder/Implementations/FileSystemService.cs
using abremir.AllMyBricks.Device.Interfaces; using System.IO; namespace abremir.AllMyBricks.DatabaseFeeder.Implementations { public class FileSystemService : IFileSystemService { public string ThumbnailCacheFolder => string.Empty; private const string DataFolder = "data"; public bool ClearThumbnailCache() { return true; } public void EnsureLocalDataFolder() { var localDataFolder = GetLocalPathToFile(null); if (!Directory.Exists(localDataFolder)) { Directory.CreateDirectory(localDataFolder); } } public string GetLocalPathToFile(string filename, string subfolder = null) { return Path.Combine(Directory.GetCurrentDirectory(), DataFolder, string.IsNullOrWhiteSpace(subfolder?.Trim()) ? string.Empty : subfolder.Trim(), (filename ?? string.Empty).Trim()); } public string GetThumbnailFolder(string theme, string subtheme) { return string.Empty; } public void SaveThumbnailToCache(string theme, string subtheme, string filename, byte[] thumbnail) { } } }
using abremir.AllMyBricks.Device.Interfaces; namespace abremir.AllMyBricks.DatabaseFeeder.Implementations { public class FileSystemService : IFileSystemService { public string ThumbnailCacheFolder => string.Empty; public bool ClearThumbnailCache() { return true; } public string GetLocalPathToFile(string filename, string subfolder = null) { return string.Empty; } public string GetThumbnailFolder(string theme, string subtheme) { return string.Empty; } public void SaveThumbnailToCache(string theme, string subtheme, string filename, byte[] thumbnail) { } } }
mit
C#
3035c33648bf504eb65e1ebe4fb9acb016eff96c
Fix credits
matteocontrini/locuspocusbot
LocusPocusBot/Handlers/HelpHandler.cs
LocusPocusBot/Handlers/HelpHandler.cs
using LocusPocusBot.Rooms; using System.Text; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types.Enums; namespace LocusPocusBot.Handlers { public class HelpHandler : HandlerBase { private readonly IBotService bot; private readonly Department[] departments; public HelpHandler(IBotService botService, Department[] departments) { this.bot = botService; this.departments = departments; } public override async Task Run() { StringBuilder msg = new StringBuilder(); msg.AppendLine("*LocusPocus* è il bot per controllare la disponibilità delle aule presso i poli dell'Università di Trento 🎓"); msg.AppendLine(); msg.AppendLine("👉 *Usa uno di questi comandi per ottenere la lista delle aule libere*"); msg.AppendLine(); foreach (Department dep in this.departments) { msg.Append('/'); msg.AppendLine(dep.Slug); } msg.AppendLine(); msg.AppendLine("🤫 Il bot è sviluppato da Matteo Contrini (@matteosonoio)"); msg.AppendLine(); msg.AppendLine("👏 Un grazie speciale a Alessandro per il nome del bot, a Dario per il logo e a Emilio per l'aiuto con alcuni dipartimenti"); msg.AppendLine(); msg.AppendLine("🤓 Il bot è [open source](https://github.com/matteocontrini/locuspocusbot)"); await this.bot.Client.SendTextMessageAsync( chatId: this.Chat.Id, text: msg.ToString(), parseMode: ParseMode.Markdown, disableWebPagePreview: true ); } } }
using LocusPocusBot.Rooms; using System.Text; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Types.Enums; namespace LocusPocusBot.Handlers { public class HelpHandler : HandlerBase { private readonly IBotService bot; private readonly Department[] departments; public HelpHandler(IBotService botService, Department[] departments) { this.bot = botService; this.departments = departments; } public override async Task Run() { StringBuilder msg = new StringBuilder(); msg.AppendLine("*LocusPocus* è il bot per controllare la disponibilità delle aule presso i poli dell'Università di Trento 🎓"); msg.AppendLine(); msg.AppendLine("👉 *Usa uno di questi comandi per ottenere la lista delle aule libere*"); msg.AppendLine(); foreach (Department dep in this.departments) { msg.Append('/'); msg.AppendLine(dep.Slug); } msg.AppendLine(); msg.AppendLine("🤫 Il bot è sviluppato da Matteo Contrini (@matteosonoio) con la collaborazione di Emilio Molinari"); msg.AppendLine(); msg.AppendLine("👏 Un grazie speciale a Alessandro Conti per il nome del bot e a [Dario Crisafulli](https://botfactory.it/#chisiamo) per il logo!"); msg.AppendLine(); msg.AppendLine("🤓 Il bot è [open source](https://github.com/matteocontrini/locuspocusbot)"); await this.bot.Client.SendTextMessageAsync( chatId: this.Chat.Id, text: msg.ToString(), parseMode: ParseMode.Markdown, disableWebPagePreview: true ); } } }
mit
C#
6982aae1d7a5b7c64ccf76ac012a7ee5b729950d
increase version
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Nager.Date/Properties/AssemblyInfo.cs
Nager.Date/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("Nager.Date")] [assembly: AssemblyDescription("Calculate Public Holiday for any Year")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.Date")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")] // 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.10")] [assembly: AssemblyFileVersion("1.0.0.10")]
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("Nager.Date")] [assembly: AssemblyDescription("Calculate Public Holiday for any Year")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("nager.at")] [assembly: AssemblyProduct("Nager.Date")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")] // 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.8")] [assembly: AssemblyFileVersion("1.0.0.8")]
mit
C#
61e9ee28d2264087205303b15de69d0de1068ea9
Fix bug where window instance was null on world map.
neitsa/PrepareLanding,neitsa/PrepareLanding
src/Defs/MainButtonWorkerToggleWorld.cs
src/Defs/MainButtonWorkerToggleWorld.cs
using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior (go to the world map) base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // don't add a new window if the window is already there; if it's not create a new one. if (PrepareLanding.Instance.MainWindow == null) PrepareLanding.Instance.MainWindow = new MainWindow(PrepareLanding.Instance.GameData); // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } }
using RimWorld; using Verse; namespace PrepareLanding.Defs { /// <summary> /// This class is called from a definition file when clicking the "World" button on the bottom menu bar while playing /// (see "PrepareLanding/Defs/Misc/MainButtonDefs/MainButtons.xml"). /// </summary> public class MainButtonWorkerToggleWorld : MainButtonWorker_ToggleWorld { public override void Activate() { // default behavior base.Activate(); // do not show the main window if in tutorial mode if (TutorSystem.TutorialMode) { Log.Message( "[PrepareLanding] MainButtonWorkerToggleWorld: Tutorial mode detected: not showing main window."); return; } // show the main window, minimized. PrepareLanding.Instance.MainWindow.Show(true); } } }
mit
C#
2fe1fefa338d3aac7aed6d7161dc0e2191dd52dd
Set HttpOnly to true to protect cookies
ZocDoc/ServiceStack,MindTouch/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,nataren/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit
src/ServiceStack/ServiceHost/Cookies.cs
src/ServiceStack/ServiceHost/Cookies.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; using System.Web; using ServiceStack.Common.Web; namespace ServiceStack.ServiceHost { public class Cookies : ICookies { readonly IHttpResponse httpRes; private static readonly DateTime Session = DateTime.MinValue; private static readonly DateTime Permanaent = DateTime.UtcNow.AddYears(20); private const string RootPath = "/"; public Cookies(IHttpResponse httpRes) { this.httpRes = httpRes; } /// <summary> /// Sets a persistent cookie which never expires /// </summary> public void AddPermanentCookie(string cookieName, string cookieValue) { AddCookie(new Cookie(cookieName, cookieValue, RootPath) { Expires = Permanaent, }); } /// <summary> /// Sets a session cookie which expires after the browser session closes /// </summary> public void AddSessionCookie(string cookieName, string cookieValue) { AddCookie(new Cookie(cookieName, cookieValue, RootPath)); } /// <summary> /// Deletes a specified cookie by setting its value to empty and expiration to -1 days /// </summary> public void DeleteCookie(string cookieName) { var cookie = String.Format("{0}=;expires={1};path=/", cookieName, DateTime.UtcNow.AddDays(-1).ToString("R")); httpRes.AddHeader(HttpHeaders.SetCookie, cookie); } public HttpCookie ToHttpCookie(Cookie cookie) { var httpCookie = new HttpCookie(cookie.Name, cookie.Value) { Path = cookie.Path, Expires = cookie.Expires, HttpOnly = true }; if (string.IsNullOrEmpty(httpCookie.Domain)) { httpCookie.Domain = (string.IsNullOrEmpty(cookie.Domain) ? null : cookie.Domain); } return httpCookie; } public string GetHeaderValue(Cookie cookie) { return cookie.Expires == Session ? String.Format("{0}={1};path=/", cookie.Name, cookie.Value) : String.Format("{0}={1};expires={2};path={3}", cookie.Name, cookie.Value, cookie.Expires.ToString("R"), cookie.Path ?? "/"); } /// <summary> /// Sets a persistent cookie which expires after the given time /// </summary> public void AddCookie(Cookie cookie) { var aspNet = this.httpRes.OriginalResponse as HttpResponse; if (aspNet != null) { var httpCookie = ToHttpCookie(cookie); aspNet.SetCookie(httpCookie); return; } var httpListener = this.httpRes.OriginalResponse as HttpListenerResponse; if (httpListener != null) { var cookieStr = GetHeaderValue(cookie); httpListener.Headers.Add(HttpHeaders.SetCookie, cookieStr); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Text; using System.Web; using ServiceStack.Common.Web; namespace ServiceStack.ServiceHost { public class Cookies : ICookies { readonly IHttpResponse httpRes; private static readonly DateTime Session = DateTime.MinValue; private static readonly DateTime Permanaent = DateTime.UtcNow.AddYears(20); private const string RootPath = "/"; public Cookies(IHttpResponse httpRes) { this.httpRes = httpRes; } /// <summary> /// Sets a persistent cookie which never expires /// </summary> public void AddPermanentCookie(string cookieName, string cookieValue) { AddCookie(new Cookie(cookieName, cookieValue, RootPath) { Expires = Permanaent, }); } /// <summary> /// Sets a session cookie which expires after the browser session closes /// </summary> public void AddSessionCookie(string cookieName, string cookieValue) { AddCookie(new Cookie(cookieName, cookieValue, RootPath)); } /// <summary> /// Deletes a specified cookie by setting its value to empty and expiration to -1 days /// </summary> public void DeleteCookie(string cookieName) { var cookie = String.Format("{0}=;expires={1};path=/", cookieName, DateTime.UtcNow.AddDays(-1).ToString("R")); httpRes.AddHeader(HttpHeaders.SetCookie, cookie); } public HttpCookie ToHttpCookie(Cookie cookie) { var httpCookie = new HttpCookie(cookie.Name, cookie.Value) { Path = cookie.Path, Expires = cookie.Expires, }; if (string.IsNullOrEmpty(httpCookie.Domain)) { httpCookie.Domain = (string.IsNullOrEmpty(cookie.Domain) ? null : cookie.Domain); } return httpCookie; } public string GetHeaderValue(Cookie cookie) { return cookie.Expires == Session ? String.Format("{0}={1};path=/", cookie.Name, cookie.Value) : String.Format("{0}={1};expires={2};path={3}", cookie.Name, cookie.Value, cookie.Expires.ToString("R"), cookie.Path ?? "/"); } /// <summary> /// Sets a persistent cookie which expires after the given time /// </summary> public void AddCookie(Cookie cookie) { var aspNet = this.httpRes.OriginalResponse as HttpResponse; if (aspNet != null) { var httpCookie = ToHttpCookie(cookie); aspNet.SetCookie(httpCookie); return; } var httpListener = this.httpRes.OriginalResponse as HttpListenerResponse; if (httpListener != null) { var cookieStr = GetHeaderValue(cookie); httpListener.Headers.Add(HttpHeaders.SetCookie, cookieStr); } } } }
bsd-3-clause
C#
a1915cff0120b4cf3d799f96ba8b179430b29c86
Update AntimalwareScannerPartialConfigurationValidator.cs
tiksn/TIKSN-Framework
TIKSN.Framework.Core/Antimalware/AntimalwareScannerPartialConfigurationValidator.cs
TIKSN.Framework.Core/Antimalware/AntimalwareScannerPartialConfigurationValidator.cs
using FluentValidation; using TIKSN.Configuration.Validator; namespace TIKSN.Security.Antimalware { public class AntimalwareScannerPartialConfigurationValidator : PartialConfigurationFluentValidatorBase< AntimalwareScannerOptions> { public AntimalwareScannerPartialConfigurationValidator() => this.RuleFor(m => m.ApplicationName).NotNull().NotEmpty(); } }
using FluentValidation; using TIKSN.Configuration.Validator; namespace TIKSN.Security.Antimalware { public class AntimalwareScannerPartialConfigurationValidator : PartialConfigurationFluentValidatorBase<AntimalwareScannerOptions> { public AntimalwareScannerPartialConfigurationValidator() : base() { RuleFor(m => m.ApplicationName).NotNull().NotEmpty(); } } }
mit
C#
46bc87ba47a9c5c94c9cc1ee97b081b6d084667c
add callback method
splitice/SystemInteract.Net,splitice/SystemInteract.Net
SystemInteract/ProcessHelper.cs
SystemInteract/ProcessHelper.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace SystemInteract { public class ProcessHelper { private const int DefaultTimeout = 120; public static void ReadToEnd(ISystemProcess process, Action<String> output, Action<String> error, int timeout = DefaultTimeout) { DataReceivedEventHandler errorEvent = null, outEvent = null; if (process.StartInfo.RedirectStandardError) { errorEvent = (a, b) => error(b.Data); process.ErrorDataReceived += errorEvent; process.BeginErrorReadLine(); } if (process.StartInfo.RedirectStandardOutput) { outEvent = (a, b) => output(b.Data); process.OutputDataReceived += outEvent; process.BeginOutputReadLine(); } if (!process.WaitForExit(timeout * 1000)) { throw new TimeoutException(String.Format("Timeout. Process did not complete executing within {0} seconds", timeout)); } if (errorEvent != null) { process.ErrorDataReceived -= errorEvent; } if (outEvent != null) { process.OutputDataReceived -= outEvent; } } public static void ReadToEnd(ISystemProcess process, out String output, out String error, int timeout = DefaultTimeout) { StringBuilder toutput = new StringBuilder(); StringBuilder terror = new StringBuilder(); ReadToEnd(process, a=>toutput.AppendLine(a), a=>terror.AppendLine(a)); output = toutput.ToString(); error = terror.ToString(); } public static void WaitForExit(ISystemProcess process) { String temp; ReadToEnd(process, out temp, out temp); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; namespace SystemInteract { public class ProcessHelper { private const int DefaultTimeout = 120; public static void ReadToEnd(ISystemProcess process, out String output, out String error, int timeout = DefaultTimeout) { StringBuilder toutput = new StringBuilder(); StringBuilder terror = new StringBuilder(); DataReceivedEventHandler errorEvent = null, outEvent = null; if (process.StartInfo.RedirectStandardError) { errorEvent = (a, b) => terror.AppendLine(b.Data); process.ErrorDataReceived += errorEvent; process.BeginErrorReadLine(); } if (process.StartInfo.RedirectStandardOutput) { outEvent = (a, b) => toutput.AppendLine(b.Data); process.OutputDataReceived += outEvent; process.BeginOutputReadLine(); } if (!process.WaitForExit(timeout * 1000)) { throw new TimeoutException(String.Format("Timeout. Process did not complete executing within {0} seconds", timeout)); } output = toutput.ToString(); error = terror.ToString(); if (errorEvent != null) { process.ErrorDataReceived -= errorEvent; } if (outEvent != null) { process.OutputDataReceived -= outEvent; } } public static void WaitForExit(ISystemProcess process) { String temp; ReadToEnd(process, out temp, out temp); } } }
apache-2.0
C#
9e17eb234223e2b9869b159f675f3466336b54b2
Reword settings text to be ruleset agnostic
NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,DrabWeb/osu,UselessToucan/osu,ZLima12/osu,johnneijzen/osu,naoey/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,naoey/osu,peppy/osu,naoey/osu,smoogipooo/osu,DrabWeb/osu,EVAST9919/osu,peppy/osu,peppy/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,ZLima12/osu,UselessToucan/osu
osu.Game/Overlays/Settings/Sections/Gameplay/GeneralSettings.cs
osu.Game/Overlays/Settings/Sections/Gameplay/GeneralSettings.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double> { LabelText = "Background dim", Bindable = config.GetBindable<double>(OsuSetting.DimLevel), KeyboardStep = 0.1f }, new SettingsSlider<double> { LabelText = "Background blur", Bindable = config.GetBindable<double>(OsuSetting.BlurLevel), KeyboardStep = 0.1f }, new SettingsCheckbox { LabelText = "Show score overlay", Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface) }, new SettingsCheckbox { LabelText = "Always show key overlay", Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay) }, new SettingsCheckbox { LabelText = "Increase visibility of first object with \"Hidden\" mod", Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility) }, }; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Configuration; namespace osu.Game.Overlays.Settings.Sections.Gameplay { public class GeneralSettings : SettingsSubsection { protected override string Header => "General"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double> { LabelText = "Background dim", Bindable = config.GetBindable<double>(OsuSetting.DimLevel), KeyboardStep = 0.1f }, new SettingsSlider<double> { LabelText = "Background blur", Bindable = config.GetBindable<double>(OsuSetting.BlurLevel), KeyboardStep = 0.1f }, new SettingsCheckbox { LabelText = "Show score overlay", Bindable = config.GetBindable<bool>(OsuSetting.ShowInterface) }, new SettingsCheckbox { LabelText = "Always show key overlay", Bindable = config.GetBindable<bool>(OsuSetting.KeyOverlay) }, new SettingsCheckbox { LabelText = "Show approach circle on first \"Hidden\" object", Bindable = config.GetBindable<bool>(OsuSetting.IncreaseFirstObjectVisibility) }, }; } } }
mit
C#
02860dfb5cf5b49856aebed96233eb20f55b0cc2
refactor => proper case
PowerWallet/SSO_Client_CSharp,PowerWallet/SSO_Client_CSharp
src/MVC5/Filters/LogFilterAttribute.cs
src/MVC5/Filters/LogFilterAttribute.cs
using System; using System.Web.Mvc; using NLog; namespace FinApps.SSO.MVC5.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class LogAttribute : ActionFilterAttribute { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); public override void OnActionExecuting(ActionExecutingContext filterContext) { var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); logger.Debug("{0}.{1} => Executing", currentController, currentAction); } public override void OnActionExecuted(ActionExecutedContext filterContext) { var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); logger.Debug("{0}.{1} => Executed", currentController, currentAction); } } }
using System; using System.Web.Mvc; using NLog; namespace FinApps.SSO.MVC5.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class LogAttribute : ActionFilterAttribute { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); public override void OnActionExecuting(ActionExecutingContext filterContext) { var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); Logger.Debug("{0}.{1} => Executing", currentController, currentAction); } public override void OnActionExecuted(ActionExecutedContext filterContext) { var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); Logger.Debug("{0}.{1} => Executed", currentController, currentAction); } } }
apache-2.0
C#
9583ed53b751d90b2d1eebefe7e61837853a82e8
Use ToString instead as suggested in #1122.
dlemstra/Magick.NET,dlemstra/Magick.NET
src/Shared/Netstandard20/EnumHelper.cs
src/Shared/Netstandard20/EnumHelper.cs
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; namespace ImageMagick { internal static class EnumHelper { public static string ConvertFlags<TEnum>(TEnum value) where TEnum : struct, Enum => value.ToString(); public static string GetName<TEnum>(TEnum value) where TEnum : struct, Enum => Enum.GetName(typeof(TEnum), value); public static bool HasFlag<TEnum>(TEnum value, TEnum flag) where TEnum : struct, Enum => value.HasFlag(flag); public static TEnum Parse<TEnum>(int value, TEnum defaultValue) where TEnum : struct, Enum => Parse((object)value, defaultValue); public static TEnum Parse<TEnum>(string? value, TEnum defaultValue) where TEnum : struct, Enum { if (Enum.TryParse(value, true, out TEnum result)) return result; return defaultValue; } public static TEnum Parse<TEnum>(ushort value, TEnum defaultValue) where TEnum : struct, Enum => Parse((object)(int)value, defaultValue); private static TEnum Parse<TEnum>(object value, TEnum defaultValue) where TEnum : struct, Enum { if (Enum.IsDefined(typeof(TEnum), value)) return (TEnum)value; return defaultValue; } } }
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; namespace ImageMagick { internal static class EnumHelper { public static string ConvertFlags<TEnum>(TEnum value) where TEnum : struct, Enum { var flags = new List<string>(); foreach (TEnum enumValue in Enum.GetValues(typeof(TEnum))) { if (HasFlag(value, enumValue)) { var name = GetName(enumValue); if (!flags.Contains(name)) flags.Add(name); } } return string.Join(",", flags); } public static string GetName<TEnum>(TEnum value) where TEnum : struct, Enum => Enum.GetName(typeof(TEnum), value); public static bool HasFlag<TEnum>(TEnum value, TEnum flag) where TEnum : struct, Enum => value.HasFlag(flag); public static TEnum Parse<TEnum>(int value, TEnum defaultValue) where TEnum : struct, Enum => Parse((object)value, defaultValue); public static TEnum Parse<TEnum>(string? value, TEnum defaultValue) where TEnum : struct, Enum { if (Enum.TryParse(value, true, out TEnum result)) return result; return defaultValue; } public static TEnum Parse<TEnum>(ushort value, TEnum defaultValue) where TEnum : struct, Enum => Parse((object)(int)value, defaultValue); private static TEnum Parse<TEnum>(object value, TEnum defaultValue) where TEnum : struct, Enum { if (Enum.IsDefined(typeof(TEnum), value)) return (TEnum)value; return defaultValue; } } }
apache-2.0
C#
a34954b37fbdcb6e11a256b59b12fcb24df960cb
Fix recursive coin deletion
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Coins/CoinsView.cs
WalletWasabi/Coins/CoinsView.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NBitcoin; using WalletWasabi.Helpers; using WalletWasabi.Models; namespace WalletWasabi.Coins { public class CoinsView : ICoinsView { private IEnumerable<SmartCoin> Coins { get; } public CoinsView(IEnumerable<SmartCoin> coins) { Coins = Guard.NotNull(nameof(coins), coins); } public ICoinsView Unspent() => new CoinsView(Coins.Where(x => x.Unspent && !x.SpentAccordingToBackend)); public ICoinsView Available() => new CoinsView(Coins.Where(x => !x.Unavailable)); public ICoinsView CoinJoinInProcess() => new CoinsView(Coins.Where(x => x.CoinJoinInProgress)); public ICoinsView Confirmed() => new CoinsView(Coins.Where(x => x.Confirmed)); public ICoinsView Unconfirmed() => new CoinsView(Coins.Where(x => !x.Confirmed)); public ICoinsView AtBlockHeight(Height height) => new CoinsView(Coins.Where(x => x.Height == height)); public ICoinsView CreatedBy(uint256 txid) => new CoinsView(Coins.Where(x => x.TransactionId == txid)); public ICoinsView SpentBy(uint256 txid) => new CoinsView(Coins.Where(x => x.SpenderTransactionId == txid)); public ICoinsView ChildrenOf(SmartCoin coin) => new CoinsView(Coins.Where(x => x.TransactionId == coin.SpenderTransactionId)); public ICoinsView DescendantOf(SmartCoin coin) { IEnumerable<SmartCoin> Generator(SmartCoin scoin) { foreach (var child in ChildrenOf(scoin)) { foreach (var childDescendant in Generator(child)) { yield return childDescendant; } yield return child; } } return new CoinsView(Generator(coin)); } public ICoinsView DescendantOfAndSelf(SmartCoin coin) => new CoinsView(DescendantOf(coin).Concat(new[] { coin })); public ICoinsView FilterBy(Func<SmartCoin, bool> expression) => new CoinsView(Coins.Where(expression)); public ICoinsView OutPoints(IEnumerable<TxoRef> outPoints) => new CoinsView(Coins.Where(x => outPoints.Any(y => y == x.GetOutPoint()))); public SmartCoin GetByOutPoint(OutPoint outpoint) => Coins.FirstOrDefault(x => x.GetOutPoint() == outpoint); public Money TotalAmount() => Coins.Sum(x => x.Amount); public SmartCoin[] ToArray() => Coins.ToArray(); public IEnumerator<SmartCoin> GetEnumerator() => Coins.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => Coins.GetEnumerator(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using NBitcoin; using WalletWasabi.Helpers; using WalletWasabi.Models; namespace WalletWasabi.Coins { public class CoinsView : ICoinsView { private IEnumerable<SmartCoin> Coins { get; } public CoinsView(IEnumerable<SmartCoin> coins) { Coins = Guard.NotNull(nameof(coins), coins); } public ICoinsView Unspent() => new CoinsView(Coins.Where(x => x.Unspent && !x.SpentAccordingToBackend)); public ICoinsView Available() => new CoinsView(Coins.Where(x => !x.Unavailable)); public ICoinsView CoinJoinInProcess() => new CoinsView(Coins.Where(x => x.CoinJoinInProgress)); public ICoinsView Confirmed() => new CoinsView(Coins.Where(x => x.Confirmed)); public ICoinsView Unconfirmed() => new CoinsView(Coins.Where(x => !x.Confirmed)); public ICoinsView AtBlockHeight(Height height) => new CoinsView(Coins.Where(x => x.Height == height)); public ICoinsView CreatedBy(uint256 txid) => new CoinsView(Coins.Where(x => x.TransactionId == txid)); public ICoinsView SpentBy(uint256 txid) => new CoinsView(Coins.Where(x => x.SpenderTransactionId == txid)); public ICoinsView ChildrenOf(SmartCoin coin) => new CoinsView(Coins.Where(x => x.TransactionId == coin.SpenderTransactionId)); public ICoinsView DescendantOf(SmartCoin coin) { IEnumerable<SmartCoin> Generator(SmartCoin scoin) { foreach (var child in ChildrenOf(scoin)) { foreach (var childDescendant in ChildrenOf(child)) { yield return childDescendant; } yield return child; } } return new CoinsView(Generator(coin)); } public ICoinsView DescendantOfAndSelf(SmartCoin coin) => new CoinsView(DescendantOf(coin).Concat(new[] { coin })); public ICoinsView FilterBy(Func<SmartCoin, bool> expression) => new CoinsView(Coins.Where(expression)); public ICoinsView OutPoints(IEnumerable<TxoRef> outPoints) => new CoinsView(Coins.Where(x => outPoints.Any(y => y == x.GetOutPoint()))); public SmartCoin GetByOutPoint(OutPoint outpoint) => Coins.FirstOrDefault(x => x.GetOutPoint() == outpoint); public Money TotalAmount() => Coins.Sum(x => x.Amount); public SmartCoin[] ToArray() => Coins.ToArray(); public IEnumerator<SmartCoin> GetEnumerator() => Coins.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => Coins.GetEnumerator(); } }
mit
C#
d5db395056c1234136e47874c85efa5c7a78bcc1
Update version to 1.2.2.0
stevengum97/BotBuilder,msft-shahins/BotBuilder,xiangyan99/BotBuilder,msft-shahins/BotBuilder,Clairety/ConnectMe,msft-shahins/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,mmatkow/BotBuilder,stevengum97/BotBuilder,mmatkow/BotBuilder,xiangyan99/BotBuilder,xiangyan99/BotBuilder,dr-em/BotBuilder,Clairety/ConnectMe,stevengum97/BotBuilder,Clairety/ConnectMe,dr-em/BotBuilder,xiangyan99/BotBuilder,dr-em/BotBuilder,Clairety/ConnectMe,mmatkow/BotBuilder,dr-em/BotBuilder,mmatkow/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder
CSharp/Library/Properties/AssemblyInfo.cs
CSharp/Library/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("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // 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.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")] [assembly: InternalsVisibleTo("Microsoft.Bot.Sample.Tests")] [assembly: NeutralResourcesLanguage("en")]
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("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // 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.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")] [assembly: InternalsVisibleTo("Microsoft.Bot.Sample.Tests")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
a175e74edc30974e3e64aa68cb85422c9250a323
Bump version to 0.3.1
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.3.1")] [assembly: AssemblyInformationalVersionAttribute("0.3.1")] [assembly: AssemblyFileVersionAttribute("0.3.1")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.3.1"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.3.0")] [assembly: AssemblyInformationalVersionAttribute("0.3.0")] [assembly: AssemblyFileVersionAttribute("0.3.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.3.0"; } }
apache-2.0
C#
33e47ed77d91de8738bc52d5ef002b7457bb1e11
Allow AppConfigFacility calls to be chained.
adamconnelly/WindsorAppConfigFacility
AppConfigFacility/AppConfigFacility.cs
AppConfigFacility/AppConfigFacility.cs
namespace AppConfigFacility { using System; using Castle.MicroKernel.Facilities; using Castle.MicroKernel.Registration; public class AppConfigFacility : AbstractFacility { private Type _cacheType = typeof (DefaultSettingsCache); private Type _settingsProviderType = typeof (AppSettingsProvider); protected override void Init() { Kernel.Register( Component.For<ISettingsCache>().ImplementedBy(_cacheType), Component.For<ISettingsProvider>().ImplementedBy(_settingsProviderType), Component.For<AppConfigInterceptor>().LifestyleTransient()); } /// <summary> /// Enables caching of settings. This prevents multiple calls being made to the settings provider. /// </summary> public AppConfigFacility CacheSettings() { _cacheType = typeof (MemorySettingsCache); return this; } /// <summary> /// Specified the type of settings provider to use. /// </summary> /// <typeparam name="T"> /// The type of the settings provider. /// </typeparam> public AppConfigFacility UseSettingsProvider<T>() where T : ISettingsProvider { _settingsProviderType = typeof (T); return this; } } }
namespace AppConfigFacility { using System; using Castle.MicroKernel.Facilities; using Castle.MicroKernel.Registration; public class AppConfigFacility : AbstractFacility { private Type _cacheType = typeof (DefaultSettingsCache); private Type _settingsProviderType = typeof (AppSettingsProvider); protected override void Init() { Kernel.Register( Component.For<ISettingsCache>().ImplementedBy(_cacheType), Component.For<ISettingsProvider>().ImplementedBy(_settingsProviderType), Component.For<AppConfigInterceptor>().LifestyleTransient()); } /// <summary> /// Enables caching of settings. This prevents multiple calls being made to the settings provider. /// </summary> public void CacheSettings() { _cacheType = typeof (MemorySettingsCache); } /// <summary> /// Specified the type of settings provider to use. /// </summary> /// <typeparam name="T"> /// The type of the settings provider. /// </typeparam> public void UseSettingsProvider<T>() where T : ISettingsProvider { _settingsProviderType = typeof (T); } } }
mit
C#
7e69841f67b34c4588478feba6a5420705db8d58
Update ExcelApp.cs
kchen0723/ExcelAsync
ExcelAsyncWpf/ExcelOperate/ExcelApp.cs
ExcelAsyncWpf/ExcelOperate/ExcelApp.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; namespace ExcelAsyncWpf.ExcelOperate { public static class ExcelApp { public static uint ExcelMainUiThreadId { get; set; } private static Application m_currentExcel; public static Application CurrentExcel { get { return m_currentExcel; } set { m_currentExcel = value; if (m_currentExcel != null) { m_currentExcel.WorkbookNewSheet += new AppEvents_WorkbookNewSheetEventHandler(m_excelApp_WorkbookNewSheet); m_currentExcel.WorkbookActivate += new AppEvents_WorkbookActivateEventHandler(m_excelApp_WorkbookActivate); } } } static void m_excelApp_WorkbookNewSheet(Workbook Wb, object Sh) { System.Windows.MessageBox.Show("new workbook"); } private static void m_excelApp_WorkbookActivate(Workbook Wb) { System.Windows.MessageBox.Show("Workbook Activate"); } public static void AddContentMenu() { CommandBar cellMenu = CurrentExcel.CommandBars["Cell"]; //There is a bug in below line. One dot is good, too dots are bad. CommandBarButton button = cellMenu.Controls.Add(Type: MsoControlType.msoControlButton, Before: cellMenu.Controls.Count, Temporary: true) as CommandBarButton; button.Caption = "Test Button"; button.Tag = "Test Button"; button.OnAction = "OnButtonClick"; } public static void OnButtonClick() { System.Windows.MessageBox.Show("Hello from context menu"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Core; namespace ExcelAsyncWpf.ExcelOperate { public static class ExcelApp { public static uint ExcelMainUiThreadId { get; set; } private static Application m_currentExcel; public static Application CurrentExcel { get { return m_currentExcel; } set { m_currentExcel = value; if (m_currentExcel != null) { m_currentExcel.WorkbookNewSheet += new AppEvents_WorkbookNewSheetEventHandler(m_excelApp_WorkbookNewSheet); m_currentExcel.WorkbookActivate += new AppEvents_WorkbookActivateEventHandler(m_excelApp_WorkbookActivate); } } } static void m_excelApp_WorkbookNewSheet(Workbook Wb, object Sh) { System.Windows.MessageBox.Show("new workbook"); } private static void m_excelApp_WorkbookActivate(Workbook Wb) { System.Windows.MessageBox.Show("Workbook Activate"); } public static void AddContentMenu() { CommandBar cellMenu = CurrentExcel.CommandBars["Cell"]; CommandBarButton button = cellMenu.Controls.Add(Type: MsoControlType.msoControlButton, Before: cellMenu.Controls.Count, Temporary: true) as CommandBarButton; button.Caption = "Test Button"; button.Tag = "Test Button"; button.OnAction = "OnButtonClick"; } public static void OnButtonClick() { System.Windows.MessageBox.Show("Hello from context menu"); } } }
agpl-3.0
C#
68c6b23939b78753030210257b3bceca3ddfbb51
Include TestMethods
OmarBizreh/DotNetHelpers
FrameworkUnitTest/DotNetHelpersTest.cs
FrameworkUnitTest/DotNetHelpersTest.cs
using System.Collections.Generic; using DotNetHelpers.Helpers.Extensions; using DotNetHelpers.Service.Authentication; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FrameworkUnitTest { [TestClass] public class DotNetHelpersTest { private string EncryptionPass { get { return "someRandomString"; } } private Token TestToken { get; set; } [TestMethod] public void Test_CreateToken() { var tokenArgs = new Dictionary<string, string>(); tokenArgs.Add("Key1", "Value1"); tokenArgs.Add("Key2", "Value2"); this.TestToken = new Token(tokenArgs, this.EncryptionPass); Assert.IsNotNull(this.TestToken); Assert.IsInstanceOfType(this.TestToken, typeof(Token)); System.Console.WriteLine(string.Format("Generated Token: {0}\nNumber of Args: {1}", this.TestToken.AuthenticationToken, this.TestToken.Arguments.Count.ToString())); } [TestMethod] public void Test_DecodeToken() { this.Test_CreateToken(); var decodedToken = Token.DecodeToken(this.TestToken.AuthenticationToken, this.EncryptionPass); Assert.IsNotNull(decodedToken); Assert.IsInstanceOfType(decodedToken, typeof(Token)); System.Console.WriteLine(string.Format("Token decoded: {0}\nNumber of Args: {1}\nInput Token: {2}", decodedToken.AuthenticationToken, decodedToken.Arguments.Count.ToString(), this.TestToken.AuthenticationToken)); } [TestMethod] public void Test_IEnumerableExtensions() { var StringList = new List<string>() { "Val1", "Val2", "Random", "test" }; var Result = StringList.FindAllIndexOf<string>("Val1"); Assert.AreNotEqual(0, Result.Length); Result = StringList.FindAllIndexOf<string>("Val11"); Assert.AreEqual(0, Result.Length); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FrameworkUnitTest { [TestClass] public class DotNetHelpersTest { } }
apache-2.0
C#
847173dc85f4480694569a5a6591723c41df9f7e
Clean up CommandConnection Tests
rit-sse-mycroft/core
Mycroft.Tests/TestCommandConnection.cs
Mycroft.Tests/TestCommandConnection.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mycroft.App; using System.IO; using System.Diagnostics; namespace Mycroft.Tests { [TestClass] public class TestCommandConnection { [TestMethod] public void TestBodylessMessage(){ var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP")); var cmd = new CommandConnection(s); var msg = cmd.GetCommand(); Trace.WriteLine(msg); Assert.Equals(msg, "APP_UP"); } [TestMethod] public void TestBodaciousMessage() { var input = "30\nMSG_BROADCAST {\"key\": \"value\"}"; var s = new MemoryStream(Encoding.UTF8.GetBytes(input)); var cmd = new CommandConnection(s); var msg = cmd.GetCommand(); Trace.WriteLine(msg); Trace.WriteLine(input.Substring(3)); Assert.Equals(msg, input.Substring(3)); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mycroft.App; using System.IO; using System.Diagnostics; namespace Mycroft.Tests { [TestClass] public class TestCommandConnection { [TestMethod] public async Task TestBodylessMessage(){ var s = new MemoryStream(Encoding.UTF8.GetBytes("6\nAPP_UP")); var cmd = new CommandConnection(s); var msg = cmd.GetCommand(); Trace.WriteLine(msg); if (msg != "APP_UP") throw new Exception("Incorrect message!"); } [TestMethod] public async Task TestBodaciousMessage() { var input = "30\nMSG_BROADCAST {\"key\": \"value\"}"; var s = new MemoryStream(Encoding.UTF8.GetBytes(input)); var cmd = new CommandConnection(s); var msg = cmd.GetCommand(); Trace.WriteLine(msg); Trace.WriteLine(input.Substring(3)); if (msg != input.Substring(3)) throw new Exception("Incorrect message!"); } } }
bsd-3-clause
C#
436f45d0b1eccd850c5409bf70b5ec1f2e8186ff
Update invalid events table name
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
retail/interactive-tutorial/RetailEvents.Samples/setup/EventsCreateBigQueryTable.cs
retail/interactive-tutorial/RetailEvents.Samples/setup/EventsCreateBigQueryTable.cs
// Copyright 2022 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.IO; public static class EventsCreateBigQueryTable { private const string EventsFileName = "user_events.json"; private const string InvalidEventsFileName = "user_events_some_invalid.json"; private const string EventsDataSet = "user_events"; private const string EventsTable = "events"; private const string InvalidEventsTable = "events_some_invalid"; private const string EventsSchema = "events_schema.json"; private static readonly string eventsFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{EventsFileName}"); private static readonly string invalidEventsFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{InvalidEventsFileName}"); private static readonly string eventsSchemaFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{EventsSchema}"); /// <summary> /// Create events BigQuery tables with data. /// </summary> [Runner.Attributes.Example] public static void PerformCreationOfBigQueryTable() { // Create a BigQuery tables with data. CreateTestResources.CreateBQDataSet(EventsDataSet); CreateTestResources.CreateAndPopulateBQTable(EventsDataSet, EventsTable, eventsSchemaFilePath, eventsFilePath); CreateTestResources.CreateAndPopulateBQTable(EventsDataSet, InvalidEventsTable, eventsSchemaFilePath, invalidEventsFilePath); } }
// Copyright 2022 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.IO; public static class EventsCreateBigQueryTable { private const string EventsFileName = "user_events.json"; private const string InvalidEventsFileName = "user_events_some_invalid.json"; private const string EventsDataSet = "user_events"; private const string EventsTable = "events"; private const string InvalidEventsTable = "user_events_some_invalid"; private const string EventsSchema = "events_schema.json"; private static readonly string eventsFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{EventsFileName}"); private static readonly string invalidEventsFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{InvalidEventsFileName}"); private static readonly string eventsSchemaFilePath = Path.Combine(CreateTestResources.GetSolutionDirectoryFullName(), $"TestResourcesSetupCleanup/resources/{EventsSchema}"); /// <summary> /// Create events BigQuery tables with data. /// </summary> [Runner.Attributes.Example] public static void PerformCreationOfBigQueryTable() { // Create a BigQuery tables with data. CreateTestResources.CreateBQDataSet(EventsDataSet); CreateTestResources.CreateAndPopulateBQTable(EventsDataSet, EventsTable, eventsSchemaFilePath, eventsFilePath); CreateTestResources.CreateAndPopulateBQTable(EventsDataSet, InvalidEventsTable, eventsSchemaFilePath, invalidEventsFilePath); } }
apache-2.0
C#
cafd8e476324c494d2f257a68e02b250dcb1e6e7
Reduce the amount of persisted city statistics
Miragecoder/Urbanization,Miragecoder/Urbanization,Miragecoder/Urbanization
src/Mirage.Urbanization.Simulation/Persistence/PersistedCityStatisticsCollection.cs
src/Mirage.Urbanization.Simulation/Persistence/PersistedCityStatisticsCollection.cs
using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 960) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }
using System.Collections.Generic; using System.Linq; using Mirage.Urbanization.ZoneStatisticsQuerying; using System.Collections.Immutable; namespace Mirage.Urbanization.Simulation.Persistence { public class PersistedCityStatisticsCollection { private ImmutableQueue<PersistedCityStatisticsWithFinancialData> _persistedCityStatistics = ImmutableQueue<PersistedCityStatisticsWithFinancialData>.Empty; private PersistedCityStatisticsWithFinancialData _mostRecentStatistics; public void Add(PersistedCityStatisticsWithFinancialData statistics) { _persistedCityStatistics = _persistedCityStatistics.Enqueue(statistics); if (_persistedCityStatistics.Count() > 5200) _persistedCityStatistics = _persistedCityStatistics.Dequeue(); _mostRecentStatistics = statistics; } public QueryResult<PersistedCityStatisticsWithFinancialData> GetMostRecentPersistedCityStatistics() { return QueryResult<PersistedCityStatisticsWithFinancialData>.Create(_mostRecentStatistics); } public IEnumerable<PersistedCityStatisticsWithFinancialData> GetAll() { return _persistedCityStatistics; } } }
mit
C#
a4171253a38f2d09eedea9f38eb7d3eca0afebff
Make LowHealthThreshold a field.
ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,EVAST9919/osu
osu.Game/Screens/Play/HUD/FailingLayer.cs
osu.Game/Screens/Play/HUD/FailingLayer.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; namespace osu.Game.Screens.Play.HUD { /// <summary> /// An overlay layer on top of the playfield which fades to red when the current player health falls below a certain threshold defined by <see cref="LowHealthThreshold"/>. /// </summary> public class FailingLayer : HealthDisplay { private const float max_alpha = 0.4f; private readonly Box box; /// <summary> /// The threshold under which the current player life should be considered low and the layer should start fading in. /// </summary> public double LowHealthThreshold = 0.20f; public FailingLayer() { RelativeSizeAxes = Axes.Both; Child = box = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0 }; } [BackgroundDependencyLoader] private void load(OsuColour color) { box.Colour = color.Red; } protected override void Update() { box.Alpha = (float)Math.Clamp(max_alpha * (1 - Current.Value / LowHealthThreshold), 0, max_alpha); base.Update(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Graphics; namespace osu.Game.Screens.Play.HUD { /// <summary> /// An overlay layer on top of the playfield which fades to red when the current player health falls below a certain threshold defined by <see cref="LowHealthThreshold"/>. /// </summary> public class FailingLayer : HealthDisplay { private const float max_alpha = 0.4f; private readonly Box box; /// <summary> /// The threshold under which the current player life should be considered low and the layer should start fading in. /// </summary> protected double LowHealthThreshold { get; set; } = 0.20f; public FailingLayer() { RelativeSizeAxes = Axes.Both; Child = box = new Box { RelativeSizeAxes = Axes.Both, Alpha = 0 }; } [BackgroundDependencyLoader] private void load(OsuColour color) { box.Colour = color.Red; } protected override void Update() { box.Alpha = (float)Math.Clamp(max_alpha * (1 - Current.Value / LowHealthThreshold), 0, max_alpha); base.Update(); } } }
mit
C#
b0eb72a5ad36fdd61391812bc3dc5efb5fec6d27
remove old system info string gauges
MetaG8/Metrics.NET,ntent-ad/Metrics.NET,mnadel/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,huoxudong125/Metrics.NET,huoxudong125/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET,DeonHeyns/Metrics.NET,cvent/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,etishor/Metrics.NET,ntent-ad/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET
Src/Metrics/PerfCounters/SystemInfo.cs
Src/Metrics/PerfCounters/SystemInfo.cs
 using System; using Metrics.Core; namespace Metrics.PerfCounters { public class SystemInfo : BaseCounterRegristry { public SystemInfo(MetricsRegistry registry, string prefix) : base(registry, prefix) { } public void Register() { Register("AvailableRAM", () => new PerformanceCounterGauge("Memory", "Available MBytes"), Unit.Custom("Mb")); Register("CPU Usage", () => new PerformanceCounterGauge("Processor", "% Processor Time", TotalInstance), Unit.Custom("%")); Register("Disk Writes/sec", () => new DerivedGauge(new PerformanceCounterGauge("PhysicalDisk", "Disk Reads/sec", TotalInstance), f => f / 1024), Unit.Custom("kb/s")); Register("Disk Reads/sec", () => new DerivedGauge(new PerformanceCounterGauge("PhysicalDisk", "Disk Writes/sec", TotalInstance), f => f / 1024), Unit.Custom("kb/s")); } } }
 using System; using Metrics.Core; namespace Metrics.PerfCounters { public class SystemInfo : BaseCounterRegristry { public SystemInfo(MetricsRegistry registry, string prefix) : base(registry, prefix) { } public void Register() { //Register("MachineName", () => Environment.MachineName); //Register("Processor Count", () => Environment.ProcessorCount.ToString()); //Register("OperatingSystem", () => GetOSVersion()); //Register("NETVersion", () => Environment.Version.ToString()); //Register("CommandLine", () => Environment.CommandLine.Replace("\"",string.Empty).Replace("\\","/")); Register("AvailableRAM", () => new PerformanceCounterGauge("Memory", "Available MBytes"), Unit.Custom("Mb")); Register("CPU Usage", () => new PerformanceCounterGauge("Processor", "% Processor Time", TotalInstance), Unit.Custom("%")); Register("Disk Writes/sec", () => new DerivedGauge(new PerformanceCounterGauge("PhysicalDisk", "Disk Reads/sec", TotalInstance), f => f / 1024), Unit.Custom("kb/s")); Register("Disk Reads/sec", () => new DerivedGauge(new PerformanceCounterGauge("PhysicalDisk", "Disk Writes/sec", TotalInstance), f => f / 1024), Unit.Custom("kb/s")); } private static string GetOSVersion() { return string.Format("{0} {1}", Environment.OSVersion.VersionString, Environment.Is64BitOperatingSystem ? "64bit" : "32bit"); } } }
apache-2.0
C#
4d39cad23705ed9e05882edb4e2b3a0944f1b000
Remove the GC initialization code
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
runtime/GC.cs
runtime/GC.cs
using System.Runtime.InteropServices; namespace __compiler_rt { /// <summary> /// Garbage collection functionality that can be used by the compiler. /// </summary> public static unsafe class GC { private static extern void* GC_malloc(ulong size); /// <summary> /// Allocates a region of storage that is the given number of bytes in size. /// The storage is zero-initialized. /// </summary> /// <param name="size">The number of bytes to allocate.</param> public static void* Allocate(ulong size) { return GC_malloc(size); } } }
using System.Runtime.InteropServices; namespace __compiler_rt { /// <summary> /// Garbage collection functionality that can be used by the compiler. /// </summary> public static unsafe class GC { /// <summary> /// Initializes the garbage collector. /// </summary> static GC() { GC_init(); } private static extern void* GC_malloc(ulong size); private static extern void GC_init(); /// <summary> /// Allocates a region of storage that is the given number of bytes in size. /// The storage is zero-initialized. /// </summary> /// <param name="size">The number of bytes to allocate.</param> public static void* Allocate(ulong size) { return GC_malloc(size); } } }
mit
C#
ed6ebc3fbfc843cc452b2b5dd3015dd0509a1199
Fix KillReward
bunashibu/kikan
Assets/Scripts/KillReward.cs
Assets/Scripts/KillReward.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KillReward : MonoBehaviour { public int Exp { get { return _expTable.Data[_level.Lv - 1]; } } public int Gold { get { return _goldTable.Data[_level.Lv - 1]; } } [SerializeField] private DataTable _expTable; [SerializeField] private DataTable _goldTable; [SerializeField] private Level _level; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KillReward : MonoBehaviour { public int Exp { get { return _expTable.Data[_level.Lv]; } } public int Gold { get { return _goldTable.Data[_level.Lv]; } } [SerializeField] private DataTable _expTable; [SerializeField] private DataTable _goldTable; [SerializeField] private Level _level; }
mit
C#