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
468bd0ab7f05c7c84f2677a526e3b5b8639a6a85
Add helper method to return KeyModifier
bright-tools/DeRange
DeRange/Config/KeyboardShortcut.cs
DeRange/Config/KeyboardShortcut.cs
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } public KeyModifier KeyModifier { get { KeyModifier mod = KeyModifier.None; if (AltModifier) { mod |= KeyModifier.Alt; } if (WinModifier) { mod |= KeyModifier.Win; } if (ShiftModifier) { mod |= KeyModifier.Shift; } if (CtrlModifier) { mod |= KeyModifier.Ctrl; } return mod; } } } }
using System; using System.Windows.Forms; using System.Xml.Serialization; namespace DeRange.Config { [Serializable] [XmlRoot(ElementName = "KeyboardShortcut")] public class KeyboardShortcut { public bool ShiftModifier { get; set; } public bool CtrlModifier { get; set; } public bool AltModifier { get; set; } public bool WinModifier { get; set; } public Keys Key { get; set; } } }
apache-2.0
C#
9d4260187896c063bbe21af135b6248b8da555f9
Change type signature of NotNullOrEmpty to string since it's only used for strings.
devtyr/gullap
DevTyr.Gullap/Guard.cs
DevTyr.Gullap/Guard.cs
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (string obj, string argumentName) { NotNull (obj, argumentName); if (string.IsNullOrWhiteSpace(obj)) throw new ArgumentException(argumentName); } } }
using System; namespace DevTyr.Gullap { public static class Guard { public static void NotNull (object obj, string argumentName) { if (obj == null) throw new ArgumentNullException(argumentName); } public static void NotNullOrEmpty (object obj, string argumentName) { NotNull (obj, argumentName); if (!(obj is String)) return; var val = (String)obj; if (string.IsNullOrWhiteSpace(val)) throw new ArgumentException(argumentName); } } }
mit
C#
ad964d8a665c1099e25b068d30cd3464cda33d0a
change db init
Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject,Borayvor/ASP.NET-MVC-CourseProject
EntertainmentSystem/Web/EntertainmentSystem.Web/App_Start/DatabaseConfig.cs
EntertainmentSystem/Web/EntertainmentSystem.Web/App_Start/DatabaseConfig.cs
namespace EntertainmentSystem.Web.App_Start { using System.Data.Entity; using Data; public class DatabaseConfig { public static void RegisterDatabase() { ////Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntertainmentSystemDbContext, Configuration>()); Database.SetInitializer(new DropCreateDatabaseAlways<EntertainmentSystemDbContext>()); EntertainmentSystemDbContext.Create().Database.Initialize(true); } } }
namespace EntertainmentSystem.Web.App_Start { using System.Data.Entity; using Data; using Data.Migrations; public class DatabaseConfig { public static void RegisterDatabase() { Database.SetInitializer(new MigrateDatabaseToLatestVersion<EntertainmentSystemDbContext, Configuration>()); EntertainmentSystemDbContext.Create().Database.Initialize(true); } } }
mit
C#
754cb6469f33b5ab86f21c2b79e480a260c42e92
Use warning instead of warn
BlueMountainCapital/riemann-health-windows
Program.cs
Program.cs
using System; using System.Linq; using System.Threading; using riemann; namespace RiemannHealth { public class Program { public static void Main(string[] args) { string hostname; ushort port; switch (args.Length) { case 0: hostname = "localhost"; port = 5555; break; case 1: hostname = args[0]; port = 5555; break; case 2: hostname = args[0]; if (!ushort.TryParse(args[1], out port)) { Usage(); Environment.Exit(-1); } break; default: Usage(); Environment.Exit(-1); return; } var client = new Riemann(hostname, port); var reporters = Health.Reporters() .ToList(); while (true) { foreach (var reporter in reporters) { string description; float value; if (reporter.TryGetValue(out description, out value)) { string state; if (value < reporter.WarnThreshold) { state = "ok"; } else if (value < reporter.CriticalThreshold) { state = "warning"; } else { state = "critical"; } client.SendEvent(reporter.Name, state, description, value, 1); } } Thread.Sleep(TimeSpan.FromSeconds(1.0)); } } private static void Usage() { Console.WriteLine(@"riemann [riemann-host] [riemann-port]"); } } }
using System; using System.Linq; using System.Threading; using riemann; namespace RiemannHealth { public class Program { public static void Main(string[] args) { string hostname; ushort port; switch (args.Length) { case 0: hostname = "localhost"; port = 5555; break; case 1: hostname = args[0]; port = 5555; break; case 2: hostname = args[0]; if (!ushort.TryParse(args[1], out port)) { Usage(); Environment.Exit(-1); } break; default: Usage(); Environment.Exit(-1); return; } var client = new Riemann(hostname, port); var reporters = Health.Reporters() .ToList(); while (true) { foreach (var reporter in reporters) { string description; float value; if (reporter.TryGetValue(out description, out value)) { string state; if (value < reporter.WarnThreshold) { state = "ok"; } else if (value < reporter.CriticalThreshold) { state = "warn"; } else { state = "critical"; } client.SendEvent(reporter.Name, state, description, value, 1); } } Thread.Sleep(TimeSpan.FromSeconds(1.0)); } } private static void Usage() { Console.WriteLine(@"riemann [riemann-host] [riemann-port]"); } } }
apache-2.0
C#
c4af8c01a07a524ab81bd7e5470bafc2b46d1afc
Change start() to awake()
pollend/ParkitectCheats,nozols/ParkitectCheats
CheatModController.cs
CheatModController.cs
using System.Collections.Generic; using UnityEngine; using CheatMod.Windows; using CheatMod.Reference; namespace CheatMod { class CheatModController : MonoBehaviour { public static List<CMWindow> windows = new List<CMWindow>(); void Start() { Debug.Log("Started CheatModController"); //SkinCreator.ApplyStylesToSkin(); windows.Add(new MainWindow(WindowIds.MainWindow)); windows.Add(new AdvancedWindow(WindowIds.AdvancedWindow)); windows.Add(new ConfirmWindow(WindowIds.ConfirmWindow)); windows.Add(new MessageWindow(WindowIds.MessageWindow)); } void Update() { if (Input.GetKeyDown(KeyCode.T) || (Input.GetKeyDown(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.T))) { Debug.Log("Toggled Cheatmod window"); CMWindow window = getWindow(WindowIds.MainWindow); Debug.Log(window); window.ToggleWindowState(); //gettWindow(WindowIds.MainWindow).ToggleWindowState(); } } void OnGUI() { //GUI.skin = SkinCreator.skin; windows.ForEach(delegate(CMWindow window){ if (window.isOpen) { window.DrawWindow(); } }); } public static CMWindow getWindow(int id) { return windows.Find(x => x.id == id); } } }
using System.Collections.Generic; using UnityEngine; using CheatMod.Windows; using CheatMod.Reference; namespace CheatMod { class CheatModController : MonoBehaviour { public static List<CMWindow> windows = new List<CMWindow>(); void Start() { Debug.Log("Started CheatModController"); windows.Add(new MainWindow(WindowIds.MainWindow)); windows.Add(new AdvancedWindow(WindowIds.AdvancedWindow)); windows.Add(new ConfirmWindow(WindowIds.ConfirmWindow)); windows.Add(new MessageWindow(WindowIds.MessageWindow)); } void Update() { if (Input.GetKeyDown(KeyCode.T) || (Input.GetKeyDown(KeyCode.LeftAlt) && Input.GetKeyDown(KeyCode.T))) { Debug.Log("Toggled Cheatmod window"); getWindow(WindowIds.MainWindow).ToggleWindowState(); } } void OnGUI() { windows.ForEach(delegate(CMWindow window){ if (window.isOpen) { window.DrawWindow(); } }); } public static CMWindow getWindow(int id) { return windows.Find(x => x.id == id); } } }
apache-2.0
C#
a9b9c0f3bf726b4cc185ce7a5fda3ba8edb28104
update conekta.js script version
conekta/conekta-xamarin
ConektaSDK/Conekta.cs
ConektaSDK/Conekta.cs
using System; using System.Drawing; using System.Diagnostics; #if __IOS__ using Foundation; using ObjectiveC; using ObjCRuntime; using UIKit; #endif #if __ANDROID__ using Android; #endif namespace ConektaSDK { public abstract class Conekta { public static string ApiVersion { get; set; } public const string BaseUri = "https://api.conekta.io"; public static string PublicKey { get; set; } #if __IOS__ public static UIViewController _delegate { get; set; } #endif public static void collectDevice() { string SessionId = Conekta.DeviceFingerPrint (); string PublicKey = Conekta.PublicKey; string html = "<html style=\"background: blue;\"><head></head><body>"; html += "<script type=\"text/javascript\" src=\"https://conektaapi.s3.amazonaws.com/v0.5.0/js/conekta.js\" data-public-key=\"" + PublicKey + "\" data-session-id=\"" + SessionId + "\"></script>"; html += "</body></html>"; string contentPath = Environment.CurrentDirectory; #if __IOS__ UIWebView web = new UIWebView(new RectangleF(new PointF(0,0), new SizeF(0, 0))); web.LoadHtmlString(html, new NSUrl(contentPath, true)); web.ScalesPageToFit = true; Conekta._delegate.View.AddSubview(web); #endif #if __ANDROID__ #endif } public static string DeviceFingerPrint() { string uuidString = ""; #if __IOS__ //NSUuid uuid = new NSUuid(); //uuidString = uuid.AsString(); uuidString = UIKit.UIDevice.CurrentDevice.IdentifierForVendor.AsString(); uuidString = uuidString.Replace("-", ""); #elif __ANDROID__ uuidString = Android.OS.Build.Serial; #elif WINDOWS_PHONE uuidString = Windows.Phone.System.Analytics.HostInformation.PublisherHostId; #endif return uuidString; } } }
using System; using System.Drawing; using System.Diagnostics; #if __IOS__ using Foundation; using ObjectiveC; using ObjCRuntime; using UIKit; #endif #if __ANDROID__ using Android; #endif namespace ConektaSDK { public abstract class Conekta { public static string ApiVersion { get; set; } public const string BaseUri = "https://api.conekta.io"; public static string PublicKey { get; set; } #if __IOS__ public static UIViewController _delegate { get; set; } #endif public static void collectDevice() { string SessionId = Conekta.DeviceFingerPrint (); string PublicKey = Conekta.PublicKey; string html = "<html style=\"background: blue;\"><head></head><body>"; html += "<script type=\"text/javascript\" src=\"https://conektaapi.s3.amazonaws.com/v0.3.2/js/conekta.js\" data-public-key=\"" + PublicKey + "\" data-session-id=\"" + SessionId + "\"></script>"; html += "</body></html>"; string contentPath = Environment.CurrentDirectory; #if __IOS__ UIWebView web = new UIWebView(new RectangleF(new PointF(0,0), new SizeF(0, 0))); web.LoadHtmlString(html, new NSUrl(contentPath, true)); web.ScalesPageToFit = true; Conekta._delegate.View.AddSubview(web); #endif #if __ANDROID__ #endif } public static string DeviceFingerPrint() { string uuidString = ""; #if __IOS__ //NSUuid uuid = new NSUuid(); //uuidString = uuid.AsString(); uuidString = UIKit.UIDevice.CurrentDevice.IdentifierForVendor.AsString(); uuidString = uuidString.Replace("-", ""); #elif __ANDROID__ uuidString = Android.OS.Build.Serial; #elif WINDOWS_PHONE uuidString = Windows.Phone.System.Analytics.HostInformation.PublisherHostId; #endif return uuidString; } } }
mit
C#
04abb2ce8f1723fbf342d7cb215eea0d20d221bb
Update default cursor smoke implementation to use a texture
peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game.Rulesets.Osu/Skinning/Default/DefaultSmoke.cs
osu.Game.Rulesets.Osu/Skinning/Default/DefaultSmoke.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Textures; namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { [BackgroundDependencyLoader] private void load(TextureStore textures) { // ISkinSource doesn't currently fallback to global textures. // We might want to change this in the future if the intention is to allow the user to skin this as per legacy skins. Texture = textures.Get("Gameplay/osu/cursor-smoke"); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. namespace osu.Game.Rulesets.Osu.Skinning.Default { public class DefaultSmoke : Smoke { public DefaultSmoke() { Radius = 2; } } }
mit
C#
6622520aa8f7c7c507fea4d29c5ac7ca504f0939
Update the assembly info
jehugaleahsa/NDex
NDex/Properties/AssemblyInfo.cs
NDex/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Resources; 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("NDex")] [assembly: AssemblyDescription("Unified algorithm support for indexed .NET collections.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NDex")] [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("54fb5613-d63b-499b-a85a-8f39252c99d7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: InternalsVisibleTo("NDex.Tests")] [assembly: CLSCompliant(true)]
using System.Reflection; using System.Resources; 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("NDex")] [assembly: AssemblyDescription("Unified algorithm support for indexed .NET collections.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NDex")] [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("54fb5613-d63b-499b-a85a-8f39252c99d7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")] [assembly: InternalsVisibleTo("NDex.Tests")]
unlicense
C#
525cf13344e1dc25e884b35c5f4302302ba2d523
fix in dbdatadll
1Development/PermacallWebApp,1Development/PermacallWebApp,1Development/PermacallWebApp
PermacallWebApp/PCDataDLL/DB.cs
PermacallWebApp/PCDataDLL/DB.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PCDataDLL { public class DB { private static MySQLRepo mainDB; private static MySQLRepo portFolioDB; public static MySQLRepo MainDB { get { if (mainDB == null) mainDB = new MySQLRepo(SecureData.PCDBString); return mainDB; } private set { mainDB = value; } } public static MySQLRepo PFDB { get { if (portFolioDB == null) portFolioDB = new MySQLRepo(SecureData.PFDBString); return portFolioDB; } private set { portFolioDB = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PCDataDLL { public class DB { private static MySQLRepo mainDB; private static MySQLRepo portFolioDB; public static MySQLRepo MainDB { get { if (mainDB == null) mainDB = new MySQLRepo(SecureData.PCDBString); return mainDB; } private set { mainDB = value; } } public static MySQLRepo PFDB { get { if (portFolioDB == null) portFolioDB = new MySQLRepo(SecureData.PCDBString); return portFolioDB; } private set { portFolioDB = value; } } } }
mit
C#
544d32405a688d94e18ccec0463cbd20352675fc
Update RuleUpdater.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/RuleUpdater.cs
ProcessBlockUtil/RuleUpdater.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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 System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Stop The Service. */ Process.Start(systemRoot + "\\System32\\sc.exe", "stop pbuService"); Thread.Sleep(2500); /* Obtain some path. */ String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete Exist file. */ if(File.Exists(userProfile + "\\ACRules.txt")){ File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Process.Start(systemRoot + "\\System32\\sc.exe", "start pbuService"); } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) 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.Diagnostics; using System.ServiceProcess; using System.Threading; namespace ACProcessBlockUtil { class RuleUpdater { } }
apache-2.0
C#
7176e129393bbcf66f90e8f7784e7c6ad9ddaa5f
Fix Assembly Version
leocereus/WpfDesigner,icsharpcode/WpfDesigner
GlobalAssemblyInfo.cs
GlobalAssemblyInfo.cs
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // 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.Resources; using System.Reflection; [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyCompany("ic#code")] [assembly: AssemblyProduct("SharpDevelop")] [assembly: AssemblyCopyright("2000-2015 AlphaSierraPapa for the SharpDevelop Team")] [assembly: AssemblyVersion("5.*")]
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // 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.Resources; using System.Reflection; [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyCompany("ic#code")] [assembly: AssemblyProduct("SharpDevelop")] [assembly: AssemblyCopyright("2000-2015 AlphaSierraPapa for the SharpDevelop Team")]
mit
C#
7e77971e67c947f2fa1164ecc10bc0476b9cb9db
Remove AssemblyFileVersion
Seddryck/NBi,Seddryck/NBi
GlobalAssemblyInfo.cs
GlobalAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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: AssemblyCompany("NBi Team - Cédric L. Charlier")] [assembly: AssemblyProduct("NBi.Core")] [assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //Reference the testing class to ensure access to internal members [assembly: InternalsVisibleTo("NBi.Testing")] // 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.*")]
using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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: AssemblyCompany("NBi Team - Cédric L. Charlier")] [assembly: AssemblyProduct("NBi.Core")] [assembly: AssemblyCopyright("Copyright © Cédric L. Charlier 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //Reference the testing class to ensure access to internal members [assembly: InternalsVisibleTo("NBi.Testing")] // 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.*")] [assembly: AssemblyFileVersion("1.0.0.*")]
apache-2.0
C#
d1e4b2164be26209b5be9d148b91b77b1b444b76
Make Visual Studio 2017 Enterprise happy
pardeike/Harmony
Harmony/Transpilers.cs
Harmony/Transpilers.cs
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { var method = instruction.operand as MethodBase; if (method == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace Harmony { public static class Transpilers { public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to) { foreach (var instruction in instructions) { if (instruction.operand == from) instruction.operand = to; yield return instruction; } } public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text) { yield return new CodeInstruction(OpCodes.Ldstr, text); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log))); foreach (var instruction in instructions) yield return instruction; } } }
mit
C#
7fa05638dbf42d4cf964ddb919e11f5bef69c9f9
Add repos for Nuget
ApplETS/ETSMobile-WindowsPlatforms,ApplETS/ETSMobile-WindowsPlatforms
build.cake
build.cake
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// // Solution var rootFolder = "./Ets.Mobile"; var solutionPath = rootFolder + "/Ets.Mobile.WindowsPhone.sln"; var allProjectsBinPath = rootFolder + "/**/bin"; // Tests var testFolder = rootFolder + "/Ets.Mobile.Tests/"; var testProjects = new List<string>() { "Ets.Mobile.Client.Tests/Ets.Mobile.Client.Tests.csproj" }; var testBinPath = testFolder + "Ets.Mobile.Client.Tests/bin"; // Configurations var target = Argument("target", "Default"); var releaseConfiguration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // PREPARATION ////////////////////////////////////////////////////////////////////// // Define directories for tests. for(var ind = 0; ind < testProjects.Count; ind++) { testProjects[ind] = testFolder + testProjects[ind]; } ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(allProjectsBinPath); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solutionPath, new NuGetRestoreSettings() { Source = new List<string>() { "https://www.nuget.org/api/v2/", "https://api.nuget.org/v3/", "https://api.nuget.org/v3/index.json", "https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/", "http://nuget.syncfusion.com/MzAwMTE1LDEz", "http://nuget.syncfusion.com/MzAwMTE1LDEw" } }); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { // Since we use AppVeyor (with Windows Env), we'll use MSBuild MSBuild(solutionPath, settings => settings .SetConfiguration(releaseConfiguration) .SetPlatformTarget(PlatformTarget.ARM) ); // Build test projects in x86 foreach(var project in testProjects) { MSBuild(project, settings => settings .SetConfiguration(releaseConfiguration) .SetPlatformTarget(PlatformTarget.x86) .SetMSBuildPlatform(MSBuildPlatform.x86) ); } }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { XUnit2(testBinPath + "/x86/" + releaseConfiguration + "/*.Tests.dll", new XUnit2Settings { ToolPath = "./tools/xunit.runner.console/tools/xunit.console.x86.exe" }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// // Solution var rootFolder = "./Ets.Mobile"; var solutionPath = rootFolder + "/Ets.Mobile.WindowsPhone.sln"; var allProjectsBinPath = rootFolder + "/**/bin"; // Tests var testFolder = rootFolder + "/Ets.Mobile.Tests/"; var testProjects = new List<string>() { "Ets.Mobile.Client.Tests/Ets.Mobile.Client.Tests.csproj" }; var testBinPath = testFolder + "Ets.Mobile.Client.Tests/bin"; // Configurations var target = Argument("target", "Default"); var releaseConfiguration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // PREPARATION ////////////////////////////////////////////////////////////////////// // Define directories for tests. for(var ind = 0; ind < testProjects.Count; ind++) { testProjects[ind] = testFolder + testProjects[ind]; } ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(allProjectsBinPath); }); Task("Restore-NuGet-Packages") .IsDependentOn("Clean") .Does(() => { NuGetRestore(solutionPath, new NuGetRestoreSettings() { Source = new List<string>() { "https://api.nuget.org/v3/index.json", "https://www.nuget.org/api/v2/curated-feeds/microsoftdotnet/", "http://nuget.syncfusion.com/MzAwMTE1LDEz", "http://nuget.syncfusion.com/MzAwMTE1LDEw" } }); }); Task("Build") .IsDependentOn("Restore-NuGet-Packages") .Does(() => { // Since we use AppVeyor (with Windows Env), we'll use MSBuild MSBuild(solutionPath, settings => settings .SetConfiguration(releaseConfiguration) .SetPlatformTarget(PlatformTarget.ARM) ); // Build test projects in x86 foreach(var project in testProjects) { MSBuild(project, settings => settings .SetConfiguration(releaseConfiguration) .SetPlatformTarget(PlatformTarget.x86) .SetMSBuildPlatform(MSBuildPlatform.x86) ); } }); Task("Run-Unit-Tests") .IsDependentOn("Build") .Does(() => { XUnit2(testBinPath + "/x86/" + releaseConfiguration + "/*.Tests.dll", new XUnit2Settings { ToolPath = "./tools/xunit.runner.console/tools/xunit.console.x86.exe" }); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("Run-Unit-Tests"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
apache-2.0
C#
1d6dd0f0d7067db9597dcd8084697ed87c35cc33
Add Chinese translation
goldenapple3/Miscellania
Items/Materials/WormholeCrystal.cs
Items/Materials/WormholeCrystal.cs
 using System; using Terraria; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; namespace GoldensMisc.Items.Materials { public class WormholeCrystal : ModItem { public override bool Autoload(ref string name) { return Config.WormholeMirror; } public override void SetStaticDefaults() { Tooltip.SetDefault("'You feel like it pulls you in as you hold it...'\n" + "This material currently has no use within Miscellania.\n" + "You can sell it or keep it in case of future mod updates."); DisplayName.AddTranslation(GameCulture.Russian, "Кристалл-червоточина"); Tooltip.AddTranslation(GameCulture.Russian, "'Держа его в руке, вы чувствуете, что вас засасывет...'\n" + "На данный момент этот материал не имеет использований.\n" + "Можете или продать, или оставить себе на случай будущих апдейтов."); DisplayName.AddTranslation(GameCulture.Chinese, "虫洞结晶"); Tooltip.AddTranslation(GameCulture.Chinese, "'当你握着它的时候,你觉得它把你吸引住了...'\n" + "这种材料在Miscellania中暂时没有用处.\n" + "你可以将其出售或保留以备将来的Mod更新."); ItemID.Sets.ItemNoGravity[item.type] = true; } public override void SetDefaults() { item.width = 20; item.height = 20; //item.rare = 8; item.rare = -1; item.value = Item.sellPrice(0, 1); item.maxStack = 99; item.alpha = 50; } } }
 using System; using Terraria; using Terraria.ID; using Terraria.Localization; using Terraria.ModLoader; namespace GoldensMisc.Items.Materials { public class WormholeCrystal : ModItem { public override bool Autoload(ref string name) { return Config.WormholeMirror; } public override void SetStaticDefaults() { Tooltip.SetDefault("'You feel like it pulls you in as you hold it...'\n" + "This material currently has no use within Miscellania.\n" + "You can sell it or keep it in case of future mod updates."); DisplayName.AddTranslation(GameCulture.Russian, "Кристалл-червоточина"); Tooltip.AddTranslation(GameCulture.Russian, "'Держа его в руке, вы чувствуете, что вас засасывет...'\n" + "На данный момент этот материал не имеет использований.\n" + "Можете или продать, или оставить себе на случай будущих апдейтов."); ItemID.Sets.ItemNoGravity[item.type] = true; } public override void SetDefaults() { item.width = 20; item.height = 20; //item.rare = 8; item.rare = -1; item.value = Item.sellPrice(0, 1); item.maxStack = 99; item.alpha = 50; } } }
mit
C#
b06906eabac9cafb6d7d36a698e177761556e37f
fix stream returns
Pondidum/Ledger,Pondidum/Ledger
Ledger.Stores.Fs.Tests/TestBase.cs
Ledger.Stores.Fs.Tests/TestBase.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ledger.Infrastructure; using NSubstitute; using TestsDomain; namespace Ledger.Stores.Fs.Tests { public class TestBase { public List<string> Events { get; private set; } public List<string> Snapshots { get; private set; } public TestBase() { Events = new List<string>(); Snapshots = new List<string>(); } protected void Save(AggregateRoot<Guid> aggregate) { var events = new MemoryStream(); var snapshots = new MemoryStream(); var fileSystem = Substitute.For<IFileSystem>(); fileSystem.AppendTo("fs\\Guid.events.json").Returns(events); fileSystem.AppendTo("fs\\Guid.snapshots.json").Returns(snapshots); var fs = new FileEventStore(fileSystem, "fs"); var store = new AggregateStore<Guid>(fs); store.Save(aggregate); Events.Clear(); Events.AddRange(FromStream(events)); Snapshots.Clear(); Snapshots.AddRange(FromStream(snapshots)); } protected Candidate Load(Guid id) { var events = ToStream(Events); var snapshots = ToStream(Snapshots); var fileSystem = Substitute.For<IFileSystem>(); fileSystem.ReadFile("fs\\Guid.events.json").Returns(events); fileSystem.ReadFile("fs\\Guid.snapshots.json").Returns(snapshots); fileSystem.FileExists(Arg.Any<string>()).Returns(true); var fs = new FileEventStore(fileSystem, "fs"); var store = new AggregateStore<Guid>(fs); return store.Load(id, () => new Candidate()); } private static List<string> FromStream(MemoryStream stream) { var copy = new MemoryStream(stream.ToArray()); using (var reader = new StreamReader(copy)) { return reader .ReadToEnd() .Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .ToList(); } } private static Stream ToStream(IEnumerable<string> items) { var ms = new MemoryStream(); var sw = new StreamWriter(ms); items.ForEach(x => sw.WriteLine(x)); sw.Flush(); ms.Position = 0; return ms; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ledger.Infrastructure; using NSubstitute; using TestsDomain; namespace Ledger.Stores.Fs.Tests { public class TestBase { public List<string> Events { get; private set; } public List<string> Snapshots { get; private set; } public TestBase() { Events = new List<string>(); Snapshots = new List<string>(); } protected void Save(AggregateRoot<Guid> aggregate) { var events = new MemoryStream(); var snapshots = new MemoryStream(); var fileSystem = Substitute.For<IFileSystem>(); fileSystem.AppendTo("fs\\Guid.events.json").Returns(events); fileSystem.AppendTo("fs\\Guid.snapshots.json").Returns(snapshots); var fs = new FileEventStore(fileSystem, "fs"); var store = new AggregateStore<Guid>(fs); store.Save(aggregate); Events.Clear(); Events.AddRange(FromStream(events)); Snapshots.Clear(); Snapshots.AddRange(FromStream(snapshots)); } protected Candidate Load(Guid id) { var events = ToStream(Events); var snapshots = ToStream(Snapshots); var fileSystem = Substitute.For<IFileSystem>(); fileSystem.AppendTo("fs\\Guid.events.json").Returns(events); fileSystem.AppendTo("fs\\Guid.snapshots.json").Returns(snapshots); var fs = new FileEventStore(fileSystem, "fs"); var store = new AggregateStore<Guid>(fs); return store.Load(id, () => new Candidate()); } private static List<string> FromStream(MemoryStream stream) { var copy = new MemoryStream(stream.ToArray()); using (var reader = new StreamReader(copy)) { return reader .ReadToEnd() .Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries) .ToList(); } } private static Stream ToStream(IEnumerable<string> items) { var ms = new MemoryStream(); var sw = new StreamWriter(ms); items.ForEach(x => sw.WriteLine(x)); ms.Position = 0; return ms; } } }
lgpl-2.1
C#
cab699f1a773d96d41b23cd66804a7c331b5b060
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.41.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.40.*")]
mit
C#
9b0be318fe76e8f4ccc6d0c50f9dc061a78058dc
Remove unused links from the layout page
appharbor/ConsolR,vendettamit/compilify,vendettamit/compilify,jrusbatch/compilify,appharbor/ConsolR,jrusbatch/compilify
Web/Views/Shared/_Layout.cshtml
Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - Compilify, an interactive web interface for the .NET compiler</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="image/x-icon" rel="shortcut icon" href="/favicon.ico" /> <link type="text/css" rel="stylesheet" href="//fonts.googleapis.com/css?family=Droid+Sans+Mono" /> <link type="text/css" rel="stylesheet" href="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/css")" /> @Html.Analytics() </head> <body dir="ltr"> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="brand" href="@Url.Action("Index", "Home")"> <h1>compilify<strong>.net</strong></h1> </a> @*<ul class="nav pull-right"> <li> <a href="#">sign in</a> </li> </ul>*@ </div> </div> </div> <div id="content" class="container-fluid"> @RenderBody() </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/js")"></script> @RenderSection("PageScripts", false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@ViewBag.Title - Compilify, a Roslyn-based Web Interface for the C# Compiler</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link type="image/x-icon" rel="shortcut icon" href="/favicon.ico" /> <link type="text/css" rel="stylesheet" href="//fonts.googleapis.com/css?family=Droid+Sans+Mono" /> <link type="text/css" rel="stylesheet" href="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/css")" /> @Html.Analytics() </head> <body dir="ltr"> <div class="navbar navbar-fixed-top"> <div class="navbar-inner"> <div class="container-fluid"> <a class="brand" href="@Url.Action("Index", "Home")"> <h1>compilify<strong>.net</strong></h1> </a> <ul class="nav"> <li> <a href="#">save</a> </li> <li> <a href="#">share</a> </li> </ul> <ul class="nav pull-right"> <li> <a href="#">sign in</a> </li> </ul> </div> </div> </div> <div id="content" class="container-fluid"> @RenderBody() </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script> <script src="@Microsoft.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/js")"></script> @RenderSection("PageScripts", false) </body> </html>
mit
C#
093b6bac5967947186649a6abebf21e71340aab3
Improve string and date Util methods (#477)
Oucema90/RiotSharp,JanOuborny/RiotSharp,BenFradet/RiotSharp,frederickrogan/RiotSharp
RiotSharp/Misc/Util.cs
RiotSharp/Misc/Util.cs
using System; using System.Collections.Generic; using System.Linq; using RiotSharp.MatchEndpoint.Enums; namespace RiotSharp.Misc { static class Util { public static DateTime BaseDateTime = new DateTime(1970, 1, 1); public static DateTime ToDateTimeFromMilliSeconds(this long millis) { return BaseDateTime.AddMilliseconds(millis); } public static long ToLong(this DateTime dateTime) { var span = dateTime - BaseDateTime; return (long)span.TotalMilliseconds; } public static string BuildIdsString(List<int> ids) { return string.Join(",", ids); } public static string BuildIdsString(List<long> ids) { return string.Join(",", ids); } public static string BuildNamesString(List<string> names) { return string.Join(",", names.Select(Uri.EscapeDataString)); } public static string BuildQueuesString(List<string> queues) { return string.Join(",", queues); } public static string BuildSeasonString(List<Season> seasons) { return string.Join(",", seasons.Select(s => s.ToCustomString())); } } }
using System; using System.Collections.Generic; using RiotSharp.MatchEndpoint.Enums; namespace RiotSharp.Misc { static class Util { public static DateTime ToDateTimeFromMilliSeconds(this long millis) { var dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0); dateTime = dateTime.AddMilliseconds(millis); return dateTime; } public static long ToLong(this DateTime dateTime) { var span = dateTime - new DateTime(1970, 1, 1, 0, 0, 0, 0); return (long)span.TotalMilliseconds; } public static string BuildIdsString(List<int> ids) { string concatenatedIds = string.Empty; for (int i = 0; i < ids.Count - 1; i++) { concatenatedIds += ids[i] + ","; } return concatenatedIds + ids[ids.Count - 1]; } public static string BuildIdsString(List<long> ids) { string concatenatedIds = string.Empty; for (int i = 0; i < ids.Count - 1; i++) { concatenatedIds += ids[i] + ","; } return concatenatedIds + ids[ids.Count - 1]; } public static string BuildNamesString(List<string> names) { string concatenatedNames = string.Empty; for (int i = 0; i < names.Count - 1; i++) { concatenatedNames += Uri.EscapeDataString(names[i]) + ","; } return concatenatedNames + Uri.EscapeDataString(names[names.Count - 1]); } public static string BuildQueuesString(List<string> queues) { string concatenatedQueues = string.Empty; for (int i = 0; i < queues.Count - 1; i++) { concatenatedQueues += queues[i] + ","; } return concatenatedQueues + queues[queues.Count - 1]; } public static string BuildSeasonString(List<Season> seasons) { string concatenatedQueues = string.Empty; for (int i = 0; i < seasons.Count - 1; i++) { concatenatedQueues += seasons[i].ToCustomString() + ","; } return concatenatedQueues + seasons[seasons.Count - 1].ToCustomString(); } } }
mit
C#
14b366a68dea6121c89f716fa8744bf7eb067f35
Change release type.
fuyuno/Norma
Source/Norma/Models/ProductInfo.cs
Source/Norma/Models/ProductInfo.cs
using System; using System.Collections.Generic; using System.Reflection; using Norma.Models.Libraries; using LibMetroRadiance = Norma.Models.Libraries.MetroRadiance; namespace Norma.Models { internal static class ProductInfo { public static string Name => GetAssemblyInfo<AssemblyTitleAttribute>().Title; public static Lazy<string> Description => new Lazy<string>(() => GetAssemblyInfo<AssemblyDescriptionAttribute>().Description); public static Lazy<string> Company => new Lazy<string>(() => GetAssemblyInfo<AssemblyCompanyAttribute>().Company); public static string Copyright => GetAssemblyInfo<AssemblyCopyrightAttribute>().Copyright; public static string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(); public static ReleaseType ReleaseType => ReleaseType.Release; public static string Support => "https://github.com/fuyuno/Norma"; public static Lazy<List<Library>> Libraries => new Lazy<List<Library>>(() => new List<Library> { new CEF(), new CEFSharp(), new CommonServiceLocator(), new DesktopToast(), new EntityFramework(), new HardcodetWpfNotifyIcon(), new LibMetroRadiance(), new NewtonsoftJson(), new NotificationsExtensions(), new PrismLibrary(), new ReactiveProperty(), new RxNET(), new SqLiteCodeFirst(), new SqLiteProvider(), new Unity() }); private static T GetAssemblyInfo<T>() where T : Attribute => (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T)); } }
using System; using System.Collections.Generic; using System.Reflection; using Norma.Models.Libraries; using LibMetroRadiance = Norma.Models.Libraries.MetroRadiance; namespace Norma.Models { internal static class ProductInfo { public static string Name => GetAssemblyInfo<AssemblyTitleAttribute>().Title; public static Lazy<string> Description => new Lazy<string>(() => GetAssemblyInfo<AssemblyDescriptionAttribute>().Description); public static Lazy<string> Company => new Lazy<string>(() => GetAssemblyInfo<AssemblyCompanyAttribute>().Company); public static string Copyright => GetAssemblyInfo<AssemblyCopyrightAttribute>().Copyright; public static string Version => Assembly.GetExecutingAssembly().GetName().Version.ToString(); public static ReleaseType ReleaseType => ReleaseType.Preview; public static string Support => "https://github.com/fuyuno/Norma"; public static Lazy<List<Library>> Libraries => new Lazy<List<Library>>(() => new List<Library> { new CEF(), new CEFSharp(), new CommonServiceLocator(), new DesktopToast(), new EntityFramework(), new HardcodetWpfNotifyIcon(), new LibMetroRadiance(), new NewtonsoftJson(), new NotificationsExtensions(), new PrismLibrary(), new ReactiveProperty(), new RxNET(), new SqLiteCodeFirst(), new SqLiteProvider(), new Unity() }); private static T GetAssemblyInfo<T>() where T : Attribute => (T) Attribute.GetCustomAttribute(Assembly.GetExecutingAssembly(), typeof(T)); } }
mit
C#
406b6fcc760d74962a0c9744f31985c9e535b335
Update version
MisinformedDNA/Elmah.AzureTableStorage,FreedomMercenary/Elmah.AzureTableStorage,LionLai/Elmah.AzureTableStorage
src/Elmah.AzureTableStorage/Properties/AssemblyInfo.cs
src/Elmah.AzureTableStorage/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("ELMAH on Azure Table Storage")] [assembly: AssemblyDescription("ELMAH with configuration for getting started quickly on Azure Table Storage as the error log.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dan Friedman, Dragon Door Publications")] [assembly: AssemblyProduct("ELMAH on Azure Table Storage")] [assembly: AssemblyCopyright("Copyright © 2013. All rights reserved.")] [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("9bff690b-8426-4e8a-8a93-5a2055b1f410")] // 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.5.2.0")] [assembly: AssemblyFileVersion("0.5.2.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("ELMAH on Azure Table Storage")] [assembly: AssemblyDescription("ELMAH with configuration for getting started quickly on Azure Table Storage as the error log.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Dan Friedman, Dragon Door Publications")] [assembly: AssemblyProduct("ELMAH on Azure Table Storage")] [assembly: AssemblyCopyright("Copyright © 2013. All rights reserved.")] [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("9bff690b-8426-4e8a-8a93-5a2055b1f410")] // 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.5.1.0")] [assembly: AssemblyFileVersion("0.5.1.0")]
apache-2.0
C#
fe3ab94afbfc84665e28fa8df731a507d6a3656c
Fix mania judgement regression
peppy/osu,smoogipooo/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,Nabile-Rahmani/osu,DrabWeb/osu,ZLima12/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,UselessToucan/osu,naoey/osu,ppy/osu,2yangk23/osu,Frontear/osuKyzer,UselessToucan/osu,naoey/osu,NeoAdonis/osu,DrabWeb/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,NeoAdonis/osu,naoey/osu,ZLima12/osu
osu.Game.Rulesets.Mania/UI/DrawableManiaJudgement.cs
osu.Game.Rulesets.Mania/UI/DrawableManiaJudgement.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Rulesets.Judgements; namespace osu.Game.Rulesets.Mania.UI { internal class DrawableManiaJudgement : DrawableJudgement { public DrawableManiaJudgement(Judgement judgement) : base(judgement) { } [BackgroundDependencyLoader] private void load() { if (JudgementText != null) JudgementText.TextSize = 25; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(50, Easing.OutQuint); if (Judgement.IsHit) { this.ScaleTo(0.8f); this.ScaleTo(1, 250, Easing.OutElastic); this.Delay(50).FadeOut(200).ScaleTo(0.75f, 250); } Expire(); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Game.Rulesets.Judgements; namespace osu.Game.Rulesets.Mania.UI { internal class DrawableManiaJudgement : DrawableJudgement { public DrawableManiaJudgement(Judgement judgement) : base(judgement) { JudgementText.TextSize = 25; } protected override void LoadComplete() { base.LoadComplete(); this.FadeInFromZero(50, Easing.OutQuint); if (Judgement.IsHit) { this.ScaleTo(0.8f); this.ScaleTo(1, 250, Easing.OutElastic); this.Delay(50).FadeOut(200).ScaleTo(0.75f, 250); } Expire(); } } }
mit
C#
af4adb6339e807ee71be35766c1366fb67fcbf38
Add xmldoc
2yangk23/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,EVAST9919/osu,ppy/osu,peppy/osu,smoogipooo/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,ZLima12/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu
osu.Game/Beatmaps/Drawables/GroupedDifficultyIcon.cs
osu.Game/Beatmaps/Drawables/GroupedDifficultyIcon.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets; using osuTK.Graphics; namespace osu.Game.Beatmaps.Drawables { /// <summary> /// A difficulty icon that contains a counter on the right-side of it. /// </summary> /// <remarks> /// Used in cases when there are too many difficulty icons to show. /// </remarks> public class GroupedDifficultyIcon : DifficultyIcon { private readonly OsuSpriteText counter; private List<BeatmapInfo> beatmaps; protected List<BeatmapInfo> Beatmaps { get => beatmaps; set { beatmaps = value; updateDisplay(); } } public GroupedDifficultyIcon(List<BeatmapInfo> beatmaps, RulesetInfo ruleset, Color4 counterColour) : base(null, ruleset, false) { this.beatmaps = beatmaps; AddInternal(counter = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Padding = new MarginPadding { Left = Size.X }, Margin = new MarginPadding { Left = 2, Right = 5 }, Font = OsuFont.GetFont(size: 14, weight: FontWeight.SemiBold), Colour = counterColour, }); updateDisplay(); } private void updateDisplay() { if (beatmaps == null || beatmaps.Count == 0) return; Beatmap = beatmaps.OrderBy(b => b.StarDifficulty).Last(); counter.Text = beatmaps.Count.ToString(); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets; using osuTK.Graphics; namespace osu.Game.Beatmaps.Drawables { public class GroupedDifficultyIcon : DifficultyIcon { private readonly OsuSpriteText counter; private List<BeatmapInfo> beatmaps; protected List<BeatmapInfo> Beatmaps { get => beatmaps; set { beatmaps = value; updateDisplay(); } } public GroupedDifficultyIcon(List<BeatmapInfo> beatmaps, RulesetInfo ruleset, Color4 counterColour) : base(null, ruleset, false) { this.beatmaps = beatmaps; AddInternal(counter = new OsuSpriteText { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Padding = new MarginPadding { Left = Size.X }, Margin = new MarginPadding { Left = 2, Right = 5 }, Font = OsuFont.GetFont(size: 14, weight: FontWeight.SemiBold), Colour = counterColour, }); updateDisplay(); } private void updateDisplay() { if (beatmaps == null || beatmaps.Count == 0) return; Beatmap = beatmaps.OrderBy(b => b.StarDifficulty).Last(); counter.Text = beatmaps.Count.ToString(); } } }
mit
C#
51d5faf65114e4a8c7974570526b505acd060837
Mark calling convention on GInterface callbacks
sillsdev/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,akrisiun/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,Gankov/gtk-sharp
glib/GInterfaceAdapter.cs
glib/GInterfaceAdapter.cs
// GInterfaceAdapter.cs // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GLib { using System; using System.Runtime.InteropServices; [UnmanagedFunctionPointer (CallingConvention.Cdecl)] public delegate void GInterfaceInitHandler (IntPtr iface_ptr, IntPtr data); [UnmanagedFunctionPointer (CallingConvention.Cdecl)] internal delegate void GInterfaceFinalizeHandler (IntPtr iface_ptr, IntPtr data); internal struct GInterfaceInfo { internal GInterfaceInitHandler InitHandler; internal GInterfaceFinalizeHandler FinalizeHandler; internal IntPtr Data; } public abstract class GInterfaceAdapter { GInterfaceInfo info; protected GInterfaceAdapter () { } protected GInterfaceInitHandler InitHandler { set { info.InitHandler = value; } } public abstract GType GType { get; } public abstract IntPtr Handle { get; } internal GInterfaceInfo Info { get { if (info.Data == IntPtr.Zero) info.Data = (IntPtr) GCHandle.Alloc (this); return info; } } } }
// GInterfaceAdapter.cs // // Author: Mike Kestner <mkestner@novell.com> // // Copyright (c) 2007 Novell, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace GLib { using System; using System.Runtime.InteropServices; public delegate void GInterfaceInitHandler (IntPtr iface_ptr, IntPtr data); internal delegate void GInterfaceFinalizeHandler (IntPtr iface_ptr, IntPtr data); internal struct GInterfaceInfo { internal GInterfaceInitHandler InitHandler; internal GInterfaceFinalizeHandler FinalizeHandler; internal IntPtr Data; } public abstract class GInterfaceAdapter { GInterfaceInfo info; protected GInterfaceAdapter () { } protected GInterfaceInitHandler InitHandler { set { info.InitHandler = value; } } public abstract GType GType { get; } public abstract IntPtr Handle { get; } internal GInterfaceInfo Info { get { if (info.Data == IntPtr.Zero) info.Data = (IntPtr) GCHandle.Alloc (this); return info; } } } }
lgpl-2.1
C#
e3505d5f53751fc05c223e568b75ec27c8481820
Remove space
mganss/HtmlSanitizer
test/HtmlSanitizer.Benchmark/HtmlSanitizerBenchmark.cs
test/HtmlSanitizer.Benchmark/HtmlSanitizerBenchmark.cs
using System.IO; using BenchmarkDotNet.Attributes; namespace Ganss.XSS.Benchmark { [MemoryDiagnoser] public class HtmlSanitizerBenchmark { private HtmlSanitizer sanitizer; private string googleFileContent; private string largeFileContent; [GlobalSetup] public void GlobalSetup() { googleFileContent = File.ReadAllText("google.html"); largeFileContent = File.ReadAllText("ecmascript.html"); sanitizer = new HtmlSanitizer(); } /// <summary> /// Small content produced by for example Orchard, nothing to sanitize. /// </summary> [Benchmark] public void SanitizeSmall() { sanitizer.Sanitize("<p>Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airman's earth, if free men make it, will be truly round: a globe in practice, not in theory.</p>\n<p>Science cuts two ways, of course; its products can be used for both good and evil. But there's no turning back from science. The early warnings about technological dangers also come from science.</p>\n<p>What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.</p>\n<p>A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That's how I felt seeing the Earth for the first time. I could not help but love and cherish her.</p>\n<p>For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.</p>\n"); } /// <summary> /// Google is script-heavy. /// </summary> [Benchmark] public void SanitizeGoogle() { sanitizer.Sanitize(googleFileContent); } /// <summary> /// Partial ECMAScript is DOM-heavy. /// </summary> [Benchmark] public void SanitizeLarge() { sanitizer.Sanitize(largeFileContent); } } }
using System.IO; using BenchmarkDotNet.Attributes; namespace Ganss.XSS.Benchmark { [MemoryDiagnoser] public class HtmlSanitizerBenchmark { private HtmlSanitizer sanitizer; private string googleFileContent; private string largeFileContent; [GlobalSetup] public void GlobalSetup() { googleFileContent = File.ReadAllText("google.html"); largeFileContent = File.ReadAllText("ecmascript.html"); sanitizer = new HtmlSanitizer(); } /// <summary> /// Small content produced by for example Orchard, nothing to sanitize. /// </summary> [Benchmark] public void SanitizeSmall() { sanitizer.Sanitize("<p>Never in all their history have men been able truly to conceive of the world as one: a single sphere, a globe, having the qualities of a globe, a round earth in which all the directions eventually meet, in which there is no center because every point, or none, is center — an equal earth which all men occupy as equals. The airman's earth, if free men make it, will be truly round: a globe in practice, not in theory.</p>\n<p>Science cuts two ways, of course; its products can be used for both good and evil. But there's no turning back from science. The early warnings about technological dangers also come from science.</p>\n<p>What was most significant about the lunar voyage was not that man set foot on the Moon but that they set eye on the earth.</p>\n<p>A Chinese tale tells of some men sent to harm a young girl who, upon seeing her beauty, become her protectors rather than her violators. That's how I felt seeing the Earth for the first time. I could not help but love and cherish her.</p>\n<p>For those who have seen the Earth from space, and for the hundreds and perhaps thousands more who will, the experience most certainly changes your perspective. The things that we share in our world are far more valuable than those which divide us.</p>\n"); } /// <summary> /// Google is script-heavy. /// </summary> [Benchmark] public void SanitizeGoogle() { sanitizer.Sanitize(googleFileContent); } /// <summary> /// Partial ECMAScript is DOM-heavy. /// </summary> [Benchmark] public void SanitizeLarge() { sanitizer.Sanitize(largeFileContent); } } }
mit
C#
2d98526f121b0e7e78d83e1d14c306624d52ba77
Change method names
danielmundt/csremote
source/Remoting.Client/FormMain.cs
source/Remoting.Client/FormMain.cs
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Runtime.Remoting; using System.Text; using System.Threading; using System.Windows.Forms; using Remoting.Core; using Remoting.Core.Channels; using Remoting.Core.Events; namespace Remoting.Client { public partial class FormMain : Form { #region Fields private IRemoteService service; #endregion Fields #region Constructors public FormMain() { InitializeComponent(); InitializeClient(); } #endregion Constructors #region Delegates delegate void SetTextCallback(string text); #endregion Delegates #region Methods private void DispatchCall() { try { EventProxy proxy = new EventProxy(tbClientId.Text); proxy.EventDispatched += new EventHandler<EventDispatchedEventArgs>(proxy_EventDispatched); service.DispatchCall(proxy, "Hello World"); } catch (RemotingException ex) { MessageBox.Show(this, ex.Message, "Error"); } } private void btnSend_Click(object sender, EventArgs e) { DispatchCall(); } private void FormMain_Load(object sender, EventArgs e) { tbClientId.Text = Guid.NewGuid().ToString("N"); } private void InitializeClient() { ClientChannel channel = (ClientChannel)ChannelFactory.GetChannel( ChannelFactory.Type.Client); if (channel != null) { service = channel.Initialize(); } } private void proxy_EventDispatched(object sender, EventDispatchedEventArgs e) { SetText(string.Format("EventDispatched: {0}{1}", (string)e.Data, Environment.NewLine)); } private void SetText(string text) { // thread-safe call if (tbLog.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { tbLog.AppendText(text); } } #endregion Methods } }
#region Header // Copyright (C) 2012 Daniel Schubert // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE // AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #endregion Header using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Runtime.Remoting; using System.Text; using System.Threading; using System.Windows.Forms; using Remoting.Core; using Remoting.Core.Channels; using Remoting.Core.Events; namespace Remoting.Client { public partial class FormMain : Form { #region Fields private IRemoteService service; #endregion Fields #region Constructors public FormMain() { InitializeComponent(); InitializeClient(); } #endregion Constructors #region Delegates delegate void SetTextCallback(string text); #endregion Delegates #region Methods public void SendMessage() { try { EventProxy proxy = new EventProxy(tbClientId.Text); proxy.EventDispatched += new EventHandler<EventDispatchedEventArgs>(proxy_EventDispatched); service.DispatchCall(proxy, "Hello World"); } catch (RemotingException ex) { MessageBox.Show(this, ex.Message, "Error"); } } private void btnSend_Click(object sender, EventArgs e) { SendMessage(); } private void FormMain_Load(object sender, EventArgs e) { tbClientId.Text = Guid.NewGuid().ToString("N"); } private void InitializeClient() { ClientChannel channel = (ClientChannel)ChannelFactory.GetChannel( ChannelFactory.Type.Client); if (channel != null) { service = channel.Initialize(); } } private void proxy_EventDispatched(object sender, EventDispatchedEventArgs e) { SetText(string.Format("EventDispatched: {0}{1}", (string)e.Data, Environment.NewLine)); } private void SetText(string text) { // thread-safe call if (tbLog.InvokeRequired) { SetTextCallback d = new SetTextCallback(SetText); this.Invoke(d, new object[] { text }); } else { tbLog.AppendText(text); } } #endregion Methods } }
mit
C#
91f854bba71a8c1b613597f38467c2ea3ab7c350
check loaded level first
Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer
140-speedrun-timer/GameObservers/TitleScreenObserver.cs
140-speedrun-timer/GameObservers/TitleScreenObserver.cs
using System.Reflection; using UnityEngine; namespace SpeedrunTimerMod.GameObservers { [GameObserver] class TitleScreenObserver : MonoBehaviour { static FieldInfo _titleScreenStateField; TitleScreen _titlescreen; object _titleScreenStateStart; object _prevTitleScreenState; void Awake() { if (Application.loadedLevelName != "Level_Menu") { Destroy(this); return; } if (_titleScreenStateField == null) _titleScreenStateField = typeof(TitleScreen) .GetField("myState", BindingFlags.Instance | BindingFlags.NonPublic); } void Start() { var titlescreenObj = GameObject.Find("_TitleScreen"); if (titlescreenObj == null) { Debug.Log($"{nameof(TitleScreenObserver)}: Couldn't find _TitleScreen object"); Destroy(this); return; } _titlescreen = titlescreenObj.GetComponent<TitleScreen>(); } void Update() { if (_titleScreenStateStart == null) _titleScreenStateStart = _titleScreenStateField.GetValue(_titlescreen); } void LateUpdate() { if (_titleScreenStateStart == null || SpeedrunTimer.Instance.IsRunning) return; var titleScreenState = _titleScreenStateField.GetValue(_titlescreen); if (titleScreenState != _prevTitleScreenState && _titleScreenStateStart == _prevTitleScreenState) { SpeedrunTimer.Instance.StartTimer(); Debug.Log("SpeedrunTimer started: " + DebugBeatListener.DebugStr); } _prevTitleScreenState = titleScreenState; } } }
using System.Reflection; using UnityEngine; namespace SpeedrunTimerMod.GameObservers { [GameObserver] class TitleScreenObserver : MonoBehaviour { static FieldInfo _titleScreenStateField; TitleScreen _titlescreen; object _titleScreenStateStart; object _prevTitleScreenState; void Awake() { if (_titleScreenStateField == null) _titleScreenStateField = typeof(TitleScreen) .GetField("myState", BindingFlags.Instance | BindingFlags.NonPublic); if (Application.loadedLevelName != "Level_Menu") Destroy(this); } void Start() { var titlescreenObj = GameObject.Find("_TitleScreen"); if (titlescreenObj == null) { Debug.Log($"{nameof(TitleScreenObserver)}: Couldn't find _TitleScreen object"); Destroy(this); return; } _titlescreen = titlescreenObj.GetComponent<TitleScreen>(); } void Update() { if (_titleScreenStateStart == null) _titleScreenStateStart = _titleScreenStateField.GetValue(_titlescreen); } void LateUpdate() { if (_titleScreenStateStart == null || SpeedrunTimer.Instance.IsRunning) return; var titleScreenState = _titleScreenStateField.GetValue(_titlescreen); if (titleScreenState != _prevTitleScreenState && _titleScreenStateStart == _prevTitleScreenState) { SpeedrunTimer.Instance.StartTimer(); Debug.Log("SpeedrunTimer started: " + DebugBeatListener.DebugStr); } _prevTitleScreenState = titleScreenState; } } }
unlicense
C#
4af3fa4eb2354699456c8e104734175f20302848
Fix build
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer.Common/Altcoins/Liquid/LiquidExtensions.cs
BTCPayServer.Common/Altcoins/Liquid/LiquidExtensions.cs
#if ALTCOINS using System.Collections.Generic; using System.Linq; namespace BTCPayServer { public static class LiquidExtensions { public static IEnumerable<string> GetAllElementsSubChains(this BTCPayNetworkProvider networkProvider) { var elementsBased = networkProvider.GetAll().OfType<ElementsBTCPayNetwork>(); var parentChains = elementsBased.Select(network => network.NetworkCryptoCode.ToUpperInvariant()).Distinct(); return networkProvider.GetAll().OfType<ElementsBTCPayNetwork>() .Where(network => parentChains.Contains(network.NetworkCryptoCode)).Select(network => network.CryptoCode.ToUpperInvariant()); } } } #endif
#if ALTCOINS using System.Collections.Generic; using System.Linq; namespace BTCPayServer { public static class LiquidExtensions { public static IEnumerable<string> GetAllElementsSubChains(this BTCPayNetworkProvider networkProvider) { var elementsBased = networkProvider.GetAll().OfType<ElementsBTCPayNetwork>(); var parentChains = elementsBased.Select(network => network.NetworkCryptoCode.ToUpperInvariant()).Distinct(); return networkProvider.UnfilteredNetworks.GetAll().OfType<ElementsBTCPayNetwork>() .Where(network => parentChains.Contains(network.NetworkCryptoCode)).Select(network => network.CryptoCode.ToUpperInvariant()); } } } #endif
mit
C#
025fbe3dec5ed5296f61e0e4c01988273ab26604
bump version
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
configuration/SharedAssemblyInfo.cs
configuration/SharedAssemblyInfo.cs
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-beta3")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
using System.Reflection; // Assembly Info that is shared across the product [assembly: AssemblyProduct("InEngine.NET")] [assembly: AssemblyVersion("2.0.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-beta2")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ethan Hann")] [assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyDescription("")]
mit
C#
d670a50271687c9ee21d24e21804c8a7db9195cd
make middleware config param required
CoreAPM/DotNetAgent
CoreAPM.NET.CoreMiddleware/CoreAPMServicesExtensions.cs
CoreAPM.NET.CoreMiddleware/CoreAPMServicesExtensions.cs
using System; using System.Net.Http; using CoreAPM.NET.Agent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; namespace CoreAPM.NET.CoreMiddleware { public static class CoreAPMServicesExtensions { public static void AddCoreAPM(this IServiceCollection services, IConfiguration configuration) { services.TryAddTransient<CoreAPMMiddleware>(); services.TryAddTransient<HttpClient>(); services.TryAddTransient<IAgent, QueuedAgent>(); services.TryAddTransient<IServerConfig>(sp => new ServerConfig(configuration)); services.TryAddTransient<Func<ITimer>>(t => () => new Timer()); } } }
using System; using System.Net.Http; using CoreAPM.NET.Agent; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CoreAPM.NET.CoreMiddleware { public static class CoreAPMServicesExtensions { public static void AddCoreAPM(this IServiceCollection services, IConfiguration config = null) { services.AddTransient<CoreAPMMiddleware>(); services.AddTransient<HttpClient>(); services.AddTransient<IAgent, QueuedAgent>(); services.AddTransient<IConfig, Config>(); services.AddTransient<Func<ITimer>>(t => () => new Timer()); if (config != null) services.AddTransient(c => config); } } }
mit
C#
bfe39f7486f77d078a30ce498f4f42981280f24d
Fix project icon not showing on VS project tree (#401)
nanoframework/nf-Visual-Studio-extension
source/VisualStudio.Extension/ProjectSystem/ProjectTreePropertiesProvider.cs
source/VisualStudio.Extension/ProjectSystem/ProjectTreePropertiesProvider.cs
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // using Microsoft.VisualStudio.ProjectSystem; using System.ComponentModel.Composition; namespace nanoFramework.Tools.VisualStudio.Extension { /// <summary> /// Updates nodes in the project tree by overriding property values calculated so far by lower priority providers. /// </summary> [Export(typeof(IProjectTreePropertiesProvider))] [AppliesTo(NanoCSharpProjectUnconfigured.UniqueCapability)] // need to set an order here so it can override the default CPS icon [Order(100)] internal class ProjectTreePropertiesProvider : IProjectTreePropertiesProvider { /// <summary> /// Calculates new property values for each node in the project tree. /// </summary> /// <param name="propertyContext">Context information that can be used for the calculation.</param> /// <param name="propertyValues">Values calculated so far for the current node by lower priority tree properties providers.</param> public void CalculatePropertyValues( IProjectTreeCustomizablePropertyContext propertyContext, IProjectTreeCustomizablePropertyValues propertyValues) { // set the icon for the root project node if (propertyValues.Flags.Contains(ProjectTreeFlags.Common.ProjectRoot)) { propertyValues.Icon = NanoFrameworkMonikers.NanoFrameworkProject.ToProjectSystemType(); propertyValues.ExpandedIcon = NanoFrameworkMonikers.NanoFrameworkProject.ToProjectSystemType(); } } } }
// // Copyright (c) 2017 The nanoFramework project contributors // See LICENSE file in the project root for full license information. // using Microsoft.VisualStudio.ProjectSystem; using System.ComponentModel.Composition; namespace nanoFramework.Tools.VisualStudio.Extension { /// <summary> /// Updates nodes in the project tree by overriding property values calcuated so far by lower priority providers. /// </summary> [Export(typeof(IProjectTreePropertiesProvider))] [AppliesTo(NanoCSharpProjectUnconfigured.UniqueCapability)] internal class ProjectTreePropertiesProvider : IProjectTreePropertiesProvider { /// <summary> /// Calculates new property values for each node in the project tree. /// </summary> /// <param name="propertyContext">Context information that can be used for the calculation.</param> /// <param name="propertyValues">Values calculated so far for the current node by lower priority tree properties providers.</param> public void CalculatePropertyValues( IProjectTreeCustomizablePropertyContext propertyContext, IProjectTreeCustomizablePropertyValues propertyValues) { // set the icon for the root project node if (propertyValues.Flags.Contains(ProjectTreeFlags.Common.ProjectRoot)) { propertyValues.Icon = NanoFrameworkMonikers.NanoFrameworkProject.ToProjectSystemType(); propertyValues.ExpandedIcon = NanoFrameworkMonikers.NanoFrameworkProject.ToProjectSystemType(); } } } }
mit
C#
b6346115c92264aba60867c293a8f0c91f1fe176
update identity resource mappings
IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework,IdentityServer/IdentityServer4.EntityFramework
src/IdentityServer4.EntityFramework/Mappers/IdentityResourceMapperProfile.cs
src/IdentityServer4.EntityFramework/Mappers/IdentityResourceMapperProfile.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 AutoMapper; namespace IdentityServer4.EntityFramework.Mappers { /// <summary> /// Defines entity/model mapping for identity resources. /// </summary> /// <seealso cref="AutoMapper.Profile" /> public class IdentityResourceMapperProfile : Profile { /// <summary> /// <see cref="IdentityResourceMapperProfile"/> /// </summary> public IdentityResourceMapperProfile() { CreateMap<Entities.IdentityResource, Models.IdentityResource>(MemberList.Destination) .ConstructUsing(src => new Models.IdentityResource()) .ReverseMap(); CreateMap<Entities.IdentityClaim, string>() .ConstructUsing(x => x.Type) .ReverseMap() .ForMember(dest => dest.Type, opt => opt.MapFrom(src => src)); } } }
// 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.Linq; using AutoMapper; using IdentityServer4.EntityFramework.Entities; namespace IdentityServer4.EntityFramework.Mappers { /// <summary> /// Defines entity/model mapping for identity resources. /// </summary> /// <seealso cref="AutoMapper.Profile" /> public class IdentityResourceMapperProfile : Profile { /// <summary> /// <see cref="IdentityResourceMapperProfile"/> /// </summary> public IdentityResourceMapperProfile() { // entity to model CreateMap<IdentityResource, Models.IdentityResource>(MemberList.Destination) .ConstructUsing(src => new Models.IdentityResource()) .ForMember(x => x.UserClaims, opt => opt.MapFrom(src => src.UserClaims.Select(x => x.Type))); // model to entity CreateMap<Models.IdentityResource, IdentityResource>(MemberList.Source) .ForMember(x => x.UserClaims, opts => opts.MapFrom(src => src.UserClaims.Select(x => new IdentityClaim { Type = x }))); } } }
apache-2.0
C#
ac14ce96d1677c3c05319082f328424e974b6139
Remove commented code
z4kn4fein/stashbox
src/Lifetime/ScopedLifetimeBase.cs
src/Lifetime/ScopedLifetimeBase.cs
using Stashbox.BuildUp; using Stashbox.Registration; using Stashbox.Resolution; using System; using System.Linq.Expressions; using System.Threading; namespace Stashbox.Lifetime { /// <summary> /// Represents a shared base class for scoped lifetimes. /// </summary> public abstract class ScopedLifetimeBase : LifetimeBase { private static int scopeIdCounter; /// <summary> /// The id of the scope. /// </summary> protected readonly int ScopeId = Interlocked.Increment(ref scopeIdCounter); /// <summary> /// The object used to synchronization. /// </summary> protected readonly object Sync = new object(); /// <summary> /// Produces a factory expression to produce scoped instances. /// </summary> /// <param name="containerContext">The container context.</param> /// <param name="serviceRegistration">The service registration.</param> /// <param name="objectBuilder">The object builder.</param> /// <param name="resolutionContext">The resolution context.</param> /// <param name="resolveType">The resolve type.</param> /// <returns>The factory expression.</returns> public Expression GetFactoryExpression(IContainerContext containerContext, IServiceRegistration serviceRegistration, IObjectBuilder objectBuilder, ResolutionContext resolutionContext, Type resolveType) { var expr = base.GetExpression(containerContext, serviceRegistration, objectBuilder, resolutionContext, resolveType); return expr?.CompileDelegate(resolutionContext).AsConstant(); } /// <summary> /// Stores the given expression in a local variable and saves it into the resolution context for further reuse. /// </summary> /// <param name="expression">The expression to store.</param> /// <param name="resolutionContext">The resolution context.</param> /// <param name="resolveType">The resolve type.</param> /// <returns>The local variable.</returns> public Expression StoreExpressionIntoLocalVariable(Expression expression, ResolutionContext resolutionContext, Type resolveType) { var variable = resolveType.AsVariable(); resolutionContext.AddDefinedVariable(this.ScopeId, variable); resolutionContext.AddInstruction(variable.AssignTo(expression)); return variable; } } }
using Stashbox.BuildUp; using Stashbox.Registration; using Stashbox.Resolution; using System; using System.Linq.Expressions; using System.Threading; namespace Stashbox.Lifetime { /// <summary> /// Represents a shared base class for scoped lifetimes. /// </summary> public abstract class ScopedLifetimeBase : LifetimeBase { private static int scopeIdCounter; /// <summary> /// The id of the scope. /// </summary> protected readonly int ScopeId = Interlocked.Increment(ref scopeIdCounter); /// <summary> /// The object used to synchronization. /// </summary> protected readonly object Sync = new object(); /// <summary> /// Produces a factory expression to produce scoped instances. /// </summary> /// <param name="containerContext">The container context.</param> /// <param name="serviceRegistration">The service registration.</param> /// <param name="objectBuilder">The object builder.</param> /// <param name="resolutionContext">The resolution context.</param> /// <param name="resolveType">The resolve type.</param> /// <returns>The factory expression.</returns> public Expression GetFactoryExpression(IContainerContext containerContext, IServiceRegistration serviceRegistration, IObjectBuilder objectBuilder, ResolutionContext resolutionContext, Type resolveType) { var expr = base.GetExpression(containerContext, serviceRegistration, objectBuilder, resolutionContext, resolveType); return expr?.CompileDelegate(resolutionContext).AsConstant();//.AsLambda(resolutionContext.CurrentScopeParameter); } /// <summary> /// Stores the given expression in a local variable and saves it into the resolution context for further reuse. /// </summary> /// <param name="expression">The expression to store.</param> /// <param name="resolutionContext">The resolution context.</param> /// <param name="resolveType">The resolve type.</param> /// <returns>The local variable.</returns> public Expression StoreExpressionIntoLocalVariable(Expression expression, ResolutionContext resolutionContext, Type resolveType) { var variable = resolveType.AsVariable(); resolutionContext.AddDefinedVariable(this.ScopeId, variable); resolutionContext.AddInstruction(variable.AssignTo(expression)); return variable; } } }
mit
C#
3894622ddcb255346b49d23f65b6bd1009ca7bc3
Remove redundant initializing field by default
2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,smoogipooo/osu,Nabile-Rahmani/osu,naoey/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,naoey/osu,peppy/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,2yangk23/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,naoey/osu,EVAST9919/osu,johnneijzen/osu,DrabWeb/osu,Frontear/osuKyzer,johnneijzen/osu
osu.Game/Beatmaps/BeatmapDifficulty.cs
osu.Game/Beatmaps/BeatmapDifficulty.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace osu.Game.Beatmaps { public class BeatmapDifficulty { /// <summary> /// The default value used for all difficulty settings except <see cref="SliderMultiplier"/> and <see cref="SliderTickRate"/>. /// </summary> public const float DEFAULT_DIFFICULTY = 5; [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [JsonIgnore] public int ID { get; set; } public float DrainRate { get; set; } = DEFAULT_DIFFICULTY; public float CircleSize { get; set; } = DEFAULT_DIFFICULTY; public float OverallDifficulty { get; set; } = DEFAULT_DIFFICULTY; private float? approachRate; public float ApproachRate { get { return approachRate ?? OverallDifficulty; } set { approachRate = value; } } public float SliderMultiplier { get; set; } = 1; public float SliderTickRate { get; set; } = 1; /// <summary> /// Maps a difficulty value [0, 10] to a two-piece linear range of values. /// </summary> /// <param name="difficulty">The difficulty value to be mapped.</param> /// <param name="min">Minimum of the resulting range which will be achieved by a difficulty value of 0.</param> /// <param name="mid">Midpoint of the resulting range which will be achieved by a difficulty value of 5.</param> /// <param name="max">Maximum of the resulting range which will be achieved by a difficulty value of 10.</param> /// <returns>Value to which the difficulty value maps in the specified range.</returns> public static double DifficultyRange(double difficulty, double min, double mid, double max) { if (difficulty > 5) return mid + (max - mid) * (difficulty - 5) / 5; if (difficulty < 5) return mid - (mid - min) * (5 - difficulty) / 5; return mid; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel.DataAnnotations.Schema; using Newtonsoft.Json; namespace osu.Game.Beatmaps { public class BeatmapDifficulty { /// <summary> /// The default value used for all difficulty settings except <see cref="SliderMultiplier"/> and <see cref="SliderTickRate"/>. /// </summary> public const float DEFAULT_DIFFICULTY = 5; [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [JsonIgnore] public int ID { get; set; } public float DrainRate { get; set; } = DEFAULT_DIFFICULTY; public float CircleSize { get; set; } = DEFAULT_DIFFICULTY; public float OverallDifficulty { get; set; } = DEFAULT_DIFFICULTY; private float? approachRate = null; public float ApproachRate { get { return approachRate ?? OverallDifficulty; } set { approachRate = value; } } public float SliderMultiplier { get; set; } = 1; public float SliderTickRate { get; set; } = 1; /// <summary> /// Maps a difficulty value [0, 10] to a two-piece linear range of values. /// </summary> /// <param name="difficulty">The difficulty value to be mapped.</param> /// <param name="min">Minimum of the resulting range which will be achieved by a difficulty value of 0.</param> /// <param name="mid">Midpoint of the resulting range which will be achieved by a difficulty value of 5.</param> /// <param name="max">Maximum of the resulting range which will be achieved by a difficulty value of 10.</param> /// <returns>Value to which the difficulty value maps in the specified range.</returns> public static double DifficultyRange(double difficulty, double min, double mid, double max) { if (difficulty > 5) return mid + (max - mid) * (difficulty - 5) / 5; if (difficulty < 5) return mid - (mid - min) * (5 - difficulty) / 5; return mid; } } }
mit
C#
e09c547338b1bc8acdb6bc24f817a4d8d6aa5f8a
make the field in map enumerator readonly
yanggujun/commonsfornet,yanggujun/commonsfornet
src/Commons.Collections/Map/MapEnumerator.cs
src/Commons.Collections/Map/MapEnumerator.cs
// Copyright CommonsForNET 2014. // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; namespace Commons.Collections.Map { internal class MapEnumerator : IDictionaryEnumerator { private readonly IDictionary map; private readonly IDictionaryEnumerator iter; public MapEnumerator(IDictionary map) { this.map = map; iter = this.map.GetEnumerator(); } public DictionaryEntry Entry { get { var entry = new DictionaryEntry(iter.Key, iter.Value); return entry; } } public object Key { get { return Entry.Key; } } public object Value { get { return Entry.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return iter.MoveNext(); } public void Reset() { iter.Reset(); } } }
// Copyright CommonsForNET 2014. // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections; using System.Collections.Generic; namespace Commons.Collections.Map { internal class MapEnumerator : IDictionaryEnumerator { private IDictionary map; private IDictionaryEnumerator iter; public MapEnumerator(IDictionary map) { this.map = map; iter = this.map.GetEnumerator(); } public DictionaryEntry Entry { get { var entry = new DictionaryEntry(iter.Key, iter.Value); return entry; } } public object Key { get { return Entry.Key; } } public object Value { get { return Entry.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return iter.MoveNext(); } public void Reset() { iter.Reset(); } } }
apache-2.0
C#
346a603dc79f92985b5fdce1d345f3cbbf71766d
Update HexToColorConverter.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Converters/HexToColorConverter.cs
src/Core2D/Converters/HexToColorConverter.cs
#nullable enable using System; using System.Globalization; using Avalonia; using Avalonia.Data.Converters; using Avalonia.Media; namespace Core2D.Converters; public class HexToColorConverter : IValueConverter { public static HexToColorConverter Instance = new(); public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is string s && (targetType == typeof(Color?) || targetType == typeof(Color))) { try { if (Color.TryParse(s, out var color)) { return color; } } catch (Exception) { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is Color c && targetType == typeof(string)) { try { return $"#{c.ToUint32():x8}"; } catch (Exception) { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } }
#nullable enable using System; using System.Globalization; using Avalonia; using Avalonia.Data.Converters; using Avalonia.Media; namespace Core2D.Converters; public class HexToColorConverter : IValueConverter { public static HexToColorConverter Instance = new(); public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is string s && targetType == typeof(Color)) { try { if (Color.TryParse(s, out var color)) { return color; } } catch (Exception) { return AvaloniaProperty.UnsetValue; } } if (value is uint n && targetType == typeof(Color)) { try { return Color.FromUInt32(n); } catch (Exception) { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) { if (value is Color c1 && targetType == typeof(string)) { try { return $"#{c1.ToUint32():x8}"; } catch (Exception) { return AvaloniaProperty.UnsetValue; } } if (value is Color c2 && targetType == typeof(uint)) { try { return c2.ToUint32(); } catch (Exception) { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } }
mit
C#
8a1a12c39a217f4b8b2c63b2dc8ff058df012ec0
Check the right thing lol
krille90/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,krille90/unitystation
UnityProject/Assets/Scripts/Inventory/DamageOnPickUp.cs
UnityProject/Assets/Scripts/Inventory/DamageOnPickUp.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageOnPickUp : MonoBehaviour, IServerInventoryMove { /// <summary> /// Does damage to active left or right arm. /// </summary> public bool doesDamage; /// <summary> /// 1 = 100% /// </summary> public float doesDamageChance = 1f; public float amountOfDamage = 10f; public AttackType attackType; public DamageType damageType; public ItemTrait[] protectionItemTraits; private PlayerScript player; public void OnInventoryMoveServer(InventoryMove info) { if (info.InventoryMoveType != InventoryMoveType.Add) return; if (info.ToSlot != null && info.ToSlot?.NamedSlot != null) { player = info.ToRootPlayer?.PlayerScript; if (player != null) { DoDamage(info); } } } private void DoDamage(InventoryMove info) { if (doesDamage && Random.value < doesDamageChance) { foreach (var trait in protectionItemTraits) { if (trait == null || Validations.HasItemTrait(player.Equipment.GetClothingItem(NamedSlot.hands).GameObjectReference, trait)) return; } if (info.ToSlot.NamedSlot == NamedSlot.leftHand) { player.playerHealth.ApplyDamageToBodypart(gameObject, amountOfDamage, attackType, damageType, BodyPartType.LeftArm); } else { player.playerHealth.ApplyDamageToBodypart(gameObject, amountOfDamage, attackType, damageType, BodyPartType.RightArm); } Chat.AddExamineMsgFromServer(player.gameObject, "<color=red>You injure yourself picking up the " + GetComponent<ItemAttributesV2>().ArticleName + "</color>"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DamageOnPickUp : MonoBehaviour, IServerInventoryMove { /// <summary> /// Does damage to active left or right arm. /// </summary> public bool doesDamage; /// <summary> /// 1 = 100% /// </summary> public float doesDamageChance = 1f; public float amountOfDamage = 10f; public AttackType attackType; public DamageType damageType; public ItemTrait[] protectionItemTraits; private PlayerScript player; public void OnInventoryMoveServer(InventoryMove info) { if (info.InventoryMoveType != InventoryMoveType.Add) return; if (info.ToSlot != null && info.ToSlot?.NamedSlot != null) { player = info.ToRootPlayer?.PlayerScript; if (player != null) { DoDamage(info); } } } private void DoDamage(InventoryMove info) { if (doesDamage && Random.value < doesDamageChance) { foreach (var trait in protectionItemTraits) { if (trait == null || Validations.HasItemTrait(info.MovedObject.gameObject, trait)) return; } if (info.ToSlot.NamedSlot == NamedSlot.leftHand) { player.playerHealth.ApplyDamageToBodypart(gameObject, amountOfDamage, attackType, damageType, BodyPartType.LeftArm); } else { player.playerHealth.ApplyDamageToBodypart(gameObject, amountOfDamage, attackType, damageType, BodyPartType.RightArm); } Chat.AddExamineMsgFromServer(player.gameObject, "<color=red>You injure yourself picking up the " + GetComponent<ItemAttributesV2>().ArticleName + "</color>"); } } }
agpl-3.0
C#
9c7985e644bef68d1701fe6a7c9978fcc30a9a7b
Update ShapePresenter.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Core/Presenters/ShapePresenter.cs
src/Draw2D.Core/Presenters/ShapePresenter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Draw2D.Core.Renderers; using Draw2D.Core.Editor; namespace Draw2D.Core.Presenters { public abstract class ShapePresenter { public IDictionary<Type, ShapeHelper> Helpers { get; set; } public abstract void DrawContent(object dc, IToolContext context); public abstract void DrawWorking(object dc, IToolContext context); public abstract void DrawHelpers(object dc, IToolContext context); } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using Draw2D.Core.Renderers; using Draw2D.Core.Editor; namespace Draw2D.Core.Presenters { public abstract class ShapePresenter { public IDictionary<Type, ShapeHelper> Helpers { get; set; } public abstract void Draw(object dc, IToolContext context); public abstract void DrawHelpers(object dc, IToolContext context); } }
mit
C#
0ffbbac3be7d8631547916d72457bb7eb9e8190b
check for actual version number #136
punker76/Markdown-Edit,mike-ward/Markdown-Edit
src/MarkdownEdit/Models/Version.cs
src/MarkdownEdit/Models/Version.cs
using System; using System.Net.Http; using System.Threading.Tasks; using System.Linq; namespace MarkdownEdit.Models { internal static class Version { public const string VersionNumber = "1.25.1"; public static async Task<bool> IsCurrentVersion() { try { using (var http = new HttpClient()) { var version = await http.GetStringAsync("http://markdownedit.com/version.txt"); if (!version.All(c => c >= '0' && c <= '9' || c == '.')) return true; // network redirected to signon for instance return string.IsNullOrWhiteSpace(version) || version == VersionNumber; } } catch (Exception) { return true; } } } }
using System; using System.Net.Http; using System.Threading.Tasks; namespace MarkdownEdit.Models { internal static class Version { public const string VersionNumber = "1.25.1"; public static async Task<bool> IsCurrentVersion() { try { using (var http = new HttpClient()) { var version = await http.GetStringAsync("http://markdownedit.com/version.txt"); return string.IsNullOrWhiteSpace(version) || version == VersionNumber; } } catch (Exception) { return true; } } } }
mit
C#
0204de4c4b6b7f0369eb2d71762bef5d359aa704
add navbar with link back to homepage
ucdavis/Namster,ucdavis/Namster,ucdavis/Namster
src/Namster/Views/Home/List.cshtml
src/Namster/Views/Home/List.cshtml
@{ ViewData["Title"] = "List Results"; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet" /> <nav class="navbar navbar-dark bg-inverse" style="background-color: #002855;"> <a class="navbar-brand" href="#">NamstR</a> <ul class="nav navbar-nav"> <li class="nav-item"> <a class="nav-link" href="#">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="#">Pricing</a> </li> <li class="nav-item"> <a class="nav-link" href="#">About</a> </li> </ul> <form class="form-inline pull-xs-right" method="get" action="/"> <input class="form-control" type="text" name="query" placeholder="Search"> <button class="btn btn-success-outline" type="submit">Search</button> </form> </nav> <br/> <div class="container-fluid"> <div id="example"></div> </div> @section scripts { <environment names="Development"> <script src="https://fb.me/react-0.14.3.js"></script> <script src="https://fb.me/react-dom-0.14.3.js"></script> </environment> <environment names="Staging,Production"> <script src="https://fb.me/react-0.14.3.min.js"></script> <script src="https://fb.me/react-dom-0.14.3.min.js"></script> </environment> <script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script> <script src="~/js/dist/list.js"></script> }
@{ ViewData["Title"] = "List Results"; } <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css" rel="stylesheet" /> <div class="container-fluid"> <div id="example"></div> </div> @section scripts { <environment names="Development"> <script src="https://fb.me/react-0.14.3.js"></script> <script src="https://fb.me/react-dom-0.14.3.js"></script> </environment> <environment names="Staging,Production"> <script src="https://fb.me/react-0.14.3.min.js"></script> <script src="https://fb.me/react-dom-0.14.3.min.js"></script> </environment> <script src="//cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js"></script> <script src="~/js/dist/list.js"></script> }
mit
C#
a118a5ee4c688d180f3258c20101fdb83172853e
Make RowStrings private
12joan/hangman
table.cs
table.cs
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { return String.Join("\n", RowStrings()); } private string[] RowStrings() { var rowTexts = new List<string>(); foreach (var row in Rows) { rowTexts.Add(row.Text); } return rowTexts.ToArray(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { return String.Join("\n", RowStrings()); } public string[] RowStrings() { var rowTexts = new List<string>(); foreach (var row in Rows) { rowTexts.Add(row.Text); } return rowTexts.ToArray(); } } }
unlicense
C#
6dc7e1104f976b3b3e172f1327eeb5f9b3d8af7d
change some incorrect comments
noliar/MoreAuthentication
src/Microsoft.AspNet.Authentication.Yixin/YixinServiceCollectionExtensions.cs
src/Microsoft.AspNet.Authentication.Yixin/YixinServiceCollectionExtensions.cs
using Microsoft.AspNet.Authentication.Yixin; using Microsoft.Framework.Configuration; using Microsoft.Framework.Internal; using System; namespace Microsoft.Framework.DependencyInjection { /// <summary> /// Extension methods for using <see cref="YixinAuthenticationMiddleware" /> /// </summary> public static class YixinServiceCollectionExtensions { public static IServiceCollection ConfigureYixinAuthentication([NotNull] this IServiceCollection services, [NotNull] Action<YixinAuthenticationOptions> configure, string optionsName = "") { return services.Configure(configure, optionsName); } public static IServiceCollection ConfigureYixinAuthentication([NotNull] this IServiceCollection services, [NotNull] IConfiguration config, string optionsName = "") { return services.Configure<YixinAuthenticationOptions>(config, optionsName); } } }
using Microsoft.AspNet.Authentication.Yixin; using Microsoft.Framework.Configuration; using Microsoft.Framework.Internal; using System; namespace Microsoft.Framework.DependencyInjection { /// <summary> /// Extension methods for using <see cref="YixinServiceCollectionExtensions" /> /// </summary> public static class YixinServiceCollectionExtensions { public static IServiceCollection ConfigureYixinAuthentication([NotNull] this IServiceCollection services, [NotNull] Action<YixinAuthenticationOptions> configure, string optionsName = "") { return services.Configure(configure, optionsName); } public static IServiceCollection ConfigureYixinAuthentication([NotNull] this IServiceCollection services, [NotNull] IConfiguration config, string optionsName = "") { return services.Configure<YixinAuthenticationOptions>(config, optionsName); } } }
apache-2.0
C#
b29a36d0042672cc05eab30406ac8c1f82fb0e56
fix exception handling issue in the main layout #1653 (#1663)
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/Tooling/Bit.Tooling.Templates/TodoTemplate/Web/Shared/MainLayout.razor.cs
src/Tooling/Bit.Tooling.Templates/TodoTemplate/Web/Shared/MainLayout.razor.cs
namespace TodoTemplate.App.Shared { public partial class MainLayout : IAsyncDisposable { public bool IsUserAuthenticated { get; set; } public bool IsMenuOpen { get; set; } = false; [Inject] public IStateService StateService { get; set; } = default!; [Inject] public IExceptionHandler ExceptionHandler { get; set; } = default!; [Inject] public TodoTemplateAuthenticationStateProvider TodoTemplateAuthenticationStateProvider { get; set; } = default!; protected override async Task OnInitializedAsync() { try { TodoTemplateAuthenticationStateProvider.AuthenticationStateChanged += VerifyUserIsAuthenticatedOrNot; IsUserAuthenticated = await StateService.GetValue(nameof(IsUserAuthenticated), async () => await TodoTemplateAuthenticationStateProvider.IsUserAuthenticated()); await base.OnInitializedAsync(); } catch (Exception exp) { ExceptionHandler.OnExceptionReceived(exp); } } async void VerifyUserIsAuthenticatedOrNot(Task<AuthenticationState> task) { try { IsUserAuthenticated = await TodoTemplateAuthenticationStateProvider.IsUserAuthenticated(); } catch (Exception ex) { ExceptionHandler.OnExceptionReceived(ex); } finally { StateHasChanged(); } } private void ToggleMenuHandler() { IsMenuOpen = !IsMenuOpen; } public async ValueTask DisposeAsync() { TodoTemplateAuthenticationStateProvider.AuthenticationStateChanged -= VerifyUserIsAuthenticatedOrNot; } } }
namespace TodoTemplate.App.Shared { public partial class MainLayout : IAsyncDisposable { public bool IsUserAuthenticated { get; set; } public bool IsMenuOpen { get; set; } = false; [Inject] public IStateService StateService { get; set; } = default!; [Inject] public IExceptionHandler ExceptionHandler { get; set; } = default!; [Inject] public TodoTemplateAuthenticationStateProvider TodoTemplateAuthenticationStateProvider { get; set; } = default!; protected override async Task OnInitializedAsync() { TodoTemplateAuthenticationStateProvider.AuthenticationStateChanged += VerifyUserIsAuthenticatedOrNot; IsUserAuthenticated = await StateService.GetValue(nameof(IsUserAuthenticated), async () => await TodoTemplateAuthenticationStateProvider.IsUserAuthenticated()); await base.OnInitializedAsync(); } async void VerifyUserIsAuthenticatedOrNot(Task<AuthenticationState> task) { try { IsUserAuthenticated = await TodoTemplateAuthenticationStateProvider.IsUserAuthenticated(); } catch (Exception ex) { ExceptionHandler.OnExceptionReceived(ex); } finally { StateHasChanged(); } } private void ToggleMenuHandler() { IsMenuOpen = !IsMenuOpen; } public async ValueTask DisposeAsync() { TodoTemplateAuthenticationStateProvider.AuthenticationStateChanged -= VerifyUserIsAuthenticatedOrNot; } } }
mit
C#
571726459b40e2310d39665500418cded90098c2
Add null check to HierarchyManager Find methods
bd339/HTX-School-Trip
Assets/Scripts/HierarchyManager.cs
Assets/Scripts/HierarchyManager.cs
using UnityEngine; // wrapper for Unity 5.4 beta methods class HierarchyManager { public static GameObject Find (string name) { var go = GameObject.Find ("Root").transform.FindChildIncludingDeactivated (name); return go != null ? go.gameObject : null; } public static GameObject Find (string name, Transform t) { var go = t.FindChildIncludingDeactivated (name); return go != null ? go.gameObject : null; } public static T [] FindObjectsOfType<T> () where T : Component { return GameObject.Find ("Root").transform.GetAllComponentsInChildren<T> (); } public static T FindObjectOfType<T> () where T : Component { var a = FindObjectsOfType<T> (); return a.Length > 0 ? a [0] : null; } }
using UnityEngine; // wrapper for Unity 5.4 beta methods class HierarchyManager { public static GameObject Find (string name) { return GameObject.Find ("Root").transform.FindChildIncludingDeactivated (name).gameObject; } public static GameObject Find (string name, Transform t) { return t.FindChildIncludingDeactivated (name).gameObject; } public static T [] FindObjectsOfType<T> () where T : Component { return GameObject.Find ("Root").transform.GetAllComponentsInChildren<T> (); } public static T FindObjectOfType<T> () where T : Component { var a = FindObjectsOfType<T> (); return a.Length > 0 ? a [0] : null; } }
mit
C#
bbf9f477f3dc318045520b8a52c909b8044402d2
Update text on countdown timer GUI
hcorion/RoverVR
Assets/Scripts/Player/CountDown.cs
Assets/Scripts/Player/CountDown.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; private Text text; // Use this for initialization void Start () { curTime = maxTime; text = gameObject.GetComponent( typeof(Text) ) as Text; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); //Debug.Log(prettyTime); text.text = prettyTime; } }
using UnityEngine; using System.Collections; public class CountDown : MonoBehaviour { public float maxTime = 600; //Because it is in seconds; private float curTime; private string prettyTime; // Use this for initialization void Start () { curTime = maxTime; } // Update is called once per frame void Update () { curTime -= Time.deltaTime; //Debug.Log(curTime); prettyTime = Mathf.FloorToInt(curTime/60) + ":" + Mathf.FloorToInt((60*(curTime/60 - Mathf.Floor(curTime/60)))); Debug.Log(prettyTime); } }
mit
C#
c4098c2c5e2c336e5a9f2c70c79e49d941e22f2b
Patch Import-B2State
LordMike/B2Lib
B2Powershell/ImportStateCommand.cs
B2Powershell/ImportStateCommand.cs
using System.Management.Automation; using B2Lib; using B2Lib.Objects; namespace B2Powershell { [Cmdlet("Import", "B2State")] public class ImportStateCommand : PSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string File { get; set; } protected override void ProcessRecord() { B2Client client = new B2Client(); client.LoadState(File); B2SaveState state = client.SaveState(); this.SaveState(state); WriteObject(state); } } }
using System.Management.Automation; using B2Lib; namespace B2Powershell { [Cmdlet("Import", "B2State")] public class ImportStateCommand : PSCmdlet { [Parameter(Mandatory = true, Position = 0)] public string File { get; set; } protected override void ProcessRecord() { B2Client client = new B2Client(); client.LoadState(File); WriteObject(client.SaveState()); } } }
mit
C#
58ca652ff7d02aa7231bb271200c64819936a983
Fix GDAXFeeModel fee structure for non-BTC symbols
AlexCatarino/Lean,StefanoRaggi/Lean,AnshulYADAV007/Lean,AlexCatarino/Lean,JKarathiya/Lean,jameschch/Lean,JKarathiya/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,jameschch/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,AnshulYADAV007/Lean,Jay-Jay-D/LeanSTP,StefanoRaggi/Lean,JKarathiya/Lean,AnshulYADAV007/Lean,jameschch/Lean,jameschch/Lean,kaffeebrauer/Lean,redmeros/Lean,QuantConnect/Lean,AnshulYADAV007/Lean,QuantConnect/Lean,AlexCatarino/Lean,kaffeebrauer/Lean,kaffeebrauer/Lean,QuantConnect/Lean,StefanoRaggi/Lean,JKarathiya/Lean,jameschch/Lean,AnshulYADAV007/Lean,StefanoRaggi/Lean,Jay-Jay-D/LeanSTP,Jay-Jay-D/LeanSTP,Jay-Jay-D/LeanSTP,Jay-Jay-D/LeanSTP,redmeros/Lean,QuantConnect/Lean,redmeros/Lean,redmeros/Lean
Common/Orders/Fees/GDAXFeeModel.cs
Common/Orders/Fees/GDAXFeeModel.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; namespace QuantConnect.Orders.Fees { /// <summary> /// Provides an implementation of <see cref="IFeeModel"/> that models GDAX order fees /// </summary> public class GDAXFeeModel : IFeeModel { /// <summary> /// Tier 1 maker fees /// https://www.gdax.com/fees/BTC-USD /// </summary> private static readonly Dictionary<string, decimal> Fees = new Dictionary<string, decimal> { { "BTCUSD", 0.0025m }, { "BTCEUR", 0.0025m }, { "BTCGBP", 0.0025m }, { "ETHBTC", 0.003m }, { "ETHEUR", 0.003m }, { "ETHUSD", 0.003m }, { "LTCBTC", 0.003m }, { "LTCEUR", 0.003m }, { "LTCUSD", 0.003m }, }; /// <summary> /// Get the fee for this order /// </summary> /// <param name="security">The security matching the order</param> /// <param name="order">The order to compute fees for</param> /// <returns>The cost of the order in units of the account currency</returns> public decimal GetOrderFee(Securities.Security security, Order order) { //0% maker fee after reimbursement. if (order.Type == OrderType.Limit) { return 0m; } // currently we do not model daily rebates decimal fee; Fees.TryGetValue(security.Symbol.Value, out fee); return security.Price * order.AbsoluteQuantity * fee; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace QuantConnect.Orders.Fees { /// <summary> /// Provides an implementation of <see cref="IFeeModel"/> that models GDAX order fees /// </summary> public class GDAXFeeModel : IFeeModel { /// <summary> /// Get the fee for this order /// </summary> /// <param name="security">The security matching the order</param> /// <param name="order">The order to compute fees for</param> /// <returns>The cost of the order in units of the account currency</returns> public decimal GetOrderFee(Securities.Security security, Order order) { //0% maker fee after reimbursement. if (order.Type == OrderType.Limit) { return 0m; } //todo: fee scaling with trade size var divisor = 0.0025m; decimal fee = security.Price * (order.Quantity < 0 ? (order.Quantity * -1) : order.Quantity) * divisor; return fee; } } }
apache-2.0
C#
f425f1478a7e15c18eba82e4ec9f83a47a974988
Update Program.cs
jacobrossandersen/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //Code was added in GitHub } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { } } }
mit
C#
7427ceb80abd48be2ab8f18bc5d4fe17d8ed263b
test server side delay
gaochundong/Cowboy
Cowboy/Tests/Cowboy.WebSockets.TestAsyncWebSocketServer/TestWebSocketModule.cs
Cowboy/Tests/Cowboy.WebSockets.TestAsyncWebSocketServer/TestWebSocketModule.cs
using System; using System.Text; using System.Threading.Tasks; namespace Cowboy.WebSockets.TestAsyncWebSocketServer { public class TestWebSocketModule : AsyncWebSocketServerModule { public TestWebSocketModule() : base(@"/test") { } public override async Task OnSessionStarted(AsyncWebSocketSession session) { Console.WriteLine(string.Format("WebSocket session [{0}] has connected.", session.RemoteEndPoint)); await Task.CompletedTask; } public override async Task OnSessionTextReceived(AsyncWebSocketSession session, string text) { Console.Write(string.Format("WebSocket session [{0}] received Text --> ", session.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await session.SendTextAsync(text); } public override async Task OnSessionBinaryReceived(AsyncWebSocketSession session, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); Console.Write(string.Format("WebSocket session [{0}] received Binary --> ", session.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); //await Task.Delay(TimeSpan.FromSeconds(10)); //await Task.CompletedTask; await session.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); } public override async Task OnSessionClosed(AsyncWebSocketSession session) { Console.WriteLine(string.Format("WebSocket session [{0}] has disconnected.", session.RemoteEndPoint)); await Task.CompletedTask; } } }
using System; using System.Text; using System.Threading.Tasks; namespace Cowboy.WebSockets.TestAsyncWebSocketServer { public class TestWebSocketModule : AsyncWebSocketServerModule { public TestWebSocketModule() : base(@"/test") { } public override async Task OnSessionStarted(AsyncWebSocketSession session) { Console.WriteLine(string.Format("WebSocket session [{0}] has connected.", session.RemoteEndPoint)); await Task.CompletedTask; } public override async Task OnSessionTextReceived(AsyncWebSocketSession session, string text) { Console.Write(string.Format("WebSocket session [{0}] received Text --> ", session.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); await session.SendTextAsync(text); } public override async Task OnSessionBinaryReceived(AsyncWebSocketSession session, byte[] data, int offset, int count) { var text = Encoding.UTF8.GetString(data, offset, count); Console.Write(string.Format("WebSocket session [{0}] received Binary --> ", session.RemoteEndPoint)); Console.WriteLine(string.Format("{0}", text)); //await Task.Delay(TimeSpan.FromSeconds(10)); await Task.CompletedTask; //await session.SendBinaryAsync(Encoding.UTF8.GetBytes(text)); } public override async Task OnSessionClosed(AsyncWebSocketSession session) { Console.WriteLine(string.Format("WebSocket session [{0}] has disconnected.", session.RemoteEndPoint)); await Task.CompletedTask; } } }
mit
C#
9af2b3573dd60300e9f814f034ac5bcaa412b7dd
Fix file paths default value null
danielchalmers/DesktopWidgets
DesktopWidgets/Classes/FilePath.cs
DesktopWidgets/Classes/FilePath.cs
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } = ""; } }
using System.ComponentModel; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace DesktopWidgets.Classes { [ExpandableObject] [DisplayName("File")] public class FilePath { public FilePath(string path) { Path = path; } public FilePath() { } [DisplayName("Path")] public string Path { get; set; } } }
apache-2.0
C#
18f5c0a3c4af2e271b877799d4b7606a34367a78
Update _Menu.cshtml
PiranhaCMS/piranha.core,filipjansson/piranha.core,PiranhaCMS/piranha.core,filipjansson/piranha.core,filipjansson/piranha.core,PiranhaCMS/piranha.core,PiranhaCMS/piranha.core
templates/BasicWeb/Views/Shared/Partial/_Menu.cshtml
templates/BasicWeb/Views/Shared/Partial/_Menu.cshtml
@inject Piranha.IApi Api @{ var sitemap = Api.Sites.GetSitemap(); } @*Not the best solution but meanwhile... class = d-sm-block d-md-none is hiding on md screen solution*@ <nav class="navbar navbar-toggleable-sm navbar-dark bg-faded d-sm-block d-md-none"> <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="#"></a> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <div class="navbar-nav"> @foreach (var item in sitemap) { <a class="nav-item nav-link @(item.Id == ViewBag.CurrentPage ? "active" : "")" href="@item.Permalink"><span>@item.MenuTitle</span></a> } </div> </div> </nav> @*Not the best solution but meanwhile... class = d-none d-md-block is hiding on sm screen solution*@ <nav class="navbar d-none d-md-block"> <ul class="nav nav-site justify-content-center"> @foreach (var item in sitemap) { <li class="nav-item @(item.Id == ViewBag.CurrentPage ? "active" : "")"> <a class="nav-link" href="@item.Permalink"><span>@item.MenuTitle</span></a> </li> } </ul> </nav>
@inject Piranha.IApi Api @{ var sitemap = Api.Sites.GetSitemap(); } <ul class="nav nav-site justify-content-center"> @foreach (var item in sitemap) { <li class="nav-item @(item.Id == ViewBag.CurrentPage ? "active" : "")"> <a class="nav-link" href="@item.Permalink"><span>@item.MenuTitle</span></a> </li> } </ul>
mit
C#
930b22d30b0caaec01b6a79c9afc379ee680e969
Make it Rain now rains blocks constantly
TheMagnificentSeven/MakeItRain
Assets/Scripts/MakeItRain.cs
Assets/Scripts/MakeItRain.cs
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; int count = 0; // Use this for initialization void Start() { } // Update is called once per frame // Just for test void Update() { if (count % 100 == 0) { Rain(); count++; } count++; } // Called only when dance is finished void Rain() { int whichRain = Random.Range(1, 5); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(minX, maxX - rain.GetComponent<BoxCollider2D>().size.x); float y_rand = Random.Range(1f, 3f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y - y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
using UnityEngine; using System.Collections; public class MakeItRain : MonoBehaviour { private int numObjects = 20; private float minX = -4f; private float maxX = 4f; private GameObject rain; private GameObject rainClone; // Use this for initialization void Start() { // Here only for test Rain(); } // Update is called once per frame void Update() { } void Rain() { int whichRain = Random.Range(1, 4); switch (whichRain) { case 1: rain = GameObject.Find("Rain/healObj"); break; case 2: rain = GameObject.Find("Rain/safeObj"); break; case 3: rain = GameObject.Find("Rain/mediumObj"); break; default: rain = GameObject.Find("Rain/dangerousObj"); break; } for (int i = 0; i < numObjects; i++) { float x_rand = Random.Range(-4f, 4f); float y_rand = Random.Range(-1f, 1f); rainClone = (GameObject)Instantiate(rain, new Vector3(x_rand, rain.transform.position.y + y_rand, rain.transform.position.z), rain.transform.rotation); rainClone.GetComponent<Rigidbody2D>().gravityScale = 1; } } }
mit
C#
6f73ad28d674924b5852926af6f1a934d342c0ef
Add support for switching endianness of float and double fields
canton7/BitPacker,canton7/BitPacker
BitPacker/EndianUtilities.cs
BitPacker/EndianUtilities.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitPacker { internal static class EndianUtilities { public static Endianness HostEndianness = BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian; public static ushort Swap(ushort val) { return (ushort)(((val & 0xFF00) >> 8) | ((val & 0x00FF) << 8)); } public static short Swap(short val) { return (short)Swap((ushort)val); } public static uint Swap(uint val) { // Swap adjacent 16-bit blocks val = (val >> 16) | (val << 16); // Swap adjacent 8-bit blocks val = ((val & 0xFF00FF00) >> 8) | ((val & 0x00FF00FF) << 8); return val; } public static int Swap(int val) { return (int)Swap((uint)val); } public static ulong Swap(ulong val) { // Swap adjacent 32-bit blocks val = (val >> 32) | (val << 32); // Swap adjacent 16-bit blocks val = ((val & 0xFFFF0000FFFF0000) >> 16) | ((val & 0x0000FFFF0000FFFF) << 16); // Swap adjacent 8-bit blocks val = ((val & 0xFF00FF00FF00FF00) >> 8) | ((val & 0x00FF00FF00FF00FF) << 8); return val; } public static long Swap(long val) { return (long)Swap((ulong)val); } public static float Swap(float val) { // We can't get the raw bytes ourselves without unmanaged code, and I don't want this library to be unmanaged // So use BitConverter, even though it's slower // TODO: Profile this against BitConverter.ToSingle(BitConverter.GetBytes(val).Reverse().ToArray(), 0) // The current implementation doesn't do an array reversal and allocate, but does have more method calls return BitConverter.ToSingle(BitConverter.GetBytes(Swap(BitConverter.ToInt32(BitConverter.GetBytes(val), 0))), 0); } public static double Swap(double val) { // We can play a slightly better trick on this one return BitConverter.Int64BitsToDouble(Swap(BitConverter.DoubleToInt64Bits(val))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitPacker { internal static class EndianUtilities { public static Endianness HostEndianness = BitConverter.IsLittleEndian ? Endianness.LittleEndian : Endianness.BigEndian; public static ushort Swap(ushort val) { return (ushort)(((val & 0xFF00) >> 8) | ((val & 0x00FF) << 8)); } public static short Swap(short val) { return (short)Swap((ushort)val); } public static uint Swap(uint val) { // Swap adjacent 16-bit blocks val = (val >> 16) | (val << 16); // Swap adjacent 8-bit blocks val = ((val & 0xFF00FF00) >> 8) | ((val & 0x00FF00FF) << 8); return val; } public static int Swap(int val) { return (int)Swap((uint)val); } public static ulong Swap(ulong val) { // Swap adjacent 32-bit blocks val = (val >> 32) | (val << 32); // Swap adjacent 16-bit blocks val = ((val & 0xFFFF0000FFFF0000) >> 16) | ((val & 0x0000FFFF0000FFFF) << 16); // Swap adjacent 8-bit blocks val = ((val & 0xFF00FF00FF00FF00) >> 8) | ((val & 0x00FF00FF00FF00FF) << 8); return val; } public static long Swap(long val) { return (long)Swap((ulong)val); } } }
mit
C#
6a9e88e953108f2c1aef694a072fae9bbc85b425
fix wording on the Index page
ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me
ForneverMind/views/en/Index.cshtml
ForneverMind/views/en/Index.cshtml
@model ForneverMind.Models.PostArchiveModel @{ Layout = "en/_Layout.cshtml"; ViewBag.Title = "int 20h"; } <p>Hello!</p> <p>My name is Friedrich von Never.</p> <p>This is my website where I'm publising my technical and programming notes.</p> <h2>Latest posts</h2> <ul> @foreach (var post in Model.Posts) { <li> <a href="..@post.Url">@post.Title</a> — @post.Date.ToString("yyyy-MM-dd") </li> } </ul> <p>You can view a list of all the posts in the <a href="./archive.html">Archive</a>.</p>
@model ForneverMind.Models.PostArchiveModel @{ Layout = "en/_Layout.cshtml"; ViewBag.Title = "int 20h"; } <p>Hello!</p> <p>My name is Friedrich von Never.</p> <p>This is my website. I'm publising my technical and programming notes here.</p> <h2>Latest posts</h2> <ul> @foreach (var post in Model.Posts) { <li> <a href="..@post.Url">@post.Title</a> — @post.Date.ToString("yyyy-MM-dd") </li> } </ul> <p>You can view a list of all the posts in the <a href="./archive.html">Archive</a>.</p>
mit
C#
f8a324c15aa53aabde7b8981f329d4bae90b9377
Hide about screen
baseclass/nuserv,baseclass/nuserv,baseclass/nuserv
nuserv/Views/Shared/_Layout.cshtml
nuserv/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body ng-app="@ViewBag.App"> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("nuserv", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("repositories", "Index", "Repository")</li> @*<li>@Html.ActionLink("about", "About", "Home")</li>*@ </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - nuserv</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body ng-app="@ViewBag.App"> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("nuserv", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("repositories", "Index", "Repository")</li> <li>@Html.ActionLink("about", "About", "Home")</li> </ul> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - nuserv</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
811ca25e7c1d312e6daebba2b9be33d43eebf832
Reset ComVisible to false
Miruken-DotNet/Miruken
Miruken/Properties/AssemblyInfo.cs
Miruken/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("Miruken")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Miruken")] // 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("82c1e9de-d611-47ce-a091-2bed66df5ac6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")] //updated in TeamCity [assembly: AssemblyFileVersion("0.0.0.0")] //updated in TeamCity [assembly: AssemblyInformationalVersion("0.0.0.0")] //updated in TeamCity
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("Miruken")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Miruken")] // 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(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("82c1e9de-d611-47ce-a091-2bed66df5ac6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.0")] //updated in TeamCity [assembly: AssemblyFileVersion("0.0.0.0")] //updated in TeamCity [assembly: AssemblyInformationalVersion("0.0.0.0")] //updated in TeamCity
mit
C#
8be4a079caba68b286884885acb19875ce4d97fa
Align failing CodeContracts case better to object Invariant.
pgeerkens/Monads
MonadTests/StaticContractsCases.cs
MonadTests/StaticContractsCases.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct Maybe<T> { ///<summary>Create a new Maybe{T}.</summary> private Maybe(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = ! HasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace PGSolutions.Utilities.Monads.StaticContracts { using static Contract; public struct MaybeAssume<T> { ///<summary>Create a new Maybe{T}.</summary> private MaybeAssume(T value) : this() { Ensures(!HasValue || _value != null); _value = value; _hasValue = _value != null; } ///<summary>Returns whether this Maybe{T} has a value.</summary> public bool HasValue { get { return _hasValue; } } ///<summary>Extract value of the Maybe{T}, substituting <paramref name="defaultValue"/> as needed.</summary> [Pure] public T BitwiseOr(T defaultValue) { defaultValue.ContractedNotNull("defaultValue"); Ensures(Result<T>() != null); var result = !_hasValue ? defaultValue : _value; // Assume(result != null); return result; } /// <summary>The invariants enforced by this struct type.</summary> [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] [ContractInvariantMethod] [Pure] private void ObjectInvariant() { Invariant(!HasValue || _value != null); } readonly T _value; readonly bool _hasValue; } }
mit
C#
6fcd9cb257563f0116c5a1332d67623a1b713140
Make Blink demo hot-pluggable
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
NET/Demos/Console/Blink/Program.cs
NET/Demos/Console/Blink/Program.cs
using System; using Treehopper; using System.Threading.Tasks; using Treehopper.Desktop; using System.Windows.Threading; namespace Blink { /// <summary> /// This demo blinks the built-in LED using async programming. /// </summary> class Program { static TreehopperUsb Board; //[MTAThread] static void Main(string[] args) { // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method. Task.Run(RunBlink).Wait(); } static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.Version); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } Board.Disconnect(); } } } }
using System; using Treehopper; using System.Threading.Tasks; using Treehopper.Desktop; using System.Windows.Threading; namespace Blink { /// <summary> /// This demo blinks the built-in LED using async programming. /// </summary> class Program { static TreehopperUsb Board; //[MTAThread] static void Main(string[] args) { // We can't do async calls from the Console's Main() function, so we run all our code in a separate async method. Task.Run(RunBlink).Wait(); } static async Task RunBlink() { while (true) { Console.Write("Waiting for board..."); // Get a reference to the first TreehopperUsb board connected. This will await indefinitely until a board is connected. Board = await ConnectionService.Instance.GetFirstDeviceAsync(); Console.WriteLine("Found board: " + Board); Console.WriteLine("Version: " + Board.Version); // You must explicitly connect to a board before communicating with it await Board.ConnectAsync(); Console.WriteLine("Start blinking. Press any key to stop."); while (Board.IsConnected && !Console.KeyAvailable) { // toggle the LED. Board.Led = !Board.Led; await Task.Delay(100); } Console.ReadKey(); Board.Disconnect(); } } } }
mit
C#
78e7af5bbf74319f7869630ac750ad8b0eab8987
Disable partitioning in the bootstrapper.
ProjectExtensions/ProjectExtensions.Azure.ServiceBus
src/Samples/PubSubUsingConfiguration/Bootstrapper.cs
src/Samples/PubSubUsingConfiguration/Bootstrapper.cs
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) //.EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
using System.Configuration; using Amazon.ServiceBus.DistributedMessages.Serializers; using ProjectExtensions.Azure.ServiceBus; using ProjectExtensions.Azure.ServiceBus.Autofac.Container; namespace PubSubUsingConfiguration { static internal class Bootstrapper { public static void Initialize() { var setup = new ServiceBusSetupConfiguration() { DefaultSerializer = new GZipXmlSerializer(), ServiceBusIssuerKey = ConfigurationManager.AppSettings["ServiceBusIssuerKey"], ServiceBusIssuerName = ConfigurationManager.AppSettings["ServiceBusIssuerName"], ServiceBusNamespace = ConfigurationManager.AppSettings["ServiceBusNamespace"], ServiceBusApplicationId = "AppName" }; setup.AssembliesToRegister.Add(typeof(TestMessageSubscriber).Assembly); BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigurationSettings(setup) .EnablePartitioning(true) .DefaultSerializer(new GZipXmlSerializer()) .Configure(); /* BusConfiguration.WithSettings() .UseAutofacContainer() .ReadFromConfigFile() .ServiceBusApplicationId("AppName") .DefaultSerializer(new GZipXmlSerializer()) //.ServiceBusIssuerKey("[sb password]") //.ServiceBusIssuerName("owner") //.ServiceBusNamespace("[addresshere]") .RegisterAssembly(typeof(TestMessageSubscriber).Assembly) .Configure(); */ } } }
bsd-3-clause
C#
e94d05c0ef40dfb27d26202b0b6033e074ec6d6d
Revert "Replace Trace.WriteLine with Debug.WriteLine to resolve unknown reference."
andyfmiller/LtiLibrary
LtiLibrary.Core.Tests/SimpleHelpers/JsonAssertions.cs
LtiLibrary.Core.Tests/SimpleHelpers/JsonAssertions.cs
using System.Diagnostics; using LtiLibrary.Core.Common; using LtiLibrary.Core.Extensions; using LtiLibrary.Core.Tests.TestHelpers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NodaTime; using NodaTime.Serialization.JsonNet; using Xunit; namespace LtiLibrary.Core.Tests.SimpleHelpers { internal static class JsonAssertions { private static readonly JsonSerializerSettings SerializerSettings; static JsonAssertions() { SerializerSettings = new JsonSerializerSettings(); SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); } public static void AssertSameObjectJson(object obj, string eventReferenceFile) { var eventJsonString = JsonConvert.SerializeObject(obj, SerializerSettings); var eventJObject = JObject.Parse(eventJsonString); var refJsonString = TestUtils.LoadReferenceJsonFile(eventReferenceFile); var refJObject = JObject.Parse(refJsonString); var diff = ObjectDiffPatch.GenerateDiff(refJObject, eventJObject); Debug.WriteLine(diff.NewValues); Debug.WriteLine(diff.OldValues); Assert.Null(diff.NewValues); Assert.Null(diff.OldValues); } public static void AssertSameJsonLdObject( JsonLdObject obj, string eventReferenceFile ) { var eventJsonString = obj.ToJsonLdString(); var eventJObject = JObject.Parse( eventJsonString ); var refJsonString = TestUtils.LoadReferenceJsonFile( eventReferenceFile ); var refJObject = JObject.Parse( refJsonString ); var diff = ObjectDiffPatch.GenerateDiff( refJObject, eventJObject ); Trace.WriteLine( diff.NewValues ); Trace.WriteLine( diff.OldValues ); Assert.Null( diff.NewValues ); Assert.Null( diff.OldValues ); } } }
using System.Diagnostics; using LtiLibrary.Core.Common; using LtiLibrary.Core.Extensions; using LtiLibrary.Core.Tests.TestHelpers; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NodaTime; using NodaTime.Serialization.JsonNet; using Xunit; namespace LtiLibrary.Core.Tests.SimpleHelpers { internal static class JsonAssertions { private static readonly JsonSerializerSettings SerializerSettings; static JsonAssertions() { SerializerSettings = new JsonSerializerSettings(); SerializerSettings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); } public static void AssertSameObjectJson(object obj, string eventReferenceFile) { var eventJsonString = JsonConvert.SerializeObject(obj, SerializerSettings); var eventJObject = JObject.Parse(eventJsonString); var refJsonString = TestUtils.LoadReferenceJsonFile(eventReferenceFile); var refJObject = JObject.Parse(refJsonString); var diff = ObjectDiffPatch.GenerateDiff(refJObject, eventJObject); Debug.WriteLine(diff.NewValues); Debug.WriteLine(diff.OldValues); Assert.Null(diff.NewValues); Assert.Null(diff.OldValues); } public static void AssertSameJsonLdObject( JsonLdObject obj, string eventReferenceFile ) { var eventJsonString = obj.ToJsonLdString(); var eventJObject = JObject.Parse( eventJsonString ); var refJsonString = TestUtils.LoadReferenceJsonFile( eventReferenceFile ); var refJObject = JObject.Parse( refJsonString ); var diff = ObjectDiffPatch.GenerateDiff( refJObject, eventJObject ); Debug.WriteLine( diff.NewValues ); Debug.WriteLine( diff.OldValues ); Assert.Null( diff.NewValues ); Assert.Null( diff.OldValues ); } } }
apache-2.0
C#
a1030e23b0c3684e51b502e9637c4d61a72f5881
remove unnecessary test
ejona86/grpc,stanley-cheung/grpc,jboeuf/grpc,vjpai/grpc,muxi/grpc,vjpai/grpc,vjpai/grpc,donnadionne/grpc,firebase/grpc,ctiller/grpc,jtattermusch/grpc,ejona86/grpc,pszemus/grpc,donnadionne/grpc,ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,pszemus/grpc,firebase/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,grpc/grpc,firebase/grpc,ejona86/grpc,jboeuf/grpc,nicolasnoble/grpc,jtattermusch/grpc,ctiller/grpc,firebase/grpc,stanley-cheung/grpc,muxi/grpc,grpc/grpc,nicolasnoble/grpc,stanley-cheung/grpc,vjpai/grpc,jtattermusch/grpc,jboeuf/grpc,muxi/grpc,firebase/grpc,pszemus/grpc,muxi/grpc,jtattermusch/grpc,donnadionne/grpc,pszemus/grpc,vjpai/grpc,vjpai/grpc,vjpai/grpc,jboeuf/grpc,muxi/grpc,grpc/grpc,jtattermusch/grpc,grpc/grpc,grpc/grpc,ejona86/grpc,ctiller/grpc,ctiller/grpc,jtattermusch/grpc,ejona86/grpc,vjpai/grpc,jtattermusch/grpc,nicolasnoble/grpc,ctiller/grpc,donnadionne/grpc,vjpai/grpc,firebase/grpc,firebase/grpc,stanley-cheung/grpc,grpc/grpc,donnadionne/grpc,firebase/grpc,ejona86/grpc,muxi/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,pszemus/grpc,grpc/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,jboeuf/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,muxi/grpc,stanley-cheung/grpc,pszemus/grpc,jtattermusch/grpc,pszemus/grpc,jboeuf/grpc,ejona86/grpc,nicolasnoble/grpc,ctiller/grpc,ctiller/grpc,donnadionne/grpc,muxi/grpc,pszemus/grpc,jboeuf/grpc,nicolasnoble/grpc,ctiller/grpc,donnadionne/grpc,jboeuf/grpc,jboeuf/grpc,ejona86/grpc,ejona86/grpc,pszemus/grpc,vjpai/grpc,pszemus/grpc,firebase/grpc,stanley-cheung/grpc,jtattermusch/grpc,muxi/grpc,pszemus/grpc,ctiller/grpc,firebase/grpc,grpc/grpc,ctiller/grpc,stanley-cheung/grpc,nicolasnoble/grpc,jboeuf/grpc,donnadionne/grpc,donnadionne/grpc,ctiller/grpc,donnadionne/grpc,donnadionne/grpc,stanley-cheung/grpc,muxi/grpc,grpc/grpc,nicolasnoble/grpc,grpc/grpc,nicolasnoble/grpc,nicolasnoble/grpc,muxi/grpc,firebase/grpc,jboeuf/grpc,muxi/grpc,jtattermusch/grpc,stanley-cheung/grpc,pszemus/grpc,jtattermusch/grpc,firebase/grpc,jboeuf/grpc,grpc/grpc
src/csharp/Grpc.Core.Tests/ChannelCredentialsTest.cs
src/csharp/Grpc.Core.Tests/ChannelCredentialsTest.cs
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Grpc.Core.Internal; using NUnit.Framework; namespace Grpc.Core.Tests { public class ChannelCredentialsTest { [Test] public void InsecureCredentials_IsNonComposable() { Assert.IsFalse(ChannelCredentials.Insecure.IsComposable); } [Test] public void ChannelCredentials_CreateComposite() { var composite = ChannelCredentials.Create(new FakeChannelCredentials(true), new FakeCallCredentials()); Assert.IsFalse(composite.IsComposable); Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(null, new FakeCallCredentials())); Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(new FakeChannelCredentials(true), null)); // forbid composing non-composable Assert.Throws(typeof(ArgumentException), () => ChannelCredentials.Create(new FakeChannelCredentials(false), new FakeCallCredentials())); } [Test] public void ChannelCredentials_NativeCredentialsAreReused() { // always returning the same native object is critical for subchannel sharing to work with secure channels var creds = new SslCredentials(); var nativeCreds1 = creds.ToNativeCredentials(); var nativeCreds2 = creds.ToNativeCredentials(); Assert.AreSame(nativeCreds1, nativeCreds2); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Grpc.Core.Internal; using NUnit.Framework; namespace Grpc.Core.Tests { public class ChannelCredentialsTest { [Test] public void InsecureCredentials_IsNonComposable() { Assert.IsFalse(ChannelCredentials.Insecure.IsComposable); } [Test] public void ChannelCredentials_CreateComposite() { var composite = ChannelCredentials.Create(new FakeChannelCredentials(true), new FakeCallCredentials()); Assert.IsFalse(composite.IsComposable); Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(null, new FakeCallCredentials())); Assert.Throws(typeof(ArgumentNullException), () => ChannelCredentials.Create(new FakeChannelCredentials(true), null)); // forbid composing non-composable Assert.Throws(typeof(ArgumentException), () => ChannelCredentials.Create(new FakeChannelCredentials(false), new FakeCallCredentials())); } [Test] public void ChannelCredentials_NativeCredentialsAreReused() { // always returning the same native object is critical for subchannel sharing to work with secure channels var creds = new SslCredentials(); var nativeCreds1 = creds.ToNativeCredentials(); var nativeCreds2 = creds.ToNativeCredentials(); Assert.AreSame(nativeCreds1, nativeCreds2); } [Test] public void ChannelCredentials_CreateExceptionIsCached() { var creds = new ChannelCredentialsWithPopulateConfigurationThrows(); var ex1 = Assert.Throws(typeof(Exception), () => creds.ToNativeCredentials()); var ex2 = Assert.Throws(typeof(Exception), () => creds.ToNativeCredentials()); Assert.AreSame(ex1, ex2); } internal class ChannelCredentialsWithPopulateConfigurationThrows : ChannelCredentials { internal override bool IsComposable => false; public override void InternalPopulateConfiguration(ChannelCredentialsConfiguratorBase configurator, object state) { throw new Exception("Creation of native credentials has failed on purpose."); } } } }
apache-2.0
C#
9589c416d0403ae7e36eebac23d33a3a73e30b7b
Add logic to the xml trunk repo
Tollman/Practice
Practice.Client/Practice.Common/XmlTrunkRepository.cs
Practice.Client/Practice.Common/XmlTrunkRepository.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace Practice.Common { class XmlTrunkRepository : ITrunkRepository { private XDocument xmlTrunks; private string fileName = "BD.xml"; private int prevIndex = -1; public XmlTrunkRepository() { if (!System.IO.File.Exists(fileName)) { xmlTrunks = new XDocument(new XElement("TrunksDB")); xmlTrunks.Save(fileName); } foreach (int item in GetSmth()) { Console.WriteLine(item); } } public IEnumerable<int> GetSmth() { yield return 1; yield return 2; } public IEnumerable<Trunk> GetAll() { List<Trunk> trunks = new List<Trunk>(); xmlTrunks = XDocument.Load(fileName); Trunk newTrunk = null; foreach (XElement el in xmlTrunks.Root.Elements()) { newTrunk = new Trunk(); newTrunk.Id = Convert.ToInt32(el.Element("Id").Value); newTrunk.Name = el.Element("Name").Value; newTrunk.Address = el.Element("Address").Value; trunks.Add(newTrunk); } return trunks; } public Trunk GetById(int id) { string sId = id.ToString(); return (Trunk)xmlTrunks.Root.Descendants("Trunk").Where(t => t.Element("Id").Value == sId); } public void Add(Trunk entity) { prevIndex++; entity.Id = prevIndex; XElement trunk = new XElement("Trunk"); XElement id = new XElement("Id", entity.Id); trunk.Add(id); XElement name = new XElement("Name", entity.Name); trunk.Add(name); XElement address = new XElement("Address", entity.Address); trunk.Add(address); xmlTrunks.Root.Add(trunk); //xmlTrunks = new XDocument(new XElement("Trunk", new XElement("Id", entity.Id), new XElement("Name", entity.Name), new XElement("Address", entity.Address))); xmlTrunks.Save(fileName); } public void Remove(Trunk entity) { XElement element = xmlTrunks.Root.Descendants().FirstOrDefault(x => int.Parse(x.Element("Id").Value) == entity.Id); element.Remove(); xmlTrunks.Save(fileName); } public void Update(Trunk entity) { XElement element= xmlTrunks.Root.Descendants().FirstOrDefault(x => int.Parse(x.Element("Id").Value) == entity.Id); element.Element("Name").Value = entity.Name; xmlTrunks.Save(fileName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace Practice.Common { class XmlTrunkRepository : ITrunkRepository { private XDocument xmlTrunks; private string fileName = "BD.xml"; private int prevIndex = -1; public XmlTrunkRepository() { if (!System.IO.File.Exists(fileName)) { xmlTrunks = new XDocument(new XElement("TrunksDB")); xmlTrunks.Save(fileName); } foreach (int item in GetSmth()) { Console.WriteLine(item); } } public IEnumerable<int> GetSmth() { yield return 1; yield return 2; } public IEnumerable<Trunk> GetAll() { List<Trunk> trunks = new List<Trunk>(); xmlTrunks = XDocument.Load(fileName); Trunk newTrunk = null; foreach (XElement el in xmlTrunks.Root.Elements()) { newTrunk = new Trunk(); newTrunk.Id = Convert.ToInt32(el.Element("Id").Value); newTrunk.Name = el.Element("Name").Value; newTrunk.Address = el.Element("Address").Value; trunks.Add(newTrunk); } return trunks; } public Trunk GetById(int id) { string sId = id.ToString(); return (Trunk)xmlTrunks.Root.Descendants("Trunk").Where(t => t.Element("Id").Value == sId); } public void Add(Trunk entity) { prevIndex++; entity.Id = prevIndex; XElement trunk = new XElement("Trunk"); XElement id = new XElement("Id", entity.Id); trunk.Add(id); XElement name = new XElement("Name", entity.Name); trunk.Add(name); XElement address = new XElement("Address", entity.Address); trunk.Add(address); xmlTrunks.Root.Add(trunk); //xmlTrunks = new XDocument(new XElement("Trunk", new XElement("Id", entity.Id), new XElement("Name", entity.Name), new XElement("Address", entity.Address))); xmlTrunks.Save(fileName); } public void Remove(Trunk entity) { xmlTrunks.Remove(); } public void Update(Trunk entity) { Console.WriteLine("))):)"); } } }
apache-2.0
C#
2debd650516e2d90b419e33edf3122cc7cc2e480
Fix PatchSettings.cs namespace causing issue with the "Settings" class
Willster419/RelhaxModpack,Willster419/RelhaxModpack,Willster419/RelicModManager
RelhaxModpack/RelhaxModpack/Settings/PatchSettings.cs
RelhaxModpack/RelhaxModpack/Settings/PatchSettings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RelhaxModpack { class PatchSettings { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RelhaxModpack.Settings { class PatchSettings { } }
apache-2.0
C#
68161a5421ad7c9772bb8a6daa2e5ad8d02b7560
Fix Ctrl-X mistake.
EthanR/HaloSharp,gitFurious/HaloSharp
Source/HaloSharp.Test/Converter/GuidConverterTests.cs
Source/HaloSharp.Test/Converter/GuidConverterTests.cs
using System; using HaloSharp.Converter; using Newtonsoft.Json; using NUnit.Framework; namespace HaloSharp.Test.Converter { [TestFixture] public class GuidConverterTests { private class TestClass { [JsonProperty(PropertyName = "HighestCsrSeasonId")] [JsonConverter(typeof (GuidConverter))] public Guid? HighestCsrSeasonId { get; set; } } [Test] [TestCase("2041d318-dd22-47c2-a487-2818ecf14e41")] public void DeserializeObject_ReadJson_AreEqual(object value) { string source = $"{{\"HighestCsrSeasonId\":\"{value}\"}}"; var target = JsonConvert.DeserializeObject<TestClass>(source); Assert.AreEqual(value, target.HighestCsrSeasonId.ToString()); } [Test] [TestCase("NonSeasonal")] [TestCase(null)] [TestCase(12345)] public void DeserializeObject_ReadJson_IsNull(object value) { var source = $"{{\"HighestCsrSeasonId\":\"{value}\"}}"; var target = JsonConvert.DeserializeObject<TestClass>(source); Assert.IsNull(target.HighestCsrSeasonId); } [Test] public void SerializeObject_AreEqual() { var source = new TestClass { HighestCsrSeasonId = null }; var target = JsonConvert.SerializeObject(source); Assert.AreEqual($"{{\"HighestCsrSeasonId\":null}}", target); } [Test] [TestCase("2041d318-dd22-47c2-a487-2818ecf14e41")] public void SerializeObject_WriteJson_AreEqual(string value) { var source = new TestClass { HighestCsrSeasonId = new Guid(value) }; var target = JsonConvert.SerializeObject(source); Assert.AreEqual($"{{\"HighestCsrSeasonId\":\"{value}\"}}", target); } } }
using System; using HaloSharp.Converter; using Newtonsoft.Json; using NUnit.Framework; namespace HaloSharp.Test.Converter { [TestFixture] public class GuidConverterTests { private class TestClass { [JsonProperty(PropertyName = "HighestCsrSeasonId")] [JsonConverter(typeof (GuidConverter))] public Guid? HighestCsrSeasonId { get; set; } } [Test] [TestCase("2041d318-dd22-47c2-a487-2818ecf14e41")] public void DeserializeObject_ReadJson_AreEqual(object value) { string source = $"{{\"HighestCsrSeasonId\":\"{value}\"}}"; var target = JsonConvert.DeserializeObject<TestClass>(source); Assert.AreEqual(value, target.HighestCsrSeasonId.ToString()); } [Test] [TestCase("NonSeasonal")] [TestCase(null)] [TestCase(12345)] public void DeserializeObject_ReadJson_IsNull(object value) { var source = $"{{\"HighestCsrSeasonId\":\"{value}\"}}"; var target = JsonConvert.DeserializeObject<TestClass>(source); Assert.IsNull(target.HighestCsrSeasonId); } [Test] public void SerializeObject_AreEqual() { var source = new TestClass { HighestCsrSeasonId = null }; var target = JsonConvert.SerializeObject(source); Assert.AreEqual($"{{\"HighestCsrSeasonId\":null}}", target); } [Test] [TestCase("2041d318-dd22-47c2-a487-2818ecf14e41")] { var source = new TestClass { HighestCsrSeasonId = new Guid(value) }; var target = JsonConvert.SerializeObject(source); Assert.AreEqual($"{{\"HighestCsrSeasonId\":\"{value}\"}}", target); } } }
mit
C#
d942d739fca779e122980211b5b5e82fb17fca22
Annotate genres methods with oauth attribute.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Modules/TraktGenresModule.cs
Source/Lib/TraktApiSharp/Modules/TraktGenresModule.cs
namespace TraktApiSharp.Modules { using Attributes; using Enums; using Objects.Basic; using Requests.WithoutOAuth.Genres; using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// Provides access to data retrieving methods specific to genres. /// <para> /// This module contains all methods of the <a href ="http://docs.trakt.apiary.io/#reference/genres">"Trakt API Doc - Genres"</a> section. /// </para> /// </summary> public class TraktGenresModule : TraktBaseModule { internal TraktGenresModule(TraktClient client) : base(client) { } /// <summary> /// Gets a list of all movie genres. /// <para>OAuth authorization not required.</para> /// <para> /// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information. /// </para> /// </summary> /// <returns>A list of <see cref="TraktGenre" /> instances.</returns> /// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception> [OAuthAuthorizationRequired(false)] public async Task<IEnumerable<TraktGenre>> GetMovieGenresAsync() { var movieGenres = await QueryAsync(new TraktGenresMoviesRequest(Client)); foreach (var genre in movieGenres) genre.Type = TraktGenreType.Movies; return movieGenres; } /// <summary> /// Gets a list of all show genres. /// <para>OAuth authorization not required.</para> /// <para> /// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information. /// </para> /// </summary> /// <returns>A list of <see cref="TraktGenre" /> instances.</returns> /// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception> [OAuthAuthorizationRequired(false)] public async Task<IEnumerable<TraktGenre>> GetShowGenresAsync() { var showGenres = await QueryAsync(new TraktGenresShowsRequest(Client)); foreach (var genre in showGenres) genre.Type = TraktGenreType.Shows; return showGenres; } } }
namespace TraktApiSharp.Modules { using Enums; using Objects.Basic; using Requests.WithoutOAuth.Genres; using System.Collections.Generic; using System.Threading.Tasks; /// <summary> /// Provides access to data retrieving methods specific to genres. /// <para> /// This module contains all methods of the <a href ="http://docs.trakt.apiary.io/#reference/genres">"Trakt API Doc - Genres"</a> section. /// </para> /// </summary> public class TraktGenresModule : TraktBaseModule { internal TraktGenresModule(TraktClient client) : base(client) { } /// <summary> /// Gets a list of all movie genres. /// <para>OAuth authorization not required.</para> /// <para> /// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information. /// </para> /// </summary> /// <returns>A list of <see cref="TraktGenre" /> instances.</returns> /// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception> public async Task<IEnumerable<TraktGenre>> GetMovieGenresAsync() { var movieGenres = await QueryAsync(new TraktGenresMoviesRequest(Client)); foreach (var genre in movieGenres) genre.Type = TraktGenreType.Movies; return movieGenres; } /// <summary> /// Gets a list of all show genres. /// <para>OAuth authorization not required.</para> /// <para> /// See <a href="http://docs.trakt.apiary.io/#reference/genres/list/get-genres">"Trakt API Doc - Genres: List"</a> for more information. /// </para> /// </summary> /// <returns>A list of <see cref="TraktGenre" /> instances.</returns> /// <exception cref="Exceptions.TraktException">Thrown, if the request fails.</exception> public async Task<IEnumerable<TraktGenre>> GetShowGenresAsync() { var showGenres = await QueryAsync(new TraktGenresShowsRequest(Client)); foreach (var genre in showGenres) genre.Type = TraktGenreType.Shows; return showGenres; } } }
mit
C#
4f4d73dec39b1d9218a34f22fa6464f644fe8db4
extend Span class
MeilCli/CrossFormattedText
Source/Plugin.CrossFormattedText.Abstractions/Span.cs
Source/Plugin.CrossFormattedText.Abstractions/Span.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Plugin.CrossFormattedText.Abstractions { public class Span : IEquatable<Span> { public string Text { get; set; } = string.Empty; public SpanColor BackgroundColor { get; set; } = SpanColor.DefaultValue; public SpanColor ForegroundColor { get; set; } = SpanColor.DefaultValue; public FontAttributes FontAttributes { get; set; } = FontAttributes.None; public FontSize FontSize { get; set; } = FontSize.Normal; public ICommand Command { get; set; } /// <summary> /// If use Command, require this /// </summary> public object CommandParameter { get; set; } public override bool Equals(object obj) { if(obj == null) { return false; } if(obj is Span) { return Equals((Span)obj); } return false; } public bool Equals(Span span) { if(span == null) { return false; } if(ReferenceEquals(this,span)) { return true; } if(Text != span.Text) { return false; } if(BackgroundColor != span.BackgroundColor) { return false; } if(ForegroundColor != span.ForegroundColor) { return false; } if(FontAttributes != span.FontAttributes) { return false; } if(FontSize.Proportion != span.FontSize.Proportion) { return false; } if(Command != span.Command) { return false; } if(CommandParameter != span.CommandParameter) { return false; } return true; } public override int GetHashCode() { int hash = Text?.GetHashCode() ?? -1; hash ^= BackgroundColor.GetHashCode(); hash ^= ForegroundColor.GetHashCode(); hash ^= FontAttributes.GetHashCode(); hash ^= FontSize.Proportion.GetHashCode(); hash ^= Command?.GetHashCode() ?? -1; hash ^= CommandParameter?.GetHashCode() ?? -1; return hash; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Plugin.CrossFormattedText.Abstractions { public class Span { public string Text { get; set; } = string.Empty; public SpanColor BackgroundColor { get; set; } = SpanColor.DefaultValue; public SpanColor ForegroundColor { get; set; } = SpanColor.DefaultValue; public FontAttributes FontAttributes { get; set; } = FontAttributes.None; public FontSize FontSize { get; set; } = FontSize.Normal; public ICommand Command { get; set; } /// <summary> /// If use Command, require this /// </summary> public object CommandParameter { get; set; } } }
mit
C#
58bb93065147cc41822fdec8d54e1958db3d9a38
Fix in API, added IsLocked field to nested schema.
Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
src/Squidex/Areas/Api/Controllers/Schemas/Models/CreateSchemaNestedFieldDto.cs
src/Squidex/Areas/Api/Controllers/Schemas/Models/CreateSchemaNestedFieldDto.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is locked. /// </summary> public bool IsLocked { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.ComponentModel.DataAnnotations; namespace Squidex.Areas.Api.Controllers.Schemas.Models { public sealed class CreateSchemaNestedFieldDto { /// <summary> /// The name of the field. Must be unique within the schema. /// </summary> [Required] [RegularExpression("^[a-zA-Z0-9]+(\\-[a-zA-Z0-9]+)*$")] public string Name { get; set; } /// <summary> /// Defines if the field is hidden. /// </summary> public bool IsHidden { get; set; } /// <summary> /// Defines if the field is disabled. /// </summary> public bool IsDisabled { get; set; } /// <summary> /// The field properties. /// </summary> [Required] public FieldPropertiesDto Properties { get; set; } } }
mit
C#
1528ccd2635c7e03fd05df43731086f39ea6582a
Adjust screen resolution to samsung galaxy s4
ImperialBeasts-OxfordHack16/skybreak-android
Assets/Scripts/MainMenu.cs
Assets/Scripts/MainMenu.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { Screen.SetResolution(1080, 1920, true); //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Menu : MonoBehaviour { public Canvas MainCanvas; static public int money = 1000; public void LoadOn() { //DontDestroyOnLoad(money); Application.LoadLevel(1); } }
mit
C#
d7577266b65ec6e56de8afd21cb0abd82ca7f05f
Change team area heal quantity to 1000
bunashibu/kikan
Assets/Scripts/TeamArea.cs
Assets/Scripts/TeamArea.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; namespace Bunashibu.Kikan { public class TeamArea : Photon.MonoBehaviour, IAttacker, IPhotonBehaviour { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); } void OnTriggerStay2D(Collider2D collider) { var targetObj = collider.gameObject; if (targetObj.tag != "Player") return; var target = targetObj.GetComponent<Player>(); if (!target.PhotonView.isMine) return; if (target.PlayerInfo.Team == _team) { if (target.Hp.Cur.Value == target.Hp.Max.Value) return; if (Time.time - _healTimestamp > _healInterval) { _synchronizer.SyncHeal(target.PhotonView.viewID, _quantity); _healTimestamp = Time.time; } } else { if (target.State.Invincible) return; target.State.Invincible = true; MonoUtility.Instance.DelaySec(_damageInterval, () => { target.State.Invincible = false; } ); _synchronizer.SyncAttack(photonView.viewID, target.PhotonView.viewID, _quantity, false, HitEffectType.None); } } public PhotonView PhotonView => photonView; public int Power => _quantity; public int Critical => 0; [SerializeField] private int _team; [SerializeField] private int _quantity; private SkillSynchronizer _synchronizer; private float _healInterval = 1.0f; private float _damageInterval = 1.0f; private float _healTimestamp; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Assertions; namespace Bunashibu.Kikan { public class TeamArea : Photon.MonoBehaviour, IAttacker, IPhotonBehaviour { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); } void OnTriggerStay2D(Collider2D collider) { var targetObj = collider.gameObject; if (targetObj.tag != "Player") return; var target = targetObj.GetComponent<Player>(); if (!target.PhotonView.isMine) return; if (target.PlayerInfo.Team == _team) { if (target.Hp.Cur.Value == target.Hp.Max.Value) return; if (Time.time - _healTimestamp > _healInterval) { _synchronizer.SyncHeal(target.PhotonView.viewID, target.Hp.Max.Value); _healTimestamp = Time.time; } } else { if (target.State.Invincible) return; target.State.Invincible = true; MonoUtility.Instance.DelaySec(1.0f, () => { target.State.Invincible = false; } ); _synchronizer.SyncAttack(photonView.viewID, target.PhotonView.viewID, _quantity, false, HitEffectType.None); } } public PhotonView PhotonView => photonView; public int Power => _quantity; public int Critical => 0; [SerializeField] private int _team; [SerializeField] private int _quantity; private SkillSynchronizer _synchronizer; private float _healInterval = 2.0f; private float _healTimestamp; } }
mit
C#
d94dc8a704fe55e46f120694e6f1a70e9d7e1eff
Change CGPDFString logic to use CFString to work around encoding issues. Fix bug #2878
cwensley/maccore,jorik041/maccore,mono/maccore
src/CoreGraphics/CGPDFString.cs
src/CoreGraphics/CGPDFString.cs
// // CGPDFString: Helper class to deal with CGPDFStringRef // // Authors: // Miguel de Icaza <miguel@xamarin.com> // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2011-2012 Xamarin Inc. All rights reserved // // 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.Runtime.InteropServices; using MonoMac.CoreFoundation; namespace MonoMac.CoreGraphics { // internal helper class only - we avoid exposing it to users static class CGPDFString { [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr /*CFStringRef*/ CGPDFStringCopyTextString (IntPtr /*CGPDFStringRef*/ pdfStr); static public string ToString (IntPtr pdfString) { if (pdfString == IntPtr.Zero) return null; using (var cfs = new CFString (CGPDFStringCopyTextString (pdfString), true)) { return cfs.ToString (); } } } }
// // CGPDFString: Helper class to deal with CGPDFStringRef // // Authors: // Miguel de Icaza <miguel@xamarin.com> // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2011 Xamarin Inc. All rights reserved // // 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.Runtime.InteropServices; namespace MonoMac.CoreGraphics { // internal helper class only - we avoid exposing it to users static class CGPDFString { [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFStringGetBytePtr (IntPtr pdfStr); [DllImport (Constants.CoreGraphicsLibrary)] extern static IntPtr CGPDFStringGetLength (IntPtr pdfStr); static public string ToString (IntPtr pdfString) { if (pdfString == IntPtr.Zero) return null; int n = (int) CGPDFStringGetLength (pdfString); IntPtr ptr = CGPDFStringGetBytePtr (pdfString); if (ptr == IntPtr.Zero) return null; unsafe { // the returned char* is UTF-8 encoded - see bug #975 return new string ((sbyte *) ptr, 0, n, System.Text.Encoding.UTF8); } } } }
apache-2.0
C#
19530fa692fdc772fea01117288a88d847980c2b
Refactor the error caused by a failing assertion
yawaramin/TDDUnit
Assert.cs
Assert.cs
using System; namespace TDDUnit { class Assert { private static void Fail(object expected, object actual) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { Fail(expected, actual); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { Fail(expected, actual); } } public static void That(bool condition) { Equal(true, condition); } } }
using System; namespace TDDUnit { class Assert { public static void Equal(object expected, object actual) { if (!expected.Equals(actual)) { string message = string.Format("Expected: '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void NotEqual(object expected, object actual) { if (expected.Equals(actual)) { string message = string.Format("Expected: Not '{0}'; Actual: '{1}'", expected, actual); Console.WriteLine(message); throw new TestRunException(message); } } public static void That(bool condition) { Equal(true, condition); } } }
apache-2.0
C#
46c00144f0e78e950b9e8786f325365b6e97fe7f
Update ClientContext.cs
hprose/hprose-dotnet
src/Hprose.RPC/ClientContext.cs
src/Hprose.RPC/ClientContext.cs
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ClientContext.cs | | | | ClientContext class for C#. | | | | LastModified: Jan 27, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using Hprose.IO; using System; using System.Collections.Generic; namespace Hprose.RPC { public class ClientContext : Context { public Client Client { get; private set; } public string Uri { get; set; } public Type Type { get; set; } public ClientContext(Client client, string fullname, Type type, Settings settings = null) { Client = client; Uri = (client.Uris.Count > 0) ? client.Uris[0] : ""; Type = settings?.Type; if (type != null && !type.IsAssignableFrom(Type)) Type = type; Copy(client.RequestHeaders, RequestHeaders); Copy(settings?.RequestHeaders, RequestHeaders); Copy(settings?.Context, items); } } }
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ClientContext.cs | | | | ClientContext class for C#. | | | | LastModified: Jan 27, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using Hprose.IO; using System; using System.Collections.Generic; namespace Hprose.RPC { public class ClientContext : Context { public Client Client { get; private set; } public string Uri { get; set; } public Type Type { get; set; } public ClientContext(Client client, string fullname, Type type, Settings settings = null) { Client = client; Uri = (client.Uris.Count > 0) ? client.Uris[0] : ""; Type = settings?.Type; if (!type.IsAssignableFrom(Type)) Type = type; Copy(client.RequestHeaders, RequestHeaders); Copy(settings?.RequestHeaders, RequestHeaders); Copy(settings?.Context, items); } } }
mit
C#
875cb3c352590c562e73376ac1e98f58e2a726e4
fix internals visibility
uwx/DSharpPlus,uwx/DSharpPlus
DSharpPlus/AssemblyInfo.cs
DSharpPlus/AssemblyInfo.cs
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("RayBotSharp")] [assembly: InternalsVisibleTo("RayBotSharp.MSTest")]
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Sharpbott")] [assembly: InternalsVisibleTo("Sharpbott.MSTest")]
mit
C#
adde53a55061b444cdb993dee2ac4a92907bb7e3
Make CommandLineParser annotations easier to read
RadicalZephyr/DesktopNotifier
DesktopNotifier/Program.cs
DesktopNotifier/Program.cs
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using CommandLine; using CommandLine.Text; using System.Threading; namespace DesktopNotifier { class Program { [STAThreadAttribute] static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { DisplayNotification(options); } } static void DisplayNotification(Options options) { var notifyIcon = new NotifyIcon(); if (options.iconPath != null) notifyIcon.Icon = new Icon(options.iconPath); else notifyIcon.Icon = Properties.Resources.CommandPromptIcon; notifyIcon.BalloonTipTitle = options.title; notifyIcon.BalloonTipText = options.message; notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(options.showTime); } } class Options { // Required [Option('m', "message", Required = true, DefaultValue = "Hello, World", HelpText = "The message to display.")] public string message { get; set; } // Optional [Option('t', "title", Required = false, DefaultValue = "Terminal", HelpText = "The title text to diSPLAY.")] public string title { get; set; } [Option('i', "icon", Required = false, HelpText = "(Default: This program's app icon) The path to a .ico file to display.")] public string iconPath { get; set; } [Option('s', "showTime", Required = false, DefaultValue = 10000, HelpText = "The length of time to show notification for in milliseconds.")] public int showTime { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using CommandLine; using CommandLine.Text; using System.Threading; namespace DesktopNotifier { class Program { [STAThreadAttribute] static void Main(string[] args) { var options = new Options(); if (CommandLine.Parser.Default.ParseArguments(args, options)) { DisplayNotification(options); } } static void DisplayNotification(Options options) { var notifyIcon = new NotifyIcon(); if (options.iconPath != null) notifyIcon.Icon = new Icon(options.iconPath); else notifyIcon.Icon = Properties.Resources.CommandPromptIcon; notifyIcon.BalloonTipTitle = options.title; notifyIcon.BalloonTipText = options.message; notifyIcon.Visible = true; notifyIcon.ShowBalloonTip(options.showTime); } } class Options { // Required [Option('m', "message", Required = true, DefaultValue = "Hello, World", HelpText = "The message to display.")] public string message { get; set; } // Optional [Option('t', "title", Required = false, DefaultValue = "Terminal", HelpText = "The title text to display.")] public string title { get; set; } [Option('i', "icon", Required = false, HelpText = "(Default: This program's app icon) The path to a .ico file to display.")] public string iconPath { get; set; } [Option('s', "showTime", Required = false, DefaultValue = 10000, HelpText = "The length of time to show notification for in milliseconds.")] public int showTime { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
mit
C#
90871a1c6f2896a47f275a7263cae99f0d7b76db
read file contents with all exceptions
shakuu/Homework,shakuu/Homework,shakuu/Homework,shakuu/Homework,shakuu/Homework,shakuu/Homework
[C#]-02-CSharp2/07-Exception-Handling/03-Read-File-Contents/ReadFileContents.cs
[C#]-02-CSharp2/07-Exception-Handling/03-Read-File-Contents/ReadFileContents.cs
using System; using System.IO; using System.Security; namespace _03_Read_File_Contents { class ReadFileContents { static void Main() { // https://msdn.microsoft.com/en-us/library/ms143368(v=vs.110).aspx // List of all possible exceptions // related to File.Readalltext() var path = Console.ReadLine(); string fileContent; try { fileContent = File.ReadAllText(path); } catch (ArgumentNullException e) { Console.WriteLine(e.Message); return; } catch (ArgumentException e) { Console.WriteLine(e.Message); return; } catch (PathTooLongException e) { Console.WriteLine(e.Message); return; } catch (DirectoryNotFoundException e) { Console.WriteLine(e.Message); return; } catch (FileNotFoundException e) { Console.WriteLine(e.Message); return; } catch (IOException e) { Console.WriteLine(e.Message); return; } catch (UnauthorizedAccessException e) { Console.WriteLine(e.Message); return; } catch (NotSupportedException e) { Console.WriteLine(e.Message); return; } catch (SecurityException e) { Console.WriteLine(e.Message); return; } if (fileContent == null) { return; } Console.WriteLine(fileContent); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03_Read_File_Contents { class ReadFileContents { static void Main() { var path = Console.ReadLine(); } } }
mit
C#
9b62d6c5311008f5d37faf5abc61e5183af228ae
Make task index page more mobile friendly
johanhelsing/vaskelista,johanhelsing/vaskelista
Vaskelista/Views/Task/Index.cshtml
Vaskelista/Views/Task/Index.cshtml
@model IEnumerable<Vaskelista.Models.Task> @{ ViewBag.Title = "Oppgaveoversikt"; } <h2>Planlagte oppgaver</h2> <p> <a href="@Url.Action("Index", "Room")" class="btn btn-default"><i class="fa fa-list"></i> Rom</a> <a href="@Url.Action("Create")" class ="btn btn-default"><i class="fa fa-plus"></i> Ny oppgave</a> </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Room) </th> <th> @Html.DisplayNameFor(model => model.Days) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Room.Name) </td> <td> @Html.DisplayFor(modelItem => item.Days) </td> <td> <a href="@Url.Action("Edit", new { id = item.TaskId })" class="btn btn-default btn-sm"><i class="fa fa-edit"></i></a> </td> </tr> } </table>
@model IEnumerable<Vaskelista.Models.Task> @{ ViewBag.Title = "Oppgaveoversikt"; } <h2>Planlagte oppgaver</h2> <p> @Html.ActionLink("Opprett ny oppgave", "Create") @Html.ActionLink("Romoversikt", "Index", "Room") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.Start) </th> <th> @Html.DisplayNameFor(model => model.Days) </th> <th> @Html.DisplayNameFor(model => model.Room) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.Start) </td> <td> @Html.DisplayFor(modelItem => item.Days) </td> <td> @Html.DisplayFor(modelItem => item.Room.Name) </td> <td> @Html.ActionLink("Endre", "Edit", new { id=item.TaskId }) | @Html.ActionLink("Detaljer", "Details", new { id=item.TaskId }) | @Html.ActionLink("Slett", "Delete", new { id=item.TaskId }) </td> </tr> } </table>
mit
C#
75f19f1856901a00e616aa2f2b9b05d77f110490
Clean up: removed empty line
alexandrnikitin/Topshelf.Unity
src/Topshelf.Unity.Sample/Program.cs
src/Topshelf.Unity.Sample/Program.cs
using System; using Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); 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 Microsoft.Practices.Unity; namespace Topshelf.Unity.Sample { class Program { static void Main(string[] args) { // Create your container var container = new UnityContainer(); container.RegisterType<ISampleDependency, SampleDependency>(); container.RegisterType<SampleService>(); HostFactory.Run(c => { // Pass it to Topshelf c.UseUnityContainer(container); c.Service<SampleService>(s => { // Let Topshelf use it s.ConstructUsingUnityContainer(); 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#
002621f08571fc75d00b96c3bec339b187e8d94e
update OutgoingHeaderBehavior
WojcikMike/docs.particular.net
samples/header-manipulation/Version_6/Sample/Pipeline/OutgoingHeaderBehavior.cs
samples/header-manipulation/Version_6/Sample/Pipeline/OutgoingHeaderBehavior.cs
using System; using System.Threading.Tasks; using NServiceBus.OutgoingPipeline; using NServiceBus.Pipeline; #region outgoing-header-behavior class OutgoingHeaderBehavior : Behavior<OutgoingPhysicalMessageContext> { public override async Task Invoke(OutgoingPhysicalMessageContext context, Func<Task> next) { context.Headers["OutgoingHeaderBehavior"] = "ValueOutgoingHeaderBehavior"; await next(); } } #endregion
using System; using System.Threading.Tasks; using NServiceBus.OutgoingPipeline; using NServiceBus.Pipeline; using NServiceBus.TransportDispatch; #region outgoing-header-behavior class OutgoingHeaderBehavior : Behavior<OutgoingPhysicalMessageContext> { public override async Task Invoke(OutgoingPhysicalMessageContext context, Func<Task> next) { context.SetHeader("OutgoingHeaderBehavior", "ValueOutgoingHeaderBehavior"); await next(); } } #endregion
apache-2.0
C#
2747b789d543cf045b558d557deb235477be905e
return type for AsJson fixed
FriskyLingo/sendgrid-csharp,FriskyLingo/sendgrid-csharp,kenlefeb/sendgrid-csharp,sendgrid/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp,smurfpandey/sendgrid-csharp-net40,brcaswell/sendgrid-csharp,smurfpandey/sendgrid-csharp-net40,sumeshthomas/sendgrid-csharp,sendgrid/sendgrid-csharp,sendgrid/sendgrid-csharp,dubrovkinmaxim/sendgrid-csharp,pandeysoni/sendgrid-csharp,brcaswell/sendgrid-csharp,kenlefeb/sendgrid-csharp,pandeysoni/sendgrid-csharp,sumeshthomas/sendgrid-csharp,advancedrei/sendgridplus-csharp,advancedrei/sendgridplus-csharp
SendGrid/SendGrid/IHeader.cs
SendGrid/SendGrid/IHeader.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; namespace SendGrid { public interface IHeader { void AddTo(IEnumerable<String> recipients); void AddSubVal(String tag, IEnumerable<String> substitutions); void AddUniqueIdentifier(IDictionary<String, String> identifiers); void SetCategory(String category); void Enable(String filter); void Disable(String filter); void AddFilterSetting(String filter, IEnumerable<String> settings, String value); void AddHeader(MailMessage mime); String AsJson(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; namespace SendGrid { public interface IHeader { void AddTo(IEnumerable<String> recipients); void AddSubVal(String tag, IEnumerable<String> substitutions); void AddUniqueIdentifier(IDictionary<String, String> identifiers); void SetCategory(String category); void Enable(String filter); void Disable(String filter); void AddFilterSetting(String filter, IEnumerable<String> settings, String value); void AddHeader(MailMessage mime); void AsJson(); } }
mit
C#
6464b326dff0d0e13e5bfc75b6037d59b615e686
change folder used to locate tests
lockoncode/LockOnCode.VirtualMachine,lockoncode/LockOnCode.VirtualMachine
build.cake
build.cake
#addin "Cake.Incubator" #tool "xunit.runner.console" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var binDir = ""; // Destination Binary File Directory name i.e. bin var projJson = ""; // Path to the project.json var projDir = ""; // Project Directory var solutionFile = "LockOnCode.VirtualMachine.sln"; // Solution file if needed var outputDir = Directory("Build") + Directory(configuration); // The output directory the build artifacts saved too var buildSettings = new DotNetCoreBuildSettings { Framework = "netcoreapp1.1", Configuration = "Release", OutputDirectory = outputDir }; Task("Clean") .Does(() => { if (DirectoryExists(outputDir)) { DeleteDirectory(outputDir, recursive:true); } }); Task("Restore") .Does(() => { DotNetCoreRestore(solutionFile); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(solutionFile, buildSettings); }); Task("UnitTest") .IsDependentOn("Build") .Does(() => { Information("Start Running Tests"); var testSettings = new DotNetCoreTestSettings { NoBuild = true, DiagnosticOutput = true }; var directoryToScanForTests = "./"+outputDir+"/*Tests.csproj"; Information("Scanning directory for tests: " + directoryToScanForTests); var testProjects = GetFiles(directoryToScanForTests); foreach(var testProject in testProjects) { Information("Found Test Project: " + testProject); DotNetCoreTest(testProject.ToString(), testSettings); } //XUnit2(testAssemblies);*/ //DotNetCoreTest(testProject); }); Task("Package") .IsDependentOn("Build") .Does(() => { var packSettings = new DotNetCorePackSettings { OutputDirectory = outputDir, NoBuild = true }; DotNetCorePack(projJson, packSettings); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("UnitTest"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
#addin "Cake.Incubator" #tool "xunit.runner.console" var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var binDir = ""; // Destination Binary File Directory name i.e. bin var projJson = ""; // Path to the project.json var projDir = ""; // Project Directory var solutionFile = "LockOnCode.VirtualMachine.sln"; // Solution file if needed var outputDir = Directory("Build") + Directory(configuration); // The output directory the build artifacts saved too var buildSettings = new DotNetCoreBuildSettings { Framework = "netcoreapp1.1", Configuration = "Release", OutputDirectory = outputDir }; Task("Clean") .Does(() => { if (DirectoryExists(outputDir)) { DeleteDirectory(outputDir, recursive:true); } }); Task("Restore") .Does(() => { DotNetCoreRestore(solutionFile); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(solutionFile, buildSettings); }); Task("UnitTest") .IsDependentOn("Build") .Does(() => { Information("Start Running Tests"); var testSettings = new DotNetCoreTestSettings { NoBuild = true, DiagnosticOutput = true }; var testProjects = GetFiles("./**/*Tests.csproj"); foreach(var testProject in testProjects) { Information("Found Test Project: " + testProject); DotNetCoreTest(testProject.ToString(), testSettings); } //XUnit2(testAssemblies);*/ //DotNetCoreTest(testProject); }); Task("Package") .IsDependentOn("Build") .Does(() => { var packSettings = new DotNetCorePackSettings { OutputDirectory = outputDir, NoBuild = true }; DotNetCorePack(projJson, packSettings); }); ////////////////////////////////////////////////////////////////////// // TASK TARGETS ////////////////////////////////////////////////////////////////////// Task("Default") .IsDependentOn("UnitTest"); ////////////////////////////////////////////////////////////////////// // EXECUTION ////////////////////////////////////////////////////////////////////// RunTarget(target);
mit
C#
08402c8cc9541d56dd9bb14a39c01674fd9ac808
Fix blizzy toolbar
DMagic1/CapCom,Kerbas-ad-astra/CapCom
Source/Toolbar/CC_Toolbar.cs
Source/Toolbar/CC_Toolbar.cs
#region license /*The MIT License (MIT) Contract Toolbar- Addon for toolbar interface Copyright (c) 2014 DMagic KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.IO; using System; using CapCom.Framework; using UnityEngine; namespace CapCom.Toolbar { public class CC_Toolbar : CC_MBE { private IButton contractButton; protected override void Start() { setupToolbar(); } private void setupToolbar() { if (!ToolbarManager.ToolbarAvailable) return; contractButton = ToolbarManager.Instance.add("CapCom", "CapComToolbarID"); if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/CapCom/Textures/CapComToolbarIcon.png").Replace("\\", "/"))) contractButton.TexturePath = "CapCom/Textures/CapComToolbarIcon"; else contractButton.TexturePath = "000_Toolbar/resize-cursor"; contractButton.ToolTip = "Cap Comm"; contractButton.OnClick += (e) => { if (CapCom.Instance != null) { CapCom.Instance.Window.Visible = !CapCom.Instance.Window.Visible; } }; } protected override void OnDestroy() { if (!ToolbarManager.ToolbarAvailable) return; if (contractButton != null) contractButton.Destroy(); } } }
#region license /*The MIT License (MIT) Contract Toolbar- Addon for toolbar interface Copyright (c) 2014 DMagic KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.IO; using System; using CapCom.Framework; using UnityEngine; namespace CapCom.Toolbar { class CC_Toolbar : CC_MBE { private IButton contractButton; protected override void Start() { setupToolbar(); } private void setupToolbar() { if (!ToolbarManager.ToolbarAvailable) return; contractButton = ToolbarManager.Instance.add("CapCom", "CapComToolbarID"); if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/CapCom/Textures/CapComToolbarIcon.png").Replace("\\", "/"))) contractButton.TexturePath = "CapCom/Textures/CapComToolbarIcon"; else contractButton.TexturePath = "000_Toolbar/resize-cursor"; contractButton.ToolTip = "Cap Comm"; contractButton.OnClick += (e) => { if (CapCom.Instance != null) { CapCom.Instance.Window.Visible = !CapCom.Instance.Window.Visible; } }; } protected override void OnDestroy() { if (!ToolbarManager.ToolbarAvailable) return; if (contractButton != null) contractButton.Destroy(); } } }
mit
C#
b444b6e8b8eb041579ab5b2877a562b6dd04ca76
Fix for 'new' setting button triggering if you hit enter when editing a setting.
grae22/TeamTracker
TeamTracker/Settings.aspx.cs
TeamTracker/Settings.aspx.cs
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; settingsView.Focus(); } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); settingsView.Focus(); } //--------------------------------------------------------------------------- }
using System; public partial class Settings : System.Web.UI.Page { //--------------------------------------------------------------------------- protected void Page_Load( object sender, EventArgs e ) { // Don't allow people to skip the login page. if( Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == null || (bool)Session[ SettingsLogin.SES_SETTINGS_LOGGED_IN ] == false ) { Response.Redirect( "Default.aspx" ); } dataSource.ConnectionString = Database.DB_CONNECTION_STRING; NewSetting.Click += OnNewClick; } //--------------------------------------------------------------------------- void OnNewClick( object sender, EventArgs e ) { Database.ExecSql( "DELETE FROM Setting WHERE [Key]='New Key'" ); Database.ExecSql( "INSERT INTO Setting VALUES ( 'New Key', 'New Value' )" ); settingsView.DataBind(); } //--------------------------------------------------------------------------- }
mit
C#
ebee43f2556b940623851e2e0640daa69b91afc9
Add UniTask.FromCanceled
neuecc/UniRx,TORISOUP/UniRx
Assets/Plugins/UniRx/Scripts/Async/UniTask.Factory.cs
Assets/Plugins/UniRx/Scripts/Async/UniTask.Factory.cs
#if CSHARP_7_OR_LATER #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; namespace UniRx.Async { public partial struct UniTask { static readonly UniTask FromCanceledUniTask = new Func<UniTask>(()=> { var promise = new Promise<AsyncUnit>(); promise.SetCanceled(); return new UniTask(promise); })(); public static UniTask CompletedTask { get { return new UniTask(); } } public static UniTask FromException(Exception ex) { var promise = new Promise<AsyncUnit>(); promise.SetException(ex); return new UniTask(promise); } public static UniTask<T> FromException<T>(Exception ex) { var promise = new Promise<T>(); promise.SetException(ex); return new UniTask<T>(promise); } public static UniTask<T> FromResult<T>(T value) { return new UniTask<T>(value); } public static UniTask FromCanceled() { return FromCanceledUniTask; } public static UniTask<T> FromCanceled<T>() { return FromCanceledCache<T>.Task; } static class FromCanceledCache<T> { public static readonly UniTask<T> Task; static FromCanceledCache() { var promise = new Promise<T>(); promise.SetCanceled(); Task = new UniTask<T>(promise); } } } } #endif
#if CSHARP_7_OR_LATER #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member using System; namespace UniRx.Async { public partial struct UniTask { public static UniTask CompletedTask { get { return new UniTask(); } } public static UniTask FromException(Exception ex) { var promise = new Promise<AsyncUnit>(); promise.SetException(ex); return new UniTask(promise); } public static UniTask<T> FromException<T>(Exception ex) { var promise = new Promise<T>(); promise.SetException(ex); return new UniTask<T>(promise); } public static UniTask<T> FromResult<T>(T value) { return new UniTask<T>(value); } } } #endif
mit
C#
c5ba3236073d89219fe11c11172b0d4dbd28788d
Add test
sakapon/Blaze
Blaze/UnitTest/Randomization/Lab/RandomNumbersTest.cs
Blaze/UnitTest/Randomization/Lab/RandomNumbersTest.cs
using System; using Blaze.Randomization.Lab; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Randomization.Lab { [TestClass] public class RandomNumbersTest { [TestMethod] public void GenerateByte_1() { for (var i = 0; i < 100; i++) { var x = RandomNumbers.GenerateByte(); Console.WriteLine(x); } } [TestMethod] public void GenerateDouble_From0To1_1() { for (var i = 0; i < 100; i++) { var x = RandomNumbers.GenerateDouble_From0To1(); Console.WriteLine($"{x:F3}"); Assert.IsTrue(x >= 0); Assert.IsTrue(x < 1); } } } }
using System; using Blaze.Randomization.Lab; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTest.Randomization.Lab { [TestClass] public class RandomNumbersTest { [TestMethod] public void GenerateDouble_From0To1_1() { for (var i = 0; i < 1000; i++) { var x = RandomNumbers.GenerateDouble_From0To1(); Console.WriteLine(x); Assert.IsTrue(x >= 0); Assert.IsTrue(x < 1); } } } }
mit
C#
682455e4fc3d0db782a89eab4456d4c930d886c2
Update List of ConnectorTypes to be compatible with ISOBUS.net List
ADAPT/ADAPT
source/ADAPT/Equipment/ConnectorTypeEnum.cs
source/ADAPT/Equipment/ConnectorTypeEnum.cs
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, ChassisMountedSelfPropelled } }
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Kathleen Oneal - initial API and implementation * Joe Ross, Kathleen Oneal - added values *******************************************************************************/ namespace AgGateway.ADAPT.ApplicationDataModel.Equipment { public enum ConnectorTypeEnum { Unkown, ISO64893TractorDrawbar, ISO730ThreePointHitchSemiMounted, ISO730ThreePointHitchMounted, ISO64891HitchHook, ISO64892ClevisCoupling40, ISO64894PitonTypeCoupling, ISO56922PivotWagonHitch, ISO24347BallTypeHitch, } }
epl-1.0
C#
f9ecd4fde27cb7b752598478ff6aef81a0e2e7ea
Fix some buggy behaviors in the BodyCollider.
jguarShark/Unity2D-Components,cmilr/Unity2D-Components
Actor/BodyCollider.cs
Actor/BodyCollider.cs
using UnityEngine; using System.Collections; using Matcha.Lib; [RequireComponent(typeof(BoxCollider2D))] public class BodyCollider : CacheBehaviour { private bool alreadyCollided; private PickupEntity pickupEntity; private EntityBehaviour entityBehaviour; // private CharacterEntity charEntity; void Start() { base.CacheComponents(); MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true); MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true); } void OnTriggerEnter2D(Collider2D coll) { GetColliderComponents(coll); if (coll.tag == "Prize" && !alreadyCollided) { Messenger.Broadcast<int>("prize collected", pickupEntity.worth); pickupEntity.React(); } if (coll.tag == "Enemy" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll); } if (coll.tag == "Water" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll); } } void GetColliderComponents(Collider2D coll) { pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity; // charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity; if (coll.GetComponent<EntityBehaviour>()) { entityBehaviour = coll.GetComponent<EntityBehaviour>(); alreadyCollided = entityBehaviour.alreadyCollided; } } }
using UnityEngine; using System.Collections; using Matcha.Lib; [RequireComponent(typeof(BoxCollider2D))] public class BodyCollider : CacheBehaviour { private bool alreadyCollided; private PickupEntity pickupEntity; private CharacterEntity charEntity; void Start() { base.CacheComponents(); MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true); MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true); } void OnTriggerEnter2D(Collider2D coll) { GetColliderComponents(coll); if (coll.tag == "Prize" && !alreadyCollided) { Messenger.Broadcast<int>("prize collected", pickupEntity.worth); pickupEntity.React(); } if (coll.tag == "Enemy" && !alreadyCollided) { alreadyCollided = true; Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll); } if (coll.tag == "Water" && !alreadyCollided) { alreadyCollided = true; Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll); } } void GetColliderComponents(Collider2D coll) { pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity; charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity; if (coll.GetComponent<EntityBehaviour>()) alreadyCollided = coll.GetComponent<EntityBehaviour>().alreadyCollided; } }
mit
C#
e82e171ce642347c7a3d987404b17c1e5905e8ae
Fix weightless (#9939)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Shared/Gravity/SharedGravitySystem.cs
Content.Shared/Gravity/SharedGravitySystem.cs
using Content.Shared.Clothing; using Content.Shared.Inventory; using Content.Shared.Movement.Components; using Robust.Shared.Map; using Robust.Shared.Physics; namespace Content.Shared.Gravity { public abstract class SharedGravitySystem : EntitySystem { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly InventorySystem _inventory = default!; public bool IsWeightless(EntityUid uid, PhysicsComponent? body = null, TransformComponent? xform = null) { Resolve(uid, ref body, false); if ((body?.BodyType & (BodyType.Static | BodyType.Kinematic)) != 0) return false; if (TryComp<MovementIgnoreGravityComponent>(uid, out var ignoreGravityComponent)) return ignoreGravityComponent.Weightless; if (!Resolve(uid, ref xform)) return true; bool gravityEnabled = false; // If grid / map has gravity if ((TryComp<GravityComponent>(xform.GridUid, out var gravity) || TryComp(xform.MapUid, out gravity)) && gravity.Enabled) { gravityEnabled = gravity.Enabled; if (gravityEnabled) return false; } // On the map then always weightless (unless it has gravity comp obv). if (!_mapManager.TryGetGrid(xform.GridUid, out var grid)) return true; // Something holding us down if (_inventory.TryGetSlotEntity(uid, "shoes", out var ent)) { if (TryComp<MagbootsComponent>(ent, out var boots) && boots.On) return false; } if (!gravityEnabled || !xform.Coordinates.IsValid(EntityManager)) return true; var tile = grid.GetTileRef(xform.Coordinates).Tile; return tile.IsEmpty; } public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GridInitializeEvent>(HandleGridInitialize); } private void HandleGridInitialize(GridInitializeEvent ev) { EntityManager.EnsureComponent<GravityComponent>(ev.EntityUid); } } }
using Content.Shared.Clothing; using Content.Shared.Inventory; using Content.Shared.Movement.Components; using Robust.Shared.Map; using Robust.Shared.Physics; namespace Content.Shared.Gravity { public abstract class SharedGravitySystem : EntitySystem { [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly InventorySystem _inventory = default!; public bool IsWeightless(EntityUid uid, PhysicsComponent? body = null, TransformComponent? xform = null) { Resolve(uid, ref body, false); if ((body?.BodyType & (BodyType.Static | BodyType.Kinematic)) != 0) return false; if (TryComp<MovementIgnoreGravityComponent>(uid, out var ignoreGravityComponent)) return ignoreGravityComponent.Weightless; if (!Resolve(uid, ref xform)) return true; // If grid / map has gravity if ((TryComp<GravityComponent>(xform.GridUid, out var gravity) || TryComp(xform.MapUid, out gravity)) && gravity.Enabled) return false; // On the map then always weightless (unless it has gravity comp obv). if (!_mapManager.TryGetGrid(xform.GridUid, out var grid)) return true; // Something holding us down if (_inventory.TryGetSlotEntity(uid, "shoes", out var ent)) { if (TryComp<MagbootsComponent>(ent, out var boots) && boots.On) return false; } if (!xform.Coordinates.IsValid(EntityManager)) return true; var tile = grid.GetTileRef(xform.Coordinates).Tile; return tile.IsEmpty; } public override void Initialize() { base.Initialize(); SubscribeLocalEvent<GridInitializeEvent>(HandleGridInitialize); } private void HandleGridInitialize(GridInitializeEvent ev) { EntityManager.EnsureComponent<GravityComponent>(ev.EntityUid); } } }
mit
C#
e3b35b9050cb6f70fdafbd9071bead0b68d2118d
Update ConvertTableToRange.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Tables/ConvertTableToRange.cs
Examples/CSharp/Tables/ConvertTableToRange.cs
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Tables { public class ConvertTableToRange { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Open an existing file that contains a table/list object in it Workbook wb = new Workbook(dataDir + "book1.xlsx"); //Convert the first table/list object (from the first worksheet) to normal range wb.Worksheets[0].ListObjects[0].ConvertToRange(); //Save the file wb.Save(dataDir + "output.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; namespace Aspose.Cells.Examples.Tables { public class ConvertTableToRange { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Open an existing file that contains a table/list object in it Workbook wb = new Workbook(dataDir + "book1.xlsx"); //Convert the first table/list object (from the first worksheet) to normal range wb.Worksheets[0].ListObjects[0].ConvertToRange(); //Save the file wb.Save(dataDir + "output.out.xlsx"); } } }
mit
C#
8146673f189de1e6a0671c4e8262751825dccffd
Use System.HashCode.
ryanjfitz/SimpSim.NET
SimpSim.NET/Instruction.cs
SimpSim.NET/Instruction.cs
using System; using System.Collections.Generic; namespace SimpSim.NET { public class Instruction : IEquatable<Instruction> { public Instruction(byte byte1, byte byte2) { Bytes = new[] { byte1, byte2 }; } public IReadOnlyList<byte> Bytes { get; } public byte Byte1 => Bytes[0]; public byte Byte2 => Bytes[1]; public byte Nibble1 => Byte1.HighNibble(); public byte Nibble2 => Byte1.LowNibble(); public byte Nibble3 => Byte2.HighNibble(); public byte Nibble4 => Byte2.LowNibble(); public bool Equals(Instruction other) { return other != null && Byte1 == other.Byte1 && Byte2 == other.Byte2; } public override bool Equals(object obj) { return Equals(obj as Instruction); } public override int GetHashCode() { return HashCode.Combine(Byte1, Byte2); } public override string ToString() { return Byte1.ToHexString(2) + Byte2.ToHexString(2); } } }
using System; using System.Collections.Generic; namespace SimpSim.NET { public class Instruction : IEquatable<Instruction> { public Instruction(byte byte1, byte byte2) { Bytes = new[] { byte1, byte2 }; } public IReadOnlyList<byte> Bytes { get; } public byte Byte1 => Bytes[0]; public byte Byte2 => Bytes[1]; public byte Nibble1 => Byte1.HighNibble(); public byte Nibble2 => Byte1.LowNibble(); public byte Nibble3 => Byte2.HighNibble(); public byte Nibble4 => Byte2.LowNibble(); public bool Equals(Instruction other) { return other != null && Byte1 == other.Byte1 && Byte2 == other.Byte2; } public override bool Equals(object obj) { return Equals(obj as Instruction); } public override int GetHashCode() { unchecked { int hashCode = 17; hashCode = 31 * hashCode + Byte1.GetHashCode(); hashCode = 31 * hashCode + Byte2.GetHashCode(); return hashCode; } } public override string ToString() { return Byte1.ToHexString(2) + Byte2.ToHexString(2); } } }
mit
C#
5e9c3963d6e998f361fd67a6a8231343ec34b8fe
Fix Device View
MagedAlNaamani/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,cmoussalli/DynThings,MagedAlNaamani/DynThings,MagedAlNaamani/DynThings
DynThings.WebPortal/Views/DeviceCommands/Index.cshtml
DynThings.WebPortal/Views/DeviceCommands/Index.cshtml
@model IEnumerable<DynThings.Data.Models.DeviceCommand> @{ ViewBag.Title = "DeviceCommands"; } <div class="container"> <div class="page-header"> <h1>Device's Commands</h1> </div> <div class="row"> <div class="col-md-6"> <button type="button" class="btn btn-info" onclick="LoadPart_DialogDeviceCommandAdd()" data-toggle="modal" data-target="#mdl">Add</button> </div> <div class="col-md-6"> <div class="input-group"> <input type="search" id="txtDeviceCommandSearch" class="form-control" onkeydown="if (event.keyCode == 13) { LoadPart_DeviceCommandListDiv(); return false; }" /> <div class="input-group-btn"> <button type="button" class="btn btn-primary" onclick="LoadPart_DeviceCommandListDiv()">Search</button> </div> </div> </div> </div> <br /> <div class="well well-lg"> <div id="divDeviceCommandsList"> </div> </div> </div> @section scriptfiles{ <script src="~/DynScripts/DeviceCommands.js"></script> } @section scripts{ <script> $(document).ready(function () { LoadPart_DeviceCommandListDiv(); AttachEventDeviceCommandsListPager(); }); </script> }
@model IEnumerable<DynThings.Data.Models.DeviceCommand> @{ ViewBag.Title = "DeviceCommands"; } <div class="container"> <div class="page-header"> <h1>Device's Commands</h1> </div> <div class="row"> <div class="col-md-6"> <button type="button" class="btn btn-info" onclick="LoadPart_DialogDeviceCommandAdd()" data-toggle="modal" data-target="#mdl">Add</button> </div> <div class="col-md-6"> <div class="input-group"> <input type="search" id="txtDeviceCommandSearch" class="form-control" onkeydown="if (event.keyCode == 13) { LoadPart_DeviceCommandListDiv(); return false; }" /> <div class="input-group-btn"> <button type="button" class="btn btn-primary" onclick="LoadPart_DeviceCommandListDiv()">Search</button> </div> </div> </div> </div> <br /> <div class="well well-lg"> <div id="divDeviceCommandsList"> </div> </div> </div> @section scriptfiles{ <script src="~/DynScripts/DeviceCommands.js"></script> } <script> $(document).ready(function () { LoadPart_DeviceCommandListDiv(); AttachEventDeviceCommandsListPager(); }); </script>
mit
C#
5079180529aaef6a88bc1bc9e8c31af3e5fbba75
remove unused default in EnumEqualityStep
okobylianskyi/FluentAssertions,msackton/FluentAssertions,fluentassertions/fluentassertions,rstam/fluentassertions,dennisdoomen/fluentassertions,jnyrup/fluentassertions,zmaruo/fluentassertions,AlexanderSher/fluentassertions,fluentassertions/fluentassertions,piotrpMSFT/fluentassertions,ArsenShnurkov/fluentassertions,jeroenpot/FluentAssertions,jnyrup/fluentassertions,somewhatabstract/fluentassertions,MortenBoysen/FluentAssertions,dennisdoomen/fluentassertions,SaroTasciyan/FluentAssertions,levenleven/fluentassertions,vossad01/fluentassertions,ben-m-lucas/FluentAssertions,onovotny/fluentassertions
FluentAssertions.Core/Equivalency/EnumEqualityStep.cs
FluentAssertions.Core/Equivalency/EnumEqualityStep.cs
using System; using System.Globalization; using System.Linq; namespace FluentAssertions.Equivalency { internal class EnumEqualityStep : IEquivalencyStep { /// <summary> /// Gets a value indicating whether this step can handle the current subject and/or expectation. /// </summary> public bool CanHandle(EquivalencyValidationContext context, IEquivalencyAssertionOptions config) { return context.RuntimeType != null && context.RuntimeType.IsEnum; } /// <summary> /// Applies a step as part of the task to compare two objects for structural equality. /// </summary> /// <value> /// Should return <c>true</c> if the subject matches the expectation or if no additional assertions /// have to be executed. Should return <c>false</c> otherwise. /// </value> /// <remarks> /// May throw when preconditions are not met or if it detects mismatching data. /// </remarks> public bool Handle(EquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { if (config.EnumEquivalencyHandling == EnumEquivalencyHandling.ByValue) { CompareByValue(context); } else { context.Subject.ToString().Should().Be(context.Expectation.ToString(), context.Reason, context.ReasonArgs); } return true; } private void CompareByValue(EquivalencyValidationContext context) { var subjectType = Enum.GetUnderlyingType(context.Subject.GetType()); var subjectUnderlyingValue = Convert.ChangeType(context.Subject, subjectType, CultureInfo.InvariantCulture); var expectationType = Enum.GetUnderlyingType(context.Expectation.GetType()); var expectationUnderlyingValue = Convert.ChangeType(context.Expectation, expectationType, CultureInfo.InvariantCulture); subjectUnderlyingValue.Should().Be(expectationUnderlyingValue, context.Reason, context.ReasonArgs); } } }
using System; using System.Globalization; using System.Linq; namespace FluentAssertions.Equivalency { internal class EnumEqualityStep : IEquivalencyStep { /// <summary> /// Gets a value indicating whether this step can handle the current subject and/or expectation. /// </summary> public bool CanHandle(EquivalencyValidationContext context, IEquivalencyAssertionOptions config) { return context.RuntimeType != null && context.RuntimeType.IsEnum; } /// <summary> /// Applies a step as part of the task to compare two objects for structural equality. /// </summary> /// <value> /// Should return <c>true</c> if the subject matches the expectation or if no additional assertions /// have to be executed. Should return <c>false</c> otherwise. /// </value> /// <remarks> /// May throw when preconditions are not met or if it detects mismatching data. /// </remarks> public bool Handle(EquivalencyValidationContext context, IEquivalencyValidator parent, IEquivalencyAssertionOptions config) { switch (config.EnumEquivalencyHandling) { case EnumEquivalencyHandling.ByValue: CompareByValue(context); break; case EnumEquivalencyHandling.ByName: context.Subject.ToString().Should().Be(context.Expectation.ToString(), context.Reason, context.ReasonArgs); break; default: context.Subject.Should().Be(context.Expectation, context.Reason, context.ReasonArgs); break; } return true; } private void CompareByValue(EquivalencyValidationContext context) { var subjectType = Enum.GetUnderlyingType(context.Subject.GetType()); var subjectUnderlyingValue = Convert.ChangeType(context.Subject, subjectType, CultureInfo.InvariantCulture); var expectationType = Enum.GetUnderlyingType(context.Expectation.GetType()); var expectationUnderlyingValue = Convert.ChangeType(context.Expectation, expectationType, CultureInfo.InvariantCulture); subjectUnderlyingValue.Should().Be(expectationUnderlyingValue, context.Reason, context.ReasonArgs); } } }
apache-2.0
C#
8df4ccc74263023c7236f0a0e333a2a9117a4add
Set requestBody to string.empty by default to reduce some code
bnathyuw/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,gregsochanik/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Wrapper/Requests/RequestBuilder.cs
src/SevenDigital.Api.Wrapper/Requests/RequestBuilder.cs
using System.Collections.Generic; using OAuth; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.Requests { public class RequestBuilder : IRequestBuilder { private readonly IOAuthCredentials _oAuthCredentials; private readonly RouteParamsSubstitutor _routeParamsSubstitutor; public RequestBuilder(IApiUri apiUri, IOAuthCredentials oAuthCredentials) { _oAuthCredentials = oAuthCredentials; _routeParamsSubstitutor = new RouteParamsSubstitutor(apiUri); } public Request BuildRequest(RequestData requestData) { var apiRequest = _routeParamsSubstitutor.SubstituteParamsInRequest(requestData); var fullUrl = apiRequest.AbsoluteUrl; var headers = new Dictionary<string, string>(requestData.Headers); var oauthHeader = GetAuthorizationHeader(requestData, fullUrl, apiRequest); headers.Add("Authorization", oauthHeader); if (HttpMethodHelpers.HasParams(requestData.HttpMethod) && (apiRequest.Parameters.Count > 0)) { fullUrl += "?" + apiRequest.Parameters.ToQueryString(); } var requestBody = string.Empty; if (HttpMethodHelpers.HasBody(requestData.HttpMethod)) { requestBody = apiRequest.Parameters.ToQueryString(); } return new Request(requestData.HttpMethod, fullUrl, headers, requestBody); } private string GetAuthorizationHeader(RequestData requestData, string fullUrl, ApiRequest apiRequest) { if (requestData.RequiresSignature) { return BuildOAuthHeader(requestData, fullUrl, apiRequest.Parameters); } return "oauth_consumer_key=" + _oAuthCredentials.ConsumerKey; } private string BuildOAuthHeader(RequestData requestData, string fullUrl, IDictionary<string, string> parameters) { var oauthRequest = new OAuthRequest { Type = OAuthRequestType.ProtectedResource, RequestUrl = fullUrl, Method = requestData.HttpMethod.ToString().ToUpperInvariant(), ConsumerKey = _oAuthCredentials.ConsumerKey, ConsumerSecret = _oAuthCredentials.ConsumerSecret, }; if (!string.IsNullOrEmpty(requestData.UserToken)) { oauthRequest.Token = requestData.UserToken; oauthRequest.TokenSecret = requestData.TokenSecret; } return oauthRequest.GetAuthorizationHeader(parameters); } } }
using System.Collections.Generic; using OAuth; using SevenDigital.Api.Wrapper.Http; namespace SevenDigital.Api.Wrapper.Requests { public class RequestBuilder : IRequestBuilder { private readonly IOAuthCredentials _oAuthCredentials; private readonly RouteParamsSubstitutor _routeParamsSubstitutor; public RequestBuilder(IApiUri apiUri, IOAuthCredentials oAuthCredentials) { _oAuthCredentials = oAuthCredentials; _routeParamsSubstitutor = new RouteParamsSubstitutor(apiUri); } public Request BuildRequest(RequestData requestData) { var apiRequest = _routeParamsSubstitutor.SubstituteParamsInRequest(requestData); var fullUrl = apiRequest.AbsoluteUrl; var headers = new Dictionary<string, string>(requestData.Headers); var oauthHeader = GetAuthorizationHeader(requestData, fullUrl, apiRequest); headers.Add("Authorization", oauthHeader); if (HttpMethodHelpers.HasParams(requestData.HttpMethod) && (apiRequest.Parameters.Count > 0)) { fullUrl += "?" + apiRequest.Parameters.ToQueryString(); } string requestBody; if (HttpMethodHelpers.HasBody(requestData.HttpMethod)) { requestBody = apiRequest.Parameters.ToQueryString(); } else { requestBody = string.Empty; } return new Request(requestData.HttpMethod, fullUrl, headers, requestBody); } private string GetAuthorizationHeader(RequestData requestData, string fullUrl, ApiRequest apiRequest) { if (requestData.RequiresSignature) { return BuildOAuthHeader(requestData, fullUrl, apiRequest.Parameters); } return "oauth_consumer_key=" + _oAuthCredentials.ConsumerKey; } private string BuildOAuthHeader(RequestData requestData, string fullUrl, IDictionary<string, string> parameters) { var oauthRequest = new OAuthRequest { Type = OAuthRequestType.ProtectedResource, RequestUrl = fullUrl, Method = requestData.HttpMethod.ToString().ToUpperInvariant(), ConsumerKey = _oAuthCredentials.ConsumerKey, ConsumerSecret = _oAuthCredentials.ConsumerSecret, }; if (!string.IsNullOrEmpty(requestData.UserToken)) { oauthRequest.Token = requestData.UserToken; oauthRequest.TokenSecret = requestData.TokenSecret; } return oauthRequest.GetAuthorizationHeader(parameters); } } }
mit
C#
ffd41fc544e893f19b6c25c055fb6720e5df383d
Load jQuery from Google CDN and add script to prompt IE6 users to install Chrome Frame (thieved from html5 boilerplate)
GiveCampUK/GiveCRM,GiveCampUK/GiveCRM
src/GiveCRM.Web/Views/Shared/_Layout.cshtml
src/GiveCRM.Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!-- Consider adding a manifest.appcache: h5bp.com/d/Offline --> <!--[if gt IE 8]><!--> <html class="no-jsa" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>@ViewBag.Title</title> <!-- TODO load bootstrap.min if we're in prod --> <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="@Url.Content("~/Scripts/jquery-1.6.4.min.js")"><\/script>')</script> </head> <body> <div class="page"> <div id="header" class="topbar"> @Html.Partial("_GlobHeader") </div> <div id="main" class="container"> @RenderBody() </div> <div id="footer"> @Html.Partial("_GlobFooter") </div> </div> <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you want to support IE 6. chromium.org/developers/how-tos/chrome-frame-getting-started --> <!--[if lt IE 7 ]> <script defer src="//ajax.googleapis.com/ajax/libs/chrome-frame/1.0.3/CFInstall.min.js"></script> <script defer>window.attachEvent('onload',function(){CFInstall.check({mode:'overlay'})})</script> <![endif]--> </body> </html>
<!DOCTYPE html> <!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!-- Consider adding a manifest.appcache: h5bp.com/d/Offline --> <!--[if gt IE 8]><!--> <html class="no-jsa" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><title>@ViewBag.Title</title> <!-- TODO load minified version if we're in prod (BS) / load from google CDN (jQ UI) --> <link href="@Url.Content("~/Content/bootstrap.min.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/themes/base/jquery.ui.datepicker.css")" rel="stylesheet" type="text/css" /> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <!-- TODO load me in from Google cdn --> <script src="@Url.Content("~/Scripts/jquery-1.6.4.min.js")"></script> </head> <body> <div class="page"> <div id="header" class="topbar"> @Html.Partial("_GlobHeader") </div> <div id="main" class="container"> @RenderBody() </div> <div id="footer"> @Html.Partial("_GlobFooter") </div> </div> </body> </html>
mit
C#
0930a2769b3da2bf76be9be9859ce0309a0fe520
add Size property to GroupInfo
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Data/GroupInfo.cs
TCC.Core/Data/GroupInfo.cs
using System.Collections.Generic; using System.Linq; using TeraDataLite; namespace TCC.Data { public class GroupInfo { public bool InGroup { get; private set; } public bool IsRaid { get; private set; } public bool AmILeader => Game.Me.Name == Leader.Name; public int Size { get; private set; } public GroupMemberData Leader { get; private set; } = new GroupMemberData(); private List<GroupMemberData> Members { get; set; } = new List<GroupMemberData>(); public void SetGroup(List<GroupMemberData> members, bool raid) { Members = members; Leader = members.Find(m => m.IsLeader); IsRaid = raid; InGroup = true; Size = Members.Count; } public void ChangeLeader(string name) { Members.ForEach(x => x.IsLeader = x.Name == name); Leader = Members.FirstOrDefault(m => m.Name == name); } public void Remove(uint playerId, uint serverId) { var target = Members.Find(m => m.PlayerId == playerId && m.ServerId == serverId); Members.Remove(target); Size = Members.Count; } public void Disband() { Members.Clear(); Leader = new GroupMemberData(); IsRaid = false; InGroup = false; Size = Members.Count; } public bool Has(string name) { return Members.Any(m => m.Name == name); } public bool Has(uint pId) { return Members.Any(m => m.PlayerId == pId); } public bool HasPowers(string name) { return Has(name) && Members.FirstOrDefault(x => x.Name == name)?.CanInvite == true; } public bool TryGetMember(uint playerId, uint serverId, out GroupMemberData member) { member = Members.FirstOrDefault(m => m.PlayerId == playerId && m.ServerId == serverId); return member != null; } public bool TryGetMember(string name, out GroupMemberData member) { member = Members.FirstOrDefault(m => m.Name == name); return member != null; } } }
using System.Collections.Generic; using System.Linq; using TeraDataLite; namespace TCC.Data { public class GroupInfo { public bool InGroup { get; private set; } public bool IsRaid { get; private set; } public bool AmILeader => Game.Me.Name == Leader.Name; private GroupMemberData Leader { get; set; } = new GroupMemberData(); private List<GroupMemberData> Members { get; set; } = new List<GroupMemberData>(); public void SetGroup(List<GroupMemberData> members, bool raid) { Members = members; Leader = members.Find(m => m.IsLeader); IsRaid = raid; InGroup = true; } public void ChangeLeader(string name) { Members.ForEach(x => x.IsLeader = x.Name == name); Leader = Members.FirstOrDefault(m => m.Name == name); } public void Remove(uint playerId, uint serverId) { var target = Members.Find(m => m.PlayerId == playerId && m.ServerId == serverId); Members.Remove(target); } public void Disband() { Members.Clear(); Leader = new GroupMemberData(); IsRaid = false; InGroup = false; } public bool Has(string name) { return Members.Any(m => m.Name == name); } public bool Has(uint pId) { return Members.Any(m => m.PlayerId == pId); } public bool HasPowers(string name) { return Has(name) && Members.FirstOrDefault(x => x.Name == name)?.CanInvite == true; } public bool TryGetMember(uint playerId, uint serverId, out GroupMemberData member) { member = Members.FirstOrDefault(m => m.PlayerId == playerId && m.ServerId == serverId); return member != null; } public bool TryGetMember(string name, out GroupMemberData member) { member = Members.FirstOrDefault(m => m.Name == name); return member != null; } } }
mit
C#
b73aa145813d4d8aba4f2629ae40f9e9f35c4b9d
Remove unuseful usings
shannan1989/ShannanWPF
DoingWell/App.xaml.cs
DoingWell/App.xaml.cs
using System.Windows; namespace Shnannan.DoingWell { public partial class App : Application { } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace Shnannan.DoingWell { public partial class App : Application { } }
apache-2.0
C#
9edc8486346545e43ceda7d8767ce7003f6ed0ac
Clean unnecessary using directives.
Quickshot/DupImageLib,Quickshot/DupImage
DupImage/ImageStruct.cs
DupImage/ImageStruct.cs
using System; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException(nameof(file)); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(string pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public string ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
using System; using System.Collections.Generic; using System.IO; namespace DupImage { /// <summary> /// Structure for containing image information and hash values. /// </summary> public class ImageStruct { /// <summary> /// Construct a new ImageStruct from FileInfo. /// </summary> /// <param name="file">FileInfo to be used.</param> public ImageStruct(FileInfo file) { if (file == null) throw new ArgumentNullException(nameof(file)); ImagePath = file.FullName; // Init Hash Hash = new long[1]; } /// <summary> /// Construct a new ImageStruct from image path. /// </summary> /// <param name="pathToImage">Image location</param> public ImageStruct(string pathToImage) { ImagePath = pathToImage; // Init Hash Hash = new long[1]; } /// <summary> /// ImagePath information. /// </summary> public string ImagePath { get; private set; } /// <summary> /// Hash of the image. Uses longs instead of ulong to be CLS compliant. /// </summary> public long[] Hash { get; set; } } }
unknown
C#
6e32e6040e37ab5602add4f5f21c40f88057ed80
Remove unused import
crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin
SignInCheckIn/SignInCheckIn/App_Start/WebApiConfig.cs
SignInCheckIn/SignInCheckIn/App_Start/WebApiConfig.cs
using System.Configuration; using System.Web.Http; using System.Web.Http.Cors; using Crossroads.ApiVersioning; namespace SignInCheckIn { public static class WebApiConfig { public static ApiRouteProvider ApiRouteProvider = new ApiRouteProvider(); public static void Register(HttpConfiguration config) { // Web API configuration and services // API Versioning VersionConfig.Register(config); // Configure CORS var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["CORS"], "*", "*"); cors.SupportsCredentials = true; config.EnableCors(cors); } } }
using System.Configuration; using System.Web.Http; using System.Web.Http.Cors; using Crossroads.ApiVersioning; using Crossroads.ClientApiKeys; namespace SignInCheckIn { public static class WebApiConfig { public static ApiRouteProvider ApiRouteProvider = new ApiRouteProvider(); public static void Register(HttpConfiguration config) { // Web API configuration and services // API Versioning VersionConfig.Register(config); // Configure CORS var cors = new EnableCorsAttribute(ConfigurationManager.AppSettings["CORS"], "*", "*"); cors.SupportsCredentials = true; config.EnableCors(cors); } } }
bsd-2-clause
C#
54f0ab7b705f20dee3a07ffa8cebe3a097a7125b
Test fix- catching permission denied exceptions
tzachshabtay/MonoAGS
Source/Engine/AGS.Engine.Desktop/DesktopFileSystem.cs
Source/Engine/AGS.Engine.Desktop/DesktopFileSystem.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetFiles: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetDirectories(string folder) { try { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } catch (UnauthorizedAccessException) { Debug.WriteLine($"GetDirectories: Permission denied for {folder}"); return new List<string>(); } } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
using System; using System.Collections.Generic; using System.IO; namespace AGS.Engine.Desktop { public class DesktopFileSystem : IFileSystem { #region IFileSystem implementation public string StorageFolder => Directory.GetCurrentDirectory(); //todo: find a suitable save location on desktop public IEnumerable<string> GetFiles(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetFiles(folder); } public IEnumerable<string> GetDirectories(string folder) { if (!Directory.Exists(folder)) return new List<string>(); return Directory.GetDirectories(folder); } public IEnumerable<string> GetLogicalDrives() => Directory.GetLogicalDrives(); public string GetCurrentDirectory() => Directory.GetCurrentDirectory(); public bool DirectoryExists(string folder) => Directory.Exists(folder); public bool FileExists(string path) => File.Exists(path); public Stream Open(string path) => File.OpenRead(path); public Stream Create(string path) => File.Create(path); public void Delete(string path) { File.Delete(path); } #endregion } }
artistic-2.0
C#
ef8105703be0a875c4cedb2f709be4b0aefe1826
test selectors were not working on knockoutjs.com
mirabeau-nl/WbTstr.Net,jorik041/FluentAutomation,tablesmit/FluentAutomation,jorik041/FluentAutomation,jorik041/FluentAutomation,stirno/FluentAutomation,tablesmit/FluentAutomation,stirno/FluentAutomation,stirno/FluentAutomation,mirabeau-nl/WbTstr.Net,tablesmit/FluentAutomation
SourceCode/FluentAutomation.Tests/SeleniumBugTests.cs
SourceCode/FluentAutomation.Tests/SeleniumBugTests.cs
// <copyright file="SeleniumBugTests.cs" author="Brandon Stirnaman"> // Copyright (c) 2011 Brandon Stirnaman, All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAutomation.API.Enumerations; namespace FluentAutomation.Tests { [TestClass] public class SeleniumBugTests : FluentAutomation.WatiN.FluentTest { [TestMethod] public void TestSelenium() { I.Open("http://knockoutjs.com/examples/cartEditor.html"); I.Select("Motorcycles").From(".liveExample tr select:eq(0)"); I.Select("1957 Vespa GS150").From(".liveExample tr select:eq(1)"); I.Enter(6).Quickly.In(".liveExample td.quantity input"); I.Expect.Text("$197.70").In(".liveExample tr span:eq(1)"); } [TestMethod] public void Test() { I.Open("http://developer.yahoo.com/yui/examples/dragdrop/dd-groups.html"); I.Drag("#pt1").To("#t2"); I.Drag("#pt2").To("#t1"); I.Drag("#pb1").To("#b1"); I.Drag("#pb2").To("#b2"); I.Drag("#pboth1").To("#b3"); I.Drag("#pboth2").To("#b4"); I.Drag("#pt1").To("#pt2"); I.Drag("#pboth1").To("#pb2"); } } }
// <copyright file="SeleniumBugTests.cs" author="Brandon Stirnaman"> // Copyright (c) 2011 Brandon Stirnaman, All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAutomation.API.Enumerations; namespace FluentAutomation.Tests { [TestClass] public class SeleniumBugTests : FluentAutomation.WatiN.FluentTest { [TestMethod] public void TestSelenium() { I.Open("http://knockoutjs.com/examples/cartEditor.html"); I.Select("Motorcycles").From("#cartEditor tr select:eq(0)"); I.Select("1957 Vespa GS150").From("#cartEditor tr select:eq(1)"); I.Enter(6).Quickly.In("#cartEditor td.quantity input"); I.Expect.Text("$197.70").In("#cartEditor tr span:eq(1)"); } [TestMethod] public void Test() { I.Open("http://developer.yahoo.com/yui/examples/dragdrop/dd-groups.html"); I.Drag("#pt1").To("#t2"); I.Drag("#pt2").To("#t1"); I.Drag("#pb1").To("#b1"); I.Drag("#pb2").To("#b2"); I.Drag("#pboth1").To("#b3"); I.Drag("#pboth2").To("#b4"); I.Drag("#pt1").To("#pt2"); I.Drag("#pboth1").To("#pb2"); } } }
mit
C#
6cbda108b8bca5d70f2212be520b52a80d5a3aa4
Add validation for the country parameter length
Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,akromm/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,DinoV/azure-sdk-tools,akromm/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,johnkors/azure-sdk-tools,antonba/azure-sdk-tools,Madhukarc/azure-sdk-tools,johnkors/azure-sdk-tools,markcowl/azure-sdk-tools,johnkors/azure-sdk-tools,Madhukarc/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools
WindowsAzurePowershell/src/Management.Store/Cmdlet/GetAzureStoreAvailableAddOn.cs
WindowsAzurePowershell/src/Management.Store/Cmdlet/GetAzureStoreAvailableAddOn.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Store.Cmdlet { using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Security.Permissions; using Microsoft.Samples.WindowsAzure.ServiceManagement.Marketplace.Contract; using Microsoft.Samples.WindowsAzure.ServiceManagement.Marketplace.ResourceModel; using Microsoft.WindowsAzure.Management.Cmdlets.Common; using Microsoft.WindowsAzure.Management.Store.Properties; using Microsoft.WindowsAzure.Management.Store.Model; /// <summary> /// Create scaffolding for a new node web role, change cscfg file and csdef to include the added web role /// </summary> [Cmdlet(VerbsCommon.Get, "AzureStoreAvailableAddOn"), OutputType(typeof(List<WindowsAzureOffer>))] public class GetAzureStoreAvailableAddOnCommand : CloudBaseCmdlet<IMarketplaceManagement> { public StoreClient StoreClient { get; set; } [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Country code")] [ValidateLength(2, 2)] public string Country { get; set; } [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { StoreClient = StoreClient ?? new StoreClient( CurrentSubscription.SubscriptionId, ServiceEndpoint, CurrentSubscription.Certificate, text => this.WriteDebug(text)); List<WindowsAzureOffer> result = StoreClient.GetAvailableWindowsAzureAddOns(Country ?? "US"); if (result.Count > 0) { WriteObject(result, true); } } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Store.Cmdlet { using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Security.Permissions; using Microsoft.Samples.WindowsAzure.ServiceManagement.Marketplace.Contract; using Microsoft.Samples.WindowsAzure.ServiceManagement.Marketplace.ResourceModel; using Microsoft.WindowsAzure.Management.Cmdlets.Common; using Microsoft.WindowsAzure.Management.Store.Properties; using Microsoft.WindowsAzure.Management.Store.Model; /// <summary> /// Create scaffolding for a new node web role, change cscfg file and csdef to include the added web role /// </summary> [Cmdlet(VerbsCommon.Get, "AzureStoreAvailableAddOn"), OutputType(typeof(List<WindowsAzureOffer>))] public class GetAzureStoreAvailableAddOnCommand : CloudBaseCmdlet<IMarketplaceManagement> { public StoreClient StoreClient { get; set; } [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Country code")] public string Country { get; set; } [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { StoreClient = StoreClient ?? new StoreClient( CurrentSubscription.SubscriptionId, ServiceEndpoint, CurrentSubscription.Certificate, text => this.WriteDebug(text)); List<WindowsAzureOffer> result = StoreClient.GetAvailableWindowsAzureAddOns(Country ?? "US"); if (result.Count > 0) { WriteObject(result, true); } } } }
apache-2.0
C#