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
815df34fe4c52ab4d6b339c6da3ce59493931d3d
Fix in DummyPlayer
studware/Ange-Git,NikolayIT/SantaseGameEngine,studware/Ange-Git,studware/Ange-Git
Source/AI/Santase.AI.DummyPlayer/DummyPlayer.cs
Source/AI/Santase.AI.DummyPlayer/DummyPlayer.cs
namespace Santase.AI.DummyPlayer { using System.Linq; using Santase.Logic.Extensions; using Santase.Logic.Players; /// <summary> /// This dummy player follows the rules and always plays random card. /// Dummy never changes the trump or closes the game. /// </summary> public class DummyPlayer : BasePlayer { public DummyPlayer(string name = "Dummy Player") { this.Name = name; } public override string Name { get; } public override PlayerAction GetTurn(PlayerTurnContext context) { var possibleCardsToPlay = this.PlayerActionValidator.GetPossibleCardsToPlay(context, this.Cards); var shuffledCards = possibleCardsToPlay.Shuffle(); var cardToPlay = shuffledCards.First(); return this.PlayCard(cardToPlay); } } }
namespace Santase.AI.DummyPlayer { using System.Linq; using Santase.Logic.Extensions; using Santase.Logic.Players; /// <summary> /// This dummy player follows the rules and always plays random card. /// Dummy never changes the trump or closes the game. /// </summary> public class DummyPlayer : BasePlayer { public DummyPlayer(string name = "Dummy Player") { this.Name = name; } public override string Name { get; } public override PlayerAction GetTurn(PlayerTurnContext context) { var possibleCardsToPlay = this.PlayerActionValidator.GetPossibleCardsToPlay(context, this.Cards); var shuffledCards = possibleCardsToPlay.Shuffle(); var cardToPlay = shuffledCards.First(); var action = PlayerAction.PlayCard(cardToPlay); return action; } } }
mit
C#
9cffab6ae32d16cfe001706b12fc37243c4d3bf8
Update copyright year
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/Properties/AssemblyInfo.cs
SteamAccountSwitcher/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Steam Account Switcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniel Chalmers Software")] [assembly: AssemblyProduct("Steam Account Switcher")] [assembly: AssemblyCopyright("© Daniel Chalmers 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.3.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Steam Account Switcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Daniel Chalmers Software")] [assembly: AssemblyProduct("Steam Account Switcher")] [assembly: AssemblyCopyright("© Daniel Chalmers 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Guid("22E1FAEA-639E-400B-9DCB-F2D04EC126E1")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.3.0")]
mit
C#
5a046bab385ffa2afb11709d4f38b73c695e8b15
Add InMemoryCacheTest.GetOrAdd() Add InMemoryCacheTest.Remove()
superkarn/RatanaLibrary
Tests.RatanaLibrary.Common/Cache/NoCacheTest.cs
Tests.RatanaLibrary.Common/Cache/NoCacheTest.cs
using NUnit.Framework; using RatanaLibrary.Common.Cache; using System; namespace Tests.RatanaLibrary.Common.Cache { [TestFixture] public class NoCacheTest { [Test] public void GetOrAdd() { #region Arrange // Set up some variables var cacheKey = "test-key"; var cacheValue1 = "test-value-1"; var cacheValue2 = "test-value-2"; var cache = new NoCache(); #endregion #region Act // 1 Try to save cacheValue1 under cacheKey. var returnedCachValue1 = ((ICache)cache).GetOrAdd(cacheKey, () => { return cacheValue1; }); // 2 Try to save cacheValue2 under cacheKey. var returnedCachValue2 = ((ICache)cache).GetOrAdd(cacheKey, () => { return cacheValue2; }); #endregion #region Assert // What we get back should equal what we put in, since there is no cache. Assert.AreEqual(cacheValue1, returnedCachValue1); Assert.AreEqual(cacheValue2, returnedCachValue2); #endregion } [Test] public void Remove() { #region Arrange // Set up some variables var cacheKey = "test-key"; var cacheValue1 = "test-value-1"; var cache = new NoCache(); #endregion #region Act // 1 Try to save cacheValue1 under cacheKey. var returnedCachValue1 = ((ICache)cache).GetOrAdd(cacheKey, () => { return cacheValue1; }); // 2 Remove the cacheKey ((ICache)cache).Remove(cacheKey); #endregion #region Assert // There is no cache. There is nothing to assert. // Just make sure NoCache.Remove() doesn't throw an exception #endregion } } }
using NUnit.Framework; using System; namespace Tests.RatanaLibrary.Common.Cache { [TestFixture] public class NoCacheTest { [Test] public void GetOrAdd() { throw new NotImplementedException(); } [Test] public void Remove() { throw new NotImplementedException(); } } }
apache-2.0
C#
417fac403938326d29e31991f3a1ffa0b286c056
fix getCountry
NDark/ndinfrastructure,NDark/ndinfrastructure
Unity/Platform/Region/Plugins/PlatformRegion.cs
Unity/Platform/Region/Plugins/PlatformRegion.cs
/** MIT License Copyright (c) 2017 - 2021 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); // Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getCountry"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() ret" + ret); return ret; } #endif }
/** MIT License Copyright (c) 2017 - 2021 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. */ /** * https://wenrongdev.com/unity53-native-system-language/ */ using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Runtime.InteropServices; public static class PlatformRegion { public static string CheckUnityApplicationSystemLanguage() { string ret = string.Empty; SystemLanguage unitySystemLangauge = Application.systemLanguage; ret = unitySystemLangauge.ToString(); // Debug.Log("CheckApplicationSystemLanguage() ret=" + ret); return ret ; } #if UNITY_ANDROID public static string CurrentAndroidLanguage() { string result = ""; using (AndroidJavaClass cls = new AndroidJavaClass("java.util.Locale")) { if (cls != null) { using (AndroidJavaObject locale = cls.CallStatic<AndroidJavaObject>("getDefault")) { if (locale != null) { result = locale.Call<string>("getLanguage") + "_" + locale.Call<string>("getDefault"); Debug.Log("CurrentAndroidLanguage() Android lang: " + result); } else { Debug.LogError("CurrentAndroidLanguage() locale null"); } } } else { Debug.LogError("CurrentAndroidLanguage() cls null"); } } Debug.LogWarning("CurrentAndroidLanguage() result" + result); return result; } #endif #if UNITY_IPHONE [DllImport("__Internal")] private static extern string CurIOSLang(); public static string CurrentiOSLanguage() { string ret = CurIOSLang(); Debug.LogWarning("CurrentAndroidLanguage() ret" + ret); return ret; } #endif }
mit
C#
d8c7e969005ca4fb56fe59252883d993b8a2e21f
bump assembly version
ssg/HashDepot
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HashDepot")] [assembly: AssemblyDescription("HashDepot hash functions library")] [assembly: AssemblyProduct("HashDepot")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Sedat Kapanoglu")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("020ceffe-d464-44b0-8764-eaf2cc80718d")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: InternalsVisibleTo("HashDepot.Test")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("HashDepot")] [assembly: AssemblyDescription("HashDepot hash functions library")] [assembly: AssemblyProduct("HashDepot")] [assembly: AssemblyCopyright("Copyright © 2015-2016 Sedat Kapanoglu")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("020ceffe-d464-44b0-8764-eaf2cc80718d")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("HashDepot.Test")]
mit
C#
5e7f7f48e10e43de56535390c294e051dc7b890e
Fix logger category name for BackChannelLogoutHttpClient (#4129)
IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4
src/IdentityServer4/src/Services/Default/BackChannelLogoutHttpClient.cs
src/IdentityServer4/src/Services/Default/BackChannelLogoutHttpClient.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace IdentityServer4.Services { /// <summary> /// Models making HTTP requests for back-channel logout notification. /// </summary> public class BackChannelLogoutHttpClient { private readonly HttpClient _client; private readonly ILogger<BackChannelLogoutHttpClient> _logger; /// <summary> /// Constructor for BackChannelLogoutHttpClient. /// </summary> /// <param name="client"></param> /// <param name="logger"></param> public BackChannelLogoutHttpClient(HttpClient client, ILogger<BackChannelLogoutHttpClient> logger) { _client = client; _logger = logger; } /// <summary> /// Posts the payload to the url. /// </summary> /// <param name="url"></param> /// <param name="payload"></param> /// <returns></returns> public async Task PostAsync(string url, Dictionary<string, string> payload) { try { var response = await _client.PostAsync(url, new FormUrlEncodedContent(payload)); if (response.IsSuccessStatusCode) { _logger.LogDebug("Response from back-channel logout endpoint: {url} status code: {status}", url, (int)response.StatusCode); } else { _logger.LogWarning("Response from back-channel logout endpoint: {url} status code: {status}", url, (int)response.StatusCode); } } catch (Exception ex) { _logger.LogError(ex, "Exception invoking back-channel logout for url: {url}", url); } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace IdentityServer4.Services { /// <summary> /// Models making HTTP requests for back-channel logout notification. /// </summary> public class BackChannelLogoutHttpClient { private readonly HttpClient _client; private readonly ILogger<JwtRequestUriHttpClient> _logger; /// <summary> /// Constructor for BackChannelLogoutHttpClient. /// </summary> /// <param name="client"></param> /// <param name="logger"></param> public BackChannelLogoutHttpClient(HttpClient client, ILogger<JwtRequestUriHttpClient> logger) { _client = client; _logger = logger; } /// <summary> /// Posts the payload to the url. /// </summary> /// <param name="url"></param> /// <param name="payload"></param> /// <returns></returns> public async Task PostAsync(string url, Dictionary<string, string> payload) { try { var response = await _client.PostAsync(url, new FormUrlEncodedContent(payload)); if (response.IsSuccessStatusCode) { _logger.LogDebug("Response from back-channel logout endpoint: {url} status code: {status}", url, (int)response.StatusCode); } else { _logger.LogWarning("Response from back-channel logout endpoint: {url} status code: {status}", url, (int)response.StatusCode); } } catch (Exception ex) { _logger.LogError(ex, "Exception invoking back-channel logout for url: {url}", url); } } } }
apache-2.0
C#
36706f4abb2a00c701ce7227538178f1f43d163f
Update name
roberthardy/Synthesis,kamsar/Synthesis
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("Connective DX")] [assembly: AssemblyProduct("Synthesis")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("8.1.1.0")] [assembly: AssemblyFileVersion("8.1.1.0")] [assembly: AssemblyInformationalVersion("8.1.1")] [assembly: CLSCompliant(false)]
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("ISITE Design")] [assembly: AssemblyProduct("Synthesis")] [assembly: AssemblyCopyright("Copyright © Kam Figy, ISITE Design")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("8.1.1.0")] [assembly: AssemblyFileVersion("8.1.1.0")] [assembly: AssemblyInformationalVersion("8.1.1")] [assembly: CLSCompliant(false)]
mit
C#
b8211929271433265304cc83661e4f2015eccb04
Prepare 0.6.3 release
LouisTakePILLz/ArgumentParser
ArgumentParser/Properties/AssemblyInfo.cs
ArgumentParser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a67b27e2-8841-4951-a6f0-a00d93f59560")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.3.0")] [assembly: AssemblyFileVersion("0.6.3.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a67b27e2-8841-4951-a6f0-a00d93f59560")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.6.2.0")] [assembly: AssemblyFileVersion("0.6.2.0")]
apache-2.0
C#
9dfdd2d82accc57b8aa6f0a8a656ff41ac094544
add a space in PredicateSegment.cs
sdcb/ibatis2sdmap
ibatis2sdmap/src/ibatis2sdmap/SqlSegments/PredicateSegment.cs
ibatis2sdmap/src/ibatis2sdmap/SqlSegments/PredicateSegment.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; namespace ibatis2sdmap.SqlSegments { public class PredicateSegment : SqlSegment { public string MacroName { get; } public string Property { get; } public string[] Properties { get; } public string Prepend { get; } public IEnumerable<SqlSegment> Segments { get; } public PredicateSegment(XElement xe, string macroName) { Property = xe.Attribute("property")?.Value; Properties = xe.Attribute("properties")?.Value.Split(','); if (Property == null && Properties == null) throw new ArgumentException(nameof(xe)); Prepend = xe.Attribute("prepend")?.Value ?? ""; Segments = xe.Nodes().Select(Create); MacroName = macroName; } public override string Emit() { if (Property != null) { return $"#{MacroName}<{Property}, sql{{" + $"{Prepend} {string.Concat(Segments.Select(x => x.Emit()))} " + $"}}>"; } else { return string.Join("\r\n", Properties.Select(prop => { return $"#{MacroName}<{prop}, sql{{" + $"{Prepend} {string.Concat(Segments.Select(x => x.Emit()))} " + $"}}>"; })); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Xml.Linq; namespace ibatis2sdmap.SqlSegments { public class PredicateSegment : SqlSegment { public string MacroName { get; } public string Property { get; } public string[] Properties { get; } public string Prepend { get; } public IEnumerable<SqlSegment> Segments { get; } public PredicateSegment(XElement xe, string macroName) { Property = xe.Attribute("property")?.Value; Properties = xe.Attribute("properties")?.Value.Split(','); if (Property == null && Properties == null) throw new ArgumentException(nameof(xe)); Prepend = xe.Attribute("prepend")?.Value ?? ""; Segments = xe.Nodes().Select(Create); MacroName = macroName; } public override string Emit() { if (Property != null) { return $"#{MacroName}<{Property}, sql{{" + $"{Prepend} {string.Concat(Segments.Select(x => x.Emit()))}" + $"}}>"; } else { return string.Join("\r\n", Properties.Select(prop => { return $"#{MacroName}<{prop}, sql{{" + $"{Prepend} {string.Concat(Segments.Select(x => x.Emit()))}" + $"}}>"; })); } } } }
mit
C#
41c075d378adf9924d020685328948b49d57bb58
Allow user to move in single direction
PearMed/Pear-Interaction-Engine
Assets/Pear.InteractionEngine/Scripts/Interactions/EventHandlers/Move.cs
Assets/Pear.InteractionEngine/Scripts/Interactions/EventHandlers/Move.cs
using Pear.InteractionEngine.Properties; using Pear.InteractionEngine.Utils; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.Interactions.EventHandlers { /// <summary> /// Move based on the change in property value /// </summary> public class Move : MonoBehaviour, IGameObjectPropertyEventHandler<Vector3> { [Tooltip("Move speed")] public float MoveSpeed = 1f; [Tooltip("Only move in a single direction based on the meximum direciton of the move vector")] public bool SingleDirection = false; List<GameObjectProperty<Vector3>> _properties = new List<GameObjectProperty<Vector3>>(); /// <summary> /// Move each property's owner based on the property's value /// </summary> void Update() { _properties.ForEach(p => { Vector3 moveValue = p.Value; // If we're moving in a single direction get the maximum direction an // set the other vector components to 0 if (SingleDirection) moveValue = GetMaximumDirection(moveValue); p.Owner.transform.GetOrAddComponent<ObjectWithAnchor>() .AnchorElement .transform .position += moveValue * MoveSpeed * Time.deltaTime; }); } public void RegisterProperty(GameObjectProperty<Vector3> property) { _properties.Add(property); } public void UnregisterProperty(GameObjectProperty<Vector3> property) { _properties.Remove(property); } /// <summary> /// Gets a vector with the maximum dimension non-zero and all other dimensions set to 0 /// </summary> /// <param name="moveVector">Vector to update</param> /// <returns>a vector with the maximum dimension non-zero and all other dimensions set to 0</returns> private Vector3 GetMaximumDirection(Vector3 moveVector) { Vector3 moveValue = moveVector; float absX = Mathf.Abs(moveValue.x); float absY = Mathf.Abs(moveValue.y); if (absX >= moveValue.y && absX >= moveValue.z) moveValue.y = moveValue.z = 0; else if (absY >= moveValue.x && absY >= moveValue.z) moveValue.x = moveValue.z = 0; else moveValue.x = moveValue.y = 0; return moveValue; } } }
using Pear.InteractionEngine.Properties; using Pear.InteractionEngine.Utils; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.Interactions.EventHandlers { /// <summary> /// Move based on the change in property value /// </summary> public class Move : MonoBehaviour, IGameObjectPropertyEventHandler<Vector3> { [Tooltip("Move speed")] public float MoveSpeed = 1f; List<GameObjectProperty<Vector3>> _properties = new List<GameObjectProperty<Vector3>>(); /// <summary> /// Move each property's owner based on the property's value /// </summary> void Update() { _properties.ForEach(p => { p.Owner.transform.GetOrAddComponent<ObjectWithAnchor>() .AnchorElement .transform .position += p.Value * MoveSpeed * Time.deltaTime; }); } public void RegisterProperty(GameObjectProperty<Vector3> property) { _properties.Add(property); } public void UnregisterProperty(GameObjectProperty<Vector3> property) { _properties.Remove(property); } } }
mit
C#
7baf5aa067a91ceac505b2067ffc3672bfd0d3bb
Fix camera flip bug at x=0
Divegato/small-world
Assets/Scripts/SelfLevelingController.cs
Assets/Scripts/SelfLevelingController.cs
using Assets.Scripts.Helpers; using UnityEngine; public class SelfLevelingController : MonoBehaviour { private Rigidbody2D body; void Start() { body = GetComponent<Rigidbody2D>(); } void Update() { var force = Environment.GetAverageGravitationalForce(body); transform.rotation = Quaternion.LookRotation(Vector3.forward, force * -1); } }
using System.Linq; using Assets.Scripts.Helpers; using UnityEngine; public class SelfLevelingController : MonoBehaviour { public float MaxRotateAngle = 0.25f; void Start() { } void Update() { var body = GetComponent<Rigidbody2D>(); var force = Environment.GetAverageGravitationalForce(body); gameObject.transform.up = force * -1; //var gravitySources = FindObjectsOfType<Gravity>(); //var averageForce = Vector2.zero; //foreach (var source in gravitySources) //{ // averageForce += source.GetForce(body); //} //gameObject.transform.up = averageForce.normalized * -1; //var closestPlanet = GameObject // .FindGameObjectsWithTag("Planet") // .Select(x => new // { // Vector = gameObject.transform.position - x.transform.position, // Planet = x // }) // .OrderBy(x => x.Vector.magnitude - x.Planet.GetComponent<CircleCollider2D>().radius) // .FirstOrDefault(); //var targetVector = Vector3.RotateTowards(gameObject.transform.up, closestPlanet.Vector, MaxRotateAngle, Mathf.Infinity); //gameObject.transform.up = new Vector3(targetVector.x, targetVector.y).normalized; } }
mit
C#
6455172fc0b1e7a8f585bb26338a1422520c69db
make all methods async
Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache
NuCache/Controllers/PackageController.cs
NuCache/Controllers/PackageController.cs
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using System.Web.Http; using System.Xml.Linq; using NuCache.Infrastructure; namespace NuCache.Controllers { public class PackagesController : ApiController { private readonly PackageCache _cache; private readonly WebClient _client; public PackagesController(PackageCache cache, WebClient client) { _cache = cache; _client = client; } [HttpGet] public async Task<HttpResponseMessage> Get() { return await _client.GetResponseAsync(new Uri("http://www.nuget.org/api/v2/")); } [HttpGet] public async Task<HttpResponseMessage> Metadata() { return await _client.GetResponseAsync(new Uri("http://www.nuget.org/api/v2/$metadata")); } [HttpGet] public async Task<HttpResponseMessage> List() { return await _client.GetResponseAsync(new Uri("http://www.nuget.org/api/v2/Packages")); } [HttpGet] public async Task<HttpResponseMessage> Search() { var builder = new UriBuilder(Request.RequestUri); builder.Host = "nuget.org"; builder.Port = -1; return await _client.GetResponseAsync(builder.Uri); } [HttpGet] public async Task<HttpResponseMessage> FindPackagesByID(string id) { return await _client.GetResponseAsync(new Uri("http://www.nuget.org/api/v2/FindPackagesById()?id=" + id)); } [HttpGet] public async Task<HttpResponseMessage> GetPackageByID(string packageID, string version) { var url = new Uri("http://www.nuget.org/api/v2/Package/" + packageID + "/" + version); var result = await _client.GetResponseAsync(url); var name = Path.GetFileName(result.RequestMessage.RequestUri.AbsolutePath); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = name}; return result; } } }
using System; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using System.Web.Http; using System.Xml.Linq; using NuCache.Infrastructure; namespace NuCache.Controllers { public class PackagesController : ApiController { private readonly PackageCache _cache; private readonly WebClient _client; public PackagesController(PackageCache cache, WebClient client) { _cache = cache; _client = client; } [HttpGet] public HttpResponseMessage Get() { var xml = _client.MakeRequest(new Uri("http://www.nuget.org/api/v2/")); return new HttpResponseMessage { RequestMessage = Request, Content = new XmlContent(XDocument.Parse(xml)), }; } [HttpGet] public HttpResponseMessage Metadata() { var xml = _client.MakeRequest(new Uri("http://www.nuget.org/api/v2/$metadata")); return new HttpResponseMessage { RequestMessage = Request, Content = new XmlContent(XDocument.Parse(xml)) }; } [HttpGet] public HttpResponseMessage List() { var xml = _client.MakeRequest(new Uri("http://www.nuget.org/api/v2/Packages")); return new HttpResponseMessage { RequestMessage = Request, Content = new XmlContent(XDocument.Parse(xml)), }; } [HttpGet] public async Task<HttpResponseMessage> Search() { var builder = new UriBuilder(Request.RequestUri); builder.Host = "nuget.org"; builder.Port = -1; var result = await _client.GetResponseAsync(builder.Uri); return result; } [HttpGet] public async Task<HttpResponseMessage> FindPackagesByID(string id) { var url = new Uri("http://www.nuget.org/api/v2/FindPackagesById()?id=" + id); return await _client.GetResponseAsync(url); } [HttpGet] public async Task<HttpResponseMessage> GetPackageByID(string packageID, string version) { var url = new Uri("http://www.nuget.org/api/v2/Package/" + packageID + "/" + version); var result = await _client.GetResponseAsync(url); var name = Path.GetFileName(result.RequestMessage.RequestUri.AbsolutePath); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = name}; return result; } } }
lgpl-2.1
C#
b2d2541d877cada6466c77611631b99d8dd39c4d
Enable nullablE for `System.Management.Automation.Provider.IContentReader` (#14151)
daxian-dbw/PowerShell,PaulHigin/PowerShell,daxian-dbw/PowerShell,PaulHigin/PowerShell,daxian-dbw/PowerShell,TravisEz13/PowerShell,JamesWTruher/PowerShell-1,TravisEz13/PowerShell,PaulHigin/PowerShell,daxian-dbw/PowerShell,TravisEz13/PowerShell,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,JamesWTruher/PowerShell-1,PaulHigin/PowerShell,TravisEz13/PowerShell
src/System.Management.Automation/namespaces/IContentReader.cs
src/System.Management.Automation/namespaces/IContentReader.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.IO; #nullable enable namespace System.Management.Automation.Provider { #region IContentReader /// <summary> /// A Cmdlet provider that implements the IContentCmdletProvider interface must provide an /// object that implements this interface when GetContentReader() is called. /// /// The interface allows for reading content from an item. /// </summary> public interface IContentReader : IDisposable { /// <summary> /// Reads the content from the item. /// </summary> /// <param name="readCount"> /// The number of "blocks" of data to be read from the item. /// </param> /// <returns> /// An array of the blocks of data read from the item. /// </returns> /// <remarks> /// A "block" of content is provider specific. For the file system /// a "block" may be considered a line of text, a byte, a character, or delimited string. /// /// The implementation of this method should break the content down into meaningful blocks /// that the user may want to manipulate individually. The number of blocks to return is /// indicated by the <paramref name="readCount"/> parameter. /// </remarks> IList Read(long readCount); /// <summary> /// Moves the current "block" to be read to a position relative to a place /// in the reader. /// </summary> /// <param name="offset"> /// An offset of the number of blocks to seek from the origin. /// </param> /// <param name="origin"> /// The place in the stream to start the seek from. /// </param> /// <remarks> /// The implementation of this method moves the content reader <paramref name="offset"/> /// number of blocks from the specified <paramref name="origin"/>. See <see cref="IContentReader.Read"/> /// for a description of what a block is. /// </remarks> void Seek(long offset, SeekOrigin origin); /// <summary> /// Closes the reader. Further reads should fail if the reader /// has been closed. /// </summary> /// <remarks> /// The implementation of this method should close any resources held open by the /// reader. /// </remarks> void Close(); } #endregion IContentReader }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.IO; namespace System.Management.Automation.Provider { #region IContentReader /// <summary> /// A Cmdlet provider that implements the IContentCmdletProvider interface must provide an /// object that implements this interface when GetContentReader() is called. /// /// The interface allows for reading content from an item. /// </summary> public interface IContentReader : IDisposable { /// <summary> /// Reads the content from the item. /// </summary> /// <param name="readCount"> /// The number of "blocks" of data to be read from the item. /// </param> /// <returns> /// An array of the blocks of data read from the item. /// </returns> /// <remarks> /// A "block" of content is provider specific. For the file system /// a "block" may be considered a line of text, a byte, a character, or delimited string. /// /// The implementation of this method should break the content down into meaningful blocks /// that the user may want to manipulate individually. The number of blocks to return is /// indicated by the <paramref name="readCount"/> parameter. /// </remarks> IList Read(long readCount); /// <summary> /// Moves the current "block" to be read to a position relative to a place /// in the reader. /// </summary> /// <param name="offset"> /// An offset of the number of blocks to seek from the origin. /// </param> /// <param name="origin"> /// The place in the stream to start the seek from. /// </param> /// <remarks> /// The implementation of this method moves the content reader <paramref name="offset"/> /// number of blocks from the specified <paramref name="origin"/>. See <see cref="IContentReader.Read"/> /// for a description of what a block is. /// </remarks> void Seek(long offset, SeekOrigin origin); /// <summary> /// Closes the reader. Further reads should fail if the reader /// has been closed. /// </summary> /// <remarks> /// The implementation of this method should close any resources held open by the /// reader. /// </remarks> void Close(); } #endregion IContentReader }
mit
C#
719fb7d9cb74b52042e89eb78f81324bc3e3acaf
Add abstract base class SettingProperty without type parameters.
PenguinF/sandra-three
Sandra.UI.WF/Settings/SettingProperty.cs
Sandra.UI.WF/Settings/SettingProperty.cs
/********************************************************************************* * SettingProperty.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ using System; namespace Sandra.UI.WF { /// <summary> /// Contains the declaration of a setting property, but doesn't specify its type. /// </summary> public abstract class SettingProperty { } /// <summary> /// Contains the declaration of a setting property, i.e. its name and the type of value that it takes. /// </summary> /// <typeparam name="T"> /// The .NET target <see cref="Type"/> to convert to and from. /// </typeparam> public class SettingProperty<T> : SettingProperty { /// <summary> /// Gets the name of the property. /// </summary> public SettingKey Name { get; } /// <summary> /// Gets the type of value that it contains. /// </summary> public PType<T> PType { get; } /// <summary> /// Initializes a new instance of <see cref="SettingProperty"/>. /// </summary> /// <param name="name"> /// The name of the property. /// </param> /// <param name="pType"> /// The type of value that it contains. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> and/or <paramref name="pType"/> are null. /// </exception> public SettingProperty(SettingKey name, PType<T> pType) { if (name == null) throw new ArgumentNullException(nameof(name)); if (pType == null) throw new ArgumentNullException(nameof(pType)); Name = name; PType = pType; } } }
/********************************************************************************* * SettingProperty.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ using System; namespace Sandra.UI.WF { /// <summary> /// Contains the declaration of a setting property, i.e. its name and the type of value that it takes. /// </summary> /// <typeparam name="T"> /// The .NET target <see cref="Type"/> to convert to and from. /// </typeparam> public class SettingProperty<T> { /// <summary> /// Gets the name of the property. /// </summary> public SettingKey Name { get; } /// <summary> /// Gets the type of value that it contains. /// </summary> public PType<T> PType { get; } /// <summary> /// Initializes a new instance of <see cref="SettingProperty"/>. /// </summary> /// <param name="name"> /// The name of the property. /// </param> /// <param name="pType"> /// The type of value that it contains. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="name"/> and/or <paramref name="pType"/> are null. /// </exception> public SettingProperty(SettingKey name, PType<T> pType) { if (name == null) throw new ArgumentNullException(nameof(name)); if (pType == null) throw new ArgumentNullException(nameof(pType)); Name = name; PType = pType; } } }
apache-2.0
C#
bc4ecccd56c68856055290415203fcdaa0b50fec
Remove the async runmode on swag since every command is async
Daniele122898/SoraBot-v2,Daniele122898/SoraBot-v2
SoraBot/SoraBot.Bot/Modules/FunModule.cs
SoraBot/SoraBot.Bot/Modules/FunModule.cs
using System; using System.Threading.Tasks; using Discord; using Discord.Commands; using SoraBot.Common.Extensions.Modules; namespace SoraBot.Bot.Modules { [Name("Fun")] [Summary("A bunch of fun and useless commands.")] public class FunModule : SoraSocketCommandModule { [Command("ruined"), Alias("dayruined")] [Summary("Posts the meme my disappointment is immeasurable")] public Task DayRuined() => ReplyAsync("", embed: new EmbedBuilder() { ImageUrl = "https://i.imgur.com/pIddxrw.png", Color = Purple }.Build()); [Command("swag"), Summary("Swags the chat")] public async Task Swag() { var msg = await ReplyAsync("( ͡° ͜ʖ ͡°)>⌐■-■"); await Task.Delay(1500); await msg.ModifyAsync(x => { x.Content = "( ͡⌐■ ͜ʖ ͡-■)"; }); } [Command("8ball"), Alias("8b"), Summary("Ask and get an 8ball answer")] public async Task Ball([Summary("Question"), Remainder] string question) { Random r = new Random(); await ReplyDefaultEmbed("🎱 " + ball[r.Next(ball.Length)]); } #region data private string[] ball = new[] { "Signs point to yes. ", "Yes.", "Reply hazy, try again.", "Without a doubt. ", "My sources say no. ", "As I see it, yes. ", "You may rely on it.", "Concentrate and ask again.", "Outlook not so good. ", "It is decidedly so.", "Better not tell you now.", "Very doubtful. ", "Yes - definitely. ", "It is certain. ", "Cannot predict now. ", "Most likely. ", "Ask again later. ", "My reply is no. ", "Outlook good. ", "Don't count on it." }; #endregion } }
using System; using System.Threading.Tasks; using Discord; using Discord.Commands; using SoraBot.Common.Extensions.Modules; namespace SoraBot.Bot.Modules { [Name("Fun")] [Summary("A bunch of fun and useless commands.")] public class FunModule : SoraSocketCommandModule { [Command("ruined"), Alias("dayruined")] [Summary("Posts the meme my disappointment is immeasurable")] public Task DayRuined() => ReplyAsync("", embed: new EmbedBuilder() { ImageUrl = "https://i.imgur.com/pIddxrw.png", Color = Purple }.Build()); [Command("swag", RunMode = RunMode.Async), Summary("Swags the chat")] public async Task Swag() { var msg = await ReplyAsync("( ͡° ͜ʖ ͡°)>⌐■-■"); await Task.Delay(1500); await msg.ModifyAsync(x => { x.Content = "( ͡⌐■ ͜ʖ ͡-■)"; }); } [Command("8ball"), Alias("8b"), Summary("Ask and get an 8ball answer")] public async Task Ball([Summary("Question"), Remainder] string question) { Random r = new Random(); await ReplyDefaultEmbed("🎱 " + ball[r.Next(ball.Length)]); } #region data private string[] ball = new[] { "Signs point to yes. ", "Yes.", "Reply hazy, try again.", "Without a doubt. ", "My sources say no. ", "As I see it, yes. ", "You may rely on it.", "Concentrate and ask again.", "Outlook not so good. ", "It is decidedly so.", "Better not tell you now.", "Very doubtful. ", "Yes - definitely. ", "It is certain. ", "Cannot predict now. ", "Most likely. ", "Ask again later. ", "My reply is no. ", "Outlook good. ", "Don't count on it." }; #endregion } }
agpl-3.0
C#
bc9578e8eac8a3c97aa08bc2d3fce3cdba775300
Update the FluentModelValidator in Samples
canton7/Stylet,canton7/Stylet
Samples/Stylet.Samples.ModelValidation/FluentModelValidator.cs
Samples/Stylet.Samples.ModelValidation/FluentModelValidator.cs
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.ModelValidation { public class FluentModelValidator<T> : IModelValidator<T> { private readonly IValidator<T> validator; private T subject; public FluentModelValidator(IValidator<T> validator) { this.validator = validator; } public void Initialize(object subject) { this.subject = (T)subject; } public async Task<IEnumerable<string>> ValidatePropertyAsync(string propertyName) { // If someone's calling us synchronously, and ValidationAsync does not complete synchronously, // we'll deadlock unless we continue on another thread. return (await this.validator.ValidateAsync(this.subject, CancellationToken.None, propertyName).ConfigureAwait(false)) .Errors.Select(x => x.ErrorMessage); } public async Task<Dictionary<string, IEnumerable<string>>> ValidateAllPropertiesAsync() { // If someone's calling us synchronously, and ValidationAsync does not complete synchronously, // we'll deadlock unless we continue on another thread. return (await this.validator.ValidateAsync(this.subject).ConfigureAwait(false)) .Errors.GroupBy(x => x.PropertyName) .ToDictionary(x => x.Key, x => x.Select(failure => failure.ErrorMessage)); } } }
using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.ModelValidation { public class FluentModelValidator<T> : IModelValidator<T> { private readonly IValidator<T> validator; private T subject; public FluentModelValidator(IValidator<T> validator) { this.validator = validator; } public void Initialize(object subject) { this.subject = (T)subject; } public Task<IEnumerable<string>> ValidatePropertyAsync(string propertyName) { var errors = this.validator.Validate(this.subject, propertyName).Errors.Select(x => x.ErrorMessage); return Task.FromResult(errors); } public async Task<Dictionary<string, IEnumerable<string>>> ValidateAllPropertiesAsync() { // If someone's calling us synchronously, and ValidationAsync does not complete synchronously, // we'll deadlock unless we continue on another thread. return (await this.validator.ValidateAsync(this.subject).ConfigureAwait(false)) .Errors.GroupBy(x => x.PropertyName) .ToDictionary(x => x.Key, x => x.Select(failure => failure.ErrorMessage)); } } }
mit
C#
5cbd45fa4af7fe6303615898114f46238e0698b2
Add implementation for argument exceptions for serializing.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Services/TraktSerializationService.cs
Source/Lib/TraktApiSharp/Services/TraktSerializationService.cs
namespace TraktApiSharp.Services { using Authentication; using System; /// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary> public static class TraktSerializationService { public static string Serialize(TraktAuthorization authorization) { if (authorization == null) throw new ArgumentNullException(nameof(authorization), "authorization must not be null"); return string.Empty; } public static TraktAuthorization Deserialize(string authorization) { return null; } } }
namespace TraktApiSharp.Services { using Authentication; /// <summary>Provides helper methods for serializing and deserializing Trakt objects.</summary> public static class TraktSerializationService { public static string Serialize(TraktAuthorization authorization) { return string.Empty; } public static TraktAuthorization Deserialize(string authorization) { return null; } } }
mit
C#
cd3a1cfa1221da1a118eb4b9490c9f2cf010464d
Add Snake Case Contract resolver
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets
lookups/lookup-get-addon-payfone-example-1/lookup-get-addon-payfone-1.cs
lookups/lookup-get-addon-payfone-example-1/lookup-get-addon-payfone-1.cs
using Newtonsoft.Json; using RestSharp; using RestSharp.Authenticators; using Newtonsoft.Json.Serialization; // Download the twilio-csharp library from twilio.com/docs/csharp/install using System; class Example { static void Main(string[] args) { // The C# helper library will support Add-ons in June 2016, for now we'll use a simple RestSharp HTTP client var client = new RestClient("https://lookups.twilio.com/v1/PhoneNumbers/+16502530000/?AddOns=payfone_tcpa_compliance&AddOns.payfone_tcpa_compliance.RightPartyContactedDate=20160101"); // Find your Account Sid and Auth Token at twilio.com/user/account client.Authenticator = new HttpBasicAuthenticator("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "{{ auth_token }}"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("accept", "application/json"); IRestResponse response = client.Execute(request); dynamic result = JsonConvert.DeserializeObject(response.Content, new JsonSerializerSettings { ContractResolver = new SnakeCaseContractResolver() }); Console.WriteLine(result.add_ons.results.payfone_tcpa_compliance.result.Description); Console.WriteLine(result.add_ons.results.payfone_tcpa_compliance.result.Response.NumberMatch); } public class SnakeCaseContractResolver : DefaultContractResolver { protected override string ResolvePropertyName(string propertyName) { return GetSnakeCase(propertyName); } private string GetSnakeCase(string input) { if (string.IsNullOrEmpty(input)) return input; var buffer = ""; for (var i = 0; i < input.Length; i++) { var isLast = (i == input.Length - 1); var isSecondFromLast = (i == input.Length - 2); var curr = input[i]; var next = !isLast ? input[i + 1] : '\0'; var afterNext = !isSecondFromLast && !isLast ? input[i + 2] : '\0'; buffer += char.ToLower(curr); if (!char.IsDigit(curr) && char.IsUpper(next)) { if (char.IsUpper(curr)) { if (!isLast && !isSecondFromLast && !char.IsUpper(afterNext)) buffer += "_"; } else buffer += "_"; } if (!char.IsDigit(curr) && char.IsDigit(next)) buffer += "_"; if (char.IsDigit(curr) && !char.IsDigit(next) && !isLast) buffer += "_"; } return buffer; } } }
using Newtonsoft.Json; using RestSharp; using RestSharp.Authenticators; // Download the twilio-csharp library from twilio.com/docs/csharp/install using System; class Example { static void Main(string[] args) { // The C# helper library will support Add-ons in June 2016, for now we'll use a simple RestSharp HTTP client var client = new RestClient("https://lookups.twilio.com/v1/PhoneNumbers/+16502530000/?AddOns=payfone_tcpa_compliance&AddOns.payfone_tcpa_compliance.RightPartyContactedDate=20160101"); // Find your Account Sid and Auth Token at twilio.com/user/account client.Authenticator = new HttpBasicAuthenticator("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", "{{ auth_token }}"); var request = new RestRequest(Method.GET); request.AddHeader("content-type", "application/json"); request.AddHeader("accept", "application/json"); IRestResponse response = client.Execute(request); dynamic result = JsonConvert.DeserializeObject(response.Content, new JsonSerializerSettings { ContractResolver = new SnakeCaseContractResolver() }); Console.WriteLine(result.add_ons.results.payfone_tcpa_compliance.result.Description); Console.WriteLine(result.add_ons.results.payfone_tcpa_compliance.result.Response.NumberMatch); } }
mit
C#
80b484078741c66cc93930b5f745a3d4a88fa2a0
add missing exception details for dynamic table entity. additional commit for #9
BhupinderAnand/log4net.azure,GrzegorzBlok/log4net.Azure,baumerik/log4net.Azure,stemarie/log4net.Azure
log4net.Azure/AzureDynamicLoggingEventEntity.cs
log4net.Azure/AzureDynamicLoggingEventEntity.cs
using System; using System.Collections; using System.Globalization; using log4net.Core; namespace log4net.Appender { internal sealed class AzureDynamicLoggingEventEntity : ElasticTableEntity { public AzureDynamicLoggingEventEntity(LoggingEvent e) { this["Domain"] = e.Domain; this["Identity"] = e.Identity; this["Level"] = e.Level.ToString(); this["LoggerName"] = e.LoggerName; this["Message"] = e.RenderedMessage + Environment.NewLine + e.GetExceptionString(); this["ThreadName"] = e.ThreadName; this["UserName"] = e.UserName; this["Location"] = e.LocationInformation.FullInfo; if (e.ExceptionObject != null) { this["Exception"] = e.ExceptionObject.ToString(); } Timestamp = e.TimeStamp; PartitionKey = e.LoggerName; RowKey = MakeRowKey(e); foreach (DictionaryEntry entry in e.Properties) { var key = entry.Key.ToString() .Replace(":", "_") .Replace("@", "_") .Replace(".", "_"); this[key] = entry.Value; } } private static string MakeRowKey(LoggingEvent loggingEvent) { return string.Format("{0}.{1}", loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff", DateTimeFormatInfo.InvariantInfo), Guid.NewGuid().ToString().ToLower()); } } }
using System; using System.Collections; using System.Globalization; using log4net.Core; namespace log4net.Appender { internal sealed class AzureDynamicLoggingEventEntity : ElasticTableEntity { public AzureDynamicLoggingEventEntity(LoggingEvent e) { this["Domain"] = e.Domain; this["Identity"] = e.Identity; this["Level"] = e.Level.ToString(); this["LoggerName"] = e.LoggerName; this["Message"] = e.RenderedMessage; this["ThreadName"] = e.ThreadName; this["UserName"] = e.UserName; this["Location"] = e.LocationInformation.FullInfo; if (e.ExceptionObject != null) { this["Exception"] = e.ExceptionObject.ToString(); } Timestamp = e.TimeStamp; PartitionKey = e.LoggerName; RowKey = MakeRowKey(e); foreach (DictionaryEntry entry in e.Properties) { var key = entry.Key.ToString() .Replace(":", "_") .Replace("@", "_") .Replace(".", "_"); this[key] = entry.Value; } } private static string MakeRowKey(LoggingEvent loggingEvent) { return string.Format("{0}.{1}", loggingEvent.TimeStamp.ToString("yyyy_MM_dd_HH_mm_ss_fffffff", DateTimeFormatInfo.InvariantInfo), Guid.NewGuid().ToString().ToLower()); } } }
mit
C#
c1e36065a14bd356a120df5d7566516e326edbda
Update to make hidden input for token self-closing
nikmd23/CourtesyFlush,nikmd23/CourtesyFlush,nikmd23/CourtesyFlush
source/CourtesyFlush/HtmlHelperExtension.cs
source/CourtesyFlush/HtmlHelperExtension.cs
using System.Web.Mvc; using System.Web.Mvc.Html; using CourtesyFlush; namespace System.Web.WebPages { public static class HtmlHelperExtension { public static MvcHtmlString FlushHead(this HtmlHelper html) { return FlushHead(html, null); } public static MvcHtmlString FlushHead(this HtmlHelper html, string headername) { if (String.IsNullOrWhiteSpace(headername)) headername = "_Head"; if (!html.ViewData.ContainsKey("HeadFlushed")) return html.Partial(headername); return new MvcHtmlString(string.Empty); } #if NET45 public static MvcHtmlString FlushedAntiForgeryToken(this HtmlHelper html) { var token = html.ViewContext.HttpContext.Items[ControllerBaseExtension.FlushedAntiForgeryTokenKey] as string; if (string.IsNullOrEmpty(token)) { // Fall back to the standard AntiForgeryToken if no FlushedAntiForgeryToken exists. return html.AntiForgeryToken(); } var tag = new TagBuilder("input"); tag.Attributes["type"] = "hidden"; tag.Attributes["name"] = "__RequestVerificationToken"; tag.Attributes["value"] = token; return new MvcHtmlString(tag.ToString(TagRenderMode.SelfClosing)); } #endif } }
using System.Web.Mvc; using System.Web.Mvc.Html; using CourtesyFlush; namespace System.Web.WebPages { public static class HtmlHelperExtension { public static MvcHtmlString FlushHead(this HtmlHelper html) { return FlushHead(html, null); } public static MvcHtmlString FlushHead(this HtmlHelper html, string headername) { if (String.IsNullOrWhiteSpace(headername)) headername = "_Head"; if (!html.ViewData.ContainsKey("HeadFlushed")) return html.Partial(headername); return new MvcHtmlString(string.Empty); } #if NET45 public static MvcHtmlString FlushedAntiForgeryToken(this HtmlHelper html) { var token = html.ViewContext.HttpContext.Items[ControllerBaseExtension.FlushedAntiForgeryTokenKey] as string; if (string.IsNullOrEmpty(token)) { // Fall back to the standard AntiForgeryToken if no FlushedAntiForgeryToken exists. return html.AntiForgeryToken(); } var tag = new TagBuilder("input"); tag.Attributes["type"] = "hidden"; tag.Attributes["name"] = "__RequestVerificationToken"; tag.Attributes["value"] = token; return new MvcHtmlString(tag.ToString()); } #endif } }
apache-2.0
C#
8cf4837353ff95bd9ec0f7006b3875ac9971055f
Implement diagnostic SA1411 AttributeConstructorMustNotUseUnnecessaryParenthesis (fixes #100)
DotNetAnalyzers/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/MaintainabilityRules/SA1411AttributeConstructorMustNotUseUnnecessaryParenthesis.cs
StyleCop.Analyzers/StyleCop.Analyzers/MaintainabilityRules/SA1411AttributeConstructorMustNotUseUnnecessaryParenthesis.cs
namespace StyleCop.Analyzers.MaintainabilityRules { using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; /// <summary> /// TODO. /// </summary> /// <remarks> /// <para>TODO</para> /// /// <para>A violation of this rule occurs when unnecessary parenthesis have been used in an attribute constructor. /// For example:</para> /// /// <code language="csharp"> /// [Serializable()] /// </code> /// <para>The parenthesis are unnecessary and should be removed:</para> /// <code language="csharp"> /// [Serializable] /// </code> /// </remarks> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class SA1411AttributeConstructorMustNotUseUnnecessaryParenthesis : DiagnosticAnalyzer { public const string DiagnosticId = "SA1411"; internal const string Title = "Attribute constructor must not use unnecessary parenthesis"; internal const string MessageFormat = "Attribute constructor must not use unnecessary parenthesis"; internal const string Category = "StyleCop.CSharp.MaintainabilityRules"; internal const string Description = "TODO."; internal const string HelpLink = "http://www.stylecop.com/docs/SA1411.html"; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink, WellKnownDiagnosticTags.Unnecessary); private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = ImmutableArray.Create(Descriptor); /// <inheritdoc/> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return _supportedDiagnostics; } } /// <inheritdoc/> public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(HandleAttributeArgumentListSyntax, SyntaxKind.AttributeArgumentList); } private void HandleAttributeArgumentListSyntax(SyntaxNodeAnalysisContext context) { AttributeArgumentListSyntax syntax = context.Node as AttributeArgumentListSyntax; if (syntax.Arguments.Count != 0) return; // Attribute constructor must not use unnecessary parenthesis context.ReportDiagnostic(Diagnostic.Create(Descriptor, syntax.GetLocation())); } } }
namespace StyleCop.Analyzers.MaintainabilityRules { using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; /// <summary> /// TODO. /// </summary> /// <remarks> /// <para>TODO</para> /// /// <para>A violation of this rule occurs when unnecessary parenthesis have been used in an attribute constructor. /// For example:</para> /// /// <code language="csharp"> /// [Serializable()] /// </code> /// <para>The parenthesis are unnecessary and should be removed:</para> /// <code language="csharp"> /// [Serializable] /// </code> /// </remarks> [DiagnosticAnalyzer(LanguageNames.CSharp)] public class SA1411AttributeConstructorMustNotUseUnnecessaryParenthesis : DiagnosticAnalyzer { public const string DiagnosticId = "SA1411"; internal const string Title = "Attribute constructor must not use unnecessary parenthesis"; internal const string MessageFormat = "TODO: Message format"; internal const string Category = "StyleCop.CSharp.MaintainabilityRules"; internal const string Description = "TODO."; internal const string HelpLink = "http://www.stylecop.com/docs/SA1411.html"; public static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, AnalyzerConstants.DisabledNoTests, Description, HelpLink); private static readonly ImmutableArray<DiagnosticDescriptor> _supportedDiagnostics = ImmutableArray.Create(Descriptor); /// <inheritdoc/> public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return _supportedDiagnostics; } } /// <inheritdoc/> public override void Initialize(AnalysisContext context) { // TODO: Implement analysis } } }
mit
C#
43eec4e1f237ea8877f4d90cecd05be6307b0902
Fix syntax
nikeee/HolzShots
src/HolzShots.Capture.Video/Capture/Video/FFmpeg/HttpClientExtensions.cs
src/HolzShots.Capture.Video/Capture/Video/FFmpeg/HttpClientExtensions.cs
using System; using System.Net.Http; using System.IO; using System.Threading.Tasks; using HolzShots.Net; using System.Threading; namespace HolzShots.Capture.Video.FFmpeg { /// <summary> Ref: https://stackoverflow.com/a/46497896 </summary> public static class HttpClientExtensions { public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress<TransferProgress>? progress = default, CancellationToken? cancellationToken = default) { // Get the http headers first to examine the content length using var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); var contentLength = response.Content.Headers.ContentLength; using var download = await response.Content.ReadAsStreamAsync(cancellationToken); // Ignore progress reporting when no progress reporter was // passed or when the content length is unknown if (progress == null || !contentLength.HasValue) { await download.CopyToAsync(destination, cancellationToken); return; } var totalData = new MemSize(contentLength!.Value); // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%) var relativeProgress = new Progress<long>(bytesLoaded => progress.Report(new TransferProgress(new MemSize(bytesLoaded), totalData, UploadState.Processing))); // Use extension method to report progress while downloading await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken); progress.Report(new TransferProgress(totalData, totalData, UploadState.Finished)); } } }
using System; using System.Net.Http; using System.IO; using System.Threading.Tasks; using HolzShots.Net; using System.Threading; namespace HolzShots.Capture.Video.FFmpeg { /// <summary> Ref: https://stackoverflow.com/a/46497896 </summary> public static class HttpClientExtensions { public static async Task DownloadAsync(this HttpClient client, string requestUri, Stream destination, IProgress<TransferProgress>? progress = default, CancellationToken cancellationToken? = default) { // Get the http headers first to examine the content length using var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead, cancellationToken); var contentLength = response.Content.Headers.ContentLength; using var download = await response.Content.ReadAsStreamAsync(cancellationToken); // Ignore progress reporting when no progress reporter was // passed or when the content length is unknown if (progress == null || !contentLength.HasValue) { await download.CopyToAsync(destination, cancellationToken); return; } var totalData = new MemSize(contentLength!.Value); // Convert absolute progress (bytes downloaded) into relative progress (0% - 100%) var relativeProgress = new Progress<long>(bytesLoaded => progress.Report(new TransferProgress(new MemSize(bytesLoaded), totalData, UploadState.Processing))); // Use extension method to report progress while downloading await download.CopyToAsync(destination, 81920, relativeProgress, cancellationToken); progress.Report(new TransferProgress(totalData, totalData, UploadState.Finished)); } } }
agpl-3.0
C#
a19981e7d8912e64276cd2bf4684ef38cdb23b8f
update vs to release
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
Master/Appleseed/Projects/PortableAreas/AppleseedProxy/Properties/AssemblyInfo.cs
Master/Appleseed/Projects/PortableAreas/AppleseedProxy/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppleseedProxy")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : MVC Proxy Module")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("AppleseedProxy")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ED77BC1B-D294-43E3-B1BF-1E8397810F48")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.4.131.463")] [assembly: AssemblyFileVersion("1.4.131.463")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AppleseedProxy")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : MVC Proxy Module")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("AppleseedProxy")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ED77BC1B-D294-43E3-B1BF-1E8397810F48")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.4.98.383")] [assembly: AssemblyFileVersion("1.4.98.383")]
apache-2.0
C#
2195235d64d6e5e549d39e70c20608e0cbcdee3c
Update ITrigger.cs
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactivity/ITrigger.cs
src/Avalonia.Xaml.Interactivity/ITrigger.cs
namespace Avalonia.Xaml.Interactivity; /// <summary> /// Interface implemented by all custom triggers. /// </summary> public interface ITrigger : IBehavior { /// <summary> /// Gets the collection of actions associated with the behavior. /// </summary> ActionCollection Actions { get; } }
namespace Avalonia.Xaml.Interactivity; /// <summary> /// Interface implemented by all custom triggers. /// </summary> public interface ITrigger : IBehavior { /// <summary> /// Gets the collection of actions associated with the behavior. /// </summary> ActionCollection? Actions { get; } }
mit
C#
24877b09d9b53e23d8862b9711db59b981431de4
Tidy up bootstrapper
DSaunders/EasyEvents
src/EasyEvents.SampleWebApp/Bootstrapper.cs
src/EasyEvents.SampleWebApp/Bootstrapper.cs
namespace EasyEvents.SampleWebApp { using Core; using Core.ClientInterfaces; using Core.Configuration; using Core.Stores; using Events.AppEvents; using Events.AppEvents.Handlers; using Nancy; using Nancy.Bootstrapper; using Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { container.Register<IEventHandler<AppStartedEvent>, AppStartedEventHandler>(); container.Register<IEventHandler<ThingHappenedEvent>, ThingHappenedEventHandler>(); var events = container.Resolve<IEasyEvents>(); events.Configure(new EasyEventsConfiguration { Store = new SqlEventStore("server=.;database=test;Integrated Security=true;"), HandlerFactory = type => container.Resolve(type) }); events.AddProcessorForStream(new AppEvent().Stream, async (c, e) => { if (e is ThingHappenedEvent && ((ThingHappenedEvent)e).TheThing == "broke") { await events.RaiseEventAsync(new ThingHappenedEvent("Ooooh noooo!!")); } }); events.ReplayAllEventsAsync().Wait(); events.RaiseEventAsync(new AppStartedEvent()).Wait(); } } }
namespace EasyEvents.SampleWebApp { using Core; using Core.ClientInterfaces; using Core.Configuration; using Core.Stores; using Events.AppEvents; using Events.AppEvents.Handlers; using Nancy; using Nancy.Bootstrapper; using Nancy.TinyIoc; public class Bootstrapper : DefaultNancyBootstrapper { protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines) { container.Register<IEventHandler<AppStartedEvent>, AppStartedEventHandler>(); container.Register<IEventHandler<ThingHappenedEvent>, ThingHappenedEventHandler>(); var events = container.Resolve<IEasyEvents>(); events.Configure(new EasyEventsConfiguration { Store = new SqlEventStore("server=.;database=test;Integrated Security=true;"), HandlerFactory = type => container.Resolve(type) }); events.AddProcessorForStream(new AppEvent().Stream, async (c, e) => { if (e.GetType() == typeof(ThingHappenedEvent) && ((ThingHappenedEvent)e).TheThing == "broke") { await events.RaiseEventAsync(new ThingHappenedEvent("Ooooh noooo!!")); } }); events.ReplayAllEventsAsync().Wait(); events.RaiseEventAsync(new AppStartedEvent()).Wait(); } } }
mit
C#
1697dd786e617997236c23a928b9bf3b7b284631
Allow access to the Data object
perrich/Hangfire.MemoryStorage
src/Hangfire.MemoryStorage/MemoryStorage.cs
src/Hangfire.MemoryStorage/MemoryStorage.cs
using System.Collections.Generic; using Hangfire.MemoryStorage.Database; using Hangfire.Server; using Hangfire.Storage; namespace Hangfire.MemoryStorage { public class MemoryStorage : JobStorage { private readonly MemoryStorageOptions _options; public Data Data { get; } public MemoryStorage() : this(new MemoryStorageOptions(), new Data()) { } public MemoryStorage(MemoryStorageOptions options) : this(options, new Data()) { } public MemoryStorage(MemoryStorageOptions options, Data data) { _options = options; Data = data; } public override IStorageConnection GetConnection() { return new MemoryStorageConnection(Data, _options.FetchNextJobTimeout); } public override IMonitoringApi GetMonitoringApi() { return new MemoryStorageMonitoringApi(Data); } #pragma warning disable 618 public override IEnumerable<IServerComponent> GetComponents() #pragma warning restore 618 { yield return new ExpirationManager(Data, _options.JobExpirationCheckInterval); yield return new CountersAggregator(Data, _options.CountersAggregateInterval); } } }
using System.Collections.Generic; using Hangfire.MemoryStorage.Database; using Hangfire.Server; using Hangfire.Storage; namespace Hangfire.MemoryStorage { public class MemoryStorage : JobStorage { private readonly MemoryStorageOptions _options; private readonly Data _data; public MemoryStorage() : this(new MemoryStorageOptions(), new Data()) { } public MemoryStorage(MemoryStorageOptions options) : this(options, new Data()) { } public MemoryStorage(MemoryStorageOptions options, Data data) { _options = options; _data = data; } public override IStorageConnection GetConnection() { return new MemoryStorageConnection(_data, _options.FetchNextJobTimeout); } public override IMonitoringApi GetMonitoringApi() { return new MemoryStorageMonitoringApi(_data); } #pragma warning disable 618 public override IEnumerable<IServerComponent> GetComponents() #pragma warning restore 618 { yield return new ExpirationManager(_data, _options.JobExpirationCheckInterval); yield return new CountersAggregator(_data, _options.CountersAggregateInterval); } } }
apache-2.0
C#
daf7191c7c79b8acfd446fb21bf0cb4f2389087b
fix exception
Franklin89/Blog,Franklin89/Blog
src/MLSoftware.Web/Services/EmailService.cs
src/MLSoftware.Web/Services/EmailService.cs
using System.Threading.Tasks; using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace MLSoftware.Web.Services { public class EmailService : IEmailService { private readonly IHostingEnvironment _hostingEnviroment; private readonly ILogger _logger; private readonly MailSettings _mailSettings; public EmailService(IHostingEnvironment hostingEnvironment, ILogger<EmailService> logger, IOptions<MailSettings> mailSettings) { _hostingEnviroment = hostingEnvironment; _logger = logger; _mailSettings = mailSettings.Value; } public async Task SendEmailAsync(string email, string subject, string message) { _logger.LogInformation("Sending email to {0} with the subject {1} message: {2}", email, subject, message); } } }
using System.Threading.Tasks; using System; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace MLSoftware.Web.Services { public class EmailService : IEmailService { private readonly IHostingEnvironment _hostingEnviroment; private readonly ILogger _logger; private readonly MailSettings _mailSettings; public EmailService(IHostingEnvironment hostingEnvironment, ILogger<EmailService> logger, IOptions<MailSettings> mailSettings) { _hostingEnviroment = hostingEnvironment; _logger = logger; _mailSettings = mailSettings.Value; } public async Task SendEmailAsync(string email, string subject, string message) { throw new NotImplementedException(); } } }
mit
C#
c581d6d9ff0509e79b784bfb2452f80c8fd96e40
update forattribute see cref reference
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/CommonAbstractions/ForAttribute.cs
src/Nest/CommonAbstractions/ForAttribute.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; using Elastic.Transport; namespace Nest { /// <summary> /// Makes it explicit which API this request interface maps, the name of the interface informs /// The generator how to name related types /// </summary> [AttributeUsage(AttributeTargets.Interface)] internal class MapsApiAttribute : Attribute { // ReSharper disable once UnusedParameter.Local public MapsApiAttribute(string restSpecName) { } } /// <summary> /// The preferred way to wire in a custom response formatter is for requests to override /// <see cref="RequestBase{TParameters}.RequestDefaults"/> however sometimes a request does not have /// access to enough type information. This attribute will set up the see <see cref="CustomResponseBuilderBase"/> /// in the generated client methods instead. /// </summary> [AttributeUsage(AttributeTargets.Interface)] internal class ResponseBuilderWithGeneric : Attribute { // ReSharper disable once UnusedParameter.Local public ResponseBuilderWithGeneric(string pathToBuilder) { } } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System; namespace Nest { /// <summary> /// Makes it explicit which API this request interface maps, the name of the interface informs /// The generator how to name related types /// </summary> [AttributeUsage(AttributeTargets.Interface)] internal class MapsApiAttribute : Attribute { // ReSharper disable once UnusedParameter.Local public MapsApiAttribute(string restSpecName) { } } /// <summary> /// The preferred way to wire in a custom response formatter is for requests to override /// <see cref="RequestBase{TParameters}.RequestDefaults"/> however sometimes a request does not have /// access to enough type information. This attribute will set up the <!--see cref="Elastic.Transport.RequestParameters.CustomResponseBuilder"/--> /// in the generated client methods instead. /// </summary> [AttributeUsage(AttributeTargets.Interface)] internal class ResponseBuilderWithGeneric : Attribute { // ReSharper disable once UnusedParameter.Local public ResponseBuilderWithGeneric(string pathToBuilder) { } } }
apache-2.0
C#
a70344d410458aeb0382e2f53076e5c077154946
Add keep_values gap policy (#5802) (#5807)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Aggregations/Pipeline/GapPolicy.cs
src/Nest/Aggregations/Pipeline/GapPolicy.cs
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { [StringEnum] public enum GapPolicy { [EnumMember(Value = "skip")] Skip, [EnumMember(Value = "insert_zeros")] InsertZeros, [EnumMember(Value = "keep_values")] KeepValues } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using System.Runtime.Serialization; using Elasticsearch.Net; namespace Nest { [StringEnum] public enum GapPolicy { [EnumMember(Value = "skip")] Skip, [EnumMember(Value = "insert_zeros")] InsertZeros } }
apache-2.0
C#
dfe92a0a3509a8d657c97b81bf91b8d66529a69b
Update assembly info
stevengum97/BotBuilder,yakumo/BotBuilder,dr-em/BotBuilder,xiangyan99/BotBuilder,stevengum97/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,msft-shahins/BotBuilder,mmatkow/BotBuilder,dr-em/BotBuilder,dr-em/BotBuilder,xiangyan99/BotBuilder,dr-em/BotBuilder,mmatkow/BotBuilder,yakumo/BotBuilder,Clairety/ConnectMe,Clairety/ConnectMe,mmatkow/BotBuilder,msft-shahins/BotBuilder,xiangyan99/BotBuilder,xiangyan99/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,Clairety/ConnectMe,msft-shahins/BotBuilder,Clairety/ConnectMe,mmatkow/BotBuilder,msft-shahins/BotBuilder
CSharp/Library/Properties/AssemblyInfo.cs
CSharp/Library/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.9.1.0")] [assembly: AssemblyFileVersion("1.9.1.0")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")] [assembly: InternalsVisibleTo("Microsoft.Bot.Sample.Tests")] [assembly: NeutralResourcesLanguage("en")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Microsoft.Bot.Builder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Bot Builder")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cdfec7d6-847e-4c13-956b-0a960ae3eb60")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.9.0.0")] [assembly: AssemblyFileVersion("1.9.0.0")] [assembly: InternalsVisibleTo("Microsoft.Bot.Builder.Tests")] [assembly: InternalsVisibleTo("Microsoft.Bot.Sample.Tests")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
c8d7051a954b09356c33fd2db83bbcfdfddc3ac8
Remove debug.
hulyman/circles
Assets/Scripts/Behaviors/Circle.cs
Assets/Scripts/Behaviors/Circle.cs
using UnityEngine; using System.Collections; public class Circle : MonoBehaviour { /** * Задает цвет для спрайта. */ void SetColor (Color color) { SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer> (); spriteRenderer.color = color; } /** * Уничтожает объект и сообщаем об этом. */ void Poof(){ EventManager.CirclePoof.Publish (this); Destroy (gameObject); } }
using UnityEngine; using System.Collections; public class Circle : MonoBehaviour { void SetColor (Color color) { SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer> (); spriteRenderer.color = color; } void OnMouseDown() { Debug.Log ("Clicked"); Poof (); } void Poof(){ EventManager.CirclePoof.Publish (this); Destroy (gameObject); } }
apache-2.0
C#
eab9a1d73c243292a47440d3c129e6112f49ad98
Add getter and setter to AdvancingText.advanceSpeed
Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/UI/AdvancingText.cs
Assets/Scripts/UI/AdvancingText.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using TMPro; public class AdvancingText : MonoBehaviour { [SerializeField] private float advanceSpeed; [SerializeField] private UnityEvent onComplete; private TMP_Text textMeshProComponent; private float progress; void Start () { textMeshProComponent = GetComponent<TMP_Text>();; resetAdvance(); } public void resetAdvance() { progress = 0f; setVisibleChars(0); } void Update () { if (progress < getTotalVisibleChars()) updateText(); } void updateText() { progress = Mathf.MoveTowards(progress, getTotalVisibleChars(), Time.deltaTime * advanceSpeed); setVisibleChars((int)Mathf.Floor(progress)); if (progress >= getTotalVisibleChars()) onComplete.Invoke(); } public float getAdvanceSpeed() { return advanceSpeed; } public void setAdvanceSpeed(float speed) { advanceSpeed = speed; } void setVisibleChars(int amount) { textMeshProComponent.maxVisibleCharacters = amount; } public int getVisibleChars() { return textMeshProComponent.maxVisibleCharacters; } public int getTotalVisibleChars() { var textInfo = textMeshProComponent.textInfo; return textInfo.characterCount; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using TMPro; public class AdvancingText : MonoBehaviour { [SerializeField] private float advanceSpeed; [SerializeField] private UnityEvent onComplete; private TMP_Text textMeshProComponent; private float progress; void Start () { textMeshProComponent = GetComponent<TMP_Text>();; resetAdvance(); } public void resetAdvance() { progress = 0f; setVisibleChars(0); } void Update () { if (progress < getTotalVisibleChars()) updateText(); } void updateText() { progress = Mathf.MoveTowards(progress, getTotalVisibleChars(), Time.deltaTime * advanceSpeed); setVisibleChars((int)Mathf.Floor(progress)); if (progress >= getTotalVisibleChars()) onComplete.Invoke(); } void setVisibleChars(int amount) { textMeshProComponent.maxVisibleCharacters = amount; } public int getVisibleChars() { return textMeshProComponent.maxVisibleCharacters; } public int getTotalVisibleChars() { var textInfo = textMeshProComponent.textInfo; return textInfo.characterCount; } }
mit
C#
0ba6b67de3af08c5e645af5990bc76244e70f12e
Fix default car always skiding in reverse
Nition/UnitySkidmarks
Assets/UnitySkidmarks/WheelSkid.cs
Assets/UnitySkidmarks/WheelSkid.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; // Example skid script. Put this on a WheelCollider. // Copyright 2017 Nition, BSD licence (see LICENCE file). http://nition.co [RequireComponent(typeof(WheelCollider))] public class WheelSkid : MonoBehaviour { // INSPECTOR SETTINGS [SerializeField] Rigidbody rb; [SerializeField] Skidmarks skidmarksController; // END INSPECTOR SETTINGS WheelCollider wheelCollider; WheelHit wheelHitInfo; const float SKID_FX_SPEED = 0.5f; // Min side slip speed in m/s to start showing a skid const float MAX_SKID_INTENSITY = 20.0f; // m/s where skid opacity is at full intensity const float WHEEL_SLIP_MULTIPLIER = 10.0f; // For wheelspin. Adjust how much skids show int lastSkid = -1; // Array index for the skidmarks controller. Index of last skidmark piece this wheel used float lastFixedUpdateTime; // #### UNITY INTERNAL METHODS #### protected void Awake() { wheelCollider = GetComponent<WheelCollider>(); lastFixedUpdateTime = Time.time; } protected void FixedUpdate() { lastFixedUpdateTime = Time.time; } protected void LateUpdate() { if (wheelCollider.GetGroundHit(out wheelHitInfo)) { // Check sideways speed // Gives velocity with +z being the car's forward axis Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity); float skidTotal = Mathf.Abs(localVelocity.x); // Check wheel spin as well float wheelAngularVelocity = wheelCollider.radius * ((2 * Mathf.PI * wheelCollider.rpm) / 60); float carForwardVel = Vector3.Dot(rb.velocity, transform.forward); float wheelSpin = Mathf.Abs(carForwardVel - wheelAngularVelocity) * WHEEL_SLIP_MULTIPLIER; // NOTE: This extra line should not be needed and you can take it out if you have decent wheel physics // The built-in Unity demo car is actually skidding its wheels the ENTIRE time you're accelerating, // so this fades out the wheelspin-based skid as speed increases to make it look almost OK wheelSpin = Mathf.Max(0, wheelSpin * (10 - Mathf.Abs(carForwardVel))); skidTotal += wheelSpin; // Skid if we should if (skidTotal >= SKID_FX_SPEED) { float intensity = Mathf.Clamp01(skidTotal / MAX_SKID_INTENSITY); // Account for further movement since the last FixedUpdate Vector3 skidPoint = wheelHitInfo.point + (rb.velocity * (Time.time - lastFixedUpdateTime)); lastSkid = skidmarksController.AddSkidMark(skidPoint, wheelHitInfo.normal, intensity, lastSkid); } else { lastSkid = -1; } } else { lastSkid = -1; } } // #### PUBLIC METHODS #### // #### PROTECTED/PRIVATE METHODS #### }
using System.Collections; using System.Collections.Generic; using UnityEngine; // Example skid script. Put this on a WheelCollider. // Copyright 2017 Nition, BSD licence (see LICENCE file). http://nition.co [RequireComponent(typeof(WheelCollider))] public class WheelSkid : MonoBehaviour { // INSPECTOR SETTINGS [SerializeField] Rigidbody rb; [SerializeField] Skidmarks skidmarksController; // END INSPECTOR SETTINGS WheelCollider wheelCollider; WheelHit wheelHitInfo; const float SKID_FX_SPEED = 0.5f; // Min side slip speed in m/s to start showing a skid const float MAX_SKID_INTENSITY = 20.0f; // m/s where skid opacity is at full intensity const float WHEEL_SLIP_MULTIPLIER = 10.0f; // For wheelspin. Adjust how much skids show int lastSkid = -1; // Array index for the skidmarks controller. Index of last skidmark piece this wheel used float lastFixedUpdateTime; // #### UNITY INTERNAL METHODS #### protected void Awake() { wheelCollider = GetComponent<WheelCollider>(); lastFixedUpdateTime = Time.time; } protected void FixedUpdate() { lastFixedUpdateTime = Time.time; } protected void LateUpdate() { if (wheelCollider.GetGroundHit(out wheelHitInfo)) { // Check sideways speed // Gives velocity with +z being the car's forward axis Vector3 localVelocity = transform.InverseTransformDirection(rb.velocity); float skidTotal = Mathf.Abs(localVelocity.x); // Check wheel spin as well float wheelAngularVelocity = wheelCollider.radius * ((2 * Mathf.PI * wheelCollider.rpm) / 60); float carForwardVel = Vector3.Dot(rb.velocity, transform.forward); float wheelSpin = Mathf.Abs(carForwardVel - wheelAngularVelocity) * WHEEL_SLIP_MULTIPLIER; // NOTE: This extra line should not be needed and you can take it out if you have decent wheel physics // The built-in Unity demo car is actually skidding its wheels the ENTIRE time you're accelerating, // so this fades out the wheelspin-based skid as speed increases to make it look almost OK wheelSpin = Mathf.Max(0, wheelSpin * (10 - carForwardVel)); skidTotal += wheelSpin; // Skid if we should if (skidTotal >= SKID_FX_SPEED) { float intensity = Mathf.Clamp01(skidTotal / MAX_SKID_INTENSITY); // Account for further movement since the last FixedUpdate Vector3 skidPoint = wheelHitInfo.point + (rb.velocity * (Time.time - lastFixedUpdateTime)); lastSkid = skidmarksController.AddSkidMark(skidPoint, wheelHitInfo.normal, intensity, lastSkid); } else { lastSkid = -1; } } else { lastSkid = -1; } } // #### PUBLIC METHODS #### // #### PROTECTED/PRIVATE METHODS #### }
bsd-2-clause
C#
100774db159e6670b41f043f9dd7e965eee5e997
Fix Default code identation
cesardeazevedo/Unity3D-Python-Editor,cesardeazevedo/Unity3D-Python-Editor
Assets/src/PythonBase.cs
Assets/src/PythonBase.cs
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class PythonBase : MonoBehaviour { /// <summary> /// The path of file /// </summary> public string FilePath; /// <summary> /// The name of the file. /// </summary> public string FileName = "Untitled.py"; /// <summary> /// The file created. /// </summary> public bool FileCreated, Saved, InMemory; /// <summary> /// Has changes in file /// </summary> public bool HasChanges = true; public enum Views { Code, Interpreter }; /// <summary> /// The current view. /// </summary> public Views CurrentView; /// <summary> /// The lib path. /// </summary> public static List<string> SysPath = new List<string>(); /// <summary> /// The default code. /// </summary> public static string DefaultCode = "import UnityEngine as unity\n\n"+ "class Untitled(): \n\n"+ "\tdef Start(self, this):\n"+ "\t\tpass\n\n"+ "\tdef Update(self, this):\n"+ "\t\tpass"; /// <summary> /// Reset this instance. /// </summary> public void Reset() { FilePath = string.Empty; Saved = false; HasChanges = true; FileCreated = false; FileName = "Untitled.py"; } //TODO: [ContextMenu("Cursor Block")] private void Menu() { Debug.Log("CursorBlock"); } //TODO: [ContextMenu("Vertical Bar")] private void Menu2() { Debug.Log("CursorBlock"); } }
using UnityEngine; using System.Collections.Generic; [System.Serializable] public class PythonBase : MonoBehaviour { /// <summary> /// The path of file /// </summary> public string FilePath; /// <summary> /// The name of the file. /// </summary> public string FileName = "Untitled.py"; /// <summary> /// The file created. /// </summary> public bool FileCreated, Saved, InMemory; /// <summary> /// Has changes in file /// </summary> public bool HasChanges = true; public enum Views { Code, Interpreter }; /// <summary> /// The current view. /// </summary> public Views CurrentView; /// <summary> /// The lib path. /// </summary> public static List<string> SysPath = new List<string>(); /// <summary> /// The default code. /// </summary> public static string DefaultCode = "import UnityEngine as unity\n\n"+ "class Untitled(): \n\n"+ "def Start(self, this):\n"+ "\tpass\n\n"+ "def Update(self, this):\n"+ "\tpass"; /// <summary> /// Reset this instance. /// </summary> public void Reset() { FilePath = string.Empty; Saved = false; HasChanges = true; FileCreated = false; FileName = "Untitled.py"; } //TODO: [ContextMenu("Cursor Block")] private void Menu() { Debug.Log("CursorBlock"); } //TODO: [ContextMenu("Vertical Bar")] private void Menu2() { Debug.Log("CursorBlock"); } }
mit
C#
7daddb44dfc279f89c055e56cddca7e46c7767c6
remove usings.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Shell/Commands/ToolCommands.cs
WalletWasabi.Gui/Shell/Commands/ToolCommands.cs
using AvalonStudio.Commands; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using ReactiveUI; using WalletWasabi.Gui.Tabs.WalletManager; namespace WalletWasabi.Gui.Shell.Commands { internal class ToolCommands { public ToolCommands() { WalletManagerCommand = new CommandDefinition( "Wallet Manager", null, ReactiveCommand.Create(OnWalletManager)); SettingsCommand = new CommandDefinition("Settings", null, ReactiveCommand.Create(() => { })); } private void OnWalletManager() { IoC.Get<IShell>().AddDocument(new WalletManagerViewModel()); } [ExportCommandDefinition("Tools.WalletManager")] public CommandDefinition WalletManagerCommand { get; } [ExportCommandDefinition("Tools.Settings")] public CommandDefinition SettingsCommand { get; } } }
using AvalonStudio.Commands; using AvalonStudio.Extensibility; using AvalonStudio.Shell; using ReactiveUI; using System; using System.Collections.Generic; using System.Text; using WalletWasabi.Gui.Tabs; namespace WalletWasabi.Gui.Shell.Commands { internal class ToolCommands { public ToolCommands() { WalletManagerCommand = new CommandDefinition( "Wallet Manager", null, ReactiveCommand.Create(OnWalletManager)); SettingsCommand = new CommandDefinition("Settings", null, ReactiveCommand.Create(() => { })); } private void OnWalletManager() { IoC.Get<IShell>().AddDocument(new WalletManagerViewModel()); } [ExportCommandDefinition("Tools.WalletManager")] public CommandDefinition WalletManagerCommand { get; } [ExportCommandDefinition("Tools.Settings")] public CommandDefinition SettingsCommand { get; } } }
mit
C#
2b77135b8f80a22f37b8a60c6f34d2482ffc90ec
bump version to 0.1.0
peters/assemblyinfo
src/assemblyinfo/Properties/AssemblyInfo.cs
src/assemblyinfo/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("assemblyinfo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("assemblyinfo")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")] [assembly: AssemblyInformationalVersion("0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("assemblyinfo")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("assemblyinfo")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d2587fde-ac26-43a1-bde3-920ae0fa540b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
14a797542cbfc522d95869ffe06490af9ee62bfb
Add spec to verify resource leak in temp container when ask operation times out.
eisendle/akka.net,eisendle/akka.net
src/core/Akka.Tests/Actor/AskTimeoutSpec.cs
src/core/Akka.Tests/Actor/AskTimeoutSpec.cs
//----------------------------------------------------------------------- // <copyright file="AskTimeoutSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.TestKit; using Xunit; namespace Akka.Tests.Actor { public class AskTimeoutSpec : AkkaSpec { public class SleepyActor : UntypedActor { protected override void OnReceive(object message) { Thread.Sleep(5000); Sender.Tell(message); } } public AskTimeoutSpec() : base(@"akka.actor.ask-timeout = 100ms") {} [Fact] public async Task Ask_should_honor_config_specified_timeout() { var actor = Sys.ActorOf<SleepyActor>(); try { await actor.Ask<string>("should time out"); Assert.True(false, "the ask should have timed out"); } catch (Exception e) { Assert.True(e is TaskCanceledException); } } [Fact] public async Task TimedOut_ask_should_remove_temp_actor() { var actor = Sys.ActorOf<SleepyActor>(); var actorCell = actor as ActorRefWithCell; var container = actorCell.Provider.TempContainer as VirtualPathContainer; try { await actor.Ask<string>("should time out"); } catch (Exception) { var childCounter = 0; container.ForEachChild(x => childCounter++); Assert.True(childCounter==0,"Number of children in temp container should be 0."); } } } }
//----------------------------------------------------------------------- // <copyright file="AskTimeoutSpec.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Akka.Actor; using Akka.TestKit; using Xunit; namespace Akka.Tests.Actor { public class AskTimeoutSpec : AkkaSpec { public class SleepyActor : UntypedActor { protected override void OnReceive(object message) { Thread.Sleep(5000); Sender.Tell(message); } } public AskTimeoutSpec() : base(@"akka.actor.ask-timeout = 100ms") {} [Fact] public async Task Ask_should_honor_config_specified_timeout() { var actor = Sys.ActorOf<SleepyActor>(); try { await actor.Ask<string>("should time out"); Assert.True(false, "the ask should have timed out"); } catch (Exception e) { Assert.True(e is TaskCanceledException); } } } }
apache-2.0
C#
1bf63b826b2114422cdfb729270bd7faf3cbe8d5
Remove unnecessary Time component of IDrawable
Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,RedNesto/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,RedNesto/osu-framework,ppy/osu-framework,naoey/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,default0/osu-framework,naoey/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,default0/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,paparony03/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework
osu.Framework/Graphics/IDrawable.cs
osu.Framework/Graphics/IDrawable.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.Containers; using osu.Framework.Lists; using osu.Framework.Timing; using OpenTK; namespace osu.Framework.Graphics { public interface IDrawable : IHasLifetime { Vector2 DrawSize { get; } DrawInfo DrawInfo { get; } IContainer Parent { get; set; } /// <summary> /// Whether this drawable is present for any sort of user-interaction. /// If this is false, then this drawable will not be drawn, it will not handle input, /// and it will not affect layouting (e.g. autosizing and flow). /// </summary> bool IsPresent { get; } IFrameBasedClock Clock { get; } /// <summary> /// Accepts a vector in local coordinates and converts it to coordinates in another Drawable's space. /// </summary> /// <param name="input">A vector in local coordinates.</param> /// <param name="other">The drawable in which space we want to transform the vector to.</param> /// <returns>The vector in other's coordinates.</returns> Vector2 ToSpaceOfOtherDrawable(Vector2 input, IDrawable other); /// <summary> /// Convert a position to the local coordinate system from either native or local to another drawable. /// This is *not* the same space as the Position member variable (use Parent.GetLocalPosition() in this case). /// </summary> /// <param name="screenSpacePos">The input position.</param> /// <returns>The output position.</returns> Vector2 ToLocalSpace(Vector2 screenSpacePos); BlendingMode BlendingMode { get; } } }
// 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.Containers; using osu.Framework.Lists; using osu.Framework.Timing; using OpenTK; namespace osu.Framework.Graphics { public interface IDrawable : IHasLifetime { Vector2 DrawSize { get; } DrawInfo DrawInfo { get; } IContainer Parent { get; set; } /// <summary> /// Whether this drawable is present for any sort of user-interaction. /// If this is false, then this drawable will not be drawn, it will not handle input, /// and it will not affect layouting (e.g. autosizing and flow). /// </summary> bool IsPresent { get; } FrameTimeInfo Time { get; } IFrameBasedClock Clock { get; } /// <summary> /// Accepts a vector in local coordinates and converts it to coordinates in another Drawable's space. /// </summary> /// <param name="input">A vector in local coordinates.</param> /// <param name="other">The drawable in which space we want to transform the vector to.</param> /// <returns>The vector in other's coordinates.</returns> Vector2 ToSpaceOfOtherDrawable(Vector2 input, IDrawable other); /// <summary> /// Convert a position to the local coordinate system from either native or local to another drawable. /// This is *not* the same space as the Position member variable (use Parent.GetLocalPosition() in this case). /// </summary> /// <param name="screenSpacePos">The input position.</param> /// <returns>The output position.</returns> Vector2 ToLocalSpace(Vector2 screenSpacePos); BlendingMode BlendingMode { get; } } }
mit
C#
c2af0a4afaa32347a093a97dfedb6b7ac97b54be
Add SourceMember to IMemberMap
BlaiseD/AutoMapper,lbargaoanu/AutoMapper,AutoMapper/AutoMapper,AutoMapper/AutoMapper
src/AutoMapper/IMemberMap.cs
src/AutoMapper/IMemberMap.cs
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace AutoMapper { public interface IMemberMap { TypeMap TypeMap { get; } Type SourceType { get; } IEnumerable<MemberInfo> SourceMembers { get; } LambdaExpression CustomSource { get; } Type DestinationType { get; } string DestinationName { get; } TypePair Types { get; } bool CanResolveValue { get; } bool Ignored { get; } bool Inline { get; set; } bool UseDestinationValue { get; } object NullSubstitute { get; } LambdaExpression PreCondition { get; } LambdaExpression Condition { get; } LambdaExpression CustomMapExpression { get; } LambdaExpression CustomMapFunction { get; } ValueResolverConfiguration ValueResolverConfig { get; } ValueConverterConfiguration ValueConverterConfig { get; } IEnumerable<ValueTransformerConfiguration> ValueTransformers { get; } MemberInfo SourceMember { get; } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Reflection; namespace AutoMapper { public interface IMemberMap { TypeMap TypeMap { get; } Type SourceType { get; } IEnumerable<MemberInfo> SourceMembers { get; } LambdaExpression CustomSource { get; } Type DestinationType { get; } string DestinationName { get; } TypePair Types { get; } bool CanResolveValue { get; } bool Ignored { get; } bool Inline { get; set; } bool UseDestinationValue { get; } object NullSubstitute { get; } LambdaExpression PreCondition { get; } LambdaExpression Condition { get; } LambdaExpression CustomMapExpression { get; } LambdaExpression CustomMapFunction { get; } ValueResolverConfiguration ValueResolverConfig { get; } ValueConverterConfiguration ValueConverterConfig { get; } IEnumerable<ValueTransformerConfiguration> ValueTransformers { get; } } }
mit
C#
bedb744a2e067a53d6aa5fdcbc1c6ede16245b9e
Add parentheses
ppy/osu,johnneijzen/osu,EVAST9919/osu,2yangk23/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,ZLima12/osu,smoogipoo/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Screens/Play/DimmableStoryboard.cs
osu.Game/Screens/Play/DimmableStoryboard.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.Game.Graphics.Containers; using osu.Game.Storyboards; using osu.Game.Storyboards.Drawables; namespace osu.Game.Screens.Play { /// <summary> /// A container that handles <see cref="Storyboard"/> loading, as well as applies user-specified visual settings to it. /// </summary> public class DimmableStoryboard : UserDimContainer { private readonly Storyboard storyboard; private DrawableStoryboard drawableStoryboard; public DimmableStoryboard(Storyboard storyboard) { this.storyboard = storyboard; } [BackgroundDependencyLoader] private void load() { initializeStoryboard(false); } protected override void LoadComplete() { ShowStoryboard.BindValueChanged(_ => initializeStoryboard(true), true); base.LoadComplete(); } protected override bool ShowDimContent => base.ShowDimContent || (ShowStoryboard.Value && UserDimLevel.Value < 1); private void initializeStoryboard(bool async) { if (drawableStoryboard != null) return; if (!ShowStoryboard.Value) return; drawableStoryboard = storyboard.CreateDrawable(); drawableStoryboard.Masking = true; if (async) LoadComponentAsync(drawableStoryboard, Add); else Add(drawableStoryboard); } } }
// 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.Game.Graphics.Containers; using osu.Game.Storyboards; using osu.Game.Storyboards.Drawables; namespace osu.Game.Screens.Play { /// <summary> /// A container that handles <see cref="Storyboard"/> loading, as well as applies user-specified visual settings to it. /// </summary> public class DimmableStoryboard : UserDimContainer { private readonly Storyboard storyboard; private DrawableStoryboard drawableStoryboard; public DimmableStoryboard(Storyboard storyboard) { this.storyboard = storyboard; } [BackgroundDependencyLoader] private void load() { initializeStoryboard(false); } protected override void LoadComplete() { ShowStoryboard.BindValueChanged(_ => initializeStoryboard(true), true); base.LoadComplete(); } protected override bool ShowDimContent => base.ShowDimContent || ShowStoryboard.Value && UserDimLevel.Value < 1; private void initializeStoryboard(bool async) { if (drawableStoryboard != null) return; if (!ShowStoryboard.Value) return; drawableStoryboard = storyboard.CreateDrawable(); drawableStoryboard.Masking = true; if (async) LoadComponentAsync(drawableStoryboard, Add); else Add(drawableStoryboard); } } }
mit
C#
83837d3e8f78dba58efe270d888bd8aa40c0f2ee
Fix tests in CI
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
Modix.Data.Test/TestDataContextFactory.cs
Modix.Data.Test/TestDataContextFactory.cs
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using NSubstitute; namespace Modix.Data.Test { public static class TestDataContextFactory { public static ModixContext BuildTestDataContext(Action<ModixContext> initializeAction = null) { var modixContext = Substitute.ForPartsOf<ModixContext>(new DbContextOptionsBuilder<ModixContext>() .UseInMemoryDatabase((++_databaseName).ToString()) .ConfigureWarnings(warnings => { warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning); }) .Options); if (!(initializeAction is null)) { initializeAction.Invoke(modixContext); modixContext.ResetSequenceToMaxValue( x => x.ClaimMappings, x => x.Id); modixContext.ResetSequenceToMaxValue( x => x.DesignatedChannelMappings, x => x.Id); modixContext.ResetSequenceToMaxValue( x => x.ConfigurationActions, x => x.Id); modixContext.SaveChanges(); modixContext.ClearReceivedCalls(); } return modixContext; } private static int _databaseName; } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; using NSubstitute; namespace Modix.Data.Test { public static class TestDataContextFactory { public static ModixContext BuildTestDataContext(Action<ModixContext> initializeAction = null) { var modixContext = Substitute.ForPartsOf<ModixContext>(new DbContextOptionsBuilder<ModixContext>() .UseInMemoryDatabase((++_databaseName).ToString()) .ConfigureWarnings(warnings => { warnings.Ignore(InMemoryEventId.TransactionIgnoredWarning); }) //.UseLoggerFactory(new LoggerFactory( // Enumerable.Empty<ILoggerProvider>() // .Append(new ConsoleLoggerProvider((error, logLevel) => true, true)))) //.EnableSensitiveDataLogging() .Options); if (!(initializeAction is null)) { initializeAction.Invoke(modixContext); modixContext.ResetSequenceToMaxValue( x => x.ClaimMappings, x => x.Id); modixContext.ResetSequenceToMaxValue( x => x.DesignatedChannelMappings, x => x.Id); modixContext.ResetSequenceToMaxValue( x => x.ConfigurationActions, x => x.Id); modixContext.SaveChanges(); modixContext.ClearReceivedCalls(); } return modixContext; } private static int _databaseName; } }
mit
C#
c24b3e5050d858b432e0b83fd76cdc49b435dd7c
Set tooltips on server meters
k-t/SharpHaven
MonoHaven.Client/UI/Remote/ServerMeter.cs
MonoHaven.Client/UI/Remote/ServerMeter.cs
using System.Collections.Generic; using System.Drawing; using MonoHaven.Game; using MonoHaven.UI.Widgets; namespace MonoHaven.UI.Remote { public class ServerMeter : ServerWidget { public static ServerWidget Create(ushort id, ServerWidget parent, object[] args) { var metrics = new List<Metric>(); var resName = (string)args[0]; for (int i = 1; i < args.Length; i += 2) metrics.Add(new Metric((Color)args[i], (int)args[i + 1])); var widget = new Meter(parent.Widget); widget.Background = App.Resources.GetImage(resName); widget.SetMetrics(metrics); return new ServerMeter(id, parent, widget); } private readonly Meter widget; public ServerMeter(ushort id, ServerWidget parent, Meter widget) : base(id, parent, widget) { this.widget = widget; } public override void ReceiveMessage(string message, object[] args) { if (message == "set") { var metrics = new List<Metric>(); for (int i = 0; i < args.Length; i += 2) metrics.Add(new Metric((Color)args[i], (int)args[i + 1])); widget.SetMetrics(metrics); } else if (message == "tt") { var text = (string)args[0]; widget.Tooltip = new Tooltip(text); } else base.ReceiveMessage(message, args); } } }
using System.Collections.Generic; using System.Drawing; using MonoHaven.Game; using MonoHaven.UI.Widgets; namespace MonoHaven.UI.Remote { public class ServerMeter : ServerWidget { public static ServerWidget Create(ushort id, ServerWidget parent, object[] args) { var metrics = new List<Metric>(); var resName = (string)args[0]; for (int i = 1; i < args.Length; i += 2) metrics.Add(new Metric((Color)args[i], (int)args[i + 1])); var widget = new Meter(parent.Widget); widget.Background = App.Resources.GetImage(resName); widget.SetMetrics(metrics); return new ServerMeter(id, parent, widget); } private readonly Meter widget; public ServerMeter(ushort id, ServerWidget parent, Meter widget) : base(id, parent, widget) { this.widget = widget; } public override void ReceiveMessage(string message, object[] args) { if (message == "set") { var metrics = new List<Metric>(); for (int i = 0; i < args.Length; i += 2) metrics.Add(new Metric((Color)args[i], (int)args[i + 1])); widget.SetMetrics(metrics); } else base.ReceiveMessage(message, args); } } }
mit
C#
15a7452756a2022e581bbada94221d6013f937e6
Fix editor class
bartlomiejwolk/OnCollisionActivate
Editor/GameObjectActivateEditor.cs
Editor/GameObjectActivateEditor.cs
using UnityEngine; using System.Collections; using UnityEditor; using Rotorz.ReorderableList; namespace OneDayGame { [CustomEditor(typeof(GameObjectActivate))] public class GameObjectActivateEditor : Editor { private SerializedProperty _objsToEnable; private void OnEnable() { _objsToEnable = serializedObject.FindProperty("_objsToEnable"); } public override void OnInspectorGUI() { serializedObject.Update(); ReorderableListGUI.Title("Objects to enable"); ReorderableListGUI.ListField(_objsToEnable); serializedObject.ApplyModifiedProperties(); } } }
using UnityEngine; using System.Collections; using UnityEditor; using Rotorz.ReorderableList; namespace OneDayGame { [CustomEditor(typeof(GameObjectActivate))] public class GameObjectActivateEditor : Editor { private SerializedProperty _collisionComponent; /*private SerializedProperty _tagOption; private SerializedProperty _tag;*/ private SerializedProperty _objsToEnable; private void OnEnable() { _collisionComponent = serializedObject.FindProperty("_collisionComponent"); /*_tagOption = serializedObject.FindProperty("_tagOption"); _tag = serializedObject.FindProperty("_tag");*/ _objsToEnable = serializedObject.FindProperty("_objsToEnable"); } public override void OnInspectorGUI() { base.OnInspectorGUI(); GameObjectActivate script = (GameObjectActivate)target; serializedObject.Update(); EditorGUILayout.PropertyField(_collisionComponent); /*script.ObjToEnable = (GameObject)EditorGUILayout.ObjectField( "Obj. to enable", script.ObjToEnable, typeof(GameObject), true); //script.ExcludeTag = EditorGUILayout.TextField("Exclude tag", script.ExcludeTag); EditorGUILayout.BeginHorizontal(); EditorGUIUtility.labelWidth = 70; EditorGUILayout.PropertyField(_tagOption); EditorGUIUtility.labelWidth = 40; EditorGUILayout.PropertyField(_tag); EditorGUILayout.EndHorizontal();*/ ReorderableListGUI.Title("Objects to enable"); ReorderableListGUI.ListField(_objsToEnable); // Save changes if (GUI.changed) { EditorUtility.SetDirty(script); } serializedObject.ApplyModifiedProperties(); } } }
mit
C#
c11a1daa9c44913dda08bb5e61f00901680658f4
Fix warning.
JohanLarsson/Gu.Reactive
Gu.Wpf.Reactive/Collections/NotifyCollectionChangedEventHandlerExt.cs
Gu.Wpf.Reactive/Collections/NotifyCollectionChangedEventHandlerExt.cs
namespace Gu.Wpf.Reactive { using System; using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using System.Windows.Threading; /// <summary> /// Extension methods for <see cref="NotifyCollectionChangedEventHandler"/>. /// </summary> public static class NotifyCollectionChangedEventHandlerExt { /// <summary> /// Invokes the change event on the dispatcher if needed. /// </summary> /// <param name="handler">The NotifyCollectionChangedEventHandler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/>.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static Task InvokeOnDispatcherAsync(this NotifyCollectionChangedEventHandler handler, object sender, NotifyCollectionChangedEventArgs e) { if (handler is null) { return Task.CompletedTask; } var invocationList = handler.GetInvocationList(); if (invocationList.Length == 0) { return Task.CompletedTask; } if (invocationList.Length == 1) { return NotifyAsync(sender, e, invocationList[0]); } return Task.WhenAll(invocationList.Select(x => NotifyAsync(sender, e, x))); } private static Task NotifyAsync(object sender, NotifyCollectionChangedEventArgs e, Delegate invocation) { var dispatcherObject = invocation.Target as DispatcherObject; if (dispatcherObject?.CheckAccess() == false) { #pragma warning disable VSTHRD001 // Avoid legacy thread switching APIs return dispatcherObject.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, invocation, sender, e) #pragma warning restore VSTHRD001 // Avoid legacy thread switching APIs .Task; } ((NotifyCollectionChangedEventHandler)invocation).Invoke(sender, e); return Task.CompletedTask; } } }
namespace Gu.Wpf.Reactive { using System; using System.Collections.Specialized; using System.Linq; using System.Threading.Tasks; using System.Windows.Threading; /// <summary> /// Extension methods for <see cref="NotifyCollectionChangedEventHandler"/>. /// </summary> public static class NotifyCollectionChangedEventHandlerExt { /// <summary> /// Invokes the change event on the dispatcher if needed. /// </summary> /// <param name="handler">The NotifyCollectionChangedEventHandler.</param> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="NotifyCollectionChangedEventArgs"/>.</param> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public static Task InvokeOnDispatcherAsync(this NotifyCollectionChangedEventHandler handler, object sender, NotifyCollectionChangedEventArgs e) { if (handler is null) { return Task.CompletedTask; } var invocationList = handler.GetInvocationList(); if (invocationList.Length == 0) { return Task.CompletedTask; } if (invocationList.Length == 1) { return NotifyAsync(sender, e, invocationList[0]); } return Task.WhenAll(invocationList.Select(x => NotifyAsync(sender, e, x))); } private static Task NotifyAsync(object sender, NotifyCollectionChangedEventArgs e, Delegate invocation) { var dispatcherObject = invocation.Target as DispatcherObject; if (dispatcherObject?.CheckAccess() == false) { return dispatcherObject.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, invocation, sender, e) .Task; } ((NotifyCollectionChangedEventHandler)invocation).Invoke(sender, e); return Task.CompletedTask; } } }
mit
C#
1ee679a209d2ae016746fc07ac6b790c5f880b8e
Update AssemblyInfo.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/RasterIO/AssemblyInfo.cs
src/RasterIO/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyDescription("Raster I/O for spatial modeling")]
using System.Reflection; [assembly: AssemblyDescription("Raster I/O for spatial modeling")] [assembly: AssemblyCopyright("Copyright 2010-2012 Green Code LLC")]
apache-2.0
C#
65715de428ab795719c564041fb0c99fa058decd
Fix tab expansion for package sources
mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.PowerShell.ConsoleHost.Core/MonoDevelop.PackageManagement.PowerShell.EnvDTE/ComponentModel.cs
src/MonoDevelop.PackageManagement.PowerShell.ConsoleHost.Core/MonoDevelop.PackageManagement.PowerShell.EnvDTE/ComponentModel.cs
// // ComponentModel.cs // // Author: // Matt Ward <matt.ward@microsoft.com> // // Copyright (c) 2019 Microsoft // // 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 Microsoft.VisualStudio.ComponentModelHost; using MonoDevelop.PackageManagement.PowerShell.ConsoleHost.Core; using NuGet.Protocol.Core.Types; using NuGetConsole; namespace MonoDevelop.PackageManagement.PowerShell.EnvDTE { public class ComponentModel : SComponentModel, IComponentModel { public T GetService<T> () where T : class { return GetService (typeof (T)) as T; } public object GetService (Type type) { if (type == typeof (IPowerConsoleWindow)) { return new PowerConsoleToolWindow (); } else if (type == typeof (ISourceRepositoryProvider)) { return ConsoleHostServices.SourceRepositoryProvider; } //if (type.FullName == typeof (IConsoleInitializer).FullName) { // return new ConsoleInitializer (GetConsoleHost ()); //} else if (type.FullName == typeof (IVsPackageInstallerServices).FullName) { // return new VsPackageInstallerServices (GetSolution ()); //} return null; } } }
// // ComponentModel.cs // // Author: // Matt Ward <matt.ward@microsoft.com> // // Copyright (c) 2019 Microsoft // // 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 Microsoft.VisualStudio.ComponentModelHost; using NuGetConsole; namespace MonoDevelop.PackageManagement.PowerShell.EnvDTE { public class ComponentModel : SComponentModel, IComponentModel { public T GetService<T> () where T : class { return GetService (typeof (T)) as T; } public object GetService (Type type) { if (type == typeof (IPowerConsoleWindow)) { return new PowerConsoleToolWindow (); } //if (type.FullName == typeof (IConsoleInitializer).FullName) { // return new ConsoleInitializer (GetConsoleHost ()); //} else if (type.FullName == typeof (IVsPackageInstallerServices).FullName) { // return new VsPackageInstallerServices (GetSolution ()); //} return null; } } }
mit
C#
fb91b7ebc8f7cb26415a939c5454858db30b0811
Hide the HtmlBodyPart wysiwyg editor toolbar when the editor doesn't have focus (#2591)
xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Wysiwyg.Edit.cshtml
src/OrchardCore.Modules/OrchardCore.Html/Views/HtmlBodyPart-Wysiwyg.Edit.cshtml
@model HtmlBodyPartViewModel @using OrchardCore.Html.ViewModels; @using OrchardCore.Html.Settings; @using OrchardCore.ContentManagement.Metadata.Models @{ var settings = Model.TypePartDefinition.Settings.ToObject<HtmlBodyPartSettings>(); } <script asp-name="trumbowyg" depends-on="admin" asp-src="/OrchardCore.Resources/Scripts/trumbowyg.min.js" debug-src="/OrchardCore.Resources/Scripts/trumbowyg.js" at="Foot"></script> <style asp-name="trumbowyg" asp-src="/OrchardCore.Resources/Styles/trumbowyg.min.css" debug-src="/OrchardCore.Resources/Styles/trumbowyg.css"></style> <fieldset class="form-group"> <label asp-for="Source">@Model.TypePartDefinition.DisplayName()</label> <textarea asp-for="Source" rows="5" class="form-control"></textarea> <span class="hint">@T["The body of the content item."]</span> </fieldset> <script at="Foot"> $(function () { var editor = $('#@Html.IdFor(m => m.Source)').trumbowyg(); editor.on('tbwchange', function () { $(document).trigger('contentpreview:render'); }); // hide toolbar when editor is not in focus (to avoid z-index clashes with dropdown components that may be on the page) (function toolbarToggler() { function getButtonPane(textarea) { return $(textarea).siblings('.trumbowyg-button-pane'); } editor.on('tbwfocus', function () { getButtonPane(this).fadeIn(); }); editor.on('tbwblur', function () { getButtonPane(this).fadeOut(); }); // hide initially editor.siblings('.trumbowyg-button-pane').css("display", "none"); }()); }); </script>
@model HtmlBodyPartViewModel @using OrchardCore.Html.ViewModels; @using OrchardCore.Html.Settings; @using OrchardCore.ContentManagement.Metadata.Models @{ var settings = Model.TypePartDefinition.Settings.ToObject<HtmlBodyPartSettings>(); } <script asp-name="trumbowyg" depends-on="admin" asp-src="/OrchardCore.Resources/Scripts/trumbowyg.min.js" debug-src="/OrchardCore.Resources/Scripts/trumbowyg.js" at="Foot"></script> <style asp-name="trumbowyg" asp-src="/OrchardCore.Resources/Styles/trumbowyg.min.css" debug-src="/OrchardCore.Resources/Styles/trumbowyg.css"></style> <fieldset class="form-group"> <label asp-for="Source">@Model.TypePartDefinition.DisplayName()</label> <textarea asp-for="Source" rows="5" class="form-control"></textarea> <span class="hint">@T["The body of the content item."]</span> </fieldset> <script at="Foot"> $(function () { $('#@Html.IdFor(m => m.Source)').trumbowyg().on('tbwchange', function () { $(document).trigger('contentpreview:render'); }); }); </script>
bsd-3-clause
C#
089d8bfc1b8cf8a7f1f3f790b8288cfabfb3c3b4
Remove `internal-reportinstallsuccess` from `dotnet complete`.
dasMulli/cli,livarcocc/cli-1,johnbeisner/cli,dasMulli/cli,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1,johnbeisner/cli,dasMulli/cli
src/dotnet/commands/dotnet-internal-reportinstallsuccess/InternalReportinstallsuccessCommandParser.cs
src/dotnet/commands/dotnet-internal-reportinstallsuccess/InternalReportinstallsuccessCommandParser.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.Linq; using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli { internal static class InternalReportinstallsuccessCommandParser { public static Command InternalReportinstallsuccess() => Create.Command( "internal-reportinstallsuccess", "", Accept.ExactlyOneArgument()); } }
// 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.Linq; using Microsoft.DotNet.Cli.CommandLine; namespace Microsoft.DotNet.Cli { internal static class InternalReportinstallsuccessCommandParser { public static Command InternalReportinstallsuccess() => Create.Command( "internal-reportinstallsuccess", "internal only", Accept.ExactlyOneArgument()); } }
mit
C#
dd1252fa54858aeddf2f14fc556b8638f1bcebf1
Add missing specs to RotationFactory
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Core/RotationFactory.cs
trunk/DefaultCombat/Core/RotationFactory.cs
// Copyright (C) 2011-2015 Bossland GmbH // See the file LICENSE for the source code's detailed license using System; using System.Reflection; using Buddy.Swtor; using DefaultCombat.Routines; namespace DefaultCombat.Core { public class RotationFactory { public RotationBase Build(string name) { //Set the basic class as the rotation if char has no advanced class if (BuddyTor.Me.AdvancedClass == AdvancedClass.None) { name = BuddyTor.Me.CharacterClass.ToString(); } if (name == "Rage" && BuddyTor.Me.AdvancedClass == AdvancedClass.Marauder) { name = "Fury"; } if (name == "Focus" && BuddyTor.Me.AdvancedClass == AdvancedClass.Sentinel) { name = "Concentration"; } if (name == "DirtyFighting" && BuddyTor.Me.AdvancedClass == AdvancedClass.Scoundrel) { name = "Ruffian"; } if (name == "Balance" && BuddyTor.Me.AdvancedClass == AdvancedClass.Shadow) { name = "Serenity"; } if (name == "Rage" && BuddyTor.Me.AdvancedClass == AdvancedClass.Marauder) { name = "Fury"; } if (name == "Focus" && BuddyTor.Me.AdvancedClass == AdvancedClass.Sentinel) { name = "Concentration"; } if (name == "DirtyFighting" && BuddyTor.Me.AdvancedClass == AdvancedClass.Scoundrel) { name = "Ruffian"; } if (name == "Balance" && BuddyTor.Me.AdvancedClass == AdvancedClass.Shadow) { name = "Serenity"; } if (name == "CombatMedic" && BuddyTor.Me.AdvancedClass == AdvancedClass.Mercenary) { name = "Bodyguard"; } if (name == "Firebug" && BuddyTor.Me.AdvancedClass == AdvancedClass.Powertech) { name = "Pyrotech"; } var ns = "DefaultCombat.Routines"; var assembly = Assembly.GetExecutingAssembly(); var type = assembly.GetType(ns + "." + name); var instance = Activator.CreateInstance(type); return (RotationBase) instance; } } }
// Copyright (C) 2011-2015 Bossland GmbH // See the file LICENSE for the source code's detailed license using System; using System.Reflection; using Buddy.Swtor; using DefaultCombat.Routines; namespace DefaultCombat.Core { public class RotationFactory { public RotationBase Build(string name) { //Set the basic class as the rotation if char has no advanced class if (BuddyTor.Me.AdvancedClass == AdvancedClass.None) { name = BuddyTor.Me.CharacterClass.ToString(); } if (name == "Rage" && BuddyTor.Me.AdvancedClass == AdvancedClass.Marauder) { name = "Fury"; } if (name == "Focus" && BuddyTor.Me.AdvancedClass == AdvancedClass.Sentinel) { name = "Concentration"; } if (name == "DirtyFighting" && BuddyTor.Me.AdvancedClass == AdvancedClass.Scoundrel) { name = "Ruffian"; } if (name == "Balance" && BuddyTor.Me.AdvancedClass == AdvancedClass.Shadow) { name = "Serenity"; } var ns = "DefaultCombat.Routines"; var assembly = Assembly.GetExecutingAssembly(); var type = assembly.GetType(ns + "." + name); var instance = Activator.CreateInstance(type); return (RotationBase) instance; } } }
apache-2.0
C#
eb545c5df1cc41500302e53ea8020aa6bb90cc99
Check if collection is empty before trying to manipulate first element.
rianjs/ical.net
v2/ical.NET.Collections/GroupedValueList.cs
v2/ical.NET.Collections/GroupedValueList.cs
using System; using System.Collections.Generic; using System.Linq; using Ical.Net.Collections.Interfaces; using Ical.Net.Collections.Proxies; namespace Ical.Net.Collections { public class GroupedValueList<TGroup, TInterface, TItem, TValueType> : GroupedList<TGroup, TInterface> where TInterface : class, IGroupedObject<TGroup>, IValueObject<TValueType> where TItem : new() { public virtual void Set(TGroup group, TValueType value) { Set(group, new[] { value }); } public virtual void Set(TGroup group, IEnumerable<TValueType> values) { if (ContainsKey(group)) { // Add a value to the first matching item in the list var item = AllOf(group).FirstOrDefault(); if (item != null) { item.SetValue(values); return; } } // No matching item was found, add a new item to the list var obj = Activator.CreateInstance(typeof(TItem)) as TInterface; obj.Group = group; Add(obj); obj.SetValue(values); } public virtual TType Get<TType>(TGroup group) { var firstItem = AllOf(group).FirstOrDefault(); if (firstItem?.Values != null) { return firstItem .Values .OfType<TType>() .FirstOrDefault(); } return default(TType); } public virtual IList<TType> GetMany<TType>(TGroup group) { return new GroupedValueListProxy<TGroup, TInterface, TItem, TValueType, TType>(this, group); } } }
using System; using System.Collections.Generic; using System.Linq; using Ical.Net.Collections.Interfaces; using Ical.Net.Collections.Proxies; namespace Ical.Net.Collections { public class GroupedValueList<TGroup, TInterface, TItem, TValueType> : GroupedList<TGroup, TInterface> where TInterface : class, IGroupedObject<TGroup>, IValueObject<TValueType> where TItem : new() { public virtual void Set(TGroup group, TValueType value) { Set(group, new[] { value }); } public virtual void Set(TGroup group, IEnumerable<TValueType> values) { if (ContainsKey(group)) { var items = AllOf(group); if (items != null) { // Add a value to the first matching item in the list items.First().SetValue(values); return; } } // No matching item was found, add a new item to the list var obj = Activator.CreateInstance(typeof(TItem)) as TInterface; obj.Group = group; Add(obj); obj.SetValue(values); } public virtual TType Get<TType>(TGroup group) { var firstItem = AllOf(group).FirstOrDefault(); if (firstItem?.Values != null) { return firstItem .Values .OfType<TType>() .FirstOrDefault(); } return default(TType); } public virtual IList<TType> GetMany<TType>(TGroup group) { return new GroupedValueListProxy<TGroup, TInterface, TItem, TValueType, TType>(this, group); } } }
mit
C#
c1f7c9b1ab7276db6235f359947b2052ea50df0a
Update Bank.cs
owolp/Telerik-Academy,owolp/Telerik-Academy,owolp/Telerik-Academy,owolp/Telerik-Academy
Modul-1/OOP/Homework/05-OOP-Principles-Part-2/TaskBankAccounts/Models/Bank/Bank.cs
Modul-1/OOP/Homework/05-OOP-Principles-Part-2/TaskBankAccounts/Models/Bank/Bank.cs
namespace TaskBankAccounts.Models.Bank { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using AbstractModels; public class Bank : IEnumerable<Account> { private List<Account> accounts; public Bank() { this.accounts = new List<Account>(); } public void AddAccount(Account account) { this.accounts.Add(account); } public IEnumerator<Account> GetEnumerator() { // return this.accounts.GetEnumerator(); for (int i = 0; i < this.accounts.Count; i++) { yield return this.accounts[i]; } } public void RemoveAccount(Account customer) { this.accounts.Remove(customer); } public override string ToString() { this.accounts = this.accounts.OrderBy(a => a.Balance).ToList(); StringBuilder sb = new StringBuilder(); foreach (var account in this.accounts) { sb.AppendLine(account.ToString()); } return sb.ToString(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
namespace TaskBankAccounts.Models.Bank { using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using AbstractModels; public class Bank : IEnumerable<Account> { private List<Account> accounts; public Bank() { this.accounts = new List<Account>(); } public void AddAccount(Account account) { this.accounts.Add(account); } public IEnumerator<Account> GetEnumerator() { return this.accounts.GetEnumerator(); } public void RemoveAccount(Account customer) { this.accounts.Remove(customer); } public override string ToString() { this.accounts = this.accounts.OrderBy(a => a.Balance).ToList(); StringBuilder sb = new StringBuilder(); foreach (var account in this.accounts) { sb.AppendLine(account.ToString()); } return sb.ToString(); } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
mit
C#
f4d6d9ac3ad8ac7eba2a0dafb8a33f54c38167b9
Replace order of default settings
OrleansContrib/Orleans.Providers.MongoDB
Orleans.Providers.MongoDB/StorageProviders/Serializers/JsonGrainStateSerializer.cs
Orleans.Providers.MongoDB/StorageProviders/Serializers/JsonGrainStateSerializer.cs
using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
using Microsoft.Extensions.Options; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Orleans.Providers.MongoDB.Configuration; using Orleans.Runtime; using Orleans.Serialization; namespace Orleans.Providers.MongoDB.StorageProviders.Serializers { public class JsonGrainStateSerializer : IGrainStateSerializer { private readonly JsonSerializer serializer; public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options) { var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory); options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); this.serializer = JsonSerializer.Create(jsonSettings); //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44 //// Always include the default value, so that the deserialization process can overwrite default //// values that are not equal to the system defaults. this.serializer.NullValueHandling = NullValueHandling.Include; this.serializer.DefaultValueHandling = DefaultValueHandling.Populate; } public void Deserialize(IGrainState grainState, JObject entityData) { var jsonReader = new JTokenReader(entityData); serializer.Populate(jsonReader, grainState.State); } public JObject Serialize(IGrainState grainState) { return JObject.FromObject(grainState.State, serializer); } } }
mit
C#
a0ab21f7dedaf32d543593b150ee202085a67ef8
Update assembly
andreabbondanza/DewDuck
DewDuck/Properties/AssemblyInfo.cs
DewDuck/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DewDuck")] [assembly: AssemblyDescription("A library to help with ducktyping")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dew Studio")] [assembly: AssemblyProduct("DewDuck")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DewDuck")] [assembly: AssemblyDescription("A library to help with ducktyping")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dew Studio")] [assembly: AssemblyProduct("DewDuck")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
mit
C#
11ea56b77633abdc3ce4f94fc44b18fdab29a879
Add scenario test to check the minimum string length constraint is ignored
Pvlerick/AutoFixture,sean-gilliam/AutoFixture,sergeyshushlyapin/AutoFixture,adamchester/AutoFixture,zvirja/AutoFixture,AutoFixture/AutoFixture,adamchester/AutoFixture,sergeyshushlyapin/AutoFixture
Src/AutoFixtureUnitTest/DataAnnotations/StringLengthArgumentSupportTests.cs
Src/AutoFixtureUnitTest/DataAnnotations/StringLengthArgumentSupportTests.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } [Fact] public void FixtureCorrectlyCreatesLongText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.Equal( ClassWithLengthConstrainedConstructorArgument.LongTextLength, actual.LongText.Length); // Teardown } private class ClassWithLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public const int LongTextLength = 50; public readonly string ShortText; public readonly string LongText; public ClassWithLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText, [StringLength(LongTextLength, MinimumLength = LongTextLength)]string longText) { this.ShortText = shortText; this.LongText = longText; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using Ploeh.AutoFixture; using Xunit; namespace Ploeh.AutoFixtureUnitTest.DataAnnotations { public class StringLengthArgumentSupportTests { [Fact] public void FixtureCorrectlyCreatesShortText() { // Fixture setup var fixture = new Fixture(); // Exercise system var actual = fixture.Create<ClassWithLengthConstrainedConstructorArgument>(); // Verify outcome Assert.True( actual.ShortText.Length <= ClassWithLengthConstrainedConstructorArgument.ShortTextMaximumLength, "AutoFixture should respect [StringLength] attribute on constructor arguments."); // Teardown } private class ClassWithLengthConstrainedConstructorArgument { public const int ShortTextMaximumLength = 3; public readonly string ShortText; public ClassWithLengthConstrainedConstructorArgument( [StringLength(ShortTextMaximumLength)]string shortText) { this.ShortText = shortText; } } } }
mit
C#
261038adb8b1b9e8f435b2e4c5bb169e1b6d2903
Update Material.cs
QetriX/quly
Assets/Scripts/libs/Material.cs
Assets/Scripts/libs/Material.cs
namespace com.qetrix.apps.quly.libs { using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Material { string _name; Color _color; float _weight = 0.01f; // How (+/-) and how much one unit of Material is weighing float _defense = 0.0f; // How (+/-) and how much the Material changes Qule's defense float _power = 0.0f; // How (+/-) and how much the Material changes Qule's energy power float _energy = 0.0f; // How (+/-) and how much the Material changes Qule's total energy float _regen = 0.0f; // How (+/-) and how much the Material changes Qule's energy regeneration public static Dictionary<string, int> load(string name) { Dictionary<string, int> mat = new Dictionary<string, int>(); mat.Add(name, 100); return mat; } public float weight() { return _weight; } } }
namespace Quly { using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Material { string _name; Color _color; float _weight = 0.01f; // How (+/-) and how much one unit of Material is weighing float _defense = 0.0f; // How (+/-) and how much the Material changes Qule's defense float _power = 0.0f; // How (+/-) and how much the Material changes Qule's energy power float _energy = 0.0f; // How (+/-) and how much the Material changes Qule's total energy float _regen = 0.0f; // How (+/-) and how much the Material changes Qule's energy regeneration public static Dictionary<string, int> load(string name) { Dictionary<string, int> mat = new Dictionary<string, int>(); mat.Add(name, 100); return mat; } public float weight() { return _weight; } } }
mit
C#
579879a2da24b4e46afcfa9052e1eeaa5e40bcf0
Update Sample Startup.
davidorbelian/MicroNetCore.Rest
samples/MicroNetCore.Rest.Sample/Startup.cs
samples/MicroNetCore.Rest.Sample/Startup.cs
using MicroNetCore.Collections; using MicroNetCore.Data.Abstractions; using MicroNetCore.Models; using MicroNetCore.Rest.Extensions; using MicroNetCore.Rest.MediaTypes.Hypermedia.Extensions; using MicroNetCore.Rest.MediaTypes.Json.Extensions; using MicroNetCore.Rest.Sample.Data; using MicroNetCore.Rest.Sample.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Sample { public sealed class Startup { private static readonly TypeBundle<IModel> RestTypes = new TypeBundle<IModel>(new[] {typeof(User), typeof(Role)}); public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRest(RestTypes).AddJson().AddHypermedia(); services.AddTransient<IRepositoryFactory, FakeRepositoryFactory>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
using System; using System.Collections.Generic; using MicroNetCore.Data.Abstractions; using MicroNetCore.Rest.Extensions; using MicroNetCore.Rest.MediaTypes.Hypermedia.Extensions; using MicroNetCore.Rest.MediaTypes.Json.Extensions; using MicroNetCore.Rest.Sample.Data; using MicroNetCore.Rest.Sample.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MicroNetCore.Rest.Sample { public sealed class Startup { private static readonly IEnumerable<Type> RestTypes = new[] {typeof(User), typeof(Role)}; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRest(RestTypes).AddJson().AddHypermedia(); services.AddTransient<IRepositoryFactory, FakeRepositoryFactory>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); app.UseMvc(); } } }
mit
C#
609416940c7599001dc79995e04fc3bda627c967
Fix display glitches.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Views/Shared/_OpenIdLoginBox.cshtml
src/CGO.Web/Views/Shared/_OpenIdLoginBox.cshtml
@using (Html.BeginForm("Authenticate", "User", routeValues: new { ReturnUrl = Request.QueryString["ReturnUrl"] }, method: FormMethod.Post, htmlAttributes: new { id = "openid_form" })) { <div id="openIdLogin" class="modal hide fade" style="width: 600px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3>Log In with OpenID</h3> </div> <div class="modal-body"> <input type="hidden" name="action" value="verify" /> <div id="openid_choice"> <p>Please choose the account you would like to log in with:</p> <div id="openid_btns"></div> </div> <div id="openid_input_area"> <input id="openid_identifier" name="openid_identifier" type="text" value="http://" /> </div> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Cancel</a> </div> </div> } @Styles.Render("~/bundles/openid-css") @Scripts.Render("~/bundles/openid") <script> (function () { openid.init('openid_identifier'); $('#openid_submit').addClass("btn btn-primary"); $('#openid_submit').css('margin-top', '-8px'); $('#openid_submit').css('margin-left', '5px'); $('#openid_submit').val('Log In'); })(); </script>
@using (Html.BeginForm("Authenticate", "User", routeValues: new { ReturnUrl = Request.QueryString["ReturnUrl"] }, method: FormMethod.Post, htmlAttributes: new { id = "openid_form" })) { <div id="openIdLogin" class="modal hide fade"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h3>Log In with OpenID</h3> </div> <div class="modal-body"> <input type="hidden" name="action" value="verify" /> <div id="openid_choice"> <p>Please choose the account you would like to log in with:</p> <div id="openid_btns"></div> </div> <div id="openid_input_area"> <input id="openid_identifier" name="openid_identifier" type="text" value="http://" /> </div> </div> <div class="modal-footer"> <input type="submit" id="openid_submit" class="btn btn-primary" value="Log In" /> <a href="#" class="btn" data-dismiss="modal">Cancel</a> </div> </div> } @Styles.Render("~/bundles/openid-css") @Scripts.Render("~/bundles/openid") <script> (function () { openid.init('openid_identifier'); })() </script>
mit
C#
637ed37daef68b21413fde795b4ebf14fb516494
Add INative<> to QueryPool
rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary
CSGL.Vulkan/Vulkan/QueryPool.cs
CSGL.Vulkan/Vulkan/QueryPool.cs
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class QueryPoolCreateInfo { public VkQueryType queryType; public uint queryCount; public VkQueryPipelineStatisticFlags pipelineStatistics; } public class QueryPool : IDisposable, INative<VkQueryPool> { bool disposed; VkQueryPool queryPool; public VkQueryPool Native { get { return queryPool; } } public Device Device { get; private set; } public QueryPool(Device device, QueryPoolCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; CreateQueryPool(info); } void CreateQueryPool(QueryPoolCreateInfo mInfo) { VkQueryPoolCreateInfo info = new VkQueryPoolCreateInfo(); info.sType = VkStructureType.QueryPoolCreateInfo; info.queryType = mInfo.queryType; info.queryCount = mInfo.queryCount; info.pipelineStatistics = mInfo.pipelineStatistics; Device.Commands.createQueryPool(Device.Native, ref info, Device.Instance.AllocationCallbacks, out queryPool); } public VkResult GetResults(uint firstQuery, uint queryCount, byte[] data, ulong stride, VkQueryResultFlags flags) { unsafe { fixed (byte* ptr = data) { return Device.Commands.getQueryPoolResults(Device.Native, queryPool, firstQuery, queryCount, (ulong)data.Length, (IntPtr)ptr, stride, flags ); } } } public void Dispose() { Dispose(true); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyQueryPool(Device.Native, queryPool, Device.Instance.AllocationCallbacks); disposed = true; } ~QueryPool() { Dispose(false); } } }
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public class QueryPoolCreateInfo { public VkQueryType queryType; public uint queryCount; public VkQueryPipelineStatisticFlags pipelineStatistics; } public class QueryPool : IDisposable { bool disposed; VkQueryPool queryPool; public VkQueryPool Native { get { return queryPool; } } public Device Device { get; private set; } public QueryPool(Device device, QueryPoolCreateInfo info) { if (device == null) throw new ArgumentNullException(nameof(device)); Device = device; CreateQueryPool(info); } void CreateQueryPool(QueryPoolCreateInfo mInfo) { VkQueryPoolCreateInfo info = new VkQueryPoolCreateInfo(); info.sType = VkStructureType.QueryPoolCreateInfo; info.queryType = mInfo.queryType; info.queryCount = mInfo.queryCount; info.pipelineStatistics = mInfo.pipelineStatistics; Device.Commands.createQueryPool(Device.Native, ref info, Device.Instance.AllocationCallbacks, out queryPool); } public VkResult GetResults(uint firstQuery, uint queryCount, byte[] data, ulong stride, VkQueryResultFlags flags) { unsafe { fixed (byte* ptr = data) { return Device.Commands.getQueryPoolResults(Device.Native, queryPool, firstQuery, queryCount, (ulong)data.Length, (IntPtr)ptr, stride, flags ); } } } public void Dispose() { Dispose(true); } void Dispose(bool disposing) { if (disposed) return; Device.Commands.destroyQueryPool(Device.Native, queryPool, Device.Instance.AllocationCallbacks); disposed = true; } ~QueryPool() { Dispose(false); } } }
mit
C#
3772a223cb96ebb089e8c084e4efaf1f2928c85e
Update Cake.Git to 0.19.0 version
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
Cake.Recipe/Content/addins.cake
Cake.Recipe/Content/addins.cake
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.4.0 #addin nuget:?package=Cake.Coveralls&version=0.9.0 #addin nuget:?package=Cake.Figlet&version=1.1.0 #addin nuget:?package=Cake.Git&version=0.19.0 #addin nuget:?package=Cake.Gitter&version=0.9.0 #addin nuget:?package=Cake.Graph&version=0.6.0 #addin nuget:?package=Cake.Incubator&version=2.0.2 #addin nuget:?package=Cake.Kudu&version=0.8.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.7.0 #addin nuget:?package=Cake.ReSharperReports&version=0.10.0 #addin nuget:?package=Cake.Slack&version=0.12.0 #addin nuget:?package=Cake.Transifex&version=0.7.0 #addin nuget:?package=Cake.Twitter&version=0.8.0 #addin nuget:?package=Cake.Wyam&version=1.4.1 #addin nuget:?package=Cake.Issues&version=0.4.0 #addin nuget:?package=Cake.Issues.MsBuild&version=0.4.0 #addin nuget:?package=Cake.Issues.InspectCode&version=0.4.0 #addin nuget:?package=Cake.Issues.Reporting&version=0.4.0 #addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.4.0 // Needed for Cake.Graph #addin nuget:?package=RazorEngine&version=3.10.0&loaddependencies=true Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.4.0 #addin nuget:?package=Cake.Coveralls&version=0.9.0 #addin nuget:?package=Cake.Figlet&version=1.1.0 #addin nuget:?package=Cake.Git&version=0.18.0 #addin nuget:?package=Cake.Gitter&version=0.9.0 #addin nuget:?package=Cake.Graph&version=0.6.0 #addin nuget:?package=Cake.Incubator&version=2.0.2 #addin nuget:?package=Cake.Kudu&version=0.8.0 #addin nuget:?package=Cake.MicrosoftTeams&version=0.7.0 #addin nuget:?package=Cake.ReSharperReports&version=0.10.0 #addin nuget:?package=Cake.Slack&version=0.12.0 #addin nuget:?package=Cake.Transifex&version=0.7.0 #addin nuget:?package=Cake.Twitter&version=0.8.0 #addin nuget:?package=Cake.Wyam&version=1.4.1 #addin nuget:?package=Cake.Issues&version=0.4.0 #addin nuget:?package=Cake.Issues.MsBuild&version=0.4.0 #addin nuget:?package=Cake.Issues.InspectCode&version=0.4.0 #addin nuget:?package=Cake.Issues.Reporting&version=0.4.0 #addin nuget:?package=Cake.Issues.Reporting.Generic&version=0.4.0 // Needed for Cake.Graph #addin nuget:?package=RazorEngine&version=3.10.0&loaddependencies=true Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if(BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if(BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
mit
C#
4bd56559b1d813db3dacd2b64c1fed55c3939fd3
Remove unused CannotChangeSignatureReason values
davkean/roslyn,physhi/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,tmat/roslyn,wvdd007/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,gafter/roslyn,diryboy/roslyn,aelij/roslyn,heejaechang/roslyn,gafter/roslyn,AlekseyTs/roslyn,genlu/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,jmarolf/roslyn,mavasani/roslyn,gafter/roslyn,AmadeusW/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,tmat/roslyn,dotnet/roslyn,reaction1989/roslyn,aelij/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,AlekseyTs/roslyn,aelij/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,dotnet/roslyn,stephentoub/roslyn,brettfo/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,physhi/roslyn,panopticoncentral/roslyn,davkean/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,genlu/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,wvdd007/roslyn,genlu/roslyn,davkean/roslyn,sharwell/roslyn,reaction1989/roslyn,dotnet/roslyn,stephentoub/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,bartdesmet/roslyn,reaction1989/roslyn,mavasani/roslyn,tannergooding/roslyn,tmat/roslyn,brettfo/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,physhi/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,weltkante/roslyn,weltkante/roslyn,diryboy/roslyn
src/Features/Core/Portable/ChangeSignature/CannotChangeSignatureReason.cs
src/Features/Core/Portable/ChangeSignature/CannotChangeSignatureReason.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.ChangeSignature { internal enum CannotChangeSignatureReason { None, DefinedInMetadata, IncorrectKind, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.ChangeSignature { internal enum CannotChangeSignatureReason { None, DefinedInMetadata, IncorrectKind, DeclarationLanguageServiceNotFound, DeclarationMethodPositionNotFound, } }
mit
C#
77977f47fa6d2caec3a89c2e8ab07d80b44b53d6
Break build again for TeamCity email notify test.
alexmullans/Siftables-Emulator
Siftables/MainWindow.xaml.cs
Siftables/MainWindow.xaml.cs
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoAllOfTheThings(); } } }
namespace Siftables { public partial class MainWindowView { public MainWindowView() { InitializeComponent(); DoSomething(); } } }
bsd-2-clause
C#
41e6cfb9b0c8ec640cbebc5557814b9a684e1758
Build package
rasmusjp/umbraco-ditto,AzarinSergey/umbraco-ditto,robertjf/umbraco-ditto,leekelleher/umbraco-ditto,Hendy/umbraco-ditto
src/Our.Umbraco.Ditto/Properties/VersionInfo.cs
src/Our.Umbraco.Ditto/Properties/VersionInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.5.*")] [assembly: AssemblyInformationalVersion("0.5.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18449 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.4.*")] [assembly: AssemblyInformationalVersion("0.4.1")]
mit
C#
e21ed49c5a3bf7c6eb81a152dde6d710427ac112
Remove cruft.
jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy
src/Manos/Manos/UnsafeString.cs
src/Manos/Manos/UnsafeString.cs
using System; using System.Text; namespace Manos { public class UnsafeString { private string unsafe_value; private string safe_value; private bool has_unsafe_data; public UnsafeString (string str) { this.unsafe_value = str; } public string UnsafeValue { get { return unsafe_value; } } public string SafeValue { get { if (safe_value == null) safe_value = Escape (unsafe_value, out has_unsafe_data); return safe_value; } } public bool HasUnsafefData { get { if (safe_value == null) safe_value = Escape (unsafe_value, out has_unsafe_data); return has_unsafe_data; } } public override string ToString () { return SafeValue; } public static implicit operator string (UnsafeString input) { if (input == null) return null; return input.ToString (); } public static string Escape (string input) { bool dummy; return Escape (input, out dummy); } public static string Escape (string input, out bool has_unsafe_data) { StringBuilder builder = new StringBuilder (); has_unsafe_data = false; for (int i = 0; i < input.Length; i++) { char c = input [i]; switch (c) { case '&': builder.Append ("&amp;"); has_unsafe_data = true; break; case '<': builder.Append ("&lt;"); has_unsafe_data = true; break; case '>': builder.Append ("&gt;"); has_unsafe_data = true; break; case '"': builder.Append ("&quot;"); has_unsafe_data = true; break; case '\'': builder.Append ("&#39;"); has_unsafe_data = true; break; default: builder.Append (c); break; } } if (has_unsafe_data) return builder.ToString (); return input; } } }
using System; using System.Text; namespace Manos { public class UnsafeString { private string unsafe_value; private string safe_value; private bool has_unsafe_data; public UnsafeString (string str) { this.unsafe_value = str; } public string UnsafeValue { get { return unsafe_value; } } public string SafeValue { get { if (safe_value == null) safe_value = Escape (unsafe_value, out has_unsafe_data); return safe_value; } } public bool HasUnsafefData { get { if (safe_value == null) safe_value = Escape (unsafe_value, out has_unsafe_data); return has_unsafe_data; } } public override string ToString () { return SafeValue; } public static implicit operator string (UnsafeString input) { if (input == null) return null; return input.ToString (); } /* public static explicit operator string (UnsafeString input) { return input.ToString (); } */ public static string Escape (string input) { bool dummy; return Escape (input, out dummy); } public static string Escape (string input, out bool has_unsafe_data) { StringBuilder builder = new StringBuilder (); has_unsafe_data = false; for (int i = 0; i < input.Length; i++) { char c = input [i]; switch (c) { case '&': builder.Append ("&amp;"); has_unsafe_data = true; break; case '<': builder.Append ("&lt;"); has_unsafe_data = true; break; case '>': builder.Append ("&gt;"); has_unsafe_data = true; break; case '"': builder.Append ("&quot;"); has_unsafe_data = true; break; case '\'': builder.Append ("&#39;"); has_unsafe_data = true; break; default: builder.Append (c); break; } } if (has_unsafe_data) return builder.ToString (); return input; } } }
mit
C#
ad51062145a3526daade66fe965527a779984c12
handle post
tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web
src/Tugberk.Web/Controllers/PortalController.cs
src/Tugberk.Web/Controllers/PortalController.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Tugberk.Web.Models; namespace Tugberk.Web.Controllers { [Route("portal")] public class PortalController : Controller { private readonly IImageStorage _imageStorage; public PortalController(IImageStorage imageStorage) { _imageStorage = imageStorage ?? throw new System.ArgumentNullException(nameof(imageStorage)); } public IActionResult Index() => View(); [HttpGet("posts/create")] public IActionResult CreatePost() => View(); [ValidateAntiForgeryToken] [HttpPost("posts/create")] public IActionResult CreatePost(NewPostRequestModel requestModel) { if(ModelState.IsValid) { // TODO: try to save blog post here } return View(requestModel); } [HttpGet("posts/{postId}")] public IActionResult EditPost(string postId) => View(); [ValidateAntiForgeryToken] [HttpPost("images/upload")] public async Task<IActionResult> UploadImage() { if(Request.Form.Files.Count < 1) { return BadRequest("Request contains no file to upload"); } if(Request.Form.Files.Count > 1) { return BadRequest("More than one file to upload at the same time is not supported"); } var firstFile = Request.Form.Files.First(); using(var stream = firstFile.OpenReadStream()) { var result = await _imageStorage.SaveImage(stream, firstFile.FileName); return Json(new { ImageUrl = result.Url }); } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace Tugberk.Web.Controllers { [Route("portal")] public class PortalController : Controller { private readonly IImageStorage _imageStorage; public PortalController(IImageStorage imageStorage) { _imageStorage = imageStorage ?? throw new System.ArgumentNullException(nameof(imageStorage)); } public IActionResult Index() => View(); [HttpGet("posts/create")] public IActionResult CreatePost() => View(); [HttpGet("posts/{postId}")] public IActionResult EditPost(string postId) => View(); [ValidateAntiForgeryToken] [HttpPost("images/upload")] public async Task<IActionResult> UploadImage() { if(Request.Form.Files.Count < 1) { return BadRequest("Request contains no file to upload"); } if(Request.Form.Files.Count > 1) { return BadRequest("More than one file to upload at the same time is not supported"); } var firstFile = Request.Form.Files.First(); using(var stream = firstFile.OpenReadStream()) { var result = await _imageStorage.SaveImage(stream, firstFile.FileName); return Json(new { ImageUrl = result.Url }); } } } }
agpl-3.0
C#
17f19d563bae46c6d78a9380301e6d2b455ba566
Fix bugs in the crash unprepared device
MyvarHD/Cosmos,jp2masa/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,trivalik/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,MyvarHD/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,fanoI/Cosmos,fanoI/Cosmos,zarlo/Cosmos,Cyber4/Cosmos,trivalik/Cosmos,fanoI/Cosmos,Cyber4/Cosmos,trivalik/Cosmos,Cyber4/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,zarlo/Cosmos,MyvarHD/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos
source/Cosmos.Deploy.USB/MainWindow.xaml.cs
source/Cosmos.Deploy.USB/MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.IO; namespace Cosmos.Deploy.USB { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { Title = App.Title; if (!File.Exists(App.ObjFile)) { MessageBox.Show("Specified .obj file does not exist.", Title); App.Current.Shutdown(-1); return; } tboxObjFile.Text = App.ObjFile; RefreshDrives(); } protected void RefreshDrives() { var xDrives = DriveInfo.GetDrives().Where(q => q.DriveType == DriveType.Removable).ToArray(); lboxTarget.Items.Clear(); foreach (var x in xDrives) { if (!x.IsReady) continue; decimal xSize = x.TotalSize / (1000 * 1000 * 1000); lboxTarget.Items.Add(x.Name + " " + xSize.ToString("0.0") + " GiB " + x.DriveFormat + " [" + x.VolumeLabel + "]"); } if (lboxTarget.Items.Count == 1) { lboxTarget.SelectedIndex = 0; } } private void butnRefresh_Click(object sender, RoutedEventArgs e) { RefreshDrives(); } private void butnCancel_Click(object sender, RoutedEventArgs e) { Close(); } private void butnCreate_Click(object sender, RoutedEventArgs e) { if (lboxTarget.SelectedItem == null) { MessageBox.Show("Please select a target drive.", Title); return; } string xDrive = (string)lboxTarget.SelectedItem; xDrive = xDrive[0].ToString(); try { Cosmos.Build.Common.UsbMaker.Generate(xDrive, tboxObjFile.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } MessageBox.Show("Drive " + xDrive + ": has been made a bootable Cosmos device."); Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.IO; namespace Cosmos.Deploy.USB { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); Loaded += new RoutedEventHandler(MainWindow_Loaded); } void MainWindow_Loaded(object sender, RoutedEventArgs e) { Title = App.Title; if (!File.Exists(App.ObjFile)) { MessageBox.Show("Specified .obj file does not exist.", Title); App.Current.Shutdown(-1); return; } tboxObjFile.Text = App.ObjFile; RefreshDrives(); } protected void RefreshDrives() { var xDrives = DriveInfo.GetDrives().Where(q => q.DriveType == DriveType.Removable).ToArray(); lboxTarget.Items.Clear(); foreach (var x in xDrives) { decimal xSize = x.TotalSize / (1000 * 1000 * 1000); lboxTarget.Items.Add(x.Name + " " + xSize.ToString("0.0") + " GiB " + x.DriveFormat + " [" + x.VolumeLabel + "]"); } if (lboxTarget.Items.Count == 1) { lboxTarget.SelectedIndex = 0; } } private void butnRefresh_Click(object sender, RoutedEventArgs e) { RefreshDrives(); } private void butnCancel_Click(object sender, RoutedEventArgs e) { Close(); } private void butnCreate_Click(object sender, RoutedEventArgs e) { if (lboxTarget.SelectedItem == null) { MessageBox.Show("Please select a target drive.", Title); return; } string xDrive = (string)lboxTarget.SelectedItem; xDrive = xDrive[0].ToString(); try { Cosmos.Build.Common.UsbMaker.Generate(xDrive, tboxObjFile.Text); } catch (Exception ex) { MessageBox.Show(ex.Message); return; } MessageBox.Show("Drive " + xDrive + ": has been made a bootable Cosmos device."); Close(); } } }
bsd-3-clause
C#
61517036a87711d79e7081c879af7c8300bb4878
Add in method to gauge a single point stamped with the current datetime
SkyKick/datadogcsharp
DataDogCSharp/DataDogCSharp/DataDogClient.cs
DataDogCSharp/DataDogCSharp/DataDogClient.cs
using DataDogCSharp.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace DataDogCSharp { public class DataDogClient { private string apiUrl; private HttpClient httpClient; public DataDogClient(string apiKey, string url = "https://app.datadoghq.com/api/v1/series?api_key=") { apiUrl = $"{url}{apiKey}"; httpClient = new HttpClient(); } public async Task<HttpResponseMessage> Gauge(string metric, long point, IEnumerable<string> tags) { var dataPoints = new List<DataDogPoint>() { new DataDogPoint(point) }; return await Gauge(metric, dataPoints, tags); } public async Task<HttpResponseMessage> Gauge(string metric, IEnumerable<long> points, IEnumerable<string> tags) { var dataPoints = points.Select(p => new DataDogPoint(p)); return await Gauge(metric, dataPoints, tags); } public async Task<HttpResponseMessage> Gauge(string metric, IEnumerable<DataDogPoint> points, IEnumerable<string> tags) { DataDogMetric dataMetric = new DataDogMetric() { Metric = metric, Points = points, Tags = tags, Type = "gauge" }; DataDogPayload payload = new DataDogPayload() { Series = new List<DataDogMetric>() { dataMetric } }; return await PostToDataDog(payload); } public async Task<HttpResponseMessage> PostToDataDog(DataDogPayload payload) { var json = JsonConvert.SerializeObject(payload); var content = new StringContent(json, Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync(apiUrl, content); return result; } } }
using DataDogCSharp.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace DataDogCSharp { public class DataDogClient { private string apiUrl; private HttpClient httpClient; public DataDogClient(string apiKey, string url = "https://app.datadoghq.com/api/v1/series?api_key=") { apiUrl = $"{url}{apiKey}"; httpClient = new HttpClient(); } public async Task<HttpResponseMessage> Gauge(string metric, IEnumerable<DataDogPoint> points, IEnumerable<string> tags) { DataDogMetric dataMetric = new DataDogMetric() { Metric = metric, Points = points, Tags = tags, Type = "gauge" }; DataDogPayload payload = new DataDogPayload() { Series = new List<DataDogMetric>() { dataMetric } }; return await PostToDataDog(payload); } public async Task<HttpResponseMessage> Gauge(string metric, IEnumerable<long> points, IEnumerable<string> tags) { var dataPoints = points.Select(p => new DataDogPoint(p)); return await Gauge(metric, dataPoints, tags); } public async Task<HttpResponseMessage> PostToDataDog(DataDogPayload payload) { var json = JsonConvert.SerializeObject(payload); var content = new StringContent(json, Encoding.UTF8, "application/json"); var result = await httpClient.PostAsync(apiUrl, content); return result; } } }
mit
C#
9920f24dcc629d6728fa3b6b81228ac3c30f3d7d
Update Chrome configuration in UITestFixture
atata-framework/atata-sample-app-tests
src/AtataSampleApp.AutoTests/UITestFixture.cs
src/AtataSampleApp.AutoTests/UITestFixture.cs
using Atata; using NUnit.Framework; namespace AtataSampleApp.AutoTests { [TestFixture] public class UITestFixture { [SetUp] public void SetUp() { AtataContext.Configure(). UseChrome(). WithArguments("disable-extensions", "start-maximized", "disable-infobars"). UseBaseUrl(Config.Url). UseNUnitTestName(). AddNUnitTestContextLogging(). WithMinLevel(LogLevel.Info). WithoutSectionFinish(). AddNLogLogging(). AddScreenshotFileSaving(). WithFolderPath(() => $@"Logs\{AtataContext.BuildStart:yyyy-MM-dd HH_mm_ss}\{AtataContext.Current.TestName}"). LogNUnitError(). TakeScreenshotOnNUnitError(). Build(); } [TearDown] public void TearDown() { AtataContext.Current.CleanUp(); } protected UsersPage Login() { return Go.To<SignInPage>(). Email.Set(Config.Account.Email). Password.Set(Config.Account.Password). SignIn(); } } }
using Atata; using NUnit.Framework; namespace AtataSampleApp.AutoTests { [TestFixture] public class UITestFixture { [SetUp] public void SetUp() { AtataContext.Configure(). UseChrome(). WithArguments("disable-extensions", "no-sandbox", "start-maximized"). UseBaseUrl(Config.Url). UseNUnitTestName(). AddNUnitTestContextLogging(). WithMinLevel(LogLevel.Info). WithoutSectionFinish(). AddNLogLogging(). AddScreenshotFileSaving(). WithFolderPath(() => $@"Logs\{AtataContext.BuildStart:yyyy-MM-dd HH_mm_ss}\{AtataContext.Current.TestName}"). LogNUnitError(). TakeScreenshotOnNUnitError(). Build(); } [TearDown] public void TearDown() { AtataContext.Current.CleanUp(); } protected UsersPage Login() { return Go.To<SignInPage>(). Email.Set(Config.Account.Email). Password.Set(Config.Account.Password). SignIn(); } } }
apache-2.0
C#
92cd024b578c198ad5c2c7900e8ded542af1e0ac
Bump to 0.7
github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity
common/SolutionInfo.cs
common/SolutionInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.7.0.0"; } }
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyProduct("GitHub for Unity")] [assembly: AssemblyVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyFileVersion(System.AssemblyVersionInformation.Version)] [assembly: AssemblyInformationalVersion(System.AssemblyVersionInformation.Version)] [assembly: ComVisible(false)] [assembly: AssemblyCompany("GitHub, Inc.")] [assembly: AssemblyCopyright("Copyright GitHub, Inc. 2017")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: InternalsVisibleTo("TestUtils", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("UnitTests", AllInternalsVisible = true)] [assembly: InternalsVisibleTo("IntegrationTests", AllInternalsVisible = true)] //Required for NSubstitute [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2", AllInternalsVisible = true)] //Required for Unity compilation [assembly: InternalsVisibleTo("Assembly-CSharp-Editor", AllInternalsVisible = true)] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.6.0.0"; } }
mit
C#
0f3e6a3f1aec5b1032458baed7bc4cdde6ec99af
Repair Auth Test
darilek/dotvvm,riganti/dotvvm,kiraacorsac/dotvvm,riganti/dotvvm,kiraacorsac/dotvvm,kiraacorsac/dotvvm,riganti/dotvvm,darilek/dotvvm,riganti/dotvvm,darilek/dotvvm
src/DotVVM.Samples.Tests/Complex/AuthTests.cs
src/DotVVM.Samples.Tests/Complex/AuthTests.cs
using Dotvvm.Samples.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using Riganti.Utils.Testing.SeleniumCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotVVM.Samples.Tests.Complex { [TestClass] public class AuthTests : SeleniumTestBase { [TestMethod] public void Complex_Auth() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login); browser.SendKeys("input[type=text]", "user"); browser.First("input[type=button]").Click(); browser.Wait(); browser.Refresh(); //browser.FindElements("a").ThrowIfDifferentCountThan(2); browser.Wait(); browser.Last("a").Click(); browser.SendKeys("input[type=text]", "message"); browser.ElementAt("input[type=button]", 0).Click(); browser.ElementAt("h1",1) .CheckIfInnerText( s => s.Contains("DotVVM Debugger: Error 401: Unauthorized") ); browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login); //browser.SendKeys("input[type=text]", "user"); browser.First("input#adminRole").Click(); browser.Wait(); browser.First("input[type=button]").Click(); browser.Wait(); browser.Last("a").Click(); browser.SendKeys("input[type=text]", "message"); browser.ElementAt("input[type=button]", 0).Click(); browser.Wait(); browser.First("span").CheckIfInnerText(s => s.Contains("user: message")); }); } } }
using Dotvvm.Samples.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; using Riganti.Utils.Testing.SeleniumCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotVVM.Samples.Tests.Complex { [TestClass] public class AuthTests : SeleniumTestBase { [TestMethod] public void Complex_Auth() { RunInAllBrowsers(browser => { browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login); browser.SendKeys("input[type=text]", "user"); browser.First("input[type=button]").Click(); browser.Wait(); //browser.FindElements("a").ThrowIfDifferentCountThan(2); browser.Wait(); browser.Last("a").Click(); browser.SendKeys("input[type=text]", "message"); browser.ElementAt("input[type=button]", 0).Click(); browser.First("h1") .CheckIfInnerText( s => s.Contains("DotVVM Debugger: Error 401: Unauthorized") ); browser.NavigateToUrl(SamplesRouteUrls.ComplexSamples_Auth_Login); browser.SendKeys("input[type=text]", "user"); browser.First("input#adminRole").Click(); browser.Wait(); browser.First("input[type=button]").Click(); browser.Wait(); browser.Last("a").Click(); browser.SendKeys("input[type=text]", "message"); browser.ElementAt("input[type=button]", 0).Click(); browser.Wait(); browser.First("span").CheckIfInnerText(s => s.Contains("user: message")); }); } } }
apache-2.0
C#
44218906e6086adffca030f3a3ddab31e4ee9feb
Update TheXamarinPodcast.cs
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/TheXamarinPodcast.cs
src/Firehose.Web/Authors/TheXamarinPodcast.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class TheXamarinPodcast : IAmACommunityMember, IAmAPodcast { public string FirstName => "The Xamarin"; public string LastName => "Podcast"; public string StateOrRegion => "Internet"; public string EmailAddress => "hello@xamarin.com"; public string ShortBioOrTagLine => "is the official Xamarin podcast discussing all things Xamarin!"; public Uri WebSite => new Uri("http://www.xamarinpodcast.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://feeds.fireside.fm/xamarinpodcast/rss"); } } public string TwitterHandle => "XamarinPodcast"; public string GravatarHash => "70148d964bb389d42547834e1062c886"; public string GitHubHandle => string.Empty; public GeoPosition Position => GeoPosition.Empty; public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class TheXamarinPodcast : IAmACommunityMember, IAmAPodcast { public string FirstName => "The Xamarin"; public string LastName => "Podcast"; public string StateOrRegion => "Internet"; public string EmailAddress => "hello@xamarin.com"; public string ShortBioOrTagLine => "is the official Xamarin podcast discussing all things Xamarin!"; public Uri WebSite => new Uri("http://www.xamarinpodcast.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://xamarinpodcast.fireside.fm/rss"); } } public string TwitterHandle => "XamarinPodcast"; public string GravatarHash => "70148d964bb389d42547834e1062c886"; public string GitHubHandle => string.Empty; public GeoPosition Position => GeoPosition.Empty; public string FeedLanguageCode => "en"; } }
mit
C#
e8eb5bb2573ee25173ad959c89501bb958c54e69
Reorganize stuff.
ManiaDotNet/ManiaPlanet
ManiaNet.ManiaPlanet/Nations.cs
ManiaNet.ManiaPlanet/Nations.cs
using ManiaNet.ManiaPlanet.XmlEntities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; namespace ManiaNet.ManiaPlanet { /// <summary> /// Contains static helpers and information about the various Nations. /// </summary> public static class Nations { private static Dictionary<string, Nation> nations = new Dictionary<string, Nation>(); static Nations() { XElement nationsList = XDocument.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("ManiaNet.ManiaPlanet.NationsList.xml")).Root; foreach (var nationElement in nationsList.Elements()) { Nation nation = new Nation(); nation.ParseXml(nationElement); nations.Add(nation.Path.ToLower(), nation); } } /// <summary> /// Gets the nation-information for the nation in the given zone path. /// </summary> /// <param name="path">The zone path to get the nation-information for.</param> /// <returns>The nation-information for the given zone path.</returns> public static Nation GetNation(string path) { string nationPath = GetNationPath(path).ToLower(); if (!nations.ContainsKey(nationPath)) return nations[""]; return nations[nationPath]; } /// <summary> /// Takes a zone path and stript it to be only a path to the nation. /// </summary> /// <param name="path">The zone path to strip.</param> /// <returns>The path to the nation.</returns> public static string GetNationPath(string path) { int firstPipe = path.IndexOf('|'); if (firstPipe < 0 || path.Length == firstPipe + 1) return string.Empty; int secondPipe = path.IndexOf('|', firstPipe + 1); if (secondPipe < 0 || path.Length == secondPipe + 1) return string.Empty; int thirdPipe = path.IndexOf('|', secondPipe + 1); if (thirdPipe < 0) return path; return path.Substring(0, thirdPipe); } } }
using ManiaNet.ManiaPlanet.XmlEntities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; namespace ManiaNet.ManiaPlanet { /// <summary> /// Contains static helpers and information about the various Nations. /// </summary> public static class Nations { private static Dictionary<string, Nation> nations = new Dictionary<string, Nation>(); static Nations() { XElement nationsList = XDocument.Load(Assembly.GetExecutingAssembly().GetManifestResourceStream("ManiaNet.ManiaPlanet.NationsList.xml")).Root; foreach (var nationElement in nationsList.Elements()) { Nation nation = new Nation(); if (!nation.ParseXml(nationElement)) throw new FormatException("NationsList.xml wasn't in the correct format."); nations.Add(nation.Path.ToLower(), nation); } } /// <summary> /// Gets the nation-information for the nation in the given zone path. /// </summary> /// <param name="path">The zone path to get the nation-information for.</param> /// <returns>The nation-information for the given zone path.</returns> public static Nation GetNation(string path) { string nationPath = GetNationPath(path).ToLower(); if (!nations.ContainsKey(nationPath)) return nations[""]; return nations[nationPath]; } /// <summary> /// Takes a zone path and stript it to be only a path to the nation. /// </summary> /// <param name="path">The zone path to strip.</param> /// <returns>The path to the nation.</returns> public static string GetNationPath(string path) { int firstPipe = path.IndexOf('|'); if (firstPipe < 0 || path.Length == firstPipe + 1) return string.Empty; int secondPipe = path.IndexOf('|', firstPipe + 1); if (secondPipe < 0 || path.Length == secondPipe + 1) return string.Empty; int thirdPipe = path.IndexOf('|', secondPipe + 1); if (thirdPipe < 0) return path; return path.Substring(0, thirdPipe); } } }
lgpl-2.1
C#
c512eda5ab0af2bb1af6c22880d579f0b2cacb9d
Fix indentation for scheduled triggers
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/CI/GitHubActions/Configuration/GitHubActionsScheduledTrigger.cs
source/Nuke.Common/CI/GitHubActions/Configuration/GitHubActionsScheduledTrigger.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.GitHubActions.Configuration { public class GitHubActionsScheduledTrigger : GitHubActionsDetailedTrigger { public string Cron { get; set; } public override void Write(CustomFileWriter writer) { writer.WriteLine("schedule:"); using (writer.Indent()) { writer.WriteLine($"- cron: '{Cron}'"); } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.GitHubActions.Configuration { public class GitHubActionsScheduledTrigger : GitHubActionsDetailedTrigger { public string Cron { get; set; } public override void Write(CustomFileWriter writer) { using (writer.Indent()) { writer.WriteLine("schedule:"); using (writer.Indent()) { writer.WriteLine($" - cron: '{Cron}'"); } } } } }
mit
C#
a26e210ad3eae75ed217761d96ae4ff5222b3183
Update CheckNums.cs
michaeljwebb/Algorithm-Practice
Coderbyte/CheckNums.cs
Coderbyte/CheckNums.cs
//Take both parameters being passed and return the string true if num2 is greater than num1, otherwise return the string false. //If the parameter values are equal to each other then return the string -1. using System; class MainClass { public static int CheckNums(int num1, int num2) { if(num2 > num1){ Console.WriteLine("true"); } else if(num1 == num2){ num1 = -1; } else if(num2 < num1){ Console.WriteLine("false"); } return num1; } static void Main() { // keep this function call here Console.WriteLine(CheckNums(Console.ReadLine())); } }
using System; class MainClass { public static int CheckNums(int num1, int num2) { if(num2 > num1){ Console.WriteLine("true"); } else if(num1 == num2){ num1 = -1; } else if(num2 < num1){ Console.WriteLine("false"); } return num1; } static void Main() { // keep this function call here Console.WriteLine(CheckNums(Console.ReadLine())); } }
mit
C#
f83dd046a2dd89cca73219fcc6190a9a6124273d
Use Contract.Requires for preconditions.
Perspex/Perspex,akrisiun/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia
src/Avalonia.Visuals/Media/Brush.cs
src/Avalonia.Visuals/Media/Brush.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reflection; namespace Avalonia.Media { /// <summary> /// Describes how an area is painted. /// </summary> public abstract class Brush : AvaloniaObject, IBrush { /// <summary> /// Defines the <see cref="Opacity"/> property. /// </summary> public static readonly StyledProperty<double> OpacityProperty = AvaloniaProperty.Register<Brush, double>(nameof(Opacity), 1.0); /// <summary> /// Gets or sets the opacity of the brush. /// </summary> public double Opacity { get { return GetValue(OpacityProperty); } set { SetValue(OpacityProperty, value); } } /// <summary> /// Parses a brush string. /// </summary> /// <param name="s">The brush string.</param> /// <returns>The <see cref="Color"/>.</returns> public static IBrush Parse(string s) { Contract.Requires<ArgumentNullException>(s != null); Contract.Requires<FormatException>(s.Length > 0); if (s[0] == '#') { return new SolidColorBrush(Color.Parse(s)); } var brush = KnownColors.GetKnownBrush(s); if (brush != null) { return brush; } throw new FormatException($"Invalid brush string: '{s}'."); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Linq; using System.Reflection; namespace Avalonia.Media { /// <summary> /// Describes how an area is painted. /// </summary> public abstract class Brush : AvaloniaObject, IBrush { /// <summary> /// Defines the <see cref="Opacity"/> property. /// </summary> public static readonly StyledProperty<double> OpacityProperty = AvaloniaProperty.Register<Brush, double>(nameof(Opacity), 1.0); /// <summary> /// Gets or sets the opacity of the brush. /// </summary> public double Opacity { get { return GetValue(OpacityProperty); } set { SetValue(OpacityProperty, value); } } /// <summary> /// Parses a brush string. /// </summary> /// <param name="s">The brush string.</param> /// <returns>The <see cref="Color"/>.</returns> public static IBrush Parse(string s) { if (s == null) throw new ArgumentNullException(nameof(s)); if (s.Length == 0) throw new FormatException(); if (s[0] == '#') { return new SolidColorBrush(Color.Parse(s)); } var brush = KnownColors.GetKnownBrush(s); if (brush != null) { return brush; } throw new FormatException($"Invalid brush string: '{s}'."); } } }
mit
C#
b2f9ae509c2c6ab84d5156cde18c044e5f3390ae
Check dVers versions for null (version numbers such as 1, 1.2 and 1.3)
sundhaug92/kspMan2
KerbalPackageManager/dotVersion.cs
KerbalPackageManager/dotVersion.cs
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace KerbalPackageManager { internal class dotVersion { public dotVersion(string toFilename) { var jObj = JObject.Parse(File.ReadAllText(toFilename)); Name = (string)jObj["NAME"]; Url = (Uri)jObj["URL"]; if (jObj["VERSION"] != null) { string ver = (string)jObj["VERSION"]["MAJOR"]; if (jObj["VERSION"]["MINOR"] != null) ver += "." + jObj["VERSION"]["MINOR"]; if (jObj["VERSION"]["PATCH"] != null) ver += "." + jObj["VERSION"]["PATCH"]; if (jObj["VERSION"]["BUILD"] != null) ver += "." + jObj["VERSION"]["BUILD"]; Version = new Version(ver); } else Version = null; } public string Name { get; set; } public Uri Url { get; set; } public Version Version { get; set; } } }
using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace KerbalPackageManager { internal class dotVersion { public dotVersion(string toFilename) { var jObj = JObject.Parse(File.ReadAllText(toFilename)); Name = (string)jObj["NAME"]; Url = (Uri)jObj["URL"]; var ver = jObj["VERSION"]; Version = new Version((int)ver["MAJOR"], (int)ver["MINOR"], (int)ver["PATCH"], (int)ver["BUILD"]); } public string Name { get; set; } public Uri Url { get; set; } public Version Version { get; set; } } }
mit
C#
41560b427609eb92e11e949a0e7cdfc2950e9630
Add a date stamp to output files
dustyburwell/miniature-bear
PrintScreen/Program.cs
PrintScreen/Program.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading; using System.Windows.Forms; using PrintScreen.Properties; namespace PrintScreen { static class Program { private static SynchronizationContext context; private static NotifyIcon icon; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); icon = new NotifyIcon { Visible = true, Icon = (Icon)Resources.ResourceManager.GetObject("appicon") }; icon.ContextMenu = new ContextMenu( new [] { new MenuItem("E&xit", ExitClicked) }); context = new WindowsFormsSynchronizationContext(); HotKeyManager.RegisterHotKey(Keys.PrintScreen, 0); HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed; Application.Run(new ApplicationContext()); } private static void ExitClicked(object sender, EventArgs args) { icon.Dispose(); Application.Exit(); } private static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e) { context.Send(o => TakeSnapshot(), null); } public static void TakeSnapshot() { Win32.WINDOWINFO info; Bitmap screenshot; Graphics screen; info = new Win32.WINDOWINFO(); Win32.GetWindowInfo(Win32.GetForegroundWindow(), ref info); screenshot = new Bitmap(info.rcWindow.Width, info.rcWindow.Height, PixelFormat.Format32bppArgb); screen = Graphics.FromImage(screenshot); screen.CopyFromScreen(info.rcWindow.X, info.rcWindow.Y, 0, 0, info.rcWindow.Size, CopyPixelOperation.SourceCopy); Clipboard.SetImage(screenshot); string fileName = string.Format("snapshot_{0}.png", DateTime.Now.ToString("yyyy-MM-dd_H-mm-ss")); var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), fileName); screenshot.Save(filePath, ImageFormat.Png); } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Threading; using System.Windows.Forms; using PrintScreen.Properties; namespace PrintScreen { static class Program { private static SynchronizationContext context; private static NotifyIcon icon; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); icon = new NotifyIcon { Visible = true, Icon = (Icon)Resources.ResourceManager.GetObject("appicon") }; icon.ContextMenu = new ContextMenu( new [] { new MenuItem("E&xit", ExitClicked) }); context = new WindowsFormsSynchronizationContext(); HotKeyManager.RegisterHotKey(Keys.PrintScreen, 0); HotKeyManager.HotKeyPressed += HotKeyManager_HotKeyPressed; Application.Run(new ApplicationContext()); } private static void ExitClicked(object sender, EventArgs args) { icon.Dispose(); Application.Exit(); } private static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e) { context.Send(o => TakeSnapshot(), null); } public static void TakeSnapshot() { Win32.WINDOWINFO info; Bitmap screenshot; Graphics screen; info = new Win32.WINDOWINFO(); Win32.GetWindowInfo(Win32.GetForegroundWindow(), ref info); screenshot = new Bitmap(info.rcWindow.Width, info.rcWindow.Height, PixelFormat.Format32bppArgb); screen = Graphics.FromImage(screenshot); screen.CopyFromScreen(info.rcWindow.X, info.rcWindow.Y, 0, 0, info.rcWindow.Size, CopyPixelOperation.SourceCopy); Clipboard.SetImage(screenshot); var filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "snapshot.png"); screenshot.Save(filePath, ImageFormat.Png); } } }
mit
C#
adabd456e6b6bf427aa760b2b4284353ba265d82
修复未生成必要特性集的错误。
Zongsoft/Zongsoft.Web
src/Controls/Editor.cs
src/Controls/Editor.cs
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2011-2015 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.Web. * * Zongsoft.Web is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.Web is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.Web; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.UI; namespace Zongsoft.Web.Controls { public class Editor : TextBoxBase { #region 构造函数 public Editor() { this.CssClass = "editor"; } #endregion #region 重写属性 [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DefaultValue(InputBoxType.Text)] public override InputBoxType InputType { get { return base.InputType; } set { if(value != InputBoxType.Text) throw new ArgumentOutOfRangeException(); base.InputType = value; } } #endregion #region 重写方法 protected override void RenderBeginTag(HtmlTextWriter writer) { if(string.IsNullOrWhiteSpace(this.Name) && (!string.IsNullOrWhiteSpace(this.ID))) writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ID); this.AddAttributes(writer, "CssClass"); writer.RenderBeginTag(HtmlTextWriterTag.Textarea); } protected override void RenderContent(HtmlTextWriter writer) { writer.WriteEncodedText(this.Value); } #endregion } }
/* * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2011-2015 Zongsoft Corporation <http://www.zongsoft.com> * * This file is part of Zongsoft.Web. * * Zongsoft.Web is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * Zongsoft.Web is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * You should have received a copy of the GNU Lesser General Public * License along with Zongsoft.Web; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.Web; using System.Web.UI; namespace Zongsoft.Web.Controls { public class Editor : TextBoxBase { #region 构造函数 public Editor() { this.CssClass = "editor"; } #endregion #region 重写属性 [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [DefaultValue(InputBoxType.Text)] public override InputBoxType InputType { get { return base.InputType; } set { if(value != InputBoxType.Text) throw new ArgumentOutOfRangeException(); base.InputType = value; } } #endregion #region 重写方法 protected override void RenderBeginTag(HtmlTextWriter writer) { if(string.IsNullOrWhiteSpace(this.Name) && (!string.IsNullOrWhiteSpace(this.ID))) writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ID); writer.RenderBeginTag(HtmlTextWriterTag.Textarea); } protected override void RenderContent(HtmlTextWriter writer) { writer.WriteEncodedText(this.Value); } #endregion } }
lgpl-2.1
C#
d52091407a8b1a14e037798a13dbb13c9fa4b57d
Use cast operators in KeyValue instead of properties
mfep/Duality.InputPlugin
Source/Code/CorePlugin/KeyValue.cs
Source/Code/CorePlugin/KeyValue.cs
using System; using Duality; using Duality.Input; namespace MFEP.Duality.Plugins.InputPlugin { public enum KeyType { KeyboardType = 0, MouseButtonType = 1 } public struct KeyValue { private const int mouseButtonOffset = 1000; private readonly int storeField; public KeyValue (Key key) { storeField = (int)key; } public KeyValue (MouseButton mouseButton) { storeField = (int)mouseButton + mouseButtonOffset; } public KeyType KeyType => storeField < mouseButtonOffset ? KeyType.KeyboardType : KeyType.MouseButtonType; public override bool Equals (object obj) { if (obj is KeyValue) return storeField == ((KeyValue)obj).storeField; return false; } public override int GetHashCode () { return storeField; } public static explicit operator Key (KeyValue kv) { if (kv.KeyType != KeyType.KeyboardType) throw new InvalidCastException(); return (Key)kv.storeField; } public static explicit operator MouseButton (KeyValue kv) { if (kv.KeyType != KeyType.MouseButtonType) throw new InvalidCastException(); return (MouseButton)(kv.storeField - mouseButtonOffset); } public int Index { get { switch (KeyType) { case KeyType.KeyboardType: return storeField; case KeyType.MouseButtonType: return storeField - mouseButtonOffset; default: throw new ArgumentOutOfRangeException (); } } } internal bool IsHit { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyHit ((Key)this); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonHit ((MouseButton)this); default: throw new ArgumentOutOfRangeException (); } } } internal bool IsPressed { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyPressed ((Key)this); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonPressed ((MouseButton)this); default: throw new ArgumentOutOfRangeException (); } } } internal bool IsReleased { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyReleased ((Key)this); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonReleased ((MouseButton)this); default: throw new ArgumentOutOfRangeException (); } } } } }
using System; using Duality; using Duality.Input; namespace MFEP.Duality.Plugins.InputPlugin { public enum KeyType { KeyboardType = 0, MouseButtonType = 1 } public struct KeyValue { private const int mouseButtonOffset = 1000; private readonly int storeField; public KeyValue (Key key) { storeField = (int)key; } public KeyValue (MouseButton mouseButton) { storeField = (int)mouseButton + mouseButtonOffset; } public KeyType KeyType => storeField < mouseButtonOffset ? KeyType.KeyboardType : KeyType.MouseButtonType; public override bool Equals (object obj) { if (obj is KeyValue) return storeField == ((KeyValue)obj).storeField; return false; } public override int GetHashCode () { return storeField; } public Key Key { get { if (KeyType != KeyType.KeyboardType) throw new InvalidCastException (); return (Key)storeField; } } public MouseButton MouseButton { get { if (KeyType != KeyType.MouseButtonType) throw new InvalidCastException (); return (MouseButton)(storeField - mouseButtonOffset); } } public int Index { get { switch (KeyType) { case KeyType.KeyboardType: return storeField; case KeyType.MouseButtonType: return storeField - mouseButtonOffset; default: throw new ArgumentOutOfRangeException (); } } } internal bool IsHit { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyHit (Key); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonHit (MouseButton); default: throw new ArgumentOutOfRangeException (); } } } internal bool IsPressed { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyPressed (Key); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonPressed (MouseButton); default: throw new ArgumentOutOfRangeException (); } } } internal bool IsReleased { get { switch (KeyType) { case KeyType.KeyboardType: return DualityApp.Keyboard.KeyReleased (Key); case KeyType.MouseButtonType: return DualityApp.Mouse.ButtonReleased (MouseButton); default: throw new ArgumentOutOfRangeException (); } } } } }
mit
C#
d0743806d8d8675e82afd665ecdd9bd208564cf7
Disable UnrootedConnectionsGetRemovedFromHeartbeat because it's flaky
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/Microsoft.AspNetCore.Server.Kestrel.Core.Tests/FrameConnectionManagerTests.cs
test/Microsoft.AspNetCore.Server.Kestrel.Core.Tests/FrameConnectionManagerTests.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class FrameConnectionManagerTests { [Fact(Skip = "Flaky test")] public void UnrootedConnectionsGetRemovedFromHeartbeat() { var connectionId = "0"; var trace = new Mock<IKestrelTrace>(); var frameConnectionManager = new FrameConnectionManager(trace.Object); // Create FrameConnection in inner scope so it doesn't get rooted by the current frame. UnrootedConnectionsGetRemovedFromHeartbeatInnerScope(connectionId, frameConnectionManager, trace); GC.Collect(); GC.WaitForPendingFinalizers(); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(0, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Once()); } [MethodImpl(MethodImplOptions.NoInlining)] private void UnrootedConnectionsGetRemovedFromHeartbeatInnerScope( string connectionId, FrameConnectionManager frameConnectionManager, Mock<IKestrelTrace> trace) { var serviceContext = new TestServiceContext { ConnectionManager = frameConnectionManager }; // The FrameConnection constructor adds itself to the connection manager. var ignore = new FrameConnection(new FrameConnectionContext { ServiceContext = serviceContext, ConnectionId = connectionId }); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(1, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Never()); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.CompilerServices; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.AspNetCore.Testing; using Moq; using Xunit; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Tests { public class FrameConnectionManagerTests { [Fact] public void UnrootedConnectionsGetRemovedFromHeartbeat() { var connectionId = "0"; var trace = new Mock<IKestrelTrace>(); var frameConnectionManager = new FrameConnectionManager(trace.Object); // Create FrameConnection in inner scope so it doesn't get rooted by the current frame. UnrootedConnectionsGetRemovedFromHeartbeatInnerScope(connectionId, frameConnectionManager, trace); GC.Collect(); GC.WaitForPendingFinalizers(); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(0, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Once()); } [MethodImpl(MethodImplOptions.NoInlining)] private void UnrootedConnectionsGetRemovedFromHeartbeatInnerScope( string connectionId, FrameConnectionManager frameConnectionManager, Mock<IKestrelTrace> trace) { var serviceContext = new TestServiceContext { ConnectionManager = frameConnectionManager }; // The FrameConnection constructor adds itself to the connection manager. var ignore = new FrameConnection(new FrameConnectionContext { ServiceContext = serviceContext, ConnectionId = connectionId }); var connectionCount = 0; frameConnectionManager.Walk(_ => connectionCount++); Assert.Equal(1, connectionCount); trace.Verify(t => t.ApplicationNeverCompleted(connectionId), Times.Never()); } } }
apache-2.0
C#
fee4a456979876e553c7d936d476fd503b8cd578
Add a do-nothing method Parse() to ArgParser so it passes build.
jameslan/argparser.net
ArgParser.NET/ArgParser.cs
ArgParser.NET/ArgParser.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArgParser.NET { public class ArgParser { public List<string> Parse(string[] args) { var extra = new List<string>(); return extra; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArgParser.NET { public class ArgParser { } }
mit
C#
5ffc278912ea5f62b8089852d2b4f19a4c3886b7
Refactor - rename test class
stoneass/IntUITive,stoneass/IntUITive
IntUITive.Selenium.Tests/IntuitivelyTests.cs
IntUITive.Selenium.Tests/IntuitivelyTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class EdgeCaseTests { [Test] public void Find_WithNoTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void Find_WithEmptyTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(""), Throws.Exception.TypeOf<ArgumentException>()); } [Test] public void Find_WithUnidentifiableTerm_ReturnsNothing() { var intuitively = new Intuitively(); var element = intuitively.Find("unidentifiable term"); Assert.That(element, Is.Null); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; namespace IntUITive.Selenium.Tests { [TestFixture] public class IntuitivelyTests { [Test] public void Find_WithNoTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(null), Throws.Exception.TypeOf<ArgumentNullException>()); } [Test] public void Find_WithEmptyTerm_Fails() { var intuitively = new Intuitively(); Assert.That(() => intuitively.Find(""), Throws.Exception.TypeOf<ArgumentException>()); } [Test] public void Find_WithUnidentifiableTerm_ReturnsNothing() { var intuitively = new Intuitively(); var element = intuitively.Find("unidentifiable term"); Assert.That(element, Is.Null); } } }
apache-2.0
C#
234250f914cde8a135a1e9ea828b80ce96916037
Document IDialogHandler
Octopus-ITSM/CefSharp,battewr/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,Livit/CefSharp,dga711/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,Octopus-ITSM/CefSharp,dga711/CefSharp,Octopus-ITSM/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,windygu/CefSharp,illfang/CefSharp,AJDev77/CefSharp,twxstar/CefSharp,Livit/CefSharp,rlmcneary2/CefSharp,joshvera/CefSharp,VioletLife/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,zhangjingpu/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,battewr/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,windygu/CefSharp,twxstar/CefSharp,illfang/CefSharp,joshvera/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,haozhouxu/CefSharp,Haraguroicha/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,rover886/CefSharp,windygu/CefSharp,dga711/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,illfang/CefSharp,jamespearce2006/CefSharp,dga711/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,VioletLife/CefSharp,yoder/CefSharp,twxstar/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,zhangjingpu/CefSharp,illfang/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,ITGlobal/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp,yoder/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,ITGlobal/CefSharp
CefSharp/IDialogHandler.cs
CefSharp/IDialogHandler.cs
using System.Collections.Generic; namespace CefSharp { /// <summary> /// Implement this interface to handle dialog events. The methods of this class will be called on the browser process UI thread. /// </summary> public interface IDialogHandler { /// <summary> /// Runs a file chooser dialog. /// </summary> /// <example> /// To test assign something like TempFileDialogHandler (from CefSharp.Example) to DialogHandler e.g. /// <code> /// browser.DialogHandler = new TempFileDialogHandler(); /// </code> /// Example URL to use for file browsing http://www.cs.tut.fi/~jkorpela/forms/file.html#example /// Simply click browse, the space next to the browse button should be populated with a randomly generated filename. /// </example> /// <param name="browser">the browser object</param> /// <param name="mode">represents the type of dialog to display</param> /// <param name="title">the title to be used for the dialog. It may be empty to show the default title ("Open" or "Save" /// depending on the mode).</param> /// <param name="defaultFileName">the default file name to select in the dialog.</param> /// <param name="acceptTypes">a list of valid lower-cased MIME types or file extensions specified in an input element and /// is used to restrict selectable files to such types.</param> /// <param name="result">the filename(s) the dialog returns</param> /// <returns>To display a custom dialog return true. To display the default dialog return false.</returns> bool OnFileDialog(IWebBrowser browser, CefFileDialogMode mode, string title, string defaultFileName, List<string> acceptTypes, out List<string> result); } }
using System.Collections.Generic; namespace CefSharp { public interface IDialogHandler { bool OnFileDialog(IWebBrowser browser, CefFileDialogMode mode, string title, string defaultFileName, List<string> acceptTypes, out List<string> result); } }
bsd-3-clause
C#
a6bcea71b60f476cd32ccb3fb5667248c07412e7
Hide Nuterra.Start() from API
maritaria/terratech-mod,Nuterra/Nuterra,Exund/nuterra
src/Nuterra/Nuterra.cs
src/Nuterra/Nuterra.cs
using System; using System.IO; using System.Reflection; using UnityEngine; namespace Nuterra { public static class Nuterra { public static readonly Version CurrentVersion = new Version(0, 3, 0); public static readonly string DataFolder = Path.Combine(Application.dataPath, "..\\Nuterra_Data"); public static readonly string ModsFolder = Path.Combine(Application.dataPath, "..\\Nuterra_Data\\Mods");//TODO: Start using this public static readonly string TerraTechAssemblyName = "Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; internal static void Start() { CleanLogger.Install(); Console.WriteLine($"Nuterra.Nuterra.Startup({CurrentVersion})"); if (!Directory.Exists(DataFolder)) { Console.WriteLine("Nuterra_Data is missing! mods won't be loaded"); return; } Assembly terraTech = FindTerraTechAssembly(); if (terraTech != null) { ModLoader.Instance.LoadAllMods(terraTech); } } private static Assembly FindTerraTechAssembly() { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if (asm.FullName.Equals(TerraTechAssemblyName)) { return asm; } } Console.WriteLine($"Unable to find '{TerraTechAssemblyName}'"); return null; } } }
using System; using System.IO; using System.Reflection; using UnityEngine; namespace Nuterra { public static class Nuterra { public static readonly Version CurrentVersion = new Version(0, 3, 0); public static readonly string DataFolder = Path.Combine(Application.dataPath, "..\\Nuterra_Data"); public static readonly string ModsFolder = Path.Combine(Application.dataPath, "..\\Nuterra_Data\\Mods");//TODO: Start using this public static readonly string TerraTechAssemblyName = "Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"; public static void Start() { CleanLogger.Install(); Console.WriteLine($"Nuterra.Nuterra.Startup({CurrentVersion})"); if (!Directory.Exists(DataFolder)) { Console.WriteLine("Nuterra_Data is missing! mods won't be loaded"); return; } Assembly terraTech = FindTerraTechAssembly(); if (terraTech != null) { ModLoader.Instance.LoadAllMods(terraTech); } } private static Assembly FindTerraTechAssembly() { foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if (asm.FullName.Equals(TerraTechAssemblyName)) { return asm; } } Console.WriteLine($"Unable to find '{TerraTechAssemblyName}'"); return null; } } }
mit
C#
e8eff1a193d1c199e2ffcf03b9c536fe316948dd
fix assmbly info
jmenziessmith/TagCache.Redis
src/TagCache.Redis/Properties/AssemblyInfo.cs
src/TagCache.Redis/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TagCache.Redis")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TagCache.Redis")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cce39ec4-18f0-4fe3-89df-958686c3881a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Architecture.Patterns.Cache.RedisCache")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Architecture.Patterns.Cache.RedisCache")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("cce39ec4-18f0-4fe3-89df-958686c3881a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
b25dc9ac34e57d9c0c1673965779f26d47ada309
Fix tests if .bak file exists
ermshiperete/LfMerge,ermshiperete/LfMerge,ermshiperete/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge,sillsdev/LfMerge
src/LfMerge.Core/FieldWorks/ConsoleFdoUi.cs
src/LfMerge.Core/FieldWorks/ConsoleFdoUi.cs
// Copyright (c) 2016 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.ComponentModel; using SIL.FieldWorks.FDO; namespace LfMerge.Core.FieldWorks { class ConsoleFdoUi: IFdoUI { private ISynchronizeInvoke _synchronizeInvoke; public ConsoleFdoUi(ISynchronizeInvoke synchronizeInvoke) { _synchronizeInvoke = synchronizeInvoke; } #region IFdoUI implementation public void DisplayCircularRefBreakerReport(string msg, string caption) { MainClass.Logger.Warning(msg); } public bool ConflictingSave() { MainClass.Logger.Error("ConsoleFdoUI.ConflictingSave..."); // Revert to saved state return true; } public bool ConnectionLost() { throw new NotImplementedException(); } public FileSelection ChooseFilesToUse() { throw new NotImplementedException(); } public bool RestoreLinkedFilesInProjectFolder() { throw new NotImplementedException(); } public YesNoCancel CannotRestoreLinkedFilesToOriginalLocation() { throw new NotImplementedException(); } public void DisplayMessage(MessageType type, string message, string caption, string helpTopic) { MainClass.Logger.Warning("{0}: {1}", type, message); } public void ReportException(Exception error, bool isLethal) { MainClass.Logger.Warning("Got exception: {0}: {1}\n{2}", error.GetType(), error.Message, error); } public void ReportDuplicateGuids(string errorText) { MainClass.Logger.Warning("Duplicate GUIDs: " + errorText); } public bool Retry(string msg, string caption) { Console.WriteLine(msg); return true; } public bool OfferToRestore(string projectPath, string backupPath) { return false; } public void Exit() { MainClass.Logger.Debug("Exiting"); } public ISynchronizeInvoke SynchronizeInvoke { get { return _synchronizeInvoke; } } public DateTime LastActivityTime { get { return DateTime.Now; } } #endregion } }
// Copyright (c) 2016 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.ComponentModel; using SIL.FieldWorks.FDO; namespace LfMerge.Core.FieldWorks { class ConsoleFdoUi: IFdoUI { private ISynchronizeInvoke _synchronizeInvoke; public ConsoleFdoUi(ISynchronizeInvoke synchronizeInvoke) { _synchronizeInvoke = synchronizeInvoke; } #region IFdoUI implementation public void DisplayCircularRefBreakerReport(string msg, string caption) { MainClass.Logger.Warning(msg); } public bool ConflictingSave() { MainClass.Logger.Error("ConsoleFdoUI.ConflictingSave..."); // Revert to saved state return true; } public bool ConnectionLost() { throw new NotImplementedException(); } public FileSelection ChooseFilesToUse() { throw new NotImplementedException(); } public bool RestoreLinkedFilesInProjectFolder() { throw new NotImplementedException(); } public YesNoCancel CannotRestoreLinkedFilesToOriginalLocation() { throw new NotImplementedException(); } public void DisplayMessage(MessageType type, string message, string caption, string helpTopic) { MainClass.Logger.Warning("{0}: {1}", type, message); } public void ReportException(Exception error, bool isLethal) { MainClass.Logger.Warning("Got exception: {0}: {1}\n{2}", error.GetType(), error.Message, error); } public void ReportDuplicateGuids(string errorText) { MainClass.Logger.Warning("Duplicate GUIDs: " + errorText); } public bool Retry(string msg, string caption) { Console.WriteLine(msg); return true; } public bool OfferToRestore(string projectPath, string backupPath) { throw new NotImplementedException(); } public void Exit() { MainClass.Logger.Debug("Exiting"); } public ISynchronizeInvoke SynchronizeInvoke { get { return _synchronizeInvoke; } } public DateTime LastActivityTime { get { return DateTime.Now; } } #endregion } }
mit
C#
eb344b46af1f0d8aa0b2729a1c7a9b35e62f96cf
Allow empty bodies on url encoded form data.
mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy
src/Manos/Manos.Http/HttpFormDataHandler.cs
src/Manos/Manos.Http/HttpFormDataHandler.cs
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // 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.Text; using Manos.Collections; namespace Manos.Http { public class HttpFormDataHandler : IHttpBodyHandler { private enum State { InKey, InValue, } private State state; private StringBuilder key_buffer = new StringBuilder (); private StringBuilder value_buffer = new StringBuilder (); public void HandleData (HttpEntity entity, ByteBuffer data, int pos, int len) { string str_data = entity.ContentEncoding.GetString (data.Bytes, pos, len); str_data = HttpUtility.HtmlDecode (str_data); pos = 0; len = str_data.Length; while (pos < len) { char c = str_data [pos++]; if (c == '&') { if (state == State.InKey) throw new InvalidOperationException ("& symbol can not be used in key data."); FinishPair (entity); state = State.InKey; continue; } if (c == '=') { if (state == State.InValue) throw new InvalidOperationException ("= symbol can not be used in value data."); state = State.InValue; continue; } switch (state) { case State.InKey: key_buffer.Append (c); break; case State.InValue: value_buffer.Append (c); break; } } } public void Finish (HttpEntity entity) { if (state == State.InKey && key_buffer.Length > 0) throw new HttpException ("Malformed POST data, key found without value."); FinishPair (entity); } private void FinishPair (HttpEntity entity) { if (key_buffer.Length == 0) throw new HttpException ("zero length key in www-form data."); Encoding e = entity.ContentEncoding; entity.PostData.Set (HttpUtility.UrlDecode (key_buffer.ToString (), e), HttpUtility.UrlDecode (value_buffer.ToString (), e)); key_buffer.Clear (); value_buffer.Clear (); } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com) // // 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.Text; using Manos.Collections; namespace Manos.Http { public class HttpFormDataHandler : IHttpBodyHandler { private enum State { InKey, InValue, } private State state; private StringBuilder key_buffer = new StringBuilder (); private StringBuilder value_buffer = new StringBuilder (); public void HandleData (HttpEntity entity, ByteBuffer data, int pos, int len) { string str_data = entity.ContentEncoding.GetString (data.Bytes, pos, len); str_data = HttpUtility.HtmlDecode (str_data); pos = 0; len = str_data.Length; while (pos < len) { char c = str_data [pos++]; if (c == '&') { if (state == State.InKey) throw new InvalidOperationException ("& symbol can not be used in key data."); FinishPair (entity); state = State.InKey; continue; } if (c == '=') { if (state == State.InValue) throw new InvalidOperationException ("= symbol can not be used in value data."); state = State.InValue; continue; } switch (state) { case State.InKey: key_buffer.Append (c); break; case State.InValue: value_buffer.Append (c); break; } } } public void Finish (HttpEntity entity) { if (state == State.InKey) throw new HttpException ("Malformed POST data, key found without value."); FinishPair (entity); } private void FinishPair (HttpEntity entity) { if (key_buffer.Length == 0) throw new HttpException ("zero length key in www-form data."); Encoding e = entity.ContentEncoding; entity.PostData.Set (HttpUtility.UrlDecode (key_buffer.ToString (), e), HttpUtility.UrlDecode (value_buffer.ToString (), e)); key_buffer.Clear (); value_buffer.Clear (); } } }
mit
C#
3f163237938da3f2a4c77dc8bba9c124ca78cfce
Update TiledObject.cs
prime31/Nez,prime31/Nez,eumario/Nez,prime31/Nez,ericmbernier/Nez,Blucky87/Nez
Nez-PCL/PipelineRuntime/Tiled/TiledObject.cs
Nez-PCL/PipelineRuntime/Tiled/TiledObject.cs
using System; using Microsoft.Xna.Framework; using System.Collections.Generic; namespace Nez.Tiled { public class TiledObject { public enum TiledObjectType { None, Ellipse, Image, Polygon, Polyline } public int gid; public string name; public string type; public int x; public int y; public int width; public int height; public int rotation; public bool visible; public TiledObjectType tiledObjectType; public string objectType; public Vector2[] polyPoints; public Dictionary<string,string> properties = new Dictionary<string,string>(); /// <summary> /// wraps the x/y fields in a Vector /// </summary> public Vector2 position { get { return new Vector2( x, y ); } set { x = (int)value.X; y = (int)value.Y; } } } }
using System; using Microsoft.Xna.Framework; using System.Collections.Generic; namespace Nez.Tiled { public class TiledObject { public enum TiledObjectType { None, Ellipse, Image, Polygon, Polyline } public int gid; public string name; public string type; public int x; public int y; public int width; public int height; public int rotation; public bool visible; public TiledObjectType tiledObjectType; public string objectType; public Vector2[] polyPoints; public Dictionary<string,string> properties = new Dictionary<string,string>(); public Vector2 position { get { return new Vector2(x, y); } set { x = (int)value.X; y = (int)value.Y; } } public TiledObject() {} } }
mit
C#
831ca4db338bc772b83a47413a8090be89266dd5
Add .bif to list of supported extensions.
quamotion/discutils,breezechen/DiscUtils,drebrez/DiscUtils,breezechen/DiscUtils
src/Raw/DiskFactory.cs
src/Raw/DiskFactory.cs
// // Copyright (c) 2008-2010, Kenneth Bell // // 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. // namespace DiscUtils.Raw { using System; using System.Collections.Generic; using System.IO; [VirtualDiskFactory("RAW", ".img,.ima,.vfd,.flp,.bif")] internal sealed class DiskFactory : VirtualDiskFactory { public override string[] Variants { get { return new string[] { }; } } public override DiskImageBuilder GetImageBuilder(string variant) { throw new NotSupportedException(); } public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters) { return Disk.Initialize(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, capacity, geometry); } public override VirtualDisk OpenDisk(string path, FileAccess access) { return new Disk(path, access); } public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access) { FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None; return new Disk(locator.Open(path, FileMode.Open, access, share), Ownership.Dispose); } public override VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access) { return null; } } }
// // Copyright (c) 2008-2010, Kenneth Bell // // 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. // namespace DiscUtils.Raw { using System; using System.Collections.Generic; using System.IO; [VirtualDiskFactory("RAW", ".img,.ima,.vfd,.flp")] internal sealed class DiskFactory : VirtualDiskFactory { public override string[] Variants { get { return new string[] { }; } } public override DiskImageBuilder GetImageBuilder(string variant) { throw new NotSupportedException(); } public override VirtualDisk CreateDisk(FileLocator locator, string variant, string path, long capacity, Geometry geometry, Dictionary<string, string> parameters) { return Disk.Initialize(locator.Open(path, FileMode.Create, FileAccess.ReadWrite, FileShare.None), Ownership.Dispose, capacity, geometry); } public override VirtualDisk OpenDisk(string path, FileAccess access) { return new Disk(path, access); } public override VirtualDisk OpenDisk(FileLocator locator, string path, FileAccess access) { FileShare share = access == FileAccess.Read ? FileShare.Read : FileShare.None; return new Disk(locator.Open(path, FileMode.Open, access, share), Ownership.Dispose); } public override VirtualDiskLayer OpenDiskLayer(FileLocator locator, string path, FileAccess access) { return null; } } }
mit
C#
6915240b5d17ef2b9d563f7d8a520fef267a3be6
Remove sample data
gmrukwa/da_project
Da/Services/DataService.cs
Da/Services/DataService.cs
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Backend.Entities; using Backend.Utils; namespace Da.Services { class DataService { public IEnumerable<T> GetData<T>() where T: Entity { using (var context = new Context()) { return context.Get<T>(); } } public IEnumerable<T> GetData<T>(Context context) where T : Entity { return context.Get<T>(); } // @gmrukwa: This one is useful for downloading lazily fetched deps public void GetData<T>(Action<DbSet<T>, Exception> callback) where T : Entity { using (var context = new Context()) { try { callback(context.Get<T>(), null); } catch (Exception ex) { callback(null, ex); } } } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using Backend.Entities; using Backend.Utils; namespace Da.Services { class DataService { public DataService(bool startFromScratch = false) { if (startFromScratch) BuildSampleDatabasePopulation(); } public IEnumerable<T> GetData<T>() where T: Entity { using (var context = new Context()) { return context.Get<T>(); } } public IEnumerable<T> GetData<T>(Context context) where T : Entity { return context.Get<T>(); } // @gmrukwa: This one is useful for downloading lazily fetched deps public void GetData<T>(Action<DbSet<T>, Exception> callback) where T : Entity { using (var context = new Context()) { try { callback(context.Get<T>(), null); } catch (Exception ex) { callback(null, ex); } } } private void BuildSampleDatabasePopulation() { using (var context = new Context()) { context.Database.Delete(); var site = new Site() { Address = "Somewhere", Name = "Site 1" }; context.Sites.Add(site); context.SaveChanges(); var employee1 = new Employee() { BirthDate = DateTime.Today, EmploymentDate = DateTime.Today, Name = "Jacek Bajer", Position = "Nikt", Site = site }; site.Boss = employee1; context.Employees.Add(employee1); context.SaveChanges(); var employee2 = new Employee() { BirthDate = DateTime.Today, EmploymentDate = DateTime.Today, Name = "Andriej Dudeł", Position = "Pachołek", Site = site }; context.Employees.Add(employee2); context.SaveChanges(); var project = new Project() { Description = "No one does a duck here.", Name="A project", Manager = employee1, StartDate = DateTime.Today }; context.Projects.Add(project); context.SaveChanges(); var vacation = new Vacation() { BeginningDate = DateTime.Today + TimeSpan.FromDays(1), EndDate = DateTime.Today + TimeSpan.FromDays(10), Employee = employee1 }; context.Vacations.Add(vacation); context.SaveChanges(); var salary = new Salary() { Amount = 0, Date = DateTime.Today, Employee = employee2, Paid = false, Project = project }; context.Salaries.Add(salary); context.SaveChanges(); } } } }
apache-2.0
C#
e224c969db8164b502f97dd1fb0a5acc286f1e40
Change Sample application namespace
alexandrnikitin/Topshelf.Autofac
Topshelf.Autofac.Sample/Program.cs
Topshelf.Autofac.Sample/Program.cs
using System; using Autofac; using Topshelf; using Topshelf.Autofac; namespace SampleProgram { class Program { static void Main(string[] args) { // Create your container var builder = new ContainerBuilder(); builder.RegisterType<SampleDependency>().As<ISampleDependency>(); builder.RegisterType<SampleService>(); var container = builder.Build(); HostFactory.Run(c => { // Pass it to Topshelf c.UseAutofacContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingAutofacContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } } }
using System; using Autofac; namespace Topshelf.Autofac.Sample { class Program { static void Main(string[] args) { // Create your container var builder = new ContainerBuilder(); builder.RegisterType<SampleDependency>().As<ISampleDependency>(); builder.RegisterType<SampleService>(); var container = builder.Build(); HostFactory.Run(c => { // Pass it to Topshelf c.UseAutofacContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingAutofacContainer(); s.WhenStarted((service, control) => service.Start()); s.WhenStopped((service, control) => service.Stop()); }); }); } public class SampleService { private readonly ISampleDependency _sample; public SampleService(ISampleDependency sample) { _sample = sample; } public bool Start() { Console.WriteLine("Sample Service Started."); Console.WriteLine("Sample Dependency: {0}", _sample); return _sample != null; } public bool Stop() { return _sample != null; } } public interface ISampleDependency { } public class SampleDependency : ISampleDependency { } } }
mit
C#
d6bc72390ecae791bb9feedd7d4efccd6cdacf0c
Make EnRu map public.
eealeivan/jozh-translit
Src/JoZhTranslit/TransliterationMaps/EnRu.cs
Src/JoZhTranslit/TransliterationMaps/EnRu.cs
namespace JoZhTranslit.TransliterationMaps { public class EnRu { public const string MapJson = @" { ""А"": [""A""], ""а"": [""a""], ""Б"": [""B""], ""б"": [""b""], ""В"": [""V""], ""в"": [""v""], ""Г"": [""G""], ""г"": [""g""], ""Д"": [""D""], ""д"": [""d""], ""Е"": [""E""], ""е"": [""e""], ""Ё"": [""Jo"", ""Yo""], ""ё"": [""jo"", ""yo""], ""Ж"": [""Zh""], ""ж"": [""zh""], ""З"": [""Z""], ""з"": [""z""], ""И"": [""I""], ""и"": [""i""], ""Й"": [""J""], ""й"": [""j""], ""К"": [""K""], ""к"": [""k""], ""Л"": [""L""], ""л"": [""l""], ""М"": [""M""], ""м"": [""m""], ""Н"": [""N""], ""н"": [""n""], ""О"": [""O""], ""о"": [""o""], ""П"": [""P""], ""п"": [""p""], ""Р"": [""R""], ""р"": [""r""], ""С"": [""S""], ""с"": [""s""], ""Т"": [""T""], ""т"": [""t""], ""У"": [""U""], ""у"": [""u""], ""Ф"": [""F""], ""ф"": [""f""], ""Х"": [""H"", ""X""], ""х"": [""h"", ""x""], ""Ц"": [""C""], ""ц"": [""c""], ""Ч"": [""Ch""], ""ч"": [""ch""], ""Ш"": [""Sh""], ""ш"": [""sh""], ""Щ"": [""Shh"", ""W""], ""щ"": [""shh"", ""w""], ""Ъ"": [""##""], ""ъ"": [""#""], ""Ы"": [""Y""], ""ы"": [""y""], ""Ь"": [""''""], ""ь"": [""'""], ""Э"": [""Je""], ""э"": [""je""], ""Ю"": [""Ju""], ""ю"": [""ju""], ""Я"": [""Ja""], ""я"": [""ja""] } "; } }
namespace JoZhTranslit.TransliterationMaps { internal class EnRu { public const string MapJson = @" { ""А"": [""A""], ""а"": [""a""], ""Б"": [""B""], ""б"": [""b""], ""В"": [""V""], ""в"": [""v""], ""Г"": [""G""], ""г"": [""g""], ""Д"": [""D""], ""д"": [""d""], ""Е"": [""E""], ""е"": [""e""], ""Ё"": [""Jo"", ""Yo""], ""ё"": [""jo"", ""yo""], ""Ж"": [""Zh""], ""ж"": [""zh""], ""З"": [""Z""], ""з"": [""z""], ""И"": [""I""], ""и"": [""i""], ""Й"": [""J""], ""й"": [""j""], ""К"": [""K""], ""к"": [""k""], ""Л"": [""L""], ""л"": [""l""], ""М"": [""M""], ""м"": [""m""], ""Н"": [""N""], ""н"": [""n""], ""О"": [""O""], ""о"": [""o""], ""П"": [""P""], ""п"": [""p""], ""Р"": [""R""], ""р"": [""r""], ""С"": [""S""], ""с"": [""s""], ""Т"": [""T""], ""т"": [""t""], ""У"": [""U""], ""у"": [""u""], ""Ф"": [""F""], ""ф"": [""f""], ""Х"": [""H"", ""X""], ""х"": [""h"", ""x""], ""Ц"": [""C""], ""ц"": [""c""], ""Ч"": [""Ch""], ""ч"": [""ch""], ""Ш"": [""Sh""], ""ш"": [""sh""], ""Щ"": [""Shh"", ""W""], ""щ"": [""shh"", ""w""], ""Ъ"": [""##""], ""ъ"": [""#""], ""Ы"": [""Y""], ""ы"": [""y""], ""Ь"": [""''""], ""ь"": [""'""], ""Э"": [""Je""], ""э"": [""je""], ""Ю"": [""Ju""], ""ю"": [""ju""], ""Я"": [""Ja""], ""я"": [""ja""] } "; } }
mit
C#
c86a4b56d4fa56123a592aa732d0548bc7df1850
Use NSBundle for iOS devices (#1146)
Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet
Shared/Tests.Shared/TestHelpers.cs
Shared/Tests.Shared/TestHelpers.cs
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.IO; using Realms; namespace IntegrationTests { public static class TestHelpers { public static object GetPropertyValue(object o, string propName) { return o.GetType().GetProperty(propName).GetValue(o, null); } public static void SetPropertyValue(object o, string propName, object propertyValue) { o.GetType().GetProperty(propName).SetValue(o, propertyValue); } public static T GetPropertyValue<T>(this object obj, string propertyName) { return (T)GetPropertyValue(obj, propertyName); } public static void CopyBundledDatabaseToDocuments(string realmName, string destPath = null, bool overwrite = true) { destPath = RealmConfigurationBase.GetPathToRealm(destPath); // any relative subdir or filename works #if __ANDROID__ using (var asset = Android.App.Application.Context.Assets.Open(realmName)) using (var destination = File.OpenWrite(destPath)) { asset.CopyTo(destination); } return; #endif #if __IOS__ var sourceDir = Foundation.NSBundle.MainBundle.BundlePath; #else var sourceDir = NUnit.Framework.TestContext.CurrentContext.TestDirectory; #endif File.Copy(Path.Combine(sourceDir, realmName), destPath, overwrite); } } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.IO; using Realms; namespace IntegrationTests { public static class TestHelpers { public static object GetPropertyValue(object o, string propName) { return o.GetType().GetProperty(propName).GetValue(o, null); } public static void SetPropertyValue(object o, string propName, object propertyValue) { o.GetType().GetProperty(propName).SetValue(o, propertyValue); } public static T GetPropertyValue<T>(this object obj, string propertyName) { return (T)GetPropertyValue(obj, propertyName); } public static void CopyBundledDatabaseToDocuments(string realmName, string destPath = null, bool overwrite = true) { destPath = RealmConfigurationBase.GetPathToRealm(destPath); // any relative subdir or filename works #if __ANDROID__ using (var asset = Android.App.Application.Context.Assets.Open(realmName)) using (var destination = File.OpenWrite(destPath)) { asset.CopyTo(destination); } return; #endif var sourceDir = NUnit.Framework.TestContext.CurrentContext.TestDirectory; File.Copy(Path.Combine(sourceDir, realmName), destPath, overwrite); } } }
apache-2.0
C#
d822565be8e4c18f3eede0ac016ae6457fec9019
Update RenameRequest.cs
Ar3sDevelopment/Synology,DotNetDevs/Synology,DotNetDevs/Synology
Synology.FileStation/Rename/RenameRequest.cs
Synology.FileStation/Rename/RenameRequest.cs
using Synology.Attributes; using Synology.Classes; using Synology.FileStation.FileShare.Results; using Synology.FileStation.Rename.Parameters; using Synology.Parameters; namespace Synology.FileStation.Rename { public class RenameRequest : FileStationRequest { public RenameRequest(SynologyApi api) : base(api, "Rename") { } /// <summary> /// Rename a file/folder /// </summary> /// <param name="parameters"></param> /// <returns></returns> [RequestMethod("rename")] public ResultData<FileResult> Rename(RenameParameters parameters) { return GetData<FileResult>(new SynologyRequestParameters { Version = 2, Method = "rename", Additional = parameters }); } } }
using Synology.Classes; using Synology.FileStation.FileShare.Results; using Synology.FileStation.Rename.Parameters; using Synology.Parameters; namespace Synology.FileStation.Rename { public class RenameRequest : FileStationRequest { public RenameRequest(SynologyApi api) : base(api, "Rename") { } /// <summary> /// Rename a file/folder /// </summary> /// <param name="parameters"></param> /// <returns></returns> [RequestMethod("rename")] public ResultData<FileResult> Rename(RenameParameters parameters) { return GetData<FileResult>(new SynologyRequestParameters { Version = 2, Method = "rename", Additional = parameters }); } } }
apache-2.0
C#
ec8a84e54d6b2d43eb190ab57c51654c2f972dce
Fix #738 : Sickbay module stuck in invalid state when disabled through unloaded automation
PiezPiedPy/Kerbalism,PiezPiedPy/Kerbalism,PiezPiedPy/Kerbalism
src/Kerbalism/Automation/Devices/Sickbay.cs
src/Kerbalism/Automation/Devices/Sickbay.cs
using System; using System.Collections.Generic; using UnityEngine; using KSP.Localization; namespace KERBALISM { public sealed class SickbayDevice : LoadedDevice<Sickbay> { public SickbayDevice(Sickbay module) : base(module) { } public override string Status => Lib.Color(module.running, Local.Generic_RUNNING, Lib.Kolor.Green, Local.Generic_STOPPED, Lib.Kolor.Yellow); public override void Ctrl(bool value) { module.running = value; } public override void Toggle() { Ctrl(!module.running); } public override bool IsVisible => module.slots > 0; } public sealed class ProtoSickbayDevice : ProtoDevice<Sickbay> { public ProtoSickbayDevice(Sickbay prefab, ProtoPartSnapshot protoPart, ProtoPartModuleSnapshot protoModule) : base(prefab, protoPart, protoModule) { } public override string Status => Lib.Color(Lib.Proto.GetBool(protoModule, "running"), Local.Generic_RUNNING, Lib.Kolor.Green, Local.Generic_STOPPED, Lib.Kolor.Yellow); public override void Ctrl(bool value) { Lib.Proto.Set(protoModule, "running", value); } public override void Toggle() { Ctrl(!Lib.Proto.GetBool(protoModule, "running")); } public override bool IsVisible => Lib.Proto.GetUInt(protoModule, "slots", 0) > 0; } } // KERBALISM
using System; using System.Collections.Generic; using UnityEngine; using KSP.Localization; namespace KERBALISM { public sealed class SickbayDevice : LoadedDevice<Sickbay> { public SickbayDevice(Sickbay module) : base(module) { } public override string Status => Lib.Color(module.running, Local.Generic_RUNNING, Lib.Kolor.Green, Local.Generic_STOPPED, Lib.Kolor.Yellow); public override void Ctrl(bool value) { module.running = value; } public override void Toggle() { Ctrl(!module.running); } public override bool IsVisible => module.slots > 0; } public sealed class ProtoSickbayDevice : ProtoDevice<Sickbay> { public ProtoSickbayDevice(Sickbay prefab, ProtoPartSnapshot protoPart, ProtoPartModuleSnapshot protoModule) : base(prefab, protoPart, protoModule) { } public override string Status => Lib.Color(Lib.Proto.GetBool(protoModule, "running"), Local.Generic_RUNNING, Lib.Kolor.Green, Local.Generic_STOPPED, Lib.Kolor.Yellow); public override void Ctrl(bool value) { Lib.Proto.Set(protoModule, "running", value); protoPart.resources.Find(k => k.resourceName == prefab.resource).flowState = value; } public override void Toggle() { Ctrl(!Lib.Proto.GetBool(protoModule, "running")); } public override bool IsVisible => Lib.Proto.GetUInt(protoModule, "slots", 0) > 0; } } // KERBALISM
unlicense
C#
a777b33646a2da09206d1b3f57cf592e4b672c90
Remove SingleRankNonSZArrayIndexed test.
ViktorHofer/corefx,yizhang82/corefx,alexperovich/corefx,ericstj/corefx,richlander/corefx,mmitche/corefx,ViktorHofer/corefx,Petermarcu/corefx,ericstj/corefx,rahku/corefx,dotnet-bot/corefx,krk/corefx,MaggieTsang/corefx,MaggieTsang/corefx,jlin177/corefx,mmitche/corefx,the-dwyer/corefx,JosephTremoulet/corefx,krk/corefx,Ermiar/corefx,Petermarcu/corefx,fgreinacher/corefx,weltkante/corefx,twsouthwick/corefx,dotnet-bot/corefx,BrennanConroy/corefx,nbarbettini/corefx,DnlHarvey/corefx,ViktorHofer/corefx,ravimeda/corefx,rjxby/corefx,Ermiar/corefx,jlin177/corefx,rahku/corefx,elijah6/corefx,tijoytom/corefx,krk/corefx,tijoytom/corefx,mmitche/corefx,zhenlan/corefx,Jiayili1/corefx,ViktorHofer/corefx,DnlHarvey/corefx,richlander/corefx,nbarbettini/corefx,billwert/corefx,BrennanConroy/corefx,elijah6/corefx,ravimeda/corefx,Ermiar/corefx,ericstj/corefx,gkhanna79/corefx,richlander/corefx,seanshpark/corefx,the-dwyer/corefx,ericstj/corefx,rahku/corefx,alexperovich/corefx,richlander/corefx,elijah6/corefx,zhenlan/corefx,Jiayili1/corefx,parjong/corefx,the-dwyer/corefx,nchikanov/corefx,yizhang82/corefx,DnlHarvey/corefx,parjong/corefx,mmitche/corefx,krytarowski/corefx,billwert/corefx,ravimeda/corefx,zhenlan/corefx,zhenlan/corefx,stephenmichaelf/corefx,nchikanov/corefx,Jiayili1/corefx,stone-li/corefx,richlander/corefx,twsouthwick/corefx,krk/corefx,billwert/corefx,the-dwyer/corefx,fgreinacher/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,rahku/corefx,ptoonen/corefx,Petermarcu/corefx,JosephTremoulet/corefx,fgreinacher/corefx,dhoehna/corefx,stephenmichaelf/corefx,yizhang82/corefx,billwert/corefx,stone-li/corefx,krk/corefx,MaggieTsang/corefx,ericstj/corefx,cydhaselton/corefx,elijah6/corefx,jlin177/corefx,stone-li/corefx,shimingsg/corefx,ravimeda/corefx,ptoonen/corefx,nchikanov/corefx,dotnet-bot/corefx,rjxby/corefx,wtgodbe/corefx,cydhaselton/corefx,seanshpark/corefx,Jiayili1/corefx,gkhanna79/corefx,Ermiar/corefx,wtgodbe/corefx,weltkante/corefx,gkhanna79/corefx,zhenlan/corefx,shimingsg/corefx,stone-li/corefx,cydhaselton/corefx,elijah6/corefx,rahku/corefx,yizhang82/corefx,weltkante/corefx,rjxby/corefx,axelheer/corefx,dotnet-bot/corefx,twsouthwick/corefx,dotnet-bot/corefx,nbarbettini/corefx,ViktorHofer/corefx,rubo/corefx,JosephTremoulet/corefx,Ermiar/corefx,yizhang82/corefx,axelheer/corefx,zhenlan/corefx,gkhanna79/corefx,YoupHulsebos/corefx,ptoonen/corefx,fgreinacher/corefx,axelheer/corefx,ptoonen/corefx,billwert/corefx,stone-li/corefx,rjxby/corefx,krk/corefx,wtgodbe/corefx,ravimeda/corefx,mmitche/corefx,tijoytom/corefx,wtgodbe/corefx,the-dwyer/corefx,billwert/corefx,nchikanov/corefx,YoupHulsebos/corefx,yizhang82/corefx,wtgodbe/corefx,rubo/corefx,seanshpark/corefx,Ermiar/corefx,DnlHarvey/corefx,yizhang82/corefx,dhoehna/corefx,nchikanov/corefx,stephenmichaelf/corefx,weltkante/corefx,dotnet-bot/corefx,elijah6/corefx,mazong1123/corefx,the-dwyer/corefx,mazong1123/corefx,jlin177/corefx,mazong1123/corefx,dhoehna/corefx,stephenmichaelf/corefx,rubo/corefx,stone-li/corefx,seanshpark/corefx,rjxby/corefx,ViktorHofer/corefx,mazong1123/corefx,parjong/corefx,Jiayili1/corefx,YoupHulsebos/corefx,alexperovich/corefx,the-dwyer/corefx,Petermarcu/corefx,dhoehna/corefx,wtgodbe/corefx,gkhanna79/corefx,seanshpark/corefx,YoupHulsebos/corefx,rahku/corefx,tijoytom/corefx,nbarbettini/corefx,stephenmichaelf/corefx,jlin177/corefx,ptoonen/corefx,alexperovich/corefx,cydhaselton/corefx,MaggieTsang/corefx,tijoytom/corefx,nchikanov/corefx,DnlHarvey/corefx,ptoonen/corefx,mazong1123/corefx,Petermarcu/corefx,jlin177/corefx,Jiayili1/corefx,JosephTremoulet/corefx,parjong/corefx,JosephTremoulet/corefx,parjong/corefx,YoupHulsebos/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,Ermiar/corefx,MaggieTsang/corefx,DnlHarvey/corefx,gkhanna79/corefx,mazong1123/corefx,shimingsg/corefx,richlander/corefx,weltkante/corefx,Petermarcu/corefx,dhoehna/corefx,cydhaselton/corefx,twsouthwick/corefx,jlin177/corefx,axelheer/corefx,alexperovich/corefx,krytarowski/corefx,seanshpark/corefx,krytarowski/corefx,krytarowski/corefx,axelheer/corefx,BrennanConroy/corefx,dhoehna/corefx,richlander/corefx,twsouthwick/corefx,stephenmichaelf/corefx,zhenlan/corefx,billwert/corefx,krk/corefx,seanshpark/corefx,wtgodbe/corefx,shimingsg/corefx,krytarowski/corefx,mazong1123/corefx,MaggieTsang/corefx,weltkante/corefx,YoupHulsebos/corefx,twsouthwick/corefx,MaggieTsang/corefx,elijah6/corefx,krytarowski/corefx,rjxby/corefx,JosephTremoulet/corefx,dhoehna/corefx,shimingsg/corefx,stone-li/corefx,parjong/corefx,nbarbettini/corefx,ravimeda/corefx,shimingsg/corefx,mmitche/corefx,tijoytom/corefx,weltkante/corefx,Jiayili1/corefx,nbarbettini/corefx,twsouthwick/corefx,gkhanna79/corefx,nchikanov/corefx,parjong/corefx,ptoonen/corefx,ericstj/corefx,rahku/corefx,dotnet-bot/corefx,tijoytom/corefx,rubo/corefx,alexperovich/corefx,YoupHulsebos/corefx,mmitche/corefx,nbarbettini/corefx,Petermarcu/corefx,ravimeda/corefx,alexperovich/corefx,cydhaselton/corefx,krytarowski/corefx,DnlHarvey/corefx,rubo/corefx,axelheer/corefx,cydhaselton/corefx,rjxby/corefx
src/Microsoft.CSharp/tests/ArrayHandling.cs
src/Microsoft.CSharp/tests/ArrayHandling.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Microsoft.CSharp.RuntimeBinder.Tests { public class ArrayHandling { [Fact] public void SingleRankNonSZArray() { dynamic d = Array.CreateInstance(typeof(int), new[] { 8 }, new[] { -2 }); d.SetValue(32, 3); d.SetValue(28, -1); Assert.Equal(32, d.GetValue(3)); Assert.Equal(28, d.GetValue(-1)); } [Fact] public void ArrayTypeNames() { dynamic d = Array.CreateInstance(typeof(int), new[] { 8 }, new[] { -2 }); RuntimeBinderException ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[*]", ex.Message); d = new int[3]; ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[]", ex.Message); d = new int[3, 2, 1]; ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[,,]", ex.Message); d = Array.CreateInstance(typeof(int), new[] { 3, 2, 1 }, new[] { -2, 2, -0 }); ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[,,]", ex.Message); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Microsoft.CSharp.RuntimeBinder.Tests { public class ArrayHandling { [Fact] public void SingleRankNonSZArray() { dynamic d = Array.CreateInstance(typeof(int), new[] { 8 }, new[] { -2 }); d.SetValue(32, 3); d.SetValue(28, -1); Assert.Equal(32, d.GetValue(3)); Assert.Equal(28, d.GetValue(-1)); } [Fact] public void SingleRankNonSZArrayIndexed() { dynamic d = Array.CreateInstance(typeof(int), new[] { 8 }, new[] { -2 }); d[3] = 32; d[-1] = 28; Assert.Equal(32, d[3]); Assert.Equal(28, d[-1]); } [Fact] public void ArrayTypeNames() { dynamic d = Array.CreateInstance(typeof(int), new[] { 8 }, new[] { -2 }); RuntimeBinderException ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[*]", ex.Message); d = new int[3]; ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[]", ex.Message); d = new int[3, 2, 1]; ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[,,]", ex.Message); d = Array.CreateInstance(typeof(int), new[] { 3, 2, 1 }, new[] { -2, 2, -0 }); ex = Assert.Throws<RuntimeBinderException>(() => { string s = d; }); Assert.Contains("int[,,]", ex.Message); } } }
mit
C#
8e5e5d4ebcd646f8fd0196c2e7feae3074e72d36
Fix samples
NRules/NRules
samples/ClaimsAdjudication/ClaimsExpert.Service/Infrastructure/RulesEngineLogger.cs
samples/ClaimsAdjudication/ClaimsExpert.Service/Infrastructure/RulesEngineLogger.cs
using Common.Logging; using NRules.Diagnostics; namespace NRules.Samples.ClaimsExpert.Service.Infrastructure { internal class RulesEngineLogger { private static readonly ILog Log = LogManager.GetLogger<RulesEngineLogger>(); public RulesEngineLogger(ISessionFactory sessionFactory) { sessionFactory.Events.RuleFiredEvent += OnRuleFired; sessionFactory.Events.ConditionFailedEvent += OnConditionFailedEvent; sessionFactory.Events.ActionFailedEvent += OnActionFailedEvent; } private void OnRuleFired(object sender, AgendaEventArgs args) { Log.InfoFormat("Rule fired. Rule={0}", args.Rule.Name); } private void OnConditionFailedEvent(object sender, ConditionErrorEventArgs args) { Log.ErrorFormat("Condition evaluation failed. Condition={0}, Message={1}", args.Expression, args.Exception); } private void OnActionFailedEvent(object sender, ActionErrorEventArgs args) { Log.ErrorFormat("Action evaluation failed. Action={0}, Message={1}", args.Expression, args.Exception); } } }
using Common.Logging; using NRules.Diagnostics; namespace NRules.Samples.ClaimsExpert.Service.Infrastructure { internal class RulesEngineLogger { private static readonly ILog Log = LogManager.GetLogger<RulesEngineLogger>(); public RulesEngineLogger(ISessionFactory sessionFactory) { sessionFactory.Events.RuleFiredEvent += OnRuleFired; sessionFactory.Events.ConditionFailedEvent += OnConditionFailedEvent; sessionFactory.Events.ActionFailedEvent += OnActionFailedEvent; } private void OnRuleFired(object sender, AgendaEventArgs args) { Log.InfoFormat("Rule fired. Rule={0}", args.Rule.Name); } private void OnConditionFailedEvent(object sender, ConditionErrorEventArgs args) { Log.ErrorFormat("Condition evaluation failed. Condition={0}, Message={1}", args.Condition, args.Exception); } private void OnActionFailedEvent(object sender, ActionErrorEventArgs args) { Log.ErrorFormat("Action evaluation failed. Action={0}, Message={1}", args.Action, args.Exception); } } }
mit
C#
4be8d6d5e9ef503189630ae25194944b041538e8
Update WeaverInitialiserTests.cs
Fody/Fody,GeertvanHorrik/Fody
Tests/FodyIsolated/WeaverInitialiserTests.cs
Tests/FodyIsolated/WeaverInitialiserTests.cs
using System.Collections.Generic; using System.Linq; using Fody; using Mono.Cecil; using Xunit; using Xunit.Abstractions; public class WeaverInitialiserTests : XunitLoggingBase { [Fact] public void ValidPropsFromBase() { var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll); var resolver = new MockAssemblyResolver(); var innerWeaver = BuildInnerWeaver(moduleDefinition, resolver); innerWeaver.SplitUpReferences(); var weaverEntry = new WeaverEntry { Element = "<foo/>", AssemblyPath = @"c:\FakePath\Assembly.dll" }; var moduleWeaver = new ValidFromBaseModuleWeaver(); innerWeaver.SetProperties(weaverEntry, moduleWeaver); SerializerBuilder.IgnoreMembersWithType<ModuleDefinition>(); ObjectApprover.Verify(moduleWeaver); } static InnerWeaver BuildInnerWeaver(ModuleDefinition moduleDefinition, AssemblyResolver resolver) { return new InnerWeaver { Logger = new MockBuildLogger(), AssemblyFilePath = "AssemblyFilePath", ProjectDirectoryPath = "ProjectDirectoryPath", ProjectFilePath = "ProjectFilePath", SolutionDirectoryPath = "SolutionDirectoryPath", DocumentationFilePath = "DocumentationFile", ReferenceCopyLocalPaths = new List<string> { "CopyRef1", "CopyRef2" }, References = "Ref1;Ref2", ModuleDefinition = moduleDefinition, DefineConstants = new List<string> { "Debug", "Release" }, assemblyResolver = resolver, TypeCache = new TypeCache(resolver.Resolve) }; } public WeaverInitialiserTests(ITestOutputHelper output) : base(output) { } } public class ValidFromBaseModuleWeaver : BaseModuleWeaver { public bool ExecuteCalled; public override void Execute() { ExecuteCalled = true; } public override IEnumerable<string> GetAssembliesForScanning() { return Enumerable.Empty<string>(); } }
using System.Collections.Generic; using System.Linq; using Fody; using Mono.Cecil; using ObjectApproval; using Xunit; using Xunit.Abstractions; public class WeaverInitialiserTests : XunitLoggingBase { [Fact] public void ValidPropsFromBase() { var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll); var resolver = new MockAssemblyResolver(); var innerWeaver = BuildInnerWeaver(moduleDefinition, resolver); innerWeaver.SplitUpReferences(); var weaverEntry = new WeaverEntry { Element = "<foo/>", AssemblyPath = @"c:\FakePath\Assembly.dll" }; var moduleWeaver = new ValidFromBaseModuleWeaver(); innerWeaver.SetProperties(weaverEntry, moduleWeaver); SerializerBuilder.IgnoreMembersWithType<ModuleDefinition>(); ObjectApprover.Verify(moduleWeaver); } static InnerWeaver BuildInnerWeaver(ModuleDefinition moduleDefinition, AssemblyResolver resolver) { return new InnerWeaver { Logger = new MockBuildLogger(), AssemblyFilePath = "AssemblyFilePath", ProjectDirectoryPath = "ProjectDirectoryPath", ProjectFilePath = "ProjectFilePath", SolutionDirectoryPath = "SolutionDirectoryPath", DocumentationFilePath = "DocumentationFile", ReferenceCopyLocalPaths = new List<string> { "CopyRef1", "CopyRef2" }, References = "Ref1;Ref2", ModuleDefinition = moduleDefinition, DefineConstants = new List<string> { "Debug", "Release" }, assemblyResolver = resolver, TypeCache = new TypeCache(resolver.Resolve) }; } public WeaverInitialiserTests(ITestOutputHelper output) : base(output) { } } public class ValidFromBaseModuleWeaver : BaseModuleWeaver { public bool ExecuteCalled; public override void Execute() { ExecuteCalled = true; } public override IEnumerable<string> GetAssembliesForScanning() { return Enumerable.Empty<string>(); } }
mit
C#
eff79dc7364c087f7316969c76b2aa0c3ea16254
fix test
jezzay/Test-Travis-CI,jezzay/Test-Travis-CI
TestWebApp/TestWebApp.Tests/Controllers/ValuesControllerTest.cs
TestWebApp/TestWebApp.Tests/Controllers/ValuesControllerTest.cs
using System.Collections.Generic; using System.Linq; using TestWebApp.Controllers; using Xunit; namespace TestWebApp.Tests.Controllers { public class ValuesControllerTest { [Fact] public void Get() { // Arrange var controller = new ValuesController(); // Act IEnumerable<string> result = controller.Get(); // Assert Assert.NotNull(result); Assert.Equal(2, result.Count()); Assert.Equal("value1", result.ElementAt(0)); Assert.Equal("value2", result.ElementAt(1)); } [Fact] public void GetById() { // Arrange var controller = new ValuesController(); // Act string result = controller.Get(5); // Assert Assert.Equal("value", result); } [Fact] public void Post() { // Arrange var controller = new ValuesController(); // Act controller.Post("value"); // Assert } [Fact] public void Put() { // Arrange var controller = new ValuesController(); // Act controller.Put(5, "value"); // Assert } [Fact] public void Delete() { // Arrange var controller = new ValuesController(); // Act controller.Delete(5); // Assert } } }
using System.Collections.Generic; using System.Linq; using TestWebApp.Controllers; using Xunit; namespace TestWebApp.Tests.Controllers { public class ValuesControllerTest { [Fact] public void Get() { // Arrange var controller = new ValuesController(); // Act IEnumerable<string> result = controller.Get(); // Assert Assert.NotNull(result); Assert.Equal(2, result.Count()); Assert.Equal("value1", result.ElementAt(0)); Assert.Equal("value3", result.ElementAt(1)); } [Fact] public void GetById() { // Arrange var controller = new ValuesController(); // Act string result = controller.Get(5); // Assert Assert.Equal("value", result); } [Fact] public void Post() { // Arrange var controller = new ValuesController(); // Act controller.Post("value"); // Assert } [Fact] public void Put() { // Arrange var controller = new ValuesController(); // Act controller.Put(5, "value"); // Assert } [Fact] public void Delete() { // Arrange var controller = new ValuesController(); // Act controller.Delete(5); // Assert } } }
mit
C#
122643f14315c7b4ef62296669ac9bc4d8b07089
allow multiple audiences
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Api/Startup.cs
src/SFA.DAS.EmployerAccounts.Api/Startup.cs
using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using System.Configuration; [assembly: OwinStartup(typeof(SFA.DAS.EmployerAccounts.Api.Startup))] namespace SFA.DAS.EmployerAccounts.Api { public class Startup { public void Configuration(IAppBuilder app) { _ = app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudiences = ConfigurationManager.AppSettings["idaAudience"].ToString().Split(',') } }); } } }
using Microsoft.Owin; using Microsoft.Owin.Security.ActiveDirectory; using Owin; using System.Configuration; [assembly: OwinStartup(typeof(SFA.DAS.EmployerAccounts.Api.Startup))] namespace SFA.DAS.EmployerAccounts.Api { public class Startup { public void Configuration(IAppBuilder app) { app.UseWindowsAzureActiveDirectoryBearerAuthentication(new WindowsAzureActiveDirectoryBearerAuthenticationOptions { Tenant = ConfigurationManager.AppSettings["idaTenant"], TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters { RoleClaimType = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", ValidAudience = ConfigurationManager.AppSettings["idaAudience"] } }); } } }
mit
C#
bf70cbb8648d8bd426fa9583a756431f755688e5
add trace stack in Coroutine -> resume
soulgame/slua,dayongxie/slua,pangweiwei/slua,mr-kelly/slua,DebugClub/slua,angeldnd/slua,yjpark/slua,haolly/slua_source_note,luzexi/slua-3rd-lib,luzexi/slua-3rd,lingkeyang/slua,yjpark/slua,houxuanfelix/slua,luzexi/slua-3rd-lib,thing-nacho/slua,wland/slua,pangweiwei/slua,haolly/slua_source_note,jiangzhhhh/slua,wang1986one/slua,luzexi/slua-3rd-lib,thing-nacho/slua,angeldnd/slua,pangweiwei/slua,leonardave/slua,XingHong/slua,wang1986one/slua,takaaptech/slua,lingkeyang/slua,shrimpz/slua,mr-kelly/slua,dayongxie/slua,Roland0511/slua,yaukeywang/slua-old,luzexi/slua-3rd,lingkeyang/slua,mr-kelly/slua,Salada/slua,Salada/slua,yaukeywang/slua,LacusCon/slua,yongkangchen/slua,zhukunqian/slua-1,lingkeyang/slua,yaukeywang/slua,mr-kelly/slua,chiuan/slua,soulgame/slua,chiuan/slua,yaukeywang/slua,Roland0511/slua,dayongxie/slua,yongkangchen/slua,haolly/slua_source_note,angeldnd/slua,soulgame/slua,yaukeywang/slua,luzexi/slua-3rd-lib,angeldnd/slua,soulgame/slua,yaukeywang/slua,zhukunqian/slua-1,LacusCon/slua,leonardave/slua,moto2002/slua,pangweiwei/slua,haolly/slua_source_note,thing-nacho/slua,LacusCon/slua,zhaoluxyz/slua,hlouis/slua,LacusCon/slua,luzexi/slua-3rd,slb1988/slua,hlouis/slua,DebugClub/slua,shrimpz/slua,thing-nacho/slua,thing-nacho/slua,slb1988/slua,zhukunqian/slua-1,moto2002/slua,jiangzhhhh/slua,luzexi/slua-3rd,Roland0511/slua,lingkeyang/slua,luzexi/slua-3rd,chiuan/slua,Roland0511/slua,DebugClub/slua,haolly/slua_source_note,zhaoluxyz/slua,luzexi/slua-3rd-lib,soulgame/slua,ChinaLongGanHu/slua,luzexi/slua-3rd-lib,takaaptech/slua,pangweiwei/slua,LacusCon/slua,chiuan/slua,haolly/slua_source_note,jiangzhhhh/slua,zhukunqian/slua-1,dayongxie/slua,Salada/slua,dayongxie/slua,chiuan/slua,angeldnd/slua,luzexi/slua-3rd,angeldnd/slua,wland/slua,Roland0511/slua,lyntel/slua,XingHong/slua,littleboss/slua,lingkeyang/slua,jiangzhhhh/slua,Salada/slua,littleboss/slua,DebugClub/slua,LacusCon/slua,ChinaLongGanHu/slua,yongkangchen/slua,soulgame/slua,yongkangchen/slua,jiangzhhhh/slua,chiuan/slua,mr-kelly/slua,thing-nacho/slua,Salada/slua,yaukeywang/slua-old,DebugClub/slua,zhukunqian/slua-1,Roland0511/slua,mr-kelly/slua,yongkangchen/slua,houxuanfelix/slua,DebugClub/slua,jiangzhhhh/slua,Salada/slua,lyntel/slua,yaukeywang/slua
Assets/Slua/Script/Coroutine.cs
Assets/Slua/Script/Coroutine.cs
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei siney@yeah.net // // 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 UnityEngine; using System.Collections; using LuaInterface; using SLua; using System; namespace SLua { public class LuaCoroutine : LuaObject { static MonoBehaviour mb; static public void reg(IntPtr l, MonoBehaviour m) { mb = m; reg(l, Yield, "UnityEngine"); } [MonoPInvokeCallback(typeof(LuaCSFunction))] static public int Yield(IntPtr l) { try { if (LuaDLL.lua_pushthread(l) == 1) { LuaDLL.luaL_error(l, "should put Yield call into lua coroutine."); return 0; } object y = checkObj(l, 1); Action act = () => { #if LUA_5_3 if(LuaDLL.lua_resume(l,IntPtr.Zero,0) != 0) { LuaState.errorReport(l); } #else if (LuaDLL.lua_resume(l, 0) != 0) { LuaState.errorReport(l); } #endif }; mb.StartCoroutine(yieldReturn(y, act)); #if LUA_5_3 return LuaDLL.luaS_yield(l, 0); #else return LuaDLL.lua_yield(l, 0); #endif } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public IEnumerator yieldReturn(object y, Action act) { if (y is IEnumerator) yield return mb.StartCoroutine((IEnumerator)y); else yield return y; act(); } } }
// The MIT License (MIT) // Copyright 2015 Siney/Pangweiwei siney@yeah.net // // 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 UnityEngine; using System.Collections; using LuaInterface; using SLua; using System; namespace SLua { public class LuaCoroutine : LuaObject { static MonoBehaviour mb; static public void reg(IntPtr l, MonoBehaviour m) { mb = m; reg(l, Yield, "UnityEngine"); } [MonoPInvokeCallback(typeof(LuaCSFunction))] static public int Yield(IntPtr l) { try { if (LuaDLL.lua_pushthread(l) == 1) { LuaDLL.luaL_error(l, "should put Yield call into lua coroutine."); return 0; } object y = checkObj(l, 1); Action act = () => { #if LUA_5_3 LuaDLL.lua_resume(l,IntPtr.Zero,0); #else LuaDLL.lua_resume(l, 0); #endif }; mb.StartCoroutine(yieldReturn(y, act)); #if LUA_5_3 return LuaDLL.luaS_yield(l, 0); #else return LuaDLL.lua_yield(l, 0); #endif } catch (Exception e) { LuaDLL.luaL_error(l, e.ToString()); return 0; } } static public IEnumerator yieldReturn(object y, Action act) { if (y is IEnumerator) yield return mb.StartCoroutine((IEnumerator)y); else yield return y; act(); } } }
mit
C#