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
119f3940dacfd59b648f6f1946a15be487f73dd4
Add FontId
yufeih/Nine.Graphics,studio-nine/Nine.Graphics
src/Nine.Graphics/FontId.cs
src/Nine.Graphics/FontId.cs
namespace Nine.Graphics { using System; public struct FontId : IEquatable<FontId> { public readonly int Id; public string Name => map[Id]; public static int Count => map.Count; private static readonly IdMap map = new IdMap(); public FontId(string name) { Id = map[name]; } public static implicit operator FontId(string name) => new FontId(name); public static implicit operator string(FontId textureId) => textureId.Name; public bool Equals(FontId other) => other.Id == Id; public override bool Equals(object obj) => obj is FontId && Id == ((FontId)obj).Id; public override int GetHashCode() => Id; public override string ToString() => $"[{ Id }] { Name }"; } }
mit
C#
f9cfef7b74b20be5dd93b13329eda90b75b98d4c
Create Item.Helper.cs
PokemonUnity/PokemonUnity
PokemonUnity.Shared/Inventory/Item.Helper.cs
PokemonUnity.Shared/Inventory/Item.Helper.cs
using PokemonUnity.Inventory; using PokemonUnity.Character; using System; using System.Collections.Generic; using System.Linq; using PokemonUnity.Overworld; using PokemonUnity.Monster; using PokemonUnity; namespace PokemonUnity.Inventory { /// <summary> /// Implements methods that act on arrays of items. Each element in an item /// array is itself an array of [itemID, itemCount]. /// Used by the Bag, PC item storage, and Triple Triad. /// </summary> public static partial class ItemStorageHelper { // Returns the quantity of the given item in the items array, maximum size per slot, and item ID public static int pbQuantity(KeyValuePair<Items, int>[] items,int maxsize,Items item) { int ret=0; for (int i = 0; i < maxsize; i++) { KeyValuePair<Items, int>? itemslot=items[i]; if (itemslot != null && itemslot.Value.Key==item) { ret+=itemslot.Value.Value; } } return ret; } // Deletes an item from items array, maximum size per slot, item, and number of items to delete public static bool pbDeleteItem(ref KeyValuePair<Items, int>[] items,int maxsize,Items item,int qty) { if (qty<0) throw new Exception($"Invalid value for qty: #{qty}"); if (qty==0) return true; bool ret=false; for (int i = 0; i < maxsize; i++) { KeyValuePair<Items, int>? itemslot=items[i]; if (itemslot != null && itemslot.Value.Key==item) { int amount=Math.Min(qty,itemslot.Value.Value); //itemslot.Value.Value-=amount; itemslot=new KeyValuePair<Items,int>(itemslot.Value.Key,itemslot.Value.Value-amount); qty-=amount; //if (itemslot.Value.Value==0) items[i]=null; if (itemslot.Value.Value==0) { var _ = items.ToList(); _.RemoveAt(i); items = _.ToArray(); } if (qty==0) { ret=true; break; } } } //items.compact(); return ret; } public static bool pbCanStore(KeyValuePair<Items, int>[] items,int maxsize,int maxPerSlot,Items item,int qty) { if (qty<0) throw new Exception($"Invalid value for qty: #{qty}"); if (qty==0) return true; for (int i = 0; i < maxsize; i++) { KeyValuePair<Items, int>? itemslot=items[i]; if (itemslot == null) { qty-= Math.Min(qty,maxPerSlot); if (qty==0) return true; } else if (itemslot.Value.Key==item && itemslot.Value.Value<maxPerSlot) { int newamt=itemslot.Value.Value; newamt=Math.Min(newamt+qty,maxPerSlot); qty-=(newamt-itemslot.Value.Value); if (qty==0) return true; } } return false; } public static bool pbStoreItem(ref KeyValuePair<Items, int>[] items,int maxsize,int maxPerSlot,Items item,int qty,bool sorting=false) { if (qty<0) throw new Exception($"Invalid value for qty: #{qty}"); if (qty==0) return true; for (int i = 0; i < maxsize; i++) { KeyValuePair<Items, int>? itemslot=items[i]; if (itemslot == null) { items[i]=new KeyValuePair<Items, int> (item, Math.Min(qty, maxPerSlot)); qty-=items[i].Value; if (sorting) { //if (Core.POCKETAUTOSORT[ItemData[item][ITEMPOCKET]]) items.Sort(); if (Core.POCKETAUTOSORT[(int)(Game.ItemData[item].Pocket??0)]) items.OrderBy(x => x.Key); } if (qty==0) return true; } else if (itemslot.Value.Key==item && itemslot.Value.Value<maxPerSlot) { int newamt=itemslot.Value.Value; newamt=Math.Min(newamt+qty,maxPerSlot); qty-=(newamt-itemslot.Value.Value); //itemslot.Value.Value=newamt; itemslot=new KeyValuePair<Items,int>(itemslot.Value.Key,newamt); if (qty==0) return true; } } return false; } } }
bsd-3-clause
C#
6d6e781e93688c38d473d119cad34ffec2ecae9b
move zeros
Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode,Javran/leetcode
move-zeroes/Solution.cs
move-zeroes/Solution.cs
using System; public class Solution { public void MoveZeroes(int[] nums) { int srcInd = 0, tgtInd = 0; while (srcInd < nums.Length) { // skipping zeroes while (srcInd < nums.Length && nums[srcInd] == 0) ++srcInd; // INVARIANT: // - either srcInd < nums.Length and nums[srcInd] is not zero // or srcInd >= nums.Length // - nums from index 0 to index tgtInd-1 are all processed // - tgtInd <= srcInd if (srcInd < nums.Length) { if (tgtInd != srcInd) { nums[tgtInd] = nums[srcInd]; } ++srcInd; ++tgtInd; } } // we have reached the array end, no more zeros to be copied // so we just continue and set all [tgtInd+1 ..] zero. for (int i = tgtInd; i < nums.Length; ++i) { nums[i] = 0; } } static void Main(string[] args) { int [] nums = {0,1,2,3}; foreach (var n in nums) Console.WriteLine(n); new Solution().MoveZeroes(nums); foreach (var n in nums) Console.WriteLine(n); } }
mit
C#
98230981aac505c207e142823c5935e6b29be83e
Add XAmzContentSha256Values
carbon/Amazon
src/Amazon.Core/Security/XAmzContentSha256Value.cs
src/Amazon.Core/Security/XAmzContentSha256Value.cs
namespace Amazon; internal static class XAmzContentSha256Values { public const string UnsignedPayload = "UNSIGNED-PAYLOAD"; public const string StreamingAwsHmacSha256Payload = "STREAMING-AWS4-HMAC-SHA256-PAYLOAD"; } // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming-trailers.html
mit
C#
55e1d41463c65f1e28a72f2d367fdabb63880eec
Add PropertyEqualityComparer
riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy
src/DotvvmAcademy.Meta/PropertyEqualityComparer.cs
src/DotvvmAcademy.Meta/PropertyEqualityComparer.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace DotvvmAcademy.Meta { public class PropertyEqualityComparer : IEqualityComparer<object>, IEqualityComparer { public new bool Equals(object one, object two) { var oneType = one.GetType(); var twoType = two.GetType(); var onesProperties = oneType.GetProperties(BindingFlags.Instance | BindingFlags.Public); foreach (var onesProperty in onesProperties) { var twosProperty = twoType.GetProperty(onesProperty.Name, BindingFlags.Instance | BindingFlags.Public); var onesValue = onesProperty.GetValue(one); var twosValue = twosProperty.GetValue(two); if (!onesValue.Equals(twosValue)) { return false; } } return true; } public int GetHashCode(object obj) { throw new NotImplementedException(); } } }
apache-2.0
C#
458fb046f1b24e380fc6abfe0ede2a11e9da9e84
Add RandonPageGenerator.cs
CXuesong/WikiClientLibrary
WikiClientLibrary/Generators/RandomPageGenerator.cs
WikiClientLibrary/Generators/RandomPageGenerator.cs
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Text; using WikiClientLibrary.Client; using WikiClientLibrary.Generators; using WikiClientLibrary.Generators.Primitive; using WikiClientLibrary.Pages; using WikiClientLibrary.Sites; namespace WikiClientLibrary.Generators { /// <summary> /// Gets random pages in a specific namespace. /// </summary> class RandomPageGenerator : WikiPageGenerator { /// <inheritdoc /> public RandomPageGenerator(WikiSite site) : base(site) { } protected override WikiPageStub ItemFromJson(JToken json) { return new WikiPageStub((int)json["id"], (string)json["title"], (int)json["ns"]); } public int NamespaceId { get; set; } = 0; /// <summary> /// How to filter redirects. /// </summary> public PropertyFilterOption RedirectsFilter { get; set; } /// <inheritdoc/> public override string ListName => "random"; /// <inheritdoc/> public override IEnumerable<KeyValuePair<string, object>> EnumListParameters() { return new Dictionary<string, object> { { "rnnamespace", NamespaceId}, {"rnfilterredir", RedirectsFilter}, {"rnlimit", PaginationSize}, }; } } } }
apache-2.0
C#
a0b5d8da40f5a9bfda62f5bbda901a02021de3a2
Create BenceLenart.cs (#689)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/BenceLenart.cs
src/Firehose.Web/Authors/BenceLenart.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class BenceLenart : IAmACommunityMember { public string FirstName => "Bence"; public string LastName => "Lenart"; public string ShortBioOrTagLine => "Xamarin developer and blogger."; public string StateOrRegion => "Szeged, Hungary"; public string EmailAddress => "bence960206@gmail.com"; public Uri WebSite => new Uri("ttps://officialdoniald.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://officialdoniald.com/feed"); } } public string TwitterHandle => "officialdoniald"; public string GravatarHash => "4e467fcdbb65da5080d215bf303c442a"; public string GitHubHandle => "officialdoniald"; public GeoPosition Position => new GeoPosition(46.231222, 20.119167); public string FeedLanguageCode => "en"; } }
mit
C#
554a2c21ea08f890606c0ebbbcb5f3c5ee4c7955
make refactoring auth module
CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity,CloudBreadProject/CloudBread-Client-Unity
Assets/Scripts/CloudBread/Authentication/UserAuth.cs
Assets/Scripts/CloudBread/Authentication/UserAuth.cs
using System; using UnityEngine; //using Unity namespace CloudBread.Authentication { public class UserAuth : MonoBehaviour { public UserAuth () { } public class AuthenticationToken { } public class FacebookGoogleAuthenticationToken : AuthenticationToken { public string access_token; } public class GoogleAuthenticationToken : AuthenticationToken { public string access_token; public string id_token; public string authorization_code; } public class MicrosoftAuthenticationToken : AuthenticationToken { public string authenticationToken; } public enum AuthenticationProvider { // Summary: // Microsoft Account authentication provider. MicrosoftAccount = 0, // // Summary: // Google authentication provider. Google = 1, // // Summary: // Twitter authentication provider. Twitter = 2, // // Summary: // Facebook authentication provider. Facebook = 3, } private Action<string,WWW> Callback_Success; private Action<string,WWW> Callback_Error; public void Login(AuthenticationProvider provider, string ServerAddress, string token, Action<string, WWW> callback_success, Action<string, WWW> callback_error){ var path = ".auth/login/" + provider.ToString().ToLower(); AuthenticationToken authToken = CreateToken(provider, token); string json = JsonUtility.ToJson(authToken); print (json); Callback_Success = callback_success; Callback_Error = callback_error; WWWHelper helper = WWWHelper.Instance; helper.OnHttpRequest += OnHttpRequest; helper.POST ("Login", ServerAddress + path, json); } public void Login(string ServerAddress, AuthenticationProvider provider, AuthenticationToken token, Action<string, WWW> callback_success, Action<string, WWW> callback_error){ var path = ".auth/login/" + provider.ToString().ToLower(); string json = JsonUtility.ToJson(token); print (json); Callback_Success = callback_success; Callback_Error = callback_error; WWWHelper helper = WWWHelper.Instance; helper.OnHttpRequest += OnHttpRequest; helper.POST ("Login", ServerAddress + path, json); } public void OnHttpRequest(string id, WWW www) { WWWHelper helper = WWWHelper.Instance; helper.OnHttpRequest -= OnHttpRequest; if (www.error != null) { // Debug.Log ("[Error] " + www.error); Callback_Error(id,www); } else { // Debug.Log (www.text); Callback_Success(id, www); } } private static AuthenticationToken CreateToken(AuthenticationProvider provider, string token) { AuthenticationToken authToken = new AuthenticationToken(); switch (provider) { case AuthenticationProvider.Facebook: case AuthenticationProvider.Google: case AuthenticationProvider.Twitter: { authToken = new FacebookGoogleAuthenticationToken() { access_token = token }; break; } case AuthenticationProvider.MicrosoftAccount: { authToken = new MicrosoftAuthenticationToken() { authenticationToken = token }; break; } } return authToken; } } }
mit
C#
cb3db4c14021f188594cc77f7962c70f6b5166d5
Add BoardController script
EquilibriumTechnologies/HackDay01,EquilibriumTechnologies/HackDay01
HackDay1/Assets/scripts/BoardController.cs
HackDay1/Assets/scripts/BoardController.cs
using UnityEngine; using System.Collections; /** * Make an empty GameObject, I called it ControlBox * Add this script to the ControlBox * Make the Ground (and optionally the player) a child of the ControlBox * Add a RigidBody to the ground and select Kinematic * Make walls, etc. children of the ground **/ public class BoardController : MonoBehaviour { void FixedUpdate () { float moveHorizontal = Input.GetAxis ("Horizontal"); float moveVertical = Input.GetAxis ("Vertical"); transform.Rotate (moveVertical, 0.0f, -moveHorizontal); } }
mit
C#
95456b26fbf03635091ef55ec8cc71ea0ed8b593
Add new parser test base
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-yaml/test/src/Psi/Parsing/ParserTestBase.cs
resharper/resharper-yaml/test/src/Psi/Parsing/ParserTestBase.cs
using System; using System.Linq; using JetBrains.Annotations; using JetBrains.Application.Components; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI; using JetBrains.ReSharper.Psi.ExtensionsAPI.Tree; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Impl.Shared; using JetBrains.ReSharper.Psi.Tree; using JetBrains.ReSharper.TestFramework; using JetBrains.ReSharper.TestFramework.Components.Psi; using JetBrains.Util; using NUnit.Framework; namespace JetBrains.ReSharper.Plugins.Yaml.Tests.Psi.Parsing { // This is a replacement for the standard ParserTestBase<TLanguage> that will check the nodes of the parsed tree // against the gold file, but will also assert that all top level chameleons are closed by default and open correctly. // It also asserts that each node correctly matches the textual content of the original document [Category("Parser")] public abstract class ParserTestBase<TLanguage> : BaseTestWithTextControl where TLanguage : PsiLanguageType { protected override void DoTest(IProject testProject) { ShellInstance.GetComponent<TestIdGenerator>().Reset(); using (var textControl = OpenTextControl(testProject)) { ExecuteWithGold(textControl.Document, sw => { var files = textControl .Document .GetPsiSourceFiles(Solution) .SelectMany(s => s.GetPsiFiles<TLanguage>()) .ToList(); files.Sort((file1, file2) => String.Compare(file1.Language.Name, file2.Language.Name, StringComparison.Ordinal)); foreach (var psiFile in files) { // Assert all chameleons are closed by default var chameleons = psiFile.ThisAndDescendants<IChameleonNode>(); while (chameleons.MoveNext()) { var chameleonNode = chameleons.Current; if (chameleonNode.IsOpened && !(chameleonNode is IComment)) Assertion.Fail("Found chameleon node that was opened after parser is invoked: '{0}'", chameleonNode.GetText()); chameleons.SkipThisNode(); } // Dump the PSI tree, opening all chameleons sw.WriteLine("Language: {0}", psiFile.Language); DebugUtil.DumpPsi(sw, psiFile); sw.WriteLine(); if (((IFileImpl) psiFile).SecondaryRangeTranslator is RangeTranslatorWithGeneratedRangeMap rangeTranslator) WriteCommentedText(sw, "//", rangeTranslator.Dump(psiFile)); // Verify textual contents var originalText = textControl.Document.GetText(); Assert.AreEqual(originalText, psiFile.GetText(), "Reconstructed text mismatch"); CheckRange(originalText, psiFile); } }); } } private static void CheckRange([NotNull] string documentText, [NotNull] ITreeNode node) { Assert.AreEqual(node.GetText(), documentText.Substring(node.GetTreeStartOffset().Offset, node.GetTextLength()), "node range text mismatch"); for (var child = node.FirstChild; child != null; child = child.NextSibling) CheckRange(documentText, child); } } }
apache-2.0
C#
2d23471ed433dce44a56ab393405add4ce3b2b4e
add plugins for unity3d
lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame,lightningkay/NoahGameFrame
MiniClient/Assets/Editor/NFEditorWindow.cs
MiniClient/Assets/Editor/NFEditorWindow.cs
using UnityEngine; using UnityEditor; using System.Collections; public static NFCServer CreateServer(string name) { GameObject go = new GameObject(name); NFCServer client = go.AddComponent<NFCServer>(); } public static NFCClient CreateClient(string name) { GameObject go = new GameObject(name); NFCClient client = go.AddComponent<NFCClient>(); return client; } [ExecuteInEditMode] public class NFEditorWindow : EditorWindow { [MenuItem("Window/NF/New NF Server")] public static void CreateMultiServer() { //NF.CreateServer(); } [MenuItem("Window/NF/New NF Client")] public static void CreateCient() { //NF.CreateClient(); } }
apache-2.0
C#
74dcff38b5a03e98ec36b10dc11430ac628c17e6
Create Program.cs
dhuzz/auto-install,abdussami-tayyab/auto-install
Program.cs
Program.cs
using System; using System.IO; using System.Diagnostics; using System.ComponentModel; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; namespace autoInstall { class Program { Process process = new Process(); // create a global Process int elapsedTime; // this variable holds the elapsed time of every process bool eventHandled; // this variable depends upon the process status StreamReader file = new StreamReader("input.txt"); // this is the input file that holds the working directory and commands public static void Main(string[] args) { Program prog = new Program(); // creating a Program prog.executeCommands(); } public void executeCommands() { try { processSetup(); // setup the process below string workingDirectory = file.ReadLine(); // read the working directory from the file's first line process.StartInfo.WorkingDirectory = workingDirectory; string commands = file.ReadLine(); // read all the commands while (!file.EndOfStream) commands = commands + " & " + file.ReadLine(); commands = commands + " & " + "exit"; process.StartInfo.Arguments = "/K " + commands; Console.WriteLine("File has been successfully read, now executing your commands\nRunning"); process.Start(); // starting the process } catch (Exception ex) { Console.WriteLine("An error occurred trying to execute commands" + "\n" + ex.Message); return; } const int SLEEP_AMOUNT = 100; while (!eventHandled) // runs until the process has not completed { elapsedTime += SLEEP_AMOUNT; if (elapsedTime > 30000) { break; } Thread.Sleep(SLEEP_AMOUNT); // makes the thread stop for the elapsed time } } public void processSetup() { process.StartInfo.FileName = "cmd.exe"; // the app name process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // hide the app window process.EnableRaisingEvents = true; // this triggers the event exited function when the process has exited process.Exited += new EventHandler(processExited); // adding a new event handler to the exited process } private void processExited(object sender, System.EventArgs e) { eventHandled = true; Console.WriteLine("Exit time: {0}\r\n" + "Exit code: {1}\r\nElapsed time: {2}", process.ExitTime, process.ExitCode, elapsedTime); } } }
mit
C#
bdf6c2a5edf61d89dcb095acd86672c1367e07e2
add changelog supporter promo test scene
NeoAdonis/osu,ppy/osu,peppy/osu-new,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,ppy/osu
osu.Game.Tests/Visual/Online/TestSceneChangelogSupporterPromo.cs
osu.Game.Tests/Visual/Online/TestSceneChangelogSupporterPromo.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Game.Overlays; using osu.Game.Overlays.Changelog; namespace osu.Game.Tests.Visual.Online { public class TestSceneChangelogSupporterPromo : OsuTestScene { [Cached] private readonly OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Purple); public TestSceneChangelogSupporterPromo() { Child = new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colourProvider.Background4, }, new ChangelogSupporterPromo(), } }; } } }
mit
C#
b88a8fc62feba7cd6897b489ecd6abb3ad7fe551
Add recursive OrderX function to Graph.cs, rename PointSequenceInvalidExcpetion to PointOutofBoundsException, accept points of any X value and then order them from smallest to largest, refactor Plot(List<Vector2> points) function to order X values using OrderX
sodafountan/Graphing
Graphing/PointOutofBoundsException.cs
Graphing/PointOutofBoundsException.cs
 namespace Graphing { internal class PointOutofBoundsException : System.Exception { public PointOutofBoundsException(string message = "A point is out of bounds from the graph") : base(message) { } } }
mit
C#
274c04fc1d80f3415d4cfd7c192468136a4c1d95
Add Log4NetExtensions.cs
agardiner/hfmcmd,agardiner/hfmcmd,agardiner/hfmcmd
src/Log4NetExtensions.cs
src/Log4NetExtensions.cs
using System; using System.Text; using System.Collections; using System.IO; using System.Runtime.InteropServices; using log4net; using log4net.ObjectRenderer; using log4net.Repository.Hierarchy; namespace HFMCmd { /// <summary> /// Extension methods for adding additional log shortcuts for Verbose and /// Trace level logging. /// </summary> public static class ILogExtentions { public static void Fine(this ILog log, string message, Exception exception) { log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, log4net.Core.Level.Fine, message, exception); } public static void Fine(this ILog log, string message) { log.Fine(message, null); } public static void FineFormat(this ILog log, string message, params object[] args) { if(log.Logger.IsEnabledFor(log4net.Core.Level.Fine)) { log.Fine(string.Format(message, args), null); } } public static void Trace(this ILog log, string message, Exception exception) { log.Logger.Log(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, log4net.Core.Level.Trace, message, exception); } public static void Trace(this ILog log, string message) { log.Trace(message, null); } public static void TraceFormat(this ILog log, string message, params object[] args) { if(log.Logger.IsEnabledFor(log4net.Core.Level.Trace)) { log.Trace(string.Format(message, args), null); } } } /// <summary> /// Class for handling logging of exceptions. Used to avoid the default /// behaviour of logging a full back-trace when an exception occurs. /// </summary> public sealed class ExceptionMessageRenderer : IObjectRenderer { /// Reference to the logger hierarchy private Hierarchy _logHierarchy; /// Constructor public ExceptionMessageRenderer() { _logHierarchy = LogManager.GetRepository() as Hierarchy; } /// Implementation of the IObjectRenderer interface. Called on when an /// exception is logged. public void RenderObject(RendererMap map, object obj, System.IO.TextWriter writer) { Exception ex = obj as Exception; string stackTrace = ex.StackTrace; for (; ex != null; ex = ex.InnerException) { if (ex is COMException && ex.Message.StartsWith("<?xml")) { writer.Write("HFMException message XML contents:"); writer.Write(ex); } else { writer.Write(ex.GetType().Name); writer.Write(": "); writer.Write(ex.Message); } if (ex.InnerException != null) { writer.WriteLine(); } } if (_logHierarchy.Root.Level.CompareTo(log4net.Core.Level.Fine) < 0) { writer.WriteLine(); writer.WriteLine(); writer.WriteLine("Backtrace:"); writer.Write(stackTrace); } } } }
bsd-2-clause
C#
4ef9a514f666a6c3e38c3fbcd8efffd028359134
Add support for reading DepedencyContext from deps file
ravimeda/core-setup,ellismg/core-setup,wtgodbe/core-setup,vivmishra/core-setup,joperezr/core-setup,janvorli/core-setup,vivmishra/core-setup,ellismg/core-setup,janvorli/core-setup,steveharter/core-setup,ericstj/core-setup,chcosta/core-setup,ellismg/core-setup,ramarag/core-setup,cakine/core-setup,joperezr/core-setup,MichaelSimons/core-setup,MichaelSimons/core-setup,cakine/core-setup,ericstj/core-setup,zamont/core-setup,joperezr/core-setup,rakeshsinghranchi/core-setup,wtgodbe/core-setup,ravimeda/core-setup,wtgodbe/core-setup,crummel/dotnet_core-setup,ravimeda/core-setup,ravimeda/core-setup,weshaggard/core-setup,MichaelSimons/core-setup,janvorli/core-setup,rakeshsinghranchi/core-setup,weshaggard/core-setup,joperezr/core-setup,rakeshsinghranchi/core-setup,chcosta/core-setup,chcosta/core-setup,ellismg/core-setup,MichaelSimons/core-setup,ravimeda/core-setup,zamont/core-setup,wtgodbe/core-setup,wtgodbe/core-setup,cakine/core-setup,steveharter/core-setup,vivmishra/core-setup,zamont/core-setup,MichaelSimons/core-setup,ramarag/core-setup,karajas/core-setup,cakine/core-setup,wtgodbe/core-setup,crummel/dotnet_core-setup,chcosta/core-setup,schellap/core-setup,weshaggard/core-setup,vivmishra/core-setup,joperezr/core-setup,chcosta/core-setup,vivmishra/core-setup,ericstj/core-setup,janvorli/core-setup,chcosta/core-setup,weshaggard/core-setup,ramarag/core-setup,cakine/core-setup,rakeshsinghranchi/core-setup,ellismg/core-setup,steveharter/core-setup,schellap/core-setup,crummel/dotnet_core-setup,steveharter/core-setup,gkhanna79/core-setup,ravimeda/core-setup,gkhanna79/core-setup,karajas/core-setup,janvorli/core-setup,karajas/core-setup,zamont/core-setup,joperezr/core-setup,ramarag/core-setup,rakeshsinghranchi/core-setup,gkhanna79/core-setup,vivmishra/core-setup,ramarag/core-setup,MichaelSimons/core-setup,ericstj/core-setup,zamont/core-setup,schellap/core-setup,gkhanna79/core-setup,schellap/core-setup,steveharter/core-setup,ellismg/core-setup,karajas/core-setup,zamont/core-setup,cakine/core-setup,karajas/core-setup,schellap/core-setup,weshaggard/core-setup,weshaggard/core-setup,janvorli/core-setup,crummel/dotnet_core-setup,rakeshsinghranchi/core-setup,crummel/dotnet_core-setup,gkhanna79/core-setup,ericstj/core-setup,karajas/core-setup,steveharter/core-setup,gkhanna79/core-setup,ramarag/core-setup,crummel/dotnet_core-setup,ericstj/core-setup,schellap/core-setup
DependencyContextCsvReaderTests.cs
DependencyContextCsvReaderTests.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Text; using Microsoft.Extensions.DependencyModel; using FluentAssertions; using Xunit; namespace Microsoft.Extensions.DependencyModel.Tests { public class DependencyContextCsvReaderTests { private DependencyContext Read(string text) { using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(text))) { return new DependencyContextCsvReader().Read(stream); } } [Fact] public void GroupsAssetsCorrectlyIntoLibraries() { var context = Read(@" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.Runtime.dll"" "); context.RuntimeLibraries.Should().HaveCount(1); var library = context.RuntimeLibraries.Single(); library.LibraryType.Should().Be("Package"); library.PackageName.Should().Be("runtime.any.System.AppContext"); library.Version.Should().Be("4.1.0-rc2-23811"); library.Hash.Should().Be("sha512-1"); library.Assemblies.Should().HaveCount(2).And .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll").And .Contain(a => a.Path == "lib\\dnxcore50\\System.Runtime.dll"); } [Fact] public void IgnoresAllButRuntimeAssets() { var context = Read(@" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""native"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext2.so"" "); context.RuntimeLibraries.Should().HaveCount(1); var library = context.RuntimeLibraries.Single(); library.Assemblies.Should().HaveCount(1).And .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll"); } [Fact] public void IgnoresNiDllAssemblies() { var context = Read(@" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.ni.dll"" "); context.RuntimeLibraries.Should().HaveCount(1); var library = context.RuntimeLibraries.Single(); library.Assemblies.Should().HaveCount(1).And .Contain(a => a.Path == "lib\\dnxcore50\\System.AppContext.dll"); } [Fact] public void UsesTypeNameVersionAndHashToGroup() { var context = Read(@" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23812"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-2"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Package"",""runtime.any.System.AppContext2"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" ""Project"",""runtime.any.System.AppContext"",""4.1.0-rc2-23811"",""sha512-1"",""runtime"",""System.AppContext"",""lib\\dnxcore50\\System.AppContext.dll"" "); context.RuntimeLibraries.Should().HaveCount(5); } [Theory] [InlineData("text")] [InlineData(" ")] [InlineData("\"")] [InlineData(@""",""")] [InlineData(@"\\")] public void ThrowsFormatException(string intput) { Assert.Throws<FormatException>(() => Read(intput)); } } }
mit
C#
5242888188ec129838c0a02d419c8481aab92592
bump version
jasonholloway/Fody,distantcam/Fody,ichengzi/Fody,furesoft/Fody,PKRoma/Fody,shanselman/Fody,huoxudong125/Fody,shanselman/Fody,shanselman/Fody,Fody/Fody,ColinDabritzViewpoint/Fody,GeertvanHorrik/Fody
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("1.6.4.0")] [assembly: AssemblyFileVersion("1.6.4.0")]
using System.Reflection; [assembly: AssemblyTitle("Fody")] [assembly: AssemblyProduct("Fody")] [assembly: AssemblyVersion("1.6.3.0")] [assembly: AssemblyFileVersion("1.6.3.0")]
mit
C#
c025ee03077d331ba09b75d0bf572891c7ef8e04
add OnClickOpenBrower.cs
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/UnityTools/OnClickOpenBrower.cs
Unity/UnityTools/OnClickOpenBrower.cs
/** MIT License Copyright (c) 2017 NDark Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** @file OnClickOpenBrower.cs @author NDark @date 20170501 . file started. */ using UnityEngine; public class OnClickOpenBrower : MonoBehaviour { public string m_Url = string.Empty ; public void OpenBrower() { // Debug.Log( Application.platform ) ; if( Application.platform == RuntimePlatform.WebGLPlayer ) { string url = "window.open('" + m_Url + "','aNewWindow')" ; // Debug.Log( url ) ; Application.ExternalEval( url ); } else /*if( Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor )*/ { Application.OpenURL( m_Url ) ; } } void OnClick() { OpenBrower() ; } }
mit
C#
94494e02e31a51d0d8390ac8fe3213d0a8254832
Create Problem46.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problems/Problem46.cs
Problems/Problem46.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler.Problems { class Problem46 { private Sieve s; private int upper = 10000; public Problem46() { s = new Sieve(upper); } public void Run() { for (int i = 3; i < upper; i += 2) { if (!s.prime[i]) // Composite Odd numbers { bool foundSum = false; for(int p = 0; p < s.primeList.Count(); p++) { long prime = s.primeList[p]; if (prime >= i) { break; } for(int x = 1; x < (i - prime); x++) { if (i == prime + (x * x) * 2) { foundSum = true; } } if (foundSum) { break; } } if (!foundSum) { Console.WriteLine(i); return; } } } Console.WriteLine("Not found in first " + upper.ToString()); } } }
mit
C#
6b88141e58b6d3863b1aeb9db41d39225cd00bda
Add mania sample conversion test
NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu
osu.Game.Rulesets.Mania.Tests/ManiaBeatmapSampleConversionTest.cs
osu.Game.Rulesets.Mania.Tests/ManiaBeatmapSampleConversionTest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Utils; using osu.Game.Audio; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Objects; using osu.Game.Tests.Beatmaps; namespace osu.Game.Rulesets.Mania.Tests { [TestFixture] public class ManiaBeatmapSampleConversionTest : BeatmapConversionTest<ConvertMapping<SampleConvertValue>, SampleConvertValue> { protected override string ResourceAssembly => "osu.Game.Rulesets.Mania"; public void Test(string name) => base.Test(name); protected override IEnumerable<SampleConvertValue> CreateConvertValue(HitObject hitObject) { yield return new SampleConvertValue { StartTime = hitObject.StartTime, EndTime = hitObject.GetEndTime(), Column = ((ManiaHitObject)hitObject).Column, NodeSamples = getSampleNames((hitObject as HoldNote)?.NodeSamples) }; } private IList<IList<string>> getSampleNames(List<IList<HitSampleInfo>> hitSampleInfo) => hitSampleInfo?.Select(samples => (IList<string>)samples.Select(sample => sample.LookupNames.First()).ToList()) .ToList(); protected override Ruleset CreateRuleset() => new ManiaRuleset(); } public struct SampleConvertValue : IEquatable<SampleConvertValue> { /// <summary> /// A sane value to account for osu!stable using ints everywhere. /// </summary> private const float conversion_lenience = 2; public double StartTime; public double EndTime; public int Column; public IList<IList<string>> NodeSamples; public bool Equals(SampleConvertValue other) => Precision.AlmostEquals(StartTime, other.StartTime, conversion_lenience) && Precision.AlmostEquals(EndTime, other.EndTime, conversion_lenience) && samplesEqual(NodeSamples, other.NodeSamples); private static bool samplesEqual(ICollection<IList<string>> first, ICollection<IList<string>> second) { if (first == null && second == null) return true; // both items can't be null now, so if any single one is, then they're not equal if (first == null || second == null) return false; return first.Count == second.Count && first.Zip(second).All(samples => samples.First.SequenceEqual(samples.Second)); } } }
mit
C#
4e885de6c785f6d15bf25aa562edb6da92fac72c
Prepare parser for scripting
MetacoSA/NBitcoin,MetacoSA/NBitcoin,NicolasDorier/NBitcoin
NBitcoin/Scripting/Parser/ParseException.cs
NBitcoin/Scripting/Parser/ParseException.cs
using System; namespace NBitcoin.Scripting.Parser { /// <summary> /// Represents an error that occurs during parsing. /// </summary> public class ParseException : Exception { /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class. /// </summary> public ParseException() { } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message. /// </summary> /// <param name="message">The message that describes the error.</param> public ParseException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and the position where the error occured. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="position">The position where the error occured.</param> public ParseException(string message, int position) : base(message) { Position = position; } /// <summary> /// Initializes a new instance of the <see cref="ParseException" /> class with a specified error message /// and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, /// or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public ParseException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Gets the position of the parsing failure if one is available; otherwise, null. /// </summary> public int Position { get; } } }
mit
C#
501991f788b62685167daf29b7e19491a3cd3030
Remove unused properties.
mnaiman/duplicati,sitofabi/duplicati,duplicati/duplicati,sitofabi/duplicati,duplicati/duplicati,sitofabi/duplicati,mnaiman/duplicati,mnaiman/duplicati,duplicati/duplicati,sitofabi/duplicati,mnaiman/duplicati,duplicati/duplicati,duplicati/duplicati,mnaiman/duplicati,sitofabi/duplicati
Duplicati/Library/Backend/Sia/Strings.cs
Duplicati/Library/Backend/Sia/Strings.cs
using Duplicati.Library.Localization.Short; namespace Duplicati.Library.Backend.Strings { internal static class Sia { public static string DisplayName { get { return LC.L(@"Sia Decentralized Cloud"); } } public static string Description { get { return LC.L(@"This backend can read and write data to Sia."); } } public static string SiaPathDescriptionShort { get { return LC.L(@"Backup path"); } } public static string SiaPathDescriptionLong { get { return LC.L(@"Target path, ie /backup"); } } public static string SiaPasswordShort { get { return LC.L(@"Sia password"); } } public static string SiaPasswordLong { get { return LC.L(@"Sia password"); } } public static string SiaRedundancyDescriptionShort { get { return LC.L(@"3"); } } public static string SiaRedundancyDescriptionLong { get { return LC.L(@"Minimum value is 3."); } } } }
using Duplicati.Library.Localization.Short; namespace Duplicati.Library.Backend.Strings { internal static class Sia { public static string DisplayName { get { return LC.L(@"Sia Decentralized Cloud"); } } public static string Description { get { return LC.L(@"This backend can read and write data to Sia."); } } public static string SiaHostDescriptionShort { get { return LC.L(@"Sia address"); } } public static string SiaHostDescriptionLong { get { return LC.L(@"Sia address, ie 127.0.0.1:9980"); } } public static string SiaPathDescriptionShort { get { return LC.L(@"Backup path"); } } public static string SiaPathDescriptionLong { get { return LC.L(@"Target path, ie /backup"); } } public static string SiaPasswordShort { get { return LC.L(@"Sia password"); } } public static string SiaPasswordLong { get { return LC.L(@"Sia password"); } } public static string SiaRedundancyDescriptionShort { get { return LC.L(@"3"); } } public static string SiaRedundancyDescriptionLong { get { return LC.L(@"Minimum value is 3."); } } } }
lgpl-2.1
C#
89337d08eee91d69917c6c43eab15669f602dc63
Create Problem55.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problems/Problem55.cs
Problems/Problem55.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Numerics; namespace ProjectEuler.Problems { class Problem55 { private int upper = 10000; private int lycrel = 50; private bool Palindrome(BigInteger number) { bool is_palindrome = true; string numberStr = number.ToString(); for (int i = 0; i < numberStr.Length / 2; i++) { is_palindrome &= numberStr[i] == numberStr[numberStr.Length - 1 - i]; if (!is_palindrome) { break; } } return is_palindrome; } private BigInteger ReverseAndAdd(BigInteger number) { string numberStr = number.ToString(); string invertStr = ""; for(int i=numberStr.Length-1; i>=0;i--) { invertStr += numberStr[i]; } return number + BigInteger.Parse(invertStr); } public string Run() { int count = 0; List<int> lycrel_numbers = new List<int>(); for (int number = 1; number <= upper; number++) { int i = 1; BigInteger candidate = new BigInteger(number); do { candidate = ReverseAndAdd(candidate); if (Palindrome(candidate)) { break; } i++; } while (i <= lycrel); if (i > lycrel) { lycrel_numbers.Add(number); count++; } } return count.ToString(); } } }
mit
C#
073dce1e44247018b68ecad5d4014d3f585d31bc
Remove default initialization
DrabWeb/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,paparony03/osu-framework,ppy/osu-framework,Tom94/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,default0/osu-framework,ZLima12/osu-framework,ppy/osu-framework,default0/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,peppy/osu-framework,ppy/osu-framework
osu.Framework/Graphics/Effects/BlurEffect.cs
osu.Framework/Graphics/Effects/BlurEffect.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK; using osu.Framework.Graphics.Containers; using osu.Framework.MathUtils; namespace osu.Framework.Graphics.Effects { /// <summary> /// A blur effect that wraps a drawable in a <see cref="BufferedContainer"/> which applies a blur effect to it. /// </summary> public class BlurEffect : IEffect<BufferedContainer> { /// <summary> /// The strength of the blur. Default is 1. /// </summary> public float Strength { get; set; } = 1f; /// <summary> /// The sigma of the blur. Default is (2, 2). /// </summary> public Vector2 Sigma { get; set; } = new Vector2(2f, 2f); /// <summary> /// The rotation of the blur. Default is 0. /// </summary> public float BlurRotation { get; set; } public BufferedContainer ApplyTo(Drawable drawable) { return new BufferedContainer { RelativeSizeAxes = drawable.RelativeSizeAxes, AutoSizeAxes = Axes.Both & ~drawable.RelativeSizeAxes, BlurSigma = Sigma, Anchor = drawable.Anchor, Origin = drawable.Origin, BlurRotation = BlurRotation, Padding = new MarginPadding { Horizontal = Blur.KernelSize(Sigma.X), Vertical = Blur.KernelSize(Sigma.Y) }, Alpha = Strength, Children = new[] { drawable } }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using OpenTK; using osu.Framework.Graphics.Containers; using osu.Framework.MathUtils; namespace osu.Framework.Graphics.Effects { /// <summary> /// A blur effect that wraps a drawable in a <see cref="BufferedContainer"/> which applies a blur effect to it. /// </summary> public class BlurEffect : IEffect<BufferedContainer> { /// <summary> /// The strength of the blur. Default is 1. /// </summary> public float Strength { get; set; } = 1f; /// <summary> /// The sigma of the blur. Default is (2, 2). /// </summary> public Vector2 Sigma { get; set; } = new Vector2(2f, 2f); /// <summary> /// The rotation of the blur. Default is 0. /// </summary> public float BlurRotation { get; set; } = 0f; public BufferedContainer ApplyTo(Drawable drawable) { return new BufferedContainer { RelativeSizeAxes = drawable.RelativeSizeAxes, AutoSizeAxes = Axes.Both & ~drawable.RelativeSizeAxes, BlurSigma = Sigma, Anchor = drawable.Anchor, Origin = drawable.Origin, BlurRotation = BlurRotation, Padding = new MarginPadding { Horizontal = Blur.KernelSize(Sigma.X), Vertical = Blur.KernelSize(Sigma.Y) }, Alpha = Strength, Children = new[] { drawable } }; } } }
mit
C#
29c50a99eb08cc1d007fe84548dfc19aafb6843f
Create problem010.cs
mvdiener/project_euler,mvdiener/project_euler
CSharp/problem010.cs
CSharp/problem010.cs
//The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. //Find the sum of all the primes below two million. using System; using System.Collections.Generic; using System.Linq; namespace Problem010 { class MainClass { public static void Main() { List<int> primes = FindPrimesInRange(2000000); Console.WriteLine(SumOfList(primes)); } public static List<int> FindPrimesInRange(int num) { int val; List<int> allNumbers = Enumerable.Range(2, num-1).ToList(); int count = allNumbers.Count() - 1; for (int i = 0; i < count; i++) { if (allNumbers[i] != 0) { val = allNumbers[i]; while (i + val <= count) { allNumbers[i + val] = 0; val += allNumbers[i]; } } } return allNumbers; } public static long SumOfList(List<int> list) { return list.Sum(x => (long)x); } } }
mit
C#
c2505c133ba45876969d28d6865fdd0e59744eac
Create CircularMovingSum.cs
Zephyr-Koo/sololearn-challenge
CircularMovingSum.cs
CircularMovingSum.cs
using System; using System.Collections.Generic; using System.Linq; // https://www.sololearn.com/Discuss/666260/?ref=app namespace SoloLearn { class Program { static void Main(string[] zephyr_koo) { DisplayCircularSum(new int[] { 1, 3, 4 }, 5); // Case 1 DisplayCircularSum(new int[] { 1, 6, 7, 8 }, 3); // Case 2 DisplayCircularSum(new int[] { 4, 5 }, 5); // Case 3 DisplayCircularSum(new int[] { 2, -4, 6, -7 }, 5); // Case 4 } static void DisplayCircularSum(int[] numList, int count) { var len = numList.Length; var sumArray = Enumerable.Range(0, len) .Select(n => Enumerable.Range(n, count) .Sum(i => numList[i % len])); Console.WriteLine(string.Join(", ", sumArray)); } /// <summary> /// This alternative was used to demonstrate the idea for the /// full LINQ solution above if you couldn't follow it. /// </summary> /// <param name="numList"></param> /// <param name="count"></param> static void DisplayCircularSum_PartialLINQ(int[] numList, int count) { var len = numList.Length; var sumArray = new List<int>(); for (int i = 0; i < len; i++) { var partialSum = Enumerable.Range(i, count) .Sum(n => numList[n % len]); sumArray.Add(partialSum); } Console.WriteLine(string.Join(", ", sumArray)); } } }
apache-2.0
C#
7d9c0be6f3b5d879773d56a22a0e7b16c9bdff56
Add structs for TMD file
Figglewatts/LBD2OBJ
LBD2OBJ/Types/TMD.cs
LBD2OBJ/Types/TMD.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LBD2OBJ.Types { struct TMDHEADER { uint ID; // should be 0x41 uint flags; // 0 if addresses are relative from top of block, 1 if from start of file uint numObjects; } struct OBJECT { uint vertTop; // pointer to start of vertices uint numVerts; uint normTop; // pointer to start of normals uint numNorms; uint primTop; // pointer to start of primitives uint numPrims; int scale; // unused } struct PRIMITIVE { byte mode; // b001 - poly, b010 - line, b011 - sprite byte flag; byte ilen; byte olen; } struct VERTEX { short X; short Y; short Z; } struct TMD { TMDHEADER header; OBJECT[] objTable; } }
mit
C#
04071fb48dffafc2801d94cb94cdd26f2845cd35
Add AutoSave on run feature - toggle
guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft
unity/Assets/Editor/AutoSaveOnRunMenuItem.cs
unity/Assets/Editor/AutoSaveOnRunMenuItem.cs
using UnityEngine; using UnityEditor; using UnityEditor.SceneManagement; [InitializeOnLoad] public class AutoSaveOnRunMenuItem { public const string MenuName = "Tools/Autosave On Run"; private static bool isToggled; static AutoSaveOnRunMenuItem() { EditorApplication.delayCall += () => { isToggled = EditorPrefs.GetBool(MenuName, false); UnityEditor.Menu.SetChecked(MenuName, isToggled); SetMode(); }; } [MenuItem(MenuName)] private static void ToggleMode() { isToggled = !isToggled; UnityEditor.Menu.SetChecked(MenuName, isToggled); EditorPrefs.SetBool(MenuName, isToggled); SetMode(); } private static void SetMode() { if (isToggled) { EditorApplication.playModeStateChanged += AutoSaveOnRun; } else { EditorApplication.playModeStateChanged -= AutoSaveOnRun; } } private static void AutoSaveOnRun(PlayModeStateChange state) { if (EditorApplication.isPlayingOrWillChangePlaymode && !EditorApplication.isPlaying) { Debug.Log("Auto-Saving before entering Play mode"); EditorSceneManager.SaveOpenScenes(); AssetDatabase.SaveAssets(); } } }
mit
C#
b9941ab75751a3f25ed17f22275cd31cfb52057f
Add Common class
clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch
csharp/CsSearch/CsSearch/Common.cs
csharp/CsSearch/CsSearch/Common.cs
using System; namespace CsSearch { class Common { public static void Log(string message) { Console.WriteLine(message); } } }
mit
C#
622060c56b78c9104110a92ff533e17d66bef870
Add SetupAccount view
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Views/Home/SetupAccount.cshtml
src/SFA.DAS.EmployerAccounts.Web/Views/Home/SetupAccount.cshtml
@model SFA.DAS.EmployerAccounts.Web.OrchestratorResponse<SFA.DAS.EmployerAccounts.Web.ViewModels.UserAccountsViewModel> @{ViewBag.PageID = "page-auth-setupaccount"; } @{ViewBag.Section = "home"; } @{ViewBag.Title = "Setup your account"; } @{ViewBag.HideNav = "true"; } @{ ViewBag.GaData.Vpv = "/page-auth-setupaccount"; } <div class="grid-row"> <div class="column-full"> @Html.Partial("_SetupAccount") </div> </div>
mit
C#
068e837238eb612e280ee13a121a15bb03b6f2ea
Remove usage of Lazy<DateTime> in LocalTimeKeeper
Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,QuantConnect/Lean,AnshulYADAV007/Lean,jameschch/Lean,StefanoRaggi/Lean,jameschch/Lean,StefanoRaggi/Lean,AnshulYADAV007/Lean,redmeros/Lean,AlexCatarino/Lean,JKarathiya/Lean,AlexCatarino/Lean,redmeros/Lean,jameschch/Lean,JKarathiya/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,redmeros/Lean,QuantConnect/Lean,JKarathiya/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,jameschch/Lean,redmeros/Lean,QuantConnect/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,jameschch/Lean,JKarathiya/Lean,AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,kaffeebrauer/Lean,AlexCatarino/Lean,QuantConnect/Lean,kaffeebrauer/Lean,StefanoRaggi/Lean
Common/LocalTimeKeeper.cs
Common/LocalTimeKeeper.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NodaTime; namespace QuantConnect { /// <summary> /// Represents the current local time. This object is created via the <see cref="TimeKeeper"/> to /// manage conversions to local time. /// </summary> public class LocalTimeKeeper { /// <summary> /// Event fired each time <see cref="UpdateTime"/> is called /// </summary> public event EventHandler<TimeUpdatedEventArgs> TimeUpdated; /// <summary> /// Gets the time zone of this <see cref="LocalTimeKeeper"/> /// </summary> public DateTimeZone TimeZone { get; } /// <summary> /// Gets the current time in terms of the <see cref="TimeZone"/> /// </summary> public DateTime LocalTime { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="LocalTimeKeeper"/> class /// </summary> /// <param name="utcDateTime">The current time in UTC</param> /// <param name="timeZone">The time zone</param> internal LocalTimeKeeper(DateTime utcDateTime, DateTimeZone timeZone) { TimeZone = timeZone; LocalTime = utcDateTime.ConvertTo(DateTimeZone.Utc, TimeZone); } /// <summary> /// Updates the current time of this time keeper /// </summary> /// <param name="utcDateTime">The current time in UTC</param> internal void UpdateTime(DateTime utcDateTime) { LocalTime = utcDateTime.ConvertTo(DateTimeZone.Utc, TimeZone); TimeUpdated?.Invoke(this, new TimeUpdatedEventArgs(LocalTime, TimeZone)); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using NodaTime; namespace QuantConnect { /// <summary> /// Represents the current local time. This object is created via the <see cref="TimeKeeper"/> to /// manage conversions to local time. /// </summary> public class LocalTimeKeeper { private Lazy<DateTime> _localTime; private readonly DateTimeZone _timeZone; /// <summary> /// Event fired each time <see cref="UpdateTime"/> is called /// </summary> public event EventHandler<TimeUpdatedEventArgs> TimeUpdated; /// <summary> /// Gets the time zone of this <see cref="LocalTimeKeeper"/> /// </summary> public DateTimeZone TimeZone { get { return _timeZone; } } /// <summary> /// Gets the current time in terms of the <see cref="TimeZone"/> /// </summary> public DateTime LocalTime { get { return _localTime.Value; } } /// <summary> /// Initializes a new instance of the <see cref="LocalTimeKeeper"/> class /// </summary> /// <param name="utcDateTime">The current time in UTC</param> /// <param name="timeZone">The time zone</param> internal LocalTimeKeeper(DateTime utcDateTime, DateTimeZone timeZone) { _timeZone = timeZone; _localTime = new Lazy<DateTime>(() => utcDateTime.ConvertTo(DateTimeZone.Utc, _timeZone)); } /// <summary> /// Updates the current time of this time keeper /// </summary> /// <param name="utcDateTime">The current time in UTC</param> internal void UpdateTime(DateTime utcDateTime) { // redefine the lazy conversion each time this is set _localTime = new Lazy<DateTime>(() => utcDateTime.ConvertTo(DateTimeZone.Utc, _timeZone)); if (TimeUpdated != null) { TimeUpdated(this, new TimeUpdatedEventArgs(_localTime.Value, TimeZone)); } } } }
apache-2.0
C#
a0a775e3f505538ef589db217a780974276a9b71
Add sorting change menu.
eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile,masterrr/mobile
Joey/UI/Activities/ProjectListActivity.cs
Joey/UI/Activities/ProjectListActivity.cs
using System.Collections.Generic; using Android.App; using Android.Content.PM; using Android.OS; using Toggl.Joey.UI.Fragments; using Activity = Android.Support.V7.App.AppCompatActivity; using Fragment = Android.Support.V4.App.Fragment; using FragmentManager = Android.Support.V4.App.FragmentManager; namespace Toggl.Joey.UI.Activities { [Activity (Label = "ProjectListActivity", ScreenOrientation = ScreenOrientation.Portrait, Theme = "@style/Theme.Toggl.App")] public class ProjectListActivity : BaseActivity { private static readonly string fragmentTag = "projectlist_fragment"; public static readonly string ExtraTimeEntriesIds = "com.toggl.timer.time_entries_ids"; protected override void OnCreateActivity (Bundle state) { base.OnCreateActivity (state); SetContentView (Resource.Layout.ProjectListActivityLayout); // Check if fragment is still in Fragment manager. var fragment = FragmentManager.FindFragmentByTag (fragmentTag); if (fragment == null) { var extras = Intent.Extras; if (extras == null) { Finish (); } var extraGuids = extras.GetStringArrayList (ExtraTimeEntriesIds); fragment = ProjectListFragment.NewInstance (extraGuids); FragmentManager.BeginTransaction () .Add (Resource.Id.ProjectListActivityLayout, fragment, fragmentTag) .Commit (); } else { FragmentManager.BeginTransaction () .Attach (fragment) .Commit (); } } } }
using System.Collections.Generic; using Android.App; using Android.Content.PM; using Android.OS; using Toggl.Joey.UI.Fragments; using Activity = Android.Support.V7.App.AppCompatActivity; using Fragment = Android.Support.V4.App.Fragment; using FragmentManager = Android.Support.V4.App.FragmentManager; using Toggl.Joey.UI.Views; namespace Toggl.Joey.UI.Activities { [Activity (Label = "ProjectListActivity", ScreenOrientation = ScreenOrientation.Portrait, Theme = "@style/Theme.Toggl.App")] public class ProjectListActivity : BaseActivity { private static readonly string fragmentTag = "projectlist_fragment"; public static readonly string ExtraTimeEntriesIds = "com.toggl.timer.time_entries_ids"; protected override void OnCreateActivity (Bundle state) { base.OnCreateActivity (state); SetContentView (Resource.Layout.ProjectListActivityLayout); // Check if fragment is still in Fragment manager. var fragment = FragmentManager.FindFragmentByTag (fragmentTag); if (fragment == null) { var extras = Intent.Extras; if (extras == null) { Finish (); } var extraGuids = extras.GetStringArrayList (ExtraTimeEntriesIds); fragment = ProjectListFragment.NewInstance (extraGuids); FragmentManager.BeginTransaction () .Add (Resource.Id.ProjectListActivityLayout, fragment, fragmentTag) .Commit (); } else { FragmentManager.BeginTransaction () .Attach (fragment) .Commit (); } } } }
bsd-3-clause
C#
7367e79924cced79d9d3722fd5c2b94b8c169023
Add test
ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework
osu.Framework.Tests/Visual/Platform/TestSceneAllowExitingAndroid.cs
osu.Framework.Tests/Visual/Platform/TestSceneAllowExitingAndroid.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Events; using osu.Framework.Platform; using osuTK.Graphics; using osuTK.Input; namespace osu.Framework.Tests.Visual.Platform { public class TestSceneAllowExitingAndroid : FrameworkTestScene { [Resolved] private GameHost host { get; set; } private readonly BindableBool allowExit = new BindableBool(true); public TestSceneAllowExitingAndroid() { Children = new Drawable[] { new ExitVisualiser { Width = 0.5f, RelativeSizeAxes = Axes.Both, }, new EscapeVisualizer { Colour = Color4.Black, RelativeSizeAxes = Axes.Both, Width = 0.5f, Anchor = Anchor.TopRight, Origin = Anchor.TopRight, }, }; } protected override void LoadComplete() { base.LoadComplete(); host.AllowExitingAndroid.AddSource(allowExit); } [Test] public void TestToggleSuspension() { AddToggleStep("toggle allow exit", v => allowExit.Value = v); } protected override void Dispose(bool isDisposing) { host.AllowExitingAndroid.RemoveSource(allowExit); base.Dispose(isDisposing); } private class ExitVisualiser : Box { private readonly IBindable<bool> allowExit = new Bindable<bool>(); [BackgroundDependencyLoader] private void load(GameHost host) { allowExit.BindTo(host.AllowExitingAndroid.Result); allowExit.BindValueChanged(v => Colour = v.NewValue ? Color4.Green : Color4.Red, true); } } private class EscapeVisualizer : Box { protected override bool OnKeyDown(KeyDownEvent e) { if (e.Key == Key.Escape) this.FlashColour(Color4.Blue, 700, Easing.OutQuart); return base.OnKeyDown(e); } } } }
mit
C#
00268fb16bda28e71c9ea0e2cb6e9e7e31e2100b
Add vehicleType into Command Parameter Types.
ikkentim/SampSharp,ikkentim/SampSharp,ikkentim/SampSharp
src/SampSharp.GameMode/SAMP/Commands/ParameterTypes/VehicleType.cs
src/SampSharp.GameMode/SAMP/Commands/ParameterTypes/VehicleType.cs
// SampSharp // Copyright 2017 Tim Potze // // 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.Globalization; using System.Linq; using SampSharp.GameMode.World; namespace SampSharp.GameMode.SAMP.Commands.ParameterTypes { /// <summary> /// Represents a player command parameter. /// </summary> public class VehicleType : ICommandParameterType { #region Implementation of ICommandParameterType /// <summary> /// Gets the value for the occurance of this parameter type at the start of the commandText. The processed text will be /// removed from the commandText. /// </summary> /// <param name="commandText">The command text.</param> /// <param name="output">The output.</param> /// <returns> /// true if parsed successfully; false otherwise. /// </returns> public bool Parse(ref string commandText, out object output) { var text = commandText.TrimStart(); output = null; if (string.IsNullOrEmpty(text)) return false; var word = text.Split(' ').First(); // find a vehicle with a matching id. int id; if (int.TryParse(word, NumberStyles.Integer, CultureInfo.InvariantCulture, out id)) { var vehicle = BaseVehicle.Find(id); if (vehicle != null) { output = vehicle; commandText = commandText.Substring(word.Length).TrimStart(' '); return true; } } return false; } #endregion } }
apache-2.0
C#
ac382f09a0c6d7d464b2ddb2d991b3954399f053
Fix spelling mistake
ppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,default0/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,naoey/osu-framework,ZLima12/osu-framework,naoey/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,paparony03/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,default0/osu-framework
osu.Framework/Graphics/DrawNode.cs
osu.Framework/Graphics/DrawNode.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics.OpenGL; using System; namespace osu.Framework.Graphics { /// <summary> /// Contains all the information required to draw a single <see cref="Drawable"/>. /// A hierarchy of DrawNodes is passed to the draw thread for rendering every frame. /// </summary> public class DrawNode { /// <summary> /// Contains a linear transformation, colour information, and blending information /// of this draw node. /// </summary> public DrawInfo DrawInfo; /// <summary> /// Identifies the state of this draw node with an invalidation state of its corresponding /// <see cref="Drawable"/>. Whenever the invalidation state of this draw node disagrees /// with the state of its <see cref="Drawable"/> it has to be updated. /// </summary> public long InvalidationID; /// <summary> /// Draws this draw node to the screen. /// </summary> /// <param name="vertexAction">The action to be performed on each vertex of /// the draw node in order to draw it if required. This is primarily used by /// textured sprites.</param> public virtual void Draw(Action<TexturedVertex2D> vertexAction) { GLWrapper.SetBlend(DrawInfo.Blending); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Graphics.OpenGL; using System; namespace osu.Framework.Graphics { /// <summary> /// Contains all the information required to draw a single <see cref="Drawable"/>. /// A Hierarchy of DrawNodes is passed to the draw thread for rendering every frame. /// </summary> public class DrawNode { /// <summary> /// Contains a linear transformation, colour information, and blending information /// of this draw node. /// </summary> public DrawInfo DrawInfo; /// <summary> /// Identifies the state of this draw node with an invalidation state of its corresponding /// <see cref="Drawable"/>. Whenever the invalidation state of this draw node disagrees /// with the state of its <see cref="Drawable"/> it has to be updated. /// </summary> public long InvalidationID; /// <summary> /// Draws this draw node to the screen. /// </summary> /// <param name="vertexAction">The action to be performed on each vertex of /// the draw node in order to draw it if required. This is primarily used by /// textured sprites.</param> public virtual void Draw(Action<TexturedVertex2D> vertexAction) { GLWrapper.SetBlend(DrawInfo.Blending); } } }
mit
C#
ccdf12c6a82499454285e4c1a0a8964cba25fe2c
introduce AmmyDynamicResource
isukces/isukces.code
isukces.code/Ammy/_expressions/AmmyDynamicResource.cs
isukces.code/Ammy/_expressions/AmmyDynamicResource.cs
using isukces.code.interfaces.Ammy; namespace isukces.code.Ammy { public class AmmyDynamicResource : IAmmyCodePieceConvertible { public AmmyDynamicResource(string resourceName) { ResourceName = resourceName; } public IAmmyCodePiece ToAmmyCode(IConversionCtx ctx) { return new SimpleAmmyCodePiece("resource dyn \"" + ResourceName + "\""); } // ReSharper disable once AutoPropertyCanBeMadeGetOnly.Global public string ResourceName { get; set; } } }
mit
C#
e25a4e943d5fe1ab4f73746b2705fad6a9212aae
Add missing FileResponse file
realcrowd/hellosign.net
src/RealCrowd.HelloSign/Models/FileResponse.cs
src/RealCrowd.HelloSign/Models/FileResponse.cs
using System; using System.IO; namespace RealCrowd.HelloSign.Models { [Serializable] public class FileResponse : IDisposable { private bool disposed; public Stream Stream { get; internal set; } public string FileName { get; internal set; } public void Dispose() { this.Dispose(true); } protected virtual void Dispose(bool disposing) { if (this.disposed) { return; } if (disposing && this.Stream != null) { this.Stream.Dispose(); } this.disposed = true; } } }
mit
C#
2746c4afa4df90fe05985a768a808ad3a719bda8
Add TwitchPagination object
Aux/NTwitch,Aux/NTwitch
src/NTwitch.Rest/API/TwitchPagination.cs
src/NTwitch.Rest/API/TwitchPagination.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace NTwitch.Rest { public class TwitchPagination { public int Limit { get; set; } public int Page { get; set; } public TwitchPagination(int limit = 10, int page = 1) { Limit = limit; Page = page; } public override string ToString() { if (Limit < 1 || Limit > 100) throw new ArgumentOutOfRangeException("RequestOptions.Limit must be a number between 1 and 100."); if (Page < 1) throw new ArgumentOutOfRangeException("RequestOptions.Page must be a number greater than 0."); int offset = (Limit * Page) - Limit; return "?limit=" + Limit + "&offset=" + offset; } } }
mit
C#
6676c55fe05f0f413b95740381f35738e13adfcd
Introduce InputSettings
NeoAdonis/osu,peppy/osu-new,ZLima12/osu,EVAST9919/osu,ppy/osu,naoey/osu,NeoAdonis/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,naoey/osu,2yangk23/osu,johnneijzen/osu,DrabWeb/osu,ppy/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,ZLima12/osu,smoogipooo/osu,2yangk23/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu
osu.Game/Screens/Play/PlayerSettings/InputSettings.cs
osu.Game/Screens/Play/PlayerSettings/InputSettings.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // 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.Screens.Play.PlayerSettings { public class InputSettings : PlayerSettingsGroup { protected override string Title => "Input settings"; private readonly PlayerCheckbox mouseWheelCheckbox; private readonly PlayerCheckbox mouseButtonsCheckbox; public InputSettings() { Children = new Drawable[] { mouseWheelCheckbox = new PlayerCheckbox { LabelText = "Disable mouse wheel during gameplay" }, mouseButtonsCheckbox = new PlayerCheckbox { LabelText = "Disable mouse buttons during gameplay" } }; } [BackgroundDependencyLoader] private void load(OsuConfigManager config) { mouseWheelCheckbox.Bindable = config.GetBindable<bool>(OsuSetting.MouseDisableWheel); mouseButtonsCheckbox.Bindable = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } } }
mit
C#
d2427d808fe2de3851ddef9cb8e200550ac0f9de
Implement selection sort
cschen1205/cs-algorithms,cschen1205/cs-algorithms
Algorithms/Sorting/SelectionSort.cs
Algorithms/Sorting/SelectionSort.cs
using System; using Algorithms.Utils; namespace Algorithms.Sorting { public class SelectionSort { public static void Sort<T>(T[] a, int lo, int hi, Comparison<T> comparator) { for (var i = lo; i < hi; ++i) { var max = a[i]; var J = i; for (var j = i + 1; j <= hi; ++j) { if (SortUtil.IsLessThan(a[j], a[J], comparator)) { J = j; } } SortUtil.Exchange(a, i, J); } } } }
mit
C#
db0a7c68ca920ed97bff7c358d3b68875a1e8913
Create server side API for single multiple answer question
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.Models.Question; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api/question")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [HttpGet] /// <summary> /// Gets all questions /// </summary> /// <returns>Questions list</returns> public IActionResult GetQuestions() { var questions = _questionsRepository.GetAllQuestions(); return Json(questions); } [HttpPost] /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion); return Ok(); } /// <summary> /// /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <returns></returns> public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
93055b75bfb3d1b5f2b82251dad05bbecccd2926
Add useful extensions for tree operations
jagrem/slang,jagrem/slang,jagrem/slang
slang/Lexing/Trees/TreeExtensions.cs
slang/Lexing/Trees/TreeExtensions.cs
using System.Linq; namespace slang.Lexing.Trees { public static class TreeExtensions { public static Tree AttachChild(this Tree parent, Tree child) { var parentLeaves = parent.Leaves.ToList (); var childTransitions = child.Root.Transitions.ToList (); parentLeaves.ForEach (parentLeaf => childTransitions.ForEach (childTransition => parentLeaf .Transitions .Add (childTransition.Key, childTransition.Value))); return parent; } public static Tree Merge (this Tree left, Tree right) { var tree = new Tree (); var leftTransitions = left.Root.Transitions.ToList() ; var rightTransitions = right.Root.Transitions.ToList(); var transitions = leftTransitions.Concat (rightTransitions); transitions.ToList ().ForEach (t => tree.Root.Transitions.Add (t.Key, t.Value)); return tree; } } }
mit
C#
d241dd45d66ed16542d40df7cfe3e4391e858863
add serializer file
kherr9/TransitSocial.ChicagoTransitAuthority
src/TransitSocial.ChicagoTransitAuthority.BusTracker/Serializer.cs
src/TransitSocial.ChicagoTransitAuthority.BusTracker/Serializer.cs
using System; using System.IO; using System.Xml; using System.Xml.Serialization; namespace TransitSocial.ChicagoTransitAuthority.BusTracker { public class Serializer : ISerializer { public TModel Deserialize<TModel>(string input) { using (var reader = new StringReader(input)) using (var xmlReader = XmlReader.Create(reader)) { var ser = new XmlSerializer(typeof(TModel)); return (TModel)ser.Deserialize(xmlReader); } } } }
mit
C#
6a226302d5a9d0ec26899abc7a0cbbab899bc54c
Revert changes to basic template
tomhunter-gh/Lean,kaffeebrauer/Lean,AnshulYADAV007/Lean,StefanoRaggi/Lean,andrewhart098/Lean,andrewhart098/Lean,redmeros/Lean,devalkeralia/Lean,Jay-Jay-D/LeanSTP,AlexCatarino/Lean,JKarathiya/Lean,Mendelone/forex_trading,AnshulYADAV007/Lean,Mendelone/forex_trading,andrewhart098/Lean,AlexCatarino/Lean,JKarathiya/Lean,tomhunter-gh/Lean,jameschch/Lean,StefanoRaggi/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,tomhunter-gh/Lean,young-zhang/Lean,jameschch/Lean,QuantConnect/Lean,young-zhang/Lean,devalkeralia/Lean,jameschch/Lean,kaffeebrauer/Lean,QuantConnect/Lean,StefanoRaggi/Lean,jameschch/Lean,Jay-Jay-D/LeanSTP,Jay-Jay-D/LeanSTP,Mendelone/forex_trading,StefanoRaggi/Lean,jameschch/Lean,tomhunter-gh/Lean,Jay-Jay-D/LeanSTP,devalkeralia/Lean,AlexCatarino/Lean,AlexCatarino/Lean,JKarathiya/Lean,StefanoRaggi/Lean,Mendelone/forex_trading,young-zhang/Lean,kaffeebrauer/Lean,young-zhang/Lean,devalkeralia/Lean,Jay-Jay-D/LeanSTP,AnshulYADAV007/Lean,redmeros/Lean,AnshulYADAV007/Lean,QuantConnect/Lean,redmeros/Lean,JKarathiya/Lean,andrewhart098/Lean,AnshulYADAV007/Lean,QuantConnect/Lean,redmeros/Lean
Algorithm.CSharp/BasicTemplateAlgorithm.cs
Algorithm.CSharp/BasicTemplateAlgorithm.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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 QuantConnect.Data; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Basic template algorithm simply initializes the date range and cash /// </summary> public class BasicTemplateAlgorithm : QCAlgorithm { private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddEquity("SPY", Resolution.Second); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { SetHoldings(_spy, 1); Debug("Purchased Stock"); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using QuantConnect.Data; using QuantConnect.Scheduling; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Basic template algorithm simply initializes the date range and cash /// </summary> public class BasicTemplateAlgorithm : QCAlgorithm { private Symbol _spy = QuantConnect.Symbol.Create("SPY", SecurityType.Equity, Market.USA); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 07); //Set Start Date SetEndDate(2013, 10, 11); //Set End Date SetCash(100000); //Set Strategy Cash // Find more symbols here: http://quantconnect.com/data AddEquity("SPY", Resolution.Second); var add = true; Schedule.On(DateRules.EveryDay(), TimeRules.Every(TimeSpan.FromMinutes(1)), () => { if (add) { AddEquity("AAPL", Resolution.Second, Market.USA); Debug(Time.ToString("u") + " Added Apple"); } else { RemoveSecurity("AAPL"); Debug(Time.ToString("u") + " Removed Apple"); } add = !add; }); } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { if (!Portfolio.Invested) { SetHoldings(_spy, 1); Debug("Purchased Stock"); } } } }
apache-2.0
C#
891bb29c3de5c928616d4f605c5181903fe39a99
add missing file
beyourmarket/beyourmarket,beyourmarket/beyourmarket,JCDJulian/beyourmarket,sebvst/beyourmarket,ghost6p/beyourmarket,bramazan/beyourmarket,beyourmarket/beyourmarket,REALTOBIZ/beyourmarket,ghost6p/beyourmarket,bramazan/beyourmarket,rajendra1809/beyourmarket,JCDJulian/beyourmarket,rajendra1809/beyourmarket,sebvst/beyourmarket,bramazan/beyourmarket,ghost6p/beyourmarket,JCDJulian/beyourmarket,sebvst/beyourmarket,REALTOBIZ/beyourmarket,rajendra1809/beyourmarket,REALTOBIZ/beyourmarket
src/BeYourMarket.Model/ModelsPartial/ListingReview.cs
src/BeYourMarket.Model/ModelsPartial/ListingReview.cs
using BeYourMarket.Model.Enum; using BeYourMarket.Model.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BeYourMarket.Model.Models { [MetadataType(typeof(ListingReviewMetaData))] public partial class ListingReview { public string RatingClass { get { return "s" + Math.Round(Rating * 2); } } } public class ListingReviewMetaData { } }
mit
C#
46bbf2694963abfc1e5e5b47c952085b35e1632d
Create test.cs
hallstromsimon/office365apps,hallstromsimon/office365apps
Fol/test.cs
Fol/test.cs
mit
C#
ff524e62521dc7f8180eb2578309d497a51233ee
Create new-blog.cshtml
mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,mishrsud/sudhanshutheone.com,daveaglick/daveaglick,daveaglick/daveaglick
Somedave/Views/Blog/Posts/new-blog.cshtml
Somedave/Views/Blog/Posts/new-blog.cshtml
@{ Title = "New Blog"; Lead = "Look, Ma, no database!"; //Published = new DateTime(2014, 9, 4); Tags = new[] { "blog", "meta" }; } <p>It's been a little while coming, but I'm finally launching my new blog. It's built from scratch in ASP.NET MVC. Why go to all the trouble to build a blog engine from scratch when there are a gazillion great engines already out there? That's a very good question, let's break it down.</p> <h1>Own Your Content</h1> <p>I'll thank Scott Hanselman for really driving this point home.</p> <p>So that's <em>why</em> I created this new blog, but what about <em>how</em>? This blog engine uses no database, makes it easy to mix content pages with blog articles, is hosted on GitHub, and uses continuous deployment to automatically publish to an Azure Website.</p>
mit
C#
16a421059aab7a94a00a1fc5c2af6b3121d42584
Add more unit test
mbdavid/LiteDB
LiteDB.Tests/Document/Case_Insensitive_Tests.cs
LiteDB.Tests/Document/Case_Insensitive_Tests.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Collections; using System.Collections.Generic; using System.Text; namespace LiteDB.Tests.Document { [TestClass] public class Case_Insensitive_Tests { [TestMethod] public void Get_Document_Fields_Case_Insensitive() { var doc = new BsonDocument { ["_id"] = 10, ["name"] = "John", ["Last Job This Year"] = "admin" }; Assert.AreEqual(10, doc["_id"].AsInt32); Assert.AreEqual(10, doc["_ID"].AsInt32); Assert.AreEqual(10, doc["_Id"].AsInt32); Assert.AreEqual("John", doc["name"].AsString); Assert.AreEqual("John", doc["Name"].AsString); Assert.AreEqual("John", doc["NamE"].AsString); Assert.AreEqual("admin", doc["Last Job This Year"].AsString); Assert.AreEqual("admin", doc["last JOB this YEAR"].AsString); // using expr Assert.AreEqual("admin", BsonExpression.Create("$.['Last Job This Year']").Execute(doc).First().AsString); Assert.AreEqual("admin", BsonExpression.Create("$.['Last JOB THIS Year']").Execute(doc).First().AsString); } } }
mit
C#
ea39f614adbe36b5d95cbd94e2b96ba85f3cbbc5
add fetch strategy to combine other strategies
eriklieben/ErikLieben.Data
ErikLieben.Data/Repository/CombinedFetchingStrategy.cs
ErikLieben.Data/Repository/CombinedFetchingStrategy.cs
namespace ErikLieben.Data.Repository { using System.Linq; public class CombinedFetchingStrategy<T> : IFetchingStrategy<T> { private readonly IFetchingStrategy<T>[] strategies; public CombinedFetchingStrategy(params IFetchingStrategy<T>[] stratergies) { this.strategies = stratergies; } public IQueryable<T> Apply(IQueryable<T> queryable) { foreach(var strategy in this.strategies) { queryable = strategy.Apply(queryable); } return queryable; } } }
mit
C#
4fcbe1a79bd3a95d10ffa9dfb772c12899947696
Add ExtendedDnControl. It specified format of retuned distinguished names.
dsbenghe/Novell.Directory.Ldap.NETStandard,dsbenghe/Novell.Directory.Ldap.NETStandard
src/Novell.Directory.Ldap.NETStandard/Controls/ExtendedDnControl.cs
src/Novell.Directory.Ldap.NETStandard/Controls/ExtendedDnControl.cs
/****************************************************************************** * The MIT License * Copyright (c) 2020 Miroslav Adamec * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ using System; using System.IO; using Novell.Directory.Ldap.Asn1; namespace Novell.Directory.Ldap.Controls { /// <summary> /// LDAP_SERVER_EXTENDED_DN_OID ( 1.2.840.113556.1.4.529 ) - This causes an /// LDAP server to return an extended form of the objects DN: <GUID=guid_value>;dn. /// </summary> /// <see cref="https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-adts/57056773-932c-4e55-9491-e13f49ba580c"/> public class ExtendedDnControl : LdapControl { private const string ExtendedDnControlOID = "1.2.840.113556.1.4.529"; private readonly LberEncoder encoder = new LberEncoder(); private readonly Asn1Sequence controlValue = new Asn1Sequence(); /// <summary> /// Creates a new ExtendedDnControl using the specified flag. /// </summary> /// <param name="flag">The format of the GUID that will be returned.</param> /// <param name="critical">True if the LDAP operation should be discarded if the /// control is not supported. False if the operation can be processed without /// the control.</param> public ExtendedDnControl(GuidFormatFlag flag, bool critical) : base(ExtendedDnControlOID, critical, null) { controlValue.Add(new Asn1Integer((int)flag)); try { using (var encodedData = new MemoryStream()) { controlValue.Encode(encoder, encodedData); SetValue(encodedData.ToArray()); } } catch (IOException e) { //Shouldn't occur unless there is a serious failure throw new InvalidOperationException("Unable to create instance of ExtendedDnControl", e); } } /// <summary> /// LDAP GUID format in HEX or string dashed format. /// </summary> public enum GuidFormatFlag { Hex, String } } }
mit
C#
602dfc131def2cb10459655bee8ea398414e7760
Create CameraEvent.cs
schoffi92/Unity3D-Scripts
VR/CameraEvent.cs
VR/CameraEvent.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; namespace VR { public class CameraEvent : MonoBehaviour { public const string VRINTERACTIVE_TAG = "VRInteractive"; public Camera camera; public string objName; protected ObjectEvent objEvent; public float maxDistance = 100f; // Use this for initialization void Start() { } // Update is called once per frame void Update() { //if (EventSystem.current.IsPointerOverGameObject()) return; RaycastHit hit; Ray ray = new Ray(camera.transform.position, camera.transform.forward); if (Physics.Raycast(ray, out hit, maxDistance)) { if (hit.collider.tag == VRINTERACTIVE_TAG) { ObjectEvent e; if (objName != hit.collider.gameObject.name) { e = hit.collider.GetComponent<ObjectEvent>(); } else { e = objEvent; } if (e != null) { if (objName != hit.collider.gameObject.name) { //Debug.Log("Raycast Over: '" + objName + "'"); RaycastOver(); //Debug.Log("Raycast Enter: '" + hit.collider.gameObject.name + "'"); e.RaycastEnter(); objEvent = e; objName = hit.collider.gameObject.name; } if (Input.GetMouseButtonDown(0)) { //Debug.Log("Clicked: '" + hit.collider.gameObject.name + "' == '" + objName + "'"); e.Clicked(); } } } else { RaycastOver(); } } else { RaycastOver(); } } void RaycastOver() { objName = ""; if (objEvent != null) { objEvent.RaycastOver(); objEvent = null; } } public ObjectEvent GetActiveObject() { return objEvent; } } }
mit
C#
7f2be583f673cfda7b984e77341933bc99176100
Add test
peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/Exceptions/TestSceneDependencyInjectionExceptions.cs
osu.Framework.Tests/Exceptions/TestSceneDependencyInjectionExceptions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Framework.Tests.Visual; namespace osu.Framework.Tests.Exceptions { [HeadlessTest] public class TestSceneDependencyInjectionExceptions : FrameworkTestScene { [Test] public void TestImmediateException() { Exception thrownException = null; AddStep("add thrower", () => { try { Child = new Thrower(typeof(Exception)); } catch (Exception ex) { thrownException = ex; } }); assertCorrectStack(() => thrownException); } [Test] public void TestImmediateAggregateException() { Exception thrownException = null; AddStep("add thrower", () => { try { Child = new Thrower(typeof(Exception), true); } catch (Exception ex) { thrownException = ex; } }); assertCorrectStack(() => thrownException); } [Test] public void TestAsyncException() { AsyncThrower thrower = null; AddStep("add thrower", () => Child = thrower = new AsyncThrower(typeof(Exception))); AddUntilStep("wait for exception", () => thrower.ThrownException != null); assertCorrectStack(() => thrower.ThrownException); } private void assertCorrectStack(Func<Exception> exception) => AddAssert("exception has correct callstack", () => exception().StackTrace.Contains($"{nameof(TestSceneDependencyInjectionExceptions)}.{nameof(Thrower)}")); private class AsyncThrower : CompositeDrawable { public Exception ThrownException { get; private set; } private readonly Type exceptionType; public AsyncThrower(Type exceptionType) { this.exceptionType = exceptionType; } protected override void LoadComplete() { base.LoadComplete(); LoadComponentAsync(new Thrower(exceptionType), AddInternal); } public override bool UpdateSubTree() { try { return base.UpdateSubTree(); } catch (Exception ex) { ThrownException = ex; } return true; } } private class Thrower : Drawable { private readonly Type exceptionType; private readonly bool aggregate; public Thrower(Type exceptionType, bool aggregate = false) { this.exceptionType = exceptionType; this.aggregate = aggregate; } [BackgroundDependencyLoader] private void load() { if (aggregate) { try { throw (Exception)Activator.CreateInstance(exceptionType); } catch (Exception ex) { throw new AggregateException(ex); } } throw (Exception)Activator.CreateInstance(exceptionType); } } } }
mit
C#
6f31608b8534c6bc5e6fdff007885cce88617c89
Create AttachedToVisualTreeBehavior.cs
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/AttachedToVisualTreeBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/AttachedToVisualTreeBehavior.cs
using System.Reactive.Disposables; namespace Avalonia.Xaml.Interactions.Custom; /// <summary> /// A base class for behaviors using attached to visual tree event. /// </summary> /// <typeparam name="T"></typeparam> public abstract class AttachedToVisualTreeBehavior<T> : DisposingBehavior<T> where T : Visual { private CompositeDisposable? _disposables; /// <inheritdoc /> protected override void OnAttached(CompositeDisposable disposables) { _disposables = disposables; } /// <inheritdoc /> protected override void OnAttachedToVisualTree() { OnAttachedToVisualTree(_disposables!); } /// <summary> /// Called after the behavior is attached to the <see cref="DisposingBehavior{T}.AssociatedObject"/> visual tree. /// </summary> /// <param name="disposable">The group of disposable resources that are disposed together</param> protected abstract void OnAttachedToVisualTree(CompositeDisposable disposable); }
mit
C#
66dc8f5df59c5a041a35bf641978c4714d7fb077
Add test for deserializing nullable reagent units (#4899)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.IntegrationTests/Tests/Chemistry/ReagentUnitSerializationTest.cs
Content.IntegrationTests/Tests/Chemistry/ReagentUnitSerializationTest.cs
using System.Reflection; using Content.Shared.Chemistry.Reagent; using NUnit.Framework; using Robust.Shared.Serialization.Manager; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Serialization.Markdown.Mapping; using Robust.Shared.Serialization.Markdown.Value; using Robust.UnitTesting.Shared.Serialization; namespace Content.IntegrationTests.Tests.Chemistry { public class ReagentUnitSerializationTest : SerializationTest { protected override Assembly[] Assemblies => new[] { typeof(ReagentUnitSerializationTest).Assembly }; [Test] public void DeserializeNullTest() { var node = new ValueDataNode("null"); var unit = Serialization.ReadValue<ReagentUnit?>(node); Assert.That(unit, Is.Null); } [Test] public void DeserializeNullDefinitionTest() { var node = new MappingDataNode().Add("unit", "null"); var definition = Serialization.ReadValueOrThrow<ReagentUnitTestDefinition>(node); Assert.That(definition.Unit, Is.Null); } } [DataDefinition] public class ReagentUnitTestDefinition { [DataField("unit")] public ReagentUnit? Unit { get; set; } = ReagentUnit.New(5); } }
mit
C#
299d2fa36f148354b59a19622f6f2f0cba3e20b7
Create StudentDeleteViewModel
Programazing/Open-School-Library,Programazing/Open-School-Library
src/Open-School-Library/Models/StudentViewModels/StudentDeleteViewModel.cs
src/Open-School-Library/Models/StudentViewModels/StudentDeleteViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Open_School_Library.Models.StudentViewModels { public class StudentDeleteViewModel { } }
mit
C#
41f15d69875577a8f737e5f2659820c000fe91f9
Add channels
maxlmo/outlook-matters,maxlmo/outlook-matters,makmu/outlook-matters,makmu/outlook-matters
OutlookMatters/Mattermost/Session/Channels.cs
OutlookMatters/Mattermost/Session/Channels.cs
using System.Collections.Generic; using Newtonsoft.Json; namespace OutlookMatters.Mattermost { public class Channels { [JsonProperty("channels")] public List<Channel> ChannelList { get; set; } } public class Channel { [JsonProperty("id")] public string ChannelId { get; set; } [JsonProperty("display_name")] public string ChannelName { get; set; } [JsonProperty("type")] public string Type { get; set; } } }
mit
C#
4c54c0ae53ebf2246beade5ee548aa35b10dcc3f
Create MaciejHorbacz.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/MaciejHorbacz.cs
src/Firehose.Web/Authors/MaciejHorbacz.cs
mit
C#
3e684eb1cde2a14db1d8a9c186cb39ef7e0a9926
Edit it
jogibear9988/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,2Toad/websocket-sharp,jogibear9988/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp
websocket-sharp/Net/HttpBasicIdentity.cs
websocket-sharp/Net/HttpBasicIdentity.cs
#region License /* * HttpBasicIdentity.cs * * This code is derived from HttpListenerBasicIdentity.cs (System.Net) of * Mono (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2014-2017 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Security.Principal; namespace WebSocketSharp.Net { /// <summary> /// Holds the username and password from an HTTP Basic authentication attempt. /// </summary> public class HttpBasicIdentity : GenericIdentity { #region Private Fields private string _password; #endregion #region Internal Constructors internal HttpBasicIdentity (string username, string password) : base (username, "Basic") { _password = password; } #endregion #region Public Properties /// <summary> /// Gets the password from a basic authentication attempt. /// </summary> /// <value> /// A <see cref="string"/> that represents the password. /// </value> public virtual string Password { get { return _password; } } #endregion } }
#region License /* * HttpBasicIdentity.cs * * This code is derived from HttpListenerBasicIdentity.cs (System.Net) of * Mono (http://www.mono-project.com). * * The MIT License * * Copyright (c) 2005 Novell, Inc. (http://www.novell.com) * Copyright (c) 2014-2017 sta.blockhead * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion #region Authors /* * Authors: * - Gonzalo Paniagua Javier <gonzalo@novell.com> */ #endregion using System; using System.Security.Principal; namespace WebSocketSharp.Net { /// <summary> /// Holds the username and password from an HTTP Basic authentication attempt. /// </summary> public class HttpBasicIdentity : GenericIdentity { #region Private Fields private string _password; #endregion #region Internal Constructors internal HttpBasicIdentity (string username, string password) : base (username, "Basic") { _password = password; } #endregion #region Public Properties /// <summary> /// Gets the password from an HTTP Basic authentication attempt. /// </summary> /// <value> /// A <see cref="string"/> that represents the password. /// </value> public virtual string Password { get { return _password; } } #endregion } }
mit
C#
c2b154816d4a44e718d5b1d1607fa075b5630091
Add GlobalSuppressions for FxCop
modulexcite/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli,scopely/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli
cli/src/MsgPack/GlobalSuppressions.cs
cli/src/MsgPack/GlobalSuppressions.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System.Diagnostics.CodeAnalysis; [module: SuppressMessage( "Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "MsgPack.Collections", Justification = "Under construction." )]
apache-2.0
C#
0e46b084886574a759a3d6a0a042a06ae4204fd1
Add OptionBoard structure
sm00vik/QuikSharp,buybackoff/QuikSharp,finsight/QuikSharp
src/QuikSharp/DataStructures/OptionBoard.cs
src/QuikSharp/DataStructures/OptionBoard.cs
using Newtonsoft.Json; namespace QuikSharp.DataStructures { /// <summary> /// OptionBoard structure /// </summary> public class OptionBoard { /// <summary> /// Strike /// </summary> [JsonProperty("Strike")] public int Strike { get; set; } /// <summary> /// Code /// </summary> [JsonProperty("code")] public string Code { get; set; } /// <summary> /// Volatility /// </summary> [JsonProperty("Volatility")] public double Volatility { get; set; } /// <summary> /// OptionBase /// </summary> [JsonProperty("OPTIONBASE")] public string OPTIONBASE { get; set; } /// <summary> /// Offer /// </summary> [JsonProperty("OFFER")] public int OFFER { get; set; } /// <summary> /// Longname /// </summary> [JsonProperty("Longname")] public string Longname { get; set; } /// <summary> /// Name /// </summary> [JsonProperty("Name")] public string Name { get; set; } /// <summary> /// OptionType /// </summary> [JsonProperty("OPTIONTYPE")] public string OPTIONTYPE { get; set; } /// <summary> /// ShortName /// </summary> [JsonProperty("shortname")] public string Shortname { get; set; } /// <summary> /// Bid /// </summary> [JsonProperty("BID")] public int BID { get; set; } /// <summary> /// DaysToMatDate /// </summary> [JsonProperty("DAYS_TO_MAT_DATE")] public int DAYSTOMATDATE { get; set; } } }
apache-2.0
C#
1defac6f73a8983b71bafb4b2f1ffc871db8f196
Test case: dotnet classic project with packages.config
skolima/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper
NuKeeper.Integration.Tests/NuGet/Process/NuGetUpdatePackageCommandTests.cs
NuKeeper.Integration.Tests/NuGet/Process/NuGetUpdatePackageCommandTests.cs
using System.IO; using System.Threading.Tasks; using NuGet.Versioning; using NuKeeper.Configuration; using NuKeeper.Inspection.RepositoryInspection; using NuKeeper.Integration.Tests.NuGet.Api; using NuKeeper.NuGet.Process; using NUnit.Framework; namespace NuKeeper.Integration.Tests.NuGet.Process { [TestFixture] [Category("WindowsOnly")] public class NuGetUpdatePackageCommandTests { private readonly string _testDotNetClassicProject = @"<Project ToolsVersion=""15.0"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <TargetFrameworkVersion>v4.7</TargetFrameworkVersion> </PropertyGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"; private readonly string _testPackagesConfig = @"<packages><package id=""Microsoft.AspNet.WebApi.Client"" version=""{packageVersion}"" targetFramework=""net47"" /></packages>"; private readonly string _nugetConfig = @"<configuration><config><add key=""repositoryPath"" value="".\packages"" /></config></configuration>"; [Test] public async Task ShouldUpdateDotnetClassicProject() { const string packageSource = "https://api.nuget.org/v3/index.json"; const string oldPackageVersion = "5.2.3"; const string newPackageVersion = "5.2.4"; const string expectedPackageString = "<package id=\"Microsoft.AspNet.WebApi.Client\" version=\"{packageVersion}\" targetFramework=\"net47\" />"; const string testFolder = nameof(ShouldUpdateDotnetClassicProject); var testProject = $"{testFolder}.csproj"; var workDirectory = Path.Combine(TestContext.CurrentContext.WorkDirectory, testFolder); Directory.CreateDirectory(workDirectory); var packagesFolder = Path.Combine(workDirectory, "packages"); Directory.CreateDirectory(packagesFolder); var projectContents = _testDotNetClassicProject.Replace("{packageVersion}", oldPackageVersion); var projectPath = Path.Combine(workDirectory, testProject); await File.WriteAllTextAsync(projectPath, projectContents); var packagesConfigContents = _testPackagesConfig.Replace("{packageVersion}", oldPackageVersion); var packagesConfigPath = Path.Combine(workDirectory, "packages.config"); await File.WriteAllTextAsync(packagesConfigPath, packagesConfigContents); await File.WriteAllTextAsync(Path.Combine(workDirectory, "nuget.config"), _nugetConfig); var command = new NuGetUpdatePackageCommand( new NullNuKeeperLogger(), new UserSettings { NuGetSources = new[] { packageSource } }); await command.Invoke(new NuGetVersion(newPackageVersion), packageSource, new PackageInProject("Microsoft.AspNet.WebApi.Client", oldPackageVersion, new PackagePath(workDirectory, testProject, PackageReferenceType.PackagesConfig))); var contents = await File.ReadAllTextAsync(packagesConfigPath); Assert.That(contents, Does.Contain(expectedPackageString.Replace("{packageVersion}", newPackageVersion))); Assert.That(contents, Does.Not.Contain(expectedPackageString.Replace("{packageVersion}", oldPackageVersion))); } } }
apache-2.0
C#
96be7f3d0c001a74a997c4daca58fe09cf653f70
Create NeilFifteen.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/NeilFifteen.cs
src/Firehose.Web/Authors/NeilFifteen.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class NeilFifteen : IAmACommunityMember { public string FirstName => "Neil"; public string LastName => "Fifteen"; public string ShortBioOrTagLine => "My adventures found in PowerShell..."; public string StateOrRegion => "Cheltenham, England"; public string EmailAddress => "neil@digitalfifteen.com"; public string TwitterHandle => "neil_fifteen"; public string GitHubHandle => "neilfifteen"; public string GravatarHash => "68ffe557305106c5c399682b5c869cd7"; public GeoPosition Position => new GeoPosition(51.897991, -2.071310); public Uri WebSite => new Uri("https://digitalfifteen.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://digitalfifteen.co.uk/feed.xml"); } } public string FeedLanguageCode => "en"; } }
mit
C#
7a9b42c571a07b5d56796020eae270d0384e713e
Create WaveManager.cs
highnet/Java-101,highnet/Java-101
TowerTDAlpha/WaveManager.cs
TowerTDAlpha/WaveManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WaveManager : MonoBehaviour { public Button nextWaveReadyButton; void ClickedNextWaveReadyButton() { Debug.Log("Clicked"); if (GameObject.FindObjectOfType<Spawner>().spawnQueue.Count == 0 && GameObject.FindObjectOfType<ScoreManager>().currentwave <= GameObject.FindObjectOfType<ScoreManager>().maxWave) { GameObject.FindObjectOfType<ScoreManager>().currentwave++; GameObject.FindObjectOfType<Spawner>().setSpawnData(GameObject.FindObjectOfType<ScoreManager>().currentwave); } } void bindButtons() { nextWaveReadyButton.GetComponent<Button>().onClick.AddListener(ClickedNextWaveReadyButton); } // Use this for initialization void Start () { bindButtons(); } // Update is called once per frame void Update () { } }
mit
C#
7a66fbb6c7d6b48c5456f5e2e9e3674e17ee660f
Introduce SharedDbField
pveller/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb
src/Sitecore.FakeDb.Tests/SharedDbFieldTest.cs
src/Sitecore.FakeDb.Tests/SharedDbFieldTest.cs
namespace Sitecore.FakeDb.Tests { using System.Collections.Generic; using FluentAssertions; using Ploeh.AutoFixture.Xunit2; using Sitecore.Data; using Xunit; public class SharedDbFieldTest { [Theory, AutoData] public void ShouldBeDbField(SharedDbField sut) { sut.Should().BeAssignableTo<DbField>(); } [Theory, AutoData] public void ShouldCreateFieldById(ID id) { var sut = new SharedDbField(id); sut.ID.Should().BeSameAs(id); } [Theory, AutoData] public void ShouldCreateFieldByName(string name) { var sut = new SharedDbField(name); sut.Name.Should().Be(name); } [Theory, AutoData] public void ShouldCreateFieldByNameAndId(string name, ID id) { var sut = new SharedDbField(name, id); sut.Name.Should().Be(name); sut.ID.Should().BeSameAs(id); } [Theory, AutoData] public void ShouldSetObsoleteSharedField(string name, ID id) { new SharedDbField(id).Shared.Should().BeTrue(); new SharedDbField(name).Shared.Should().BeTrue(); new SharedDbField(name, id).Shared.Should().BeTrue(); } [Theory, AutoData] public void ShouldRetunLastValueAddedIgnoringVersion([NoAutoProperties] SharedDbField sut, string value1, string expected) { sut.Add("en", value1); sut.Add("en", expected); sut.GetValue("en", 1).Should().Be(expected); sut.GetValue("en", 2).Should().Be(expected); } [Theory, AutoData] public void ShouldRetunLastValueAddedIgnoringLanguage([NoAutoProperties] SharedDbField sut, string value1, string expected) { sut.Add("en", value1); sut.Add("da", expected); sut.GetValue("en", 1).Should().Be(expected); sut.GetValue("da", 1).Should().Be(expected); } } public class SharedDbField : DbField { public SharedDbField(ID id) : base(id) { this.Shared = true; } public SharedDbField(string name) : base(name) { this.Shared = true; } public SharedDbField(string name, ID id) : base(name, id) { this.Shared = true; } public override void Add(string language, int version, string value) { base.Add(language, version, value); foreach (var langValue in this.Values) { for (var i = langValue.Value.Count - 1; i > 0; --i) { langValue.Value[i] = value; } } } } }
mit
C#
d6eee756ed75ac8222ece6336ae6965b0cb5d699
Increase version number to 1.1
SonarSource-VisualStudio/sonar-msbuild-runner,SonarSource/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,dbolkensteyn/sonar-msbuild-runner,HSAR/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-msbuild-runner,SonarSource-DotNet/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild,duncanpMS/sonar-msbuild-runner,jabbera/sonar-msbuild-runner,duncanpMS/sonar-msbuild-runner,SonarSource-VisualStudio/sonar-scanner-msbuild
AssemblyInfo.Shared.cs
AssemblyInfo.Shared.cs
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
//----------------------------------------------------------------------- // <copyright file="AssemblyInfo.Shared.cs" company="SonarSource SA and Microsoft Corporation"> // Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SonarSource and Microsoft")] [assembly: AssemblyCopyright("Copyright © SonarSource and Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)]
mit
C#
6155b4e969ac55e941326b425d82d0f6eac8bb3b
Add AssertResolver class
danielverejan/.net-wepback-config,danielverejan/.net-wepback-config
App_Start/AssetResolver.cs
App_Start/AssetResolver.cs
using System.Web.Optimization; using Backload.Bundles; using System.Web.Caching; using System.Web; using Newtonsoft.Json; using System.Diagnostics; using System.IO; using System.Collections; using System.Collections.Generic; namespace Northstar { class AssetCollection : Dictionary<string, string> { } public class StaticAssetResolver { private string assetsJsonPath; private Cache cache; private const string CACHE_KEY = "assetsJsonDictionary"; public StaticAssetResolver(string assetsJsonPath, Cache cache) { this.assetsJsonPath = assetsJsonPath; this.cache = cache; } public string GetActualPath(string assetPath) { var assets = cache.Get(CACHE_KEY) as AssetCollection; if (assets == null) { assets = GetAssetsFromFile(); cache.Insert(CACHE_KEY, assets, new CacheDependency(assetsJsonPath)); Trace.TraceInformation("Assets cache miss"); } else { Trace.TraceInformation("Assets cache hit"); } if (assets.ContainsKey(assetPath)) { return VirtualPathUtility.ToAbsolute("~/" + assets[assetPath]); } else { return ""; } } private AssetCollection GetAssetsFromFile() { return JsonConvert.DeserializeObject<AssetCollection>(File.ReadAllText(assetsJsonPath)); } } public static class StaticAssets { private static StaticAssetResolver assetResolver; public static void Initialize(StaticAssetResolver staticAssetResolver) { if (assetResolver == null) { assetResolver = staticAssetResolver; } } public static HtmlString RenderScript(string path) { var actualPath = assetResolver.GetActualPath(path); return new HtmlString(string.IsNullOrEmpty(actualPath) ? $"<!-- No script with {path} name found. -->" : $"<script src=\"{ actualPath }\"></script>"); } public static HtmlString RenderStyle(string path) { var actualPath = assetResolver.GetActualPath(path); return new HtmlString(string.IsNullOrEmpty(actualPath) ? $"<!-- No style with {path} name found. -->" : $"<link href=\"{ actualPath }\" rel=\"stylesheet\" />"); } } }
mit
C#
e658239ba32d56459e4b98650b77a3f18f7c32bd
Create Problem53.cs
fireheadmx/ProjectEuler,fireheadmx/ProjectEuler
Problems/Problem53.cs
Problems/Problem53.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Numerics; namespace ProjectEuler { class Problem53 { private Factorial fact; private int upper; public Problem53() { upper = 100; fact = new Factorial(upper); } private BigInteger C(int n, int r) { if (r <= n) { return fact.val(n) / (fact.val(r) * fact.val(n - r)); } else { return 0; } } public string Run() { int count = 0; for (int i = 1; i <= 100; i++) { for (int j = 1; j <= i; j++) { if (C(i, j) > 1000000) { count++; } } } return count.ToString(); } } }
mit
C#
17042f001ef60e5999a6b7e31c68076f2684c185
Create empty folder
lizaamini/CSharpExercises
Sheet-9/Exercise9A.cs
Sheet-9/Exercise9A.cs
mit
C#
96b6670d1fe2e3018acdfe8ee0dd98a0981b5f6f
Add mod benchmark
peppy/osu,ppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu
osu.Game.Benchmarks/BenchmarkMod.cs
osu.Game.Benchmarks/BenchmarkMod.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using BenchmarkDotNet.Attributes; using osu.Game.Rulesets.Osu.Mods; namespace osu.Game.Benchmarks { public class BenchmarkMod : BenchmarkTest { private OsuModDoubleTime mod; [Params(1, 10, 100)] public int Times { get; set; } [GlobalSetup] public void GlobalSetup() { mod = new OsuModDoubleTime(); } [Benchmark] public int ModHashCode() { var hashCode = new HashCode(); for (int i = 0; i < Times; i++) hashCode.Add(mod); return hashCode.ToHashCode(); } } }
mit
C#
5dbd96ab425cc6e07ca8b3d3c3f7f1e7d87376b9
Add a support for SYSTEM_LANGUAGE SCPI command
tparviainen/oscilloscope
SCPI/System/SYSTEM_LANGUAGE.cs
SCPI/System/SYSTEM_LANGUAGE.cs
namespace SCPI.System { public class SYSTEM_LANGUAGE : ICommand { public string Description => "Set or query the system language"; public string Command(params string[] parameters) { var cmd = ":SYSTem:LANGuage"; if (parameters.Length > 0) { var language = parameters[0]; cmd = $"{cmd} {language}"; } else { cmd += "?"; } return cmd; } public string HelpMessage() { var syntax = nameof(SYSTEM_LANGUAGE) + "\n" + nameof(SYSTEM_LANGUAGE) + " <lang>"; var parameters = " <lang> = SCH, TCH, ENGL, PORT, GERM, POL, KOR, JAPA, FREN or RUSS\n"; var example = "Example: " + nameof(SYSTEM_LANGUAGE) + " ENGL"; return $"{syntax}\n{parameters}\n{example}"; } public bool Parse(byte[] data) => true; } }
mit
C#
36eff486b0bf7c9721a0407bda31b9d8249d1107
Add extension method to prepend content to a TagHelperContent
daniel-kuon/BootstrapTagHelpers,daniel-kuon/BootstrapTagHelpers,daniel-kuon/BootstrapTagHelpers
BootstrapTagHelpers/src/BootstrapTagHelpers/TagHelperContentExtensions.cs
BootstrapTagHelpers/src/BootstrapTagHelpers/TagHelperContentExtensions.cs
namespace BootstrapTagHelpers { using Microsoft.AspNet.Razor.Runtime.TagHelpers; public static class TagHelperContentExtensions { public static void Prepend(this TagHelperContent content, string value) { if (content.IsEmpty) content.SetContent(value); else content.SetContent(value + content.GetContent()); } } }
mit
C#
5553285771cd6ebc1f359fe1b555955f8098d03a
Add Misc utilities class
tobyclh/UnityCNTK,tobyclh/UnityCNTK
Assets/UnityCNTK/HelperClasses/Ultilities.cs
Assets/UnityCNTK/HelperClasses/Ultilities.cs
using UnityEngine; using CNTK; using System; using System.Linq; using System.Collections.Generic; using UnityEngine.Assertions; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; namespace UnityCNTK { //Simple public static class Ultilities { public static Texture2D ResampleAndCrop(this Texture2D source, int targetWidth, int targetHeight) { int sourceWidth = source.width; int sourceHeight = source.height; float sourceAspect = (float)sourceWidth / sourceHeight; float targetAspect = (float)targetWidth / targetHeight; int xOffset = 0; int yOffset = 0; float factor = 1; if (sourceAspect > targetAspect) { // crop width factor = (float)targetHeight / sourceHeight; xOffset = (int)((sourceWidth - sourceHeight * targetAspect) * 0.5f); } else { // crop height factor = (float)targetWidth / sourceWidth; yOffset = (int)((sourceHeight - sourceWidth / targetAspect) * 0.5f); } Color32[] data = source.GetPixels32(); Color32[] data2 = new Color32[targetWidth * targetHeight]; for (int y = 0; y < targetHeight; y++) { for (int x = 0; x < targetWidth; x++) { var p = new Vector2(Mathf.Clamp(xOffset + x / factor, 0, sourceWidth - 1), Mathf.Clamp(yOffset + y / factor, 0, sourceHeight - 1)); // bilinear filtering var c11 = data[Mathf.FloorToInt(p.x) + sourceWidth * (Mathf.FloorToInt(p.y))]; var c12 = data[Mathf.FloorToInt(p.x) + sourceWidth * (Mathf.CeilToInt(p.y))]; var c21 = data[Mathf.CeilToInt(p.x) + sourceWidth * (Mathf.FloorToInt(p.y))]; var c22 = data[Mathf.CeilToInt(p.x) + sourceWidth * (Mathf.CeilToInt(p.y))]; var f = new Vector2(Mathf.Repeat(p.x, 1f), Mathf.Repeat(p.y, 1f)); data2[x + y * targetWidth] = Color.Lerp(Color.Lerp(c11, c12, p.y), Color.Lerp(c21, c22, p.y), p.x); } } var tex = new Texture2D(targetWidth, targetHeight); tex.SetPixels32(data2); tex.Apply(true); return tex; } } }
mit
C#
6d1b64042bf753dfe06982bbd1aa58713ab4e35d
Fix hang in host tests due to test parallelization
PowerShell/PowerShellEditorServices
test/PowerShellEditorServices.Test.Host/AssemblyInfo.cs
test/PowerShellEditorServices.Test.Host/AssemblyInfo.cs
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Xunit; // Disable test parallelization to avoid port reuse issues [assembly: CollectionBehavior(DisableTestParallelization = true)]
mit
C#
b78dc7599dd7f2e13cb3e2036e5f101a6358d3de
Add ExternalSdCardInfo class which can be used to get removable SD card information
wislon/xamarin-android-use-removable-sd-card
src/TestExternalSd/StorageClasses/ExternalSdCardInfo.cs
src/TestExternalSd/StorageClasses/ExternalSdCardInfo.cs
namespace TestExternalSd.StorageClasses { public static class ExternalSdCardInfo { private static string _path = null; private static bool? _isWriteable; private static FileSystemBlockInfo _fileSystemBlockInfo = null; /// <summary> /// Quick property you can check after initialising /// </summary> public static bool ExternalSdCardExists { get { return !string.IsNullOrWhiteSpace(GetExternalSdCardPath()); } } /// <summary> /// Returns the path to External SD card (if there is one), /// otherwise empty string if there isn't /// </summary> public static string Path { get { return _path ?? GetExternalSdCardPath(); } } /// <summary> /// Returns whether the external SD card is writeable. The first /// call to this is an expensive one, because it actually tries to /// write a test file to the external disk /// </summary> public static bool IsWriteable { get { return _isWriteable ?? IsExternalCardWriteable(); } } /// <summary> /// The values in the <see cref="FileSystemBlockInfo"/> object may have /// changed depending on what's going on in the file system, so it repopulates relatively /// expensively every time you read this property /// </summary> public static FileSystemBlockInfo FileSystemBlockInfo { get { return GetFileSystemBlockInfo(); } } private static FileSystemBlockInfo GetFileSystemBlockInfo() { if (!string.IsNullOrWhiteSpace(GetExternalSdCardPath())) { _fileSystemBlockInfo = ExternalSdStorageHelper.GetFileSystemBlockInfo(_path); return _fileSystemBlockInfo; } return null; } private static bool IsExternalCardWriteable() { if (string.IsNullOrWhiteSpace(GetExternalSdCardPath())) { return false; } _isWriteable = ExternalSdStorageHelper.IsWriteable(_path); return _isWriteable.Value; } private static string GetExternalSdCardPath() { _path = ExternalSdStorageHelper.GetExternalSdCardPath(); return _path; } } }
mit
C#
f86baa92a01229c3426b3110f2dd869b641fbae8
Create ShipSelector.cs
jon-lad/Battlefleet-Gothic
ShipSelector.cs
ShipSelector.cs
using UnityEngine; using System.Collections; public class ShipSelector : MonoBehaviour { GUIContent[] raceList; GUIContent[] impShips; GUIContent[] chaosShips; private Popup p1Race; private GUIStyle listStyle = new GUIStyle(); private void Start() { listStyle.normal.textColor = Color.white; listStyle.onHover.background = listStyle.hover.background = new Texture2D(2, 2); listStyle.padding.left = listStyle.padding.right = listStyle.padding.top = listStyle.padding.bottom = 4; raceList = new GUIContent[2]; raceList[0] = new GUIContent("Imperial"); raceList[1] = new GUIContent("Chaos"); impShips = new GUIContent[3]; impShips[0] = new GUIContent("Gothic Class Cruiser"); impShips[1] = new GUIContent("Tyrant Class Cruiser"); impShips[2] = new GUIContent("Dauntles Class Light Cruiser"); chaosShips = new GUIContent[3]; chaosShips[0] = new GUIContent("Carnage Class Cruiser"); chaosShips[1] = new GUIContent("Murder Class Cruiser"); chaosShips[2] = new GUIContent("Slaughter Class Cruiser"); p1Race = new Popup(new Rect(50, 100, 100, 20), raceList[0], raceList, "button", "box", listStyle); } private void OnGUI () { p1Race.Show(); } }
mit
C#
a1b02f445a665dee3014b1cc6d97b998e0bf9d81
Add select methods
douglasPinheiro/Selenium-Webdriver-helpers
src/SeleniumWebdriverHelpers/SeleniumWebdriverHelpers/SelectExtensions.cs
src/SeleniumWebdriverHelpers/SeleniumWebdriverHelpers/SelectExtensions.cs
using OpenQA.Selenium; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SeleniumWebdriverHelpers { public static class SelectExtensions { public static IWebElement SelectElement(this IWebDriver browser, By by) { return browser.FindElement(by); } public static IEnumerable<IWebElement> SelectElements(this IWebDriver browser, By by) { return browser.FindElements(by); } } }
mit
C#
489caed17c718faf7e39f7fa5f0f188f69afcb62
Validate Tag Helper registration system functionality.
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNet.Razor.Test/TagHelpers/TagHelperDescriptorProviderTest.cs
test/Microsoft.AspNet.Razor.Test/TagHelpers/TagHelperDescriptorProviderTest.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using Microsoft.AspNet.Razor.TagHelpers; using Xunit; namespace Microsoft.AspNet.Razor.Test.TagHelpers { public class TagHelperDescriptorProviderTest { [Fact] public void TagHelperDescriptorProvider_GetTagHelpersReturnsNothingForUnregisteredTags() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("foo"); // Assert Assert.Empty(retrievedDescriptors); } [Fact] public void TagHelperDescriptorProvider_GetTagHelpersDoesntReturnNonCatchAllTagsForCatchAll() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var catchAllDescriptor = new TagHelperDescriptor("*", "foo3", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor, catchAllDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("*"); // Assert var descriptor = Assert.Single(retrievedDescriptors); Assert.Same(catchAllDescriptor, descriptor); } [Fact] public void TagHelperDescriptorProvider_GetTagHelpersReturnsCatchAllsWithEveryTagName() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var spanDescriptor = new TagHelperDescriptor("span", "foo2", ContentBehavior.None); var catchAllDescriptor = new TagHelperDescriptor("*", "foo3", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, spanDescriptor, catchAllDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var divDescriptors = provider.GetTagHelpers("div"); var spanDescriptors = provider.GetTagHelpers("span"); // Assert // For divs Assert.Equal(2, divDescriptors.Count()); Assert.Contains(divDescriptor, divDescriptors); Assert.Contains(catchAllDescriptor, divDescriptors); // For spans Assert.Equal(2, spanDescriptors.Count()); Assert.Contains(spanDescriptor, spanDescriptors); Assert.Contains(catchAllDescriptor, spanDescriptors); } [Fact] public void TagHelperDescriptorProvider_DuplicateDescriptorsAreNotPartOfTagHelperDescriptorPool() { // Arrange var divDescriptor = new TagHelperDescriptor("div", "foo1", ContentBehavior.None); var descriptors = new TagHelperDescriptor[] { divDescriptor, divDescriptor }; var provider = new TagHelperDescriptorProvider(descriptors); // Act var retrievedDescriptors = provider.GetTagHelpers("div"); // Assert var descriptor = Assert.Single(retrievedDescriptors); Assert.Same(divDescriptor, descriptor); } } }
apache-2.0
C#
f13bde68e665088021ee1db2c43565557b30b6e8
Add test for catch hidden mod
smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu
osu.Game.Rulesets.Catch.Tests/TestSceneCatchModHidden.cs
osu.Game.Rulesets.Catch.Tests/TestSceneCatchModHidden.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Rulesets.Catch.Mods; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.Objects.Drawables; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { public class TestSceneCatchModHidden : ModTestScene { [BackgroundDependencyLoader] private void load() { LocalConfig.Set(OsuSetting.IncreaseFirstObjectVisibility, false); } [Test] public void TestJuiceStream() { CreateModTest(new ModTestData { Beatmap = new Beatmap { HitObjects = new List<HitObject> { new JuiceStream { StartTime = 1000, Path = new SliderPath(PathType.Linear, new[] { Vector2.Zero, new Vector2(0, -192) }), X = CatchPlayfield.WIDTH / 2 } } }, Mod = new CatchModHidden(), PassCondition = () => Player.Results.Count > 0 && Player.ChildrenOfType<DrawableJuiceStream>().Single().Alpha > 0 && Player.ChildrenOfType<DrawableFruit>().Last().Alpha > 0 }); } protected override Ruleset CreatePlayerRuleset() => new CatchRuleset(); } }
mit
C#
6841d1e632eeaf08ebb6c8461f5ec9bd17a622c5
Add a new interface for the JobService.
domtheluck/yellowjacket,domtheluck/yellowjacket,domtheluck/yellowjacket,domtheluck/yellowjacket
YellowJacket/src/YellowJacket.Dashboard/Services/Interfaces/IJobService.cs
YellowJacket/src/YellowJacket.Dashboard/Services/Interfaces/IJobService.cs
// *********************************************************************** // Copyright (c) 2017 Dominik Lachance // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System.Collections.Generic; using System.Threading.Tasks; using YellowJacket.Models; namespace YellowJacket.Dashboard.Services.Interfaces { internal interface IJobService { /// <summary> /// Adds the specified job to the repository. /// </summary> /// <param name="job">The job.</param> /// <returns> /// <see cref="JobModel" />. /// </returns> Task<JobModel> Add(JobModel job); /// <summary> /// Gets all jobs from the repository. /// </summary> /// <returns> /// <see cref="IEnumerable{JobModel}" />. /// </returns> Task<IEnumerable<JobModel>> GetAll(); /// <summary> /// Finds a job by its id. /// </summary> /// <param name="id">The id.</param> /// <returns> /// <see cref="JobModel" />. /// </returns> Task<JobModel> Find(string id); /// <summary> /// Removes the specified job from the repository. /// </summary> /// <param name="id">The id of the job to remove.</param> /// <returns><see cref="Task" />.</returns> Task Remove(string id); /// <summary> /// Updates the specified job. /// </summary> /// <param name="job">The job.</param> /// <returns><see cref="JobModel"/>.</returns> Task<JobModel> Update(JobModel job); } }
mit
C#
daed27460c8f2b29349401d59ac4026f2fcf8e48
Add simple user state class
ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu
osu.Game/Online/RealtimeMultiplayer/MultiplayerClientState.cs
osu.Game/Online/RealtimeMultiplayer/MultiplayerClientState.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Online.RealtimeMultiplayer { public class MultiplayerClientState { public MultiplayerClientState(in long roomId) { CurrentRoomID = roomId; } public long CurrentRoomID { get; } } }
mit
C#
35e8fb5737cb8ffcff5a94a8af3e178e6990a1da
Add ConsoleHelper.cs
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Helpers/ConsoleHelper.cs
src/WeihanLi.Common/Helpers/ConsoleHelper.cs
// Copyright (c) Weihan Li. All rights reserved. // Licensed under the Apache license. namespace WeihanLi.Common.Helpers; public static class ConsoleHelper { public static void InvokeWithConsoleColor(Action action, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor = null) { Guard.NotNull(action); var originalForegroundColor = Console.ForegroundColor; var originalBackgroundColor = Console.BackgroundColor; try { if (foregroundColor.HasValue) { Console.ForegroundColor = foregroundColor.Value; } if (backgroundColor.HasValue) { Console.BackgroundColor = backgroundColor.Value; } action(); } finally { Console.ForegroundColor = originalForegroundColor; Console.BackgroundColor = originalBackgroundColor; } } public static async Task InvokeWithConsoleColor(Func<Task> action, ConsoleColor? foregroundColor, ConsoleColor? backgroundColor = null) { Guard.NotNull(action); var originalForegroundColor = Console.ForegroundColor; var originalBackgroundColor = Console.BackgroundColor; try { if (foregroundColor.HasValue) { Console.ForegroundColor = foregroundColor.Value; } if (backgroundColor.HasValue) { Console.BackgroundColor = backgroundColor.Value; } await action(); } finally { Console.ForegroundColor = originalForegroundColor; Console.BackgroundColor = originalBackgroundColor; } } }
mit
C#
7e030e7280533cc74accbe95510c817381f9bd12
Disable unit test parallelization
jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet
apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data.Tests/AssemblyInfo.cs
apis/Google.Cloud.Spanner.Data/Google.Cloud.Spanner.Data.Tests/AssemblyInfo.cs
// Copyright 2018 Google LLC // // 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 // // https://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 Google.Cloud.ClientTesting; using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)] // Uncomment these to run the tests in a predictable order. (By fixture name, then by test case within the fixture.) // [assembly: TestCollectionOrderer(AlphabeticalOrderer.TypeName, AlphabeticalOrderer.AssemblyName)] // [assembly: TestCaseOrderer(AlphabeticalOrderer.TypeName, AlphabeticalOrderer.AssemblyName)]
apache-2.0
C#
6a18468cc39147fcf58ce6d638358da044bb6029
Create tablecontroller
maf-dosi/ModernDynamicData,maf-dosi/ModernDynamicData
src/ModernDynamicData.Host.Web/Controllers/TableController.cs
src/ModernDynamicData.Host.Web/Controllers/TableController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace ModernDynamicData.Host.Web.Controllers { public class TableController : Controller { /// <summary> /// Get all contexts /// </summary> /// <returns></returns> public IActionResult Index() { return View(); } /// <summary> /// Get all tables by context /// </summary> /// <param name="context"></param> /// <returns></returns> public IActionResult GetAllTables(string context) { return View(); } } }
mit
C#
c77919ca14b5a58e057dcd75179d20204de172f5
Create abstract report to simplify creating reports
Kentico/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector
KenticoInspector.Core/AbstractReport.cs
KenticoInspector.Core/AbstractReport.cs
using KenticoInspector.Core.Models; using System; using System.Collections.Generic; namespace KenticoInspector.Core { public abstract class AbstractReport : IReport { public string Codename => GetCodename(this.GetType()); public static string GetCodename(Type reportType) { return GetDirectParentNamespace(reportType); } public abstract IList<Version> CompatibleVersions { get; } public virtual IList<Version> IncompatibleVersions => new List<Version>(); public abstract IList<string> Tags { get; } public abstract ReportResults GetResults(); private static string GetDirectParentNamespace(Type reportType) { var fullNameSpace = reportType.Namespace; var indexAfterLastPeriod = fullNameSpace.LastIndexOf('.') + 1; return fullNameSpace.Substring(indexAfterLastPeriod, fullNameSpace.Length - indexAfterLastPeriod); } } }
mit
C#
95665bab96b3e3e8354d383dedb992057d4ed129
add change
0x53A/PropertyChanged,Fody/PropertyChanged,user1568891/PropertyChanged
PropertyChanged.Fody/OnChangedMethod.cs
PropertyChanged.Fody/OnChangedMethod.cs
using Mono.Cecil; public enum OnChangedTypes { NoArg, BeforeAfter, } public class OnChangedMethod { public MethodReference MethodReference; public OnChangedTypes OnChangedType; }
mit
C#
ccb6a2097c1fd4f7162a86aef88ce06ee4870700
Fix Rows xmldocs
doss78/SolrNet,vmanral/SolrNet,mausch/SolrNet,18098924759/SolrNet,erandr/SolrNet,18098924759/SolrNet,mausch/SolrNet,vladen/SolrNet,mausch/SolrNet,erandr/SolrNet,MetSystem/SolrNet,erandr/SolrNet,vladen/SolrNet,vladen/SolrNet,yonglehou/SolrNet,tombeany/SolrNet,yonglehou/SolrNet,chang892886597/SolrNet,doss78/SolrNet,drakeh/SolrNet,vyzvam/SolrNet,SolrNet/SolrNet,yonglehou/SolrNet,chang892886597/SolrNet,vyzvam/SolrNet,SolrNet/SolrNet,chang892886597/SolrNet,vmanral/SolrNet,MetSystem/SolrNet,vmanral/SolrNet,vyzvam/SolrNet,18098924759/SolrNet,vladen/SolrNet,drakeh/SolrNet,Laoujin/SolrNet,doss78/SolrNet,tombeany/SolrNet,Laoujin/SolrNet,tombeany/SolrNet,drakeh/SolrNet,MetSystem/SolrNet,Laoujin/SolrNet,erandr/SolrNet
SolrNet/Commands/Parameters/CommonQueryOptions.cs
SolrNet/Commands/Parameters/CommonQueryOptions.cs
using System.Collections.Generic; namespace SolrNet.Commands.Parameters { /// <summary> /// Common, shared query options /// </summary> public class CommonQueryOptions { /// <summary> /// Common, shared query options /// </summary> public CommonQueryOptions() { Fields = new List<string>(); FilterQueries = new List<ISolrQuery>(); Facet = new FacetParameters(); ExtraParams = new Dictionary<string, string>(); } /// <summary> /// Fields to retrieve. /// By default, all stored fields are returned /// </summary> public ICollection<string> Fields { get; set; } /// <summary> /// Offset in the complete result set for the queries where the set of returned documents should begin /// Default is 0 /// </summary> public int? Start { get; set; } /// <summary> /// Maximum number of documents from the complete result set to return to the client for every request. /// Default is 100000000. /// NOTE: do not rely on this default value. In a future release the default value will be reset to the Solr default. /// Always define the number of rows you want. The high value is meant to mimic a SQL query without a TOP/LIMIT clause. /// </summary> public int? Rows { get; set; } /// <summary> /// Facet parameters /// </summary> public FacetParameters Facet { get; set; } /// <summary> /// This parameter can be used to specify a query that can be used to restrict the super set of documents that can be returned, without influencing score. /// It can be very useful for speeding up complex queries since the queries specified with fq are cached independently from the main query. /// This assumes the same Filter is used again for a latter query (i.e. there's a cache hit) /// </summary> public ICollection<ISolrQuery> FilterQueries { get; set; } /// <summary> /// Extra arbitrary parameters to be passed in the request querystring /// </summary> public IEnumerable<KeyValuePair<string, string>> ExtraParams { get; set; } } }
using System.Collections.Generic; namespace SolrNet.Commands.Parameters { /// <summary> /// Common, shared query options /// </summary> public class CommonQueryOptions { /// <summary> /// Common, shared query options /// </summary> public CommonQueryOptions() { Fields = new List<string>(); FilterQueries = new List<ISolrQuery>(); Facet = new FacetParameters(); ExtraParams = new Dictionary<string, string>(); } /// <summary> /// Fields to retrieve. /// By default, all stored fields are returned /// </summary> public ICollection<string> Fields { get; set; } /// <summary> /// Offset in the complete result set for the queries where the set of returned documents should begin /// Default is 0 /// </summary> public int? Start { get; set; } /// <summary> /// Maximum number of documents from the complete result set to return to the client for every request. /// Default is 10 /// </summary> public int? Rows { get; set; } /// <summary> /// Facet parameters /// </summary> public FacetParameters Facet { get; set; } /// <summary> /// This parameter can be used to specify a query that can be used to restrict the super set of documents that can be returned, without influencing score. /// It can be very useful for speeding up complex queries since the queries specified with fq are cached independently from the main query. /// This assumes the same Filter is used again for a latter query (i.e. there's a cache hit) /// </summary> public ICollection<ISolrQuery> FilterQueries { get; set; } /// <summary> /// Extra arbitrary parameters to be passed in the request querystring /// </summary> public IEnumerable<KeyValuePair<string, string>> ExtraParams { get; set; } } }
apache-2.0
C#
adb5ff18f25349ae3ac15f486f4c5e33244027b3
Remove unnecessary changes
karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS
src/Host/Broker/Impl/Security/Certificates.cs
src/Host/Broker/Impl/Security/Certificates.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Common.Core; namespace Microsoft.R.Host.Broker.Security { internal static class Certificates { public static X509Certificate2 GetCertificateForEncryption(string certName) { return FindCertificate(certName); } private static X509Certificate2 FindCertificate(string name) { var stores = new StoreName[] { StoreName.Root, StoreName.AuthRoot, StoreName.CertificateAuthority, StoreName.My }; foreach (StoreName storeName in stores) { using (var store = new X509Store(storeName, StoreLocation.LocalMachine)) { try { store.Open(OpenFlags.OpenExistingOnly); } catch(CryptographicException) { // Not all stores may be present continue; } try { var collection = store.Certificates.Cast<X509Certificate2>(); var cert = collection.FirstOrDefault(c => c.FriendlyName.EqualsIgnoreCase(name)); if (cert == null) { cert = collection.FirstOrDefault(c => c.Subject.EqualsIgnoreCase(name)); if (cert != null) { return cert; } } } finally { store.Close(); } } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Linq; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Common.Core; namespace Microsoft.R.Host.Broker.Security { internal static class Certificates { private static readonly StoreName[] _certificateStores = ; public static X509Certificate2 GetCertificateForEncryption(string certName) { return FindCertificate(certName); } private static X509Certificate2 FindCertificate(string name) { var stores = new StoreName[] { StoreName.Root, StoreName.AuthRoot, StoreName.CertificateAuthority, StoreName.My }; foreach (StoreName storeName in stores) { using (var store = new X509Store(storeName, StoreLocation.LocalMachine)) { try { store.Open(OpenFlags.OpenExistingOnly); } catch(CryptographicException) { // Not all stores may be present continue; } try { var collection = store.Certificates.Cast<X509Certificate2>(); var cert = collection.FirstOrDefault(c => c.FriendlyName.EqualsIgnoreCase(name)); if (cert == null) { cert = collection.FirstOrDefault(c => c.Subject.EqualsIgnoreCase(name)); if (cert != null) { return cert; } } } finally { store.Close(); } } } return null; } } }
mit
C#
4d4b3ee01093ec5bb62815c83b92d2530807d82e
Create StringExtensions.cs
UnityCommunity/UnityLibrary
Assets/Scripts/Extensions/StringExtensions.cs
Assets/Scripts/Extensions/StringExtensions.cs
using UnityEngine; using System.Globalization; namespace UnityLibrary { public static class StringExtensions { public static Color ToColor(this string hex) { hex = hex.Replace("0x", ""); hex = hex.Replace("#", ""); byte a = 255; byte r = byte.Parse(hex.Substring(0,2), NumberStyles.HexNumber); byte g = byte.Parse(hex.Substring(2,2), NumberStyles.HexNumber); byte b = byte.Parse(hex.Substring(4,2), NumberStyles.HexNumber); if (hex.Length == 8) a = byte.Parse(hex.Substring(6,2), NumberStyles.HexNumber); return new Color32(r,g,b,a); } } }
mit
C#
18428cf794bdb07e5f72220b414e19b2b1893592
Improve TypeEntry.ToString
drewnoakes/servant
Servant/TypeEntry.cs
Servant/TypeEntry.cs
#region License // // Servant // // Copyright 2016-2017 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/servant // #endregion using System; using JetBrains.Annotations; namespace Servant { internal sealed class TypeEntry { public Type DeclaredType { get; } [CanBeNull] public TypeProvider Provider { get; set; } public TypeEntry(Type declaredType) => DeclaredType = declaredType; public override string ToString() { return Provider != null ? $"{DeclaredType} ({Provider.Dependencies.Count} {(Provider.Dependencies.Count == 1 ? "dependency" : "dependencies")})" : $"{DeclaredType} (no provider)"; } } }
#region License // // Servant // // Copyright 2016-2017 Drew Noakes // // 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. // // More information about this project is available at: // // https://github.com/drewnoakes/servant // #endregion using System; using JetBrains.Annotations; namespace Servant { internal sealed class TypeEntry { public Type DeclaredType { get; } [CanBeNull] public TypeProvider Provider { get; set; } public TypeEntry(Type declaredType) => DeclaredType = declaredType; public override string ToString() => $"{DeclaredType}{(Provider == null ? "(no provider)" : $"{Provider.Dependencies.Count} dependencies")}"; } }
apache-2.0
C#
84cedfa45d662a5aaabb0ff13b4b44443fc1715f
Create demo.cshtml
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
src/WebSite/Views/Content/demo.cshtml
src/WebSite/Views/Content/demo.cshtml
@section head { <meta property="og:title" content="@ViewData["Title"]" /> <meta property="og:type" content="website" /> <meta property="og:url" content="@Core.Settings.Current.WebSiteUrl" /> <meta property="og:image" content="@Core.Settings.Current.FacebookImage" /> <meta property="og:description" content="@Core.Settings.Current.DefaultDescription" /> <meta name="keywords" content="@Core.Settings.Current.DefaultKeywords" /> <meta name="description" content="@Core.Settings.Current.DefaultDescription" /> } <h1>@ViewData["Title"]</h1> <div class="row"> <article class="col-md-12"> <h2>Demo VI Sharing</h2> <div id="viAdUnit"></div> <script> (function (v,i){ // 59674276073ef41e33501409 , 59674276073ef41e33501408 var source = window.viStories.source, config = window.viStories.testcases[getParameterByName('id')].config, // tag template V3 ins,win,scr; config.DivID&&(v.getElementById(config.DivID)?(ins=v.getElementById(config.DivID),win=i):i.frameElement&&i.parent.document.getElementById(config.DivID)&&(ins=i.parent.document.getElementById(config.DivID),win=i.parent)), ins||(i.frameElement&&"1"===i.frameElement.width&&"1"===i.frameElement.height?(ins=i.frameElement.parentNode.parentNode,win=i.parent):(ins=v.body||v.documentElement.appendChild(v.createElement("body")),win=i)), scr=win.document.createElement("script"), scr.id="vi-"+config.PublisherID, scr.src=source, scr.async=!0, scr.onload=function(){win[btoa('video intelligence')].run(config,void 0===v.currentScript?v.scripts[v.scripts.length-1]:v.currentScript,source)}, ins.appendChild(scr); })(document,window) </script> <script> // Log the current testcase configuration console.log('Testcase id: ' + getParameterByName('id')); console.log('Source path: ' + window.viStories.source); console.log('Config: '); console.dir(window.viStories.testcases[getParameterByName('id')].config); </script> </article> </div>
mit
C#
605dcb82f087b966544b654ddcf0b2a69496a1c2
Include non state in states to fix in fix state migration
VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,bussemac/n2cms,nimore/n2cms,nicklv/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,bussemac/n2cms,nicklv/n2cms,bussemac/n2cms,nicklv/n2cms,n2cms/n2cms,n2cms/n2cms,bussemac/n2cms,nimore/n2cms,SntsDev/n2cms,bussemac/n2cms,nicklv/n2cms,SntsDev/n2cms,nimore/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,n2cms/n2cms,VoidPointerAB/n2cms,VoidPointerAB/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms
src/Mvc/MvcTemplates/N2/Installation/FixStateMigration.cs
src/Mvc/MvcTemplates/N2/Installation/FixStateMigration.cs
using System.Linq; using N2.Edit.Installation; using N2.Persistence; namespace N2.Management.Installation { [N2.Engine.Service(typeof(AbstractMigration))] public class FixStateMigration : AbstractMigration { IRepository<ContentItem> repository; public FixStateMigration(IRepository<ContentItem> repository) { this.repository = repository; Title = "Fix state on items with no or new state"; Description = "Changes the stat to either Waiting, Published or Expired on items with the New state."; } public override bool IsApplicable(DatabaseStatus status) { return status.DatabaseVersion < DatabaseStatus.RequiredDatabaseVersion || !status.HasSchema || repository.Find("State", ContentState.None).Any() || repository.Find("State", ContentState.New).Any(); } public override MigrationResult Migrate(DatabaseStatus preSchemaUpdateStatus) { int updatedItems = 0; using (var transaction = repository.BeginTransaction()) { foreach (var item in repository.Find("State", ContentState.New)) { Fixit(ref updatedItems, item); } foreach (var item in repository.Find("State", ContentState.None)) { Fixit(ref updatedItems, item); } transaction.Commit(); } return new MigrationResult(this) { UpdatedItems = updatedItems }; } private void Fixit(ref int updatedItems, ContentItem item) { if (item.IsExpired()) item.State = ContentState.Unpublished; else if (item.IsPublished()) item.State = ContentState.Waiting; else item.State = ContentState.Published; repository.SaveOrUpdate(item); updatedItems++; } } }
using System.Linq; using N2.Edit.Installation; using N2.Persistence; namespace N2.Management.Installation { [N2.Engine.Service(typeof(AbstractMigration))] public class FixStateMigration : AbstractMigration { IRepository<ContentItem> repository; public FixStateMigration(IRepository<ContentItem> repository) { this.repository = repository; Title = "Fix state on items with New state"; Description = "Changes the stat to either Waiting, Published or Expired on items with the New state."; } public override bool IsApplicable(DatabaseStatus status) { return status.DatabaseVersion < DatabaseStatus.RequiredDatabaseVersion || !status.HasSchema || repository.Find("State", ContentState.New).Any(); } public override MigrationResult Migrate(DatabaseStatus preSchemaUpdateStatus) { int updatedItems = 0; using (var transaction = repository.BeginTransaction()) { foreach (var item in repository.Find("State", ContentState.New)) { if (item.IsExpired()) item.State = ContentState.Unpublished; else if (item.IsPublished()) item.State = ContentState.Waiting; else item.State = ContentState.Published; repository.SaveOrUpdate(item); updatedItems++; } transaction.Commit(); } return new MigrationResult(this) { UpdatedItems = updatedItems }; } } }
lgpl-2.1
C#
0117d05f6253531861b091a1fb72705220a5c924
Disable test parallelization in sqlserver functional tests
rapidcore/rapidcore,rapidcore/rapidcore
src/sqlserver/test-functional/Properties/AssemblyInfo.cs
src/sqlserver/test-functional/Properties/AssemblyInfo.cs
using Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)]
mit
C#
b6349dd7787634204a69743109008de1630161aa
Add IHierarchicalEntity
mehrandvd/Tralus,mehrandvd/Tralus
Framework/Source/Tralus.Framework.BusinessModel/Entities/IHierarchyEntity.cs
Framework/Source/Tralus.Framework.BusinessModel/Entities/IHierarchyEntity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DevExpress.Persistent.Base.General; namespace Tralus.Framework.BusinessModel.Entities { public interface IHierarchyEntity : IHCategory, ITreeNodeImageProvider { } }
apache-2.0
C#
31addfeb0486c127acf4aef2e8dd2c3941e049d7
add skipversion, eventhough this API existed it was undocumented prior to 5.4
CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,elastic/elasticsearch-net
src/Tests/Document/Single/SourceExists/SourceExistsApiTests.cs
src/Tests/Document/Single/SourceExists/SourceExistsApiTests.cs
using System; using System.Collections.Generic; using Elasticsearch.Net; using FluentAssertions; using Nest; using Tests.Framework; using Tests.Framework.Integration; using Tests.Framework.ManagedElasticsearch.Clusters; using Tests.Framework.ManagedElasticsearch.NodeSeeders; using Tests.Framework.MockData; using Xunit; using static Nest.Infer; namespace Tests.Document.Single.SourceExists { [SkipVersion("<5.4.0", "API was documented from 5.4.0 and over")] public class SourceExistsApiTests : ApiIntegrationTestBase<WritableCluster, IExistsResponse, ISourceExistsRequest, SourceExistsDescriptor<Project>, SourceExistsRequest<Project>> { public SourceExistsApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { } protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values) { foreach (var id in values.Values) this.Client.Index(Project.Instance, i=>i.Id(id)); } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.SourceExists<Project>(CallIsolatedValue), fluentAsync: (client, f) => client.SourceExistsAsync<Project>(CallIsolatedValue), request: (client, r) => client.SourceExists(r), requestAsync: (client, r) => client.SourceExistsAsync(r) ); protected override bool ExpectIsValid => true; protected override int ExpectStatusCode => 200; protected override HttpMethod HttpMethod => HttpMethod.HEAD; protected override string UrlPath => $"/project/project/{CallIsolatedValue}/_source"; protected override bool SupportsDeserialization => false; protected override Func<SourceExistsDescriptor<Project>, ISourceExistsRequest> Fluent => null; protected override SourceExistsRequest<Project> Initializer => new SourceExistsRequest<Project>(CallIsolatedValue); } public class SourceExistsNotFoundApiTests : ApiIntegrationTestBase<WritableCluster, IExistsResponse, ISourceExistsRequest, SourceExistsDescriptor<Project>, SourceExistsRequest<Project>> { public SourceExistsNotFoundApiTests(WritableCluster cluster, EndpointUsage usage) : base(cluster, usage) { } private static IndexName IndexWithNoSource { get; } = "project-with-no-source"; private static DocumentPath<Project> Doc(string id) => new DocumentPath<Project>(id).Index(IndexWithNoSource); protected override void IntegrationSetup(IElasticClient client, CallUniqueValues values) { var index = client.CreateIndex(IndexWithNoSource, i=>i .Mappings(m=>m .Map<Project>(mm=>mm .SourceField(sf=>sf.Enabled(false)) ) ) ); index.IsValid.Should().BeTrue(index.DebugInformation); foreach (var id in values.Values) this.Client.Index(Project.Instance, i=>i.Id(id).Index(IndexWithNoSource)); } protected override LazyResponses ClientUsage() => Calls( fluent: (client, f) => client.SourceExists<Project>(Doc(CallIsolatedValue)), fluentAsync: (client, f) => client.SourceExistsAsync<Project>(Doc(CallIsolatedValue)), request: (client, r) => client.SourceExists(r), requestAsync: (client, r) => client.SourceExistsAsync(r) ); protected override bool ExpectIsValid => false; protected override int ExpectStatusCode => 404; protected override HttpMethod HttpMethod => HttpMethod.HEAD; protected override string UrlPath => $"/{IndexWithNoSource.Name}/project/{CallIsolatedValue}/_source"; protected override bool SupportsDeserialization => false; protected override Func<SourceExistsDescriptor<Project>, ISourceExistsRequest> Fluent => null; protected override SourceExistsRequest<Project> Initializer => new SourceExistsRequest<Project>(Doc(CallIsolatedValue)); } }
apache-2.0
C#
b6c45de7257580efe0c1bf7e0f4bf0ae59dd490d
add npm packages tests
lvermeulen/ProGet.Net
test/ProGet.Net.Tests/Native/NpmPackages/ProGetClientShould.cs
test/ProGet.Net.Tests/Native/NpmPackages/ProGetClientShould.cs
using System.Threading.Tasks; using Xunit; // ReSharper disable CheckNamespace namespace ProGet.Net.Tests { public partial class ProGetClientShould { [Fact] public async Task NpmPackages_GetPackageAsync() { var result = await _client.NpmPackages_GetPackageAsync(4, "express", "latest"); Assert.NotNull(result); } } }
mit
C#
bac2f145690dae22ad1595012c9f0cf1b00439d5
Create ExeptionMessages class
stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity,stoyanov7/SoftwareUniversity
C#Development/BashSoft/BashSoft/Exceptions/ExceptionMessages.cs
C#Development/BashSoft/BashSoft/Exceptions/ExceptionMessages.cs
namespace BashSoft.Exceptions { public static class ExceptionMessages { public const string DataAlreadyInitialisedException = "Data is already initialized!"; public const string DataNotInitializedExceptionMessage = "The data structure must be initialised first in order to make any operations with it."; public const string InexistingCourseInDataBase = "The course you are trying to get does not exist in the data base!"; public const string InexistingStudentInDataBase = "The user name for the student you are trying to get does not exist!"; } }
mit
C#
da3774f988d2c77dd21e647320c41e9d302122ff
Fix date nouveau tournoi
Tri125/lama,Lan-Manager/lama
Lama/UI/UC/Creation/InformationsGeneralesView.xaml.cs
Lama/UI/UC/Creation/InformationsGeneralesView.xaml.cs
using Lama.UI.Win; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; namespace Lama.UI.UC.Creation { /// <summary> /// Logique d'interaction pour InformationsGeneralesView.xaml /// </summary> public partial class InformationsGeneralesView : UserControl { public InformationsGeneralesView() { InitializeComponent(); // Fait en sorte que les dates que l'on choisie ne sont pas dans le passé dtpDateTournoi.DisplayDateStart = DateTime.Now; } private void txtNomTournoi_LostFocus(object sender, RoutedEventArgs e) { if (String.IsNullOrWhiteSpace(((TextBox)sender).Text)) { // Remettre le focus sur le textbox Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate () { txtNomTournoi.Focus(); Keyboard.Focus(txtNomTournoi); })); } } } }
using Lama.UI.Win; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Threading; namespace Lama.UI.UC.Creation { /// <summary> /// Logique d'interaction pour InformationsGeneralesView.xaml /// </summary> public partial class InformationsGeneralesView : UserControl { public InformationsGeneralesView() { InitializeComponent(); } private void txtDescription_Error(object sender, ValidationErrorEventArgs e) { MessageBox.Show("erreur!"); } private void txtNomTournoi_LostFocus(object sender, RoutedEventArgs e) { if (String.IsNullOrWhiteSpace(((TextBox)sender).Text)) { // Remettre le focus sur le textbox Dispatcher.BeginInvoke(DispatcherPriority.Input, new Action(delegate () { txtNomTournoi.Focus(); Keyboard.Focus(txtNomTournoi); })); } } } }
mit
C#
0e24d93b5b9f351f1cbe15b33d7b162452777e6a
Create GameObjectMove.cs
drawcode/labs-unity
gameobjects/GameObjectMove.cs
gameobjects/GameObjectMove.cs
using UnityEngine; using System.Collections; public class GameObjectMove : MonoBehaviour { public float translationSpeedX = 0f; public float translationSpeedY = 1f; public float translationSpeedZ = 0f; public bool local = true; public void Start() { } public void Update() { if (local == true) { transform.Translate( new Vector3(translationSpeedX, translationSpeedY, translationSpeedZ) * Time.deltaTime); } if (local == false) { transform.Translate( new Vector3(translationSpeedX, translationSpeedY, translationSpeedZ) * Time.deltaTime, Space.World); } } }
mit
C#
08814777ed01ea98ce33cbec9c63bcba5df2407b
Add worker threads
jezell/iserviceoriented,tdrake/iserviceoriented
IServiceOriented.ServiceBus.UnitTests/TestWorkerThreads.cs
IServiceOriented.ServiceBus.UnitTests/TestWorkerThreads.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using IServiceOriented.ServiceBus.Threading; using System.Threading; namespace IServiceOriented.ServiceBus.UnitTests { [TestFixture] public class TestWorkerThreads { [Test] public void Can_Start_And_Stop_Workers() { long count = 0; using(WorkerThreads threads = new WorkerThreads(TimeSpan.FromSeconds(5), (ts, obj) => { Interlocked.Increment(ref count); Thread.Sleep(100); })) { int index = threads.AddWorker(); // pause a bit and make sure thread is working Thread.Sleep(1000); Assert.AreEqual(1, threads.Count); long curCount = Interlocked.Read(ref count); Assert.AreNotEqual(0, curCount); // has value been incremented threads.RemoveWorker(index); Assert.AreEqual(0, threads.Count); // pause a bit and make sure thread is actually dead long countAfterStop = Interlocked.Read(ref count); Thread.Sleep(1000); curCount = Interlocked.Read(ref count); Assert.AreEqual(curCount, countAfterStop); } } } }
mit
C#
9a7d0e489cf726f00379917cd507839d5fe56725
add spring constraint to linkset constraint types.
M-O-S-E-S/opensim,ft-/arribasim-dev-tests,TomDataworks/opensim,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,justinccdev/opensim,ft-/arribasim-dev-tests,RavenB/opensim,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-extras,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-tests,BogusCurry/arribasim-dev,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,TomDataworks/opensim,ft-/opensim-optimizations-wip,ft-/arribasim-dev-tests,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,RavenB/opensim,justinccdev/opensim,ft-/arribasim-dev-extras,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,justinccdev/opensim,RavenB/opensim,justinccdev/opensim,BogusCurry/arribasim-dev,ft-/arribasim-dev-tests,justinccdev/opensim,RavenB/opensim,ft-/opensim-optimizations-wip-tests,OpenSimian/opensimulator,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,RavenB/opensim,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,OpenSimian/opensimulator,TomDataworks/opensim,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,TomDataworks/opensim,justinccdev/opensim,ft-/arribasim-dev-tests,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,M-O-S-E-S/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-tests,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-tests,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,RavenB/opensim
OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs
OpenSim/Region/Physics/BulletSPlugin/BSConstraintSpring.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using OpenMetaverse; namespace OpenSim.Region.Physics.BulletSPlugin { public sealed class BSConstraintSpring : BSConstraint6Dof { public override ConstraintType Type { get { return ConstraintType.D6_SPRING_CONSTRAINT_TYPE; } } public BSConstraintSpring(BulletWorld world, BulletBody obj1, BulletBody obj2, Vector3 frame1Loc, Quaternion frame1Rot, Vector3 frame2Loc, Quaternion frame2Rot, bool useLinearReferenceFrameA, bool disableCollisionsBetweenLinkedBodies) :base(world, obj1, obj2) { m_constraint = PhysicsScene.PE.Create6DofSpringConstraint(world, obj1, obj2, frame1Loc, frame1Rot, frame2Loc, frame2Rot, useLinearReferenceFrameA, disableCollisionsBetweenLinkedBodies); m_enabled = true; world.physicsScene.DetailLog("{0},BSConstraintSpring,createFrame,wID={1}, rID={2}, rBody={3}, cID={4}, cBody={5}", BSScene.DetailLogZero, world.worldID, obj1.ID, obj1.AddrString, obj2.ID, obj2.AddrString); } public bool SetEnable(int index, bool axisEnable) { bool ret = false; return ret; } public bool SetStiffness(int index, float stiffness) { bool ret = false; return ret; } public bool SetDamping(int index, float damping) { bool ret = false; return ret; } public bool SetEquilibriumPoint(int index, float eqPoint) { bool ret = false; return ret; } } }
bsd-3-clause
C#