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
ee9693806af1571fb4cd5247a7aaee413eb107c0
update TAlex.Common.Diagnostics version
T-Alex/Common
TAlex.Common.Diagnostics/Properties/AssemblyInfo.cs
TAlex.Common.Diagnostics/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("TAlex.Common.Diagnostics")] [assembly: AssemblyDescription("Set of diagnostic tools.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("T-Alex Software")] [assembly: AssemblyProduct("TAlex.Common.Diagnostics")] [assembly: AssemblyCopyright("Copyright © 2015 T-Alex Software")] [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("b32b57c8-a0c6-4ba6-9f28-ac2fd1216d7e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2.2")] [assembly: AssemblyFileVersion("1.2.2.2")]
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("TAlex.Common.Diagnostics")] [assembly: AssemblyDescription("Set of diagnostic tools.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("T-Alex Software")] [assembly: AssemblyProduct("TAlex.Common.Diagnostics")] [assembly: AssemblyCopyright("Copyright © 2015 T-Alex Software")] [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("b32b57c8-a0c6-4ba6-9f28-ac2fd1216d7e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2.1")] [assembly: AssemblyFileVersion("1.2.2.1")]
mit
C#
bc97c27d932bc5fca36b11b17aed7378ff92a886
Load config.yml from C#
irfancharania/HackyNewsClone
HackyNewsWeb/Controllers/HomeController.cs
HackyNewsWeb/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using HackyNewsDomain; namespace HackyNewsWeb.Controllers { public class HomeController : Controller { private const string CONFIG_PATH = "config.yml"; public ActionResult Index() { var configPath = Server.MapPath(CONFIG_PATH); var settings = new Data.Settings(); settings.Load(configPath); var feed = new Models.Feed(settings); var maybeItems = feed.GetItems(); return View(feed); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using HackyNewsDomain; namespace HackyNewsWeb.Controllers { public class HomeController : Controller { public ActionResult Index() { var settings = new Data.Settings(); var feed = new Models.Feed(settings); var maybeItems = feed.GetItems(); if(maybeItems.Success()) { foreach(var result in maybeItems.GetResult()) { if(result.Success()){ var item = result.GetResult().item; Console.WriteLine(item.title); } else { var item = result.GetError().Item1; var message = result.GetError().Item2; Console.WriteLine(item.title); Console.WriteLine(message); } } } return View(feed); } } }
mit
C#
a66849b77d305c86102e29741f9524a1d9657cc7
Format assembly properties
PetSerAl/PetSerAl.PowerShell.Xml.Linq
Assembly.cs
Assembly.cs
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: CLSCompliant(false)] [assembly: NeutralResourcesLanguage("en")] [assembly: AssemblyVersion("1.0.0"), AssemblyFileVersion("1.0.0")] [assembly: ComVisible(false)]
using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: CLSCompliant(false), NeutralResourcesLanguage("en"), AssemblyVersion("1.0.0"), AssemblyFileVersion("1.0.0"), ComVisible(false)]
mit
C#
6c73079b49b7cdaab489e48bb950d169fd56b608
Revert "commit me"
Ananasus/AutoShare
AutoShare/MainWindow.xaml.cs
AutoShare/MainWindow.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.IO; using System.Windows.Shapes; namespace AutoShare { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> /// public partial class MainWindow : MahApps.Metro.Controls.MetroWindow { public MainWindow() { InitializeComponent(); } private void FileDropped(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop)); foreach (string fileLoc in filePaths) { try { // Code to read the contents of the text file if (File.Exists(fileLoc)) { } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.IO; using System.Windows.Shapes; namespace AutoShare { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> /// public partial class MainWindow : MahApps.Metro.Controls.MetroWindow { public MainWindow() { InitializeComponent(); } private void FileDropped(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop)) { string[] filePaths = (string[])(e.Data.GetData(DataFormats.FileDrop)); foreach (string fileLoc in filePaths) { try { // Code to read the contents of the text file if (File.Exists(fileLoc)) { } } catch (Exception sfdb) { } } } } } }
mit
C#
e801f796ea69fbbad129fd1cd5d06bedacd521f1
Switch to version 1.3.1
Abc-Arbitrage/Zebus.Directory,Abc-Arbitrage/Zebus
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.3.1")] [assembly: AssemblyFileVersion("1.3.1")] [assembly: AssemblyInformationalVersion("1.3.1")]
using System.Reflection; [assembly: AssemblyVersion("1.3.0")] [assembly: AssemblyFileVersion("1.3.0")] [assembly: AssemblyInformationalVersion("1.3.0")]
mit
C#
ff8b98fd61a5f733789609ea91db65d4e74ed832
Update Value.cs
Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D/ViewModels/Data/Value.cs
src/Core2D/ViewModels/Data/Value.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.Collections.Generic; using Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Record value. /// </summary> public class Value : ObservableObject, IValue { private string _content; /// <inheritdoc/> [Content] public string Content { get => _content; set => Update(ref _content, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { return new Value() { Name = this.Name, Content = this.Content }; } /// <summary> /// Check whether the <see cref="Content"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeContent() => !string.IsNullOrWhiteSpace(_content); } }
// 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 Core2D.Attributes; namespace Core2D.Data { /// <summary> /// Record value. /// </summary> public class Value : ObservableObject, IValue { private string _content; /// <inheritdoc/> [Content] public string Content { get => _content; set => Update(ref _content, value); } /// <inheritdoc/> public override object Copy(IDictionary<object, object> shared) { return new Value() { Name = this.Name, Content = this.Content }; } /// <summary> /// Check whether the <see cref="Content"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public virtual bool ShouldSerializeContent() => !string.IsNullOrWhiteSpace(_content); } }
mit
C#
768f823a1a22ebb9f0d890501728449b670bd030
Bump the Collector version
mdsol/Medidata.ZipkinTracerModule
src/Medidata.ZipkinTracer.Core.Collector/Properties/AssemblyInfo.cs
src/Medidata.ZipkinTracer.Core.Collector/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("Medidata.ZipkinTracer.Core.Collector")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("Medidata Solutions, Inc.")] [assembly: AssemblyProduct("Medidata.ZipkinTracer.Core.Collector")] [assembly: AssemblyCopyright("Copyright © Medidata Solutions, Inc. 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif // 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("7d1a17a8-c4e9-46f0-83e1-623065b141a4")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0")] [assembly: AssemblyFileVersion("1.2.0")] [assembly: AssemblyInformationalVersion("1.2.0")] [assembly: InternalsVisibleTo("Medidata.ZipkinTracer.Core.Collector.Test")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Medidata.ZipkinTracer.Core.Collector")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Medidata Solutions Inc")] [assembly: AssemblyProduct("Medidata.ZipkinTracer.Core.Collector")] [assembly: AssemblyCopyright("Copyright © Medidata Solutions Inc 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7d1a17a8-c4e9-46f0-83e1-623065b141a4")] // 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.4")] [assembly: AssemblyFileVersion("1.0.4")] [assembly: AssemblyInformationalVersion("1.0.4")] [assembly: InternalsVisibleTo("Medidata.ZipkinTracer.Core.Collector.Test")]
mit
C#
5250c697c8943aad8c24cf5d31e0f0bff52deb49
Fix title of exception
2gis/Winium.Desktop,zebraxxl/Winium.Desktop,jorik041/Winium.Desktop
src/Winium.Desktop.Driver/CommandExecutors/ExecuteScriptExecutor.cs
src/Winium.Desktop.Driver/CommandExecutors/ExecuteScriptExecutor.cs
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System; using Newtonsoft.Json.Linq; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class ExecuteScriptExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var script = this.ExecutedCommand.Parameters["script"].ToString(); var prefix = string.Empty; string command; var index = script.IndexOf(':'); if (index == -1) { command = script; } else { prefix = script.Substring(0, index); command = script.Substring(++index).Trim(); } switch (prefix) { case "input": this.ExecuteInputScript(command); break; default: var msg = string.Format("Unknown script command '{0} {1}'", prefix, command); return this.JsonResponse(ResponseStatus.JavaScriptError, msg); } return this.JsonResponse(); } private void ExecuteInputScript(string command) { var args = (JArray)this.ExecutedCommand.Parameters["args"]; var elementId = args[0]["ELEMENT"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(elementId); switch (command) { case "ctrl_click": element.ClickWithPressedCtrl(); return; default: throw new NotImplementedException(string.Format("Input-command {0} is not implemented", command)); } } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System; using Newtonsoft.Json.Linq; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class ExecuteScriptExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var script = this.ExecutedCommand.Parameters["script"].ToString(); var prefix = string.Empty; string command; var index = script.IndexOf(':'); if (index == -1) { command = script; } else { prefix = script.Substring(0, index); command = script.Substring(++index).Trim(); } switch (prefix) { case "input": this.ExecuteInputScript(command); break; default: var msg = string.Format("Unknown script command '{0} {1}'", prefix, command); return this.JsonResponse(ResponseStatus.JavaScriptError, msg); } return this.JsonResponse(); } private void ExecuteInputScript(string command) { var args = (JArray)this.ExecutedCommand.Parameters["args"]; var elementId = args[0]["ELEMENT"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(elementId); switch (command) { case "ctrl_click": element.ClickWithPressedCtrl(); return; default: throw new NotImplementedException(string.Format("Input-command {0} didn't implemented", command)); } } #endregion } }
mpl-2.0
C#
419eefc0927dd7c3aae61cfb216ef1263db5885c
Make `SampleMacroFeature.ctor` public
Weingartner/SolidworksAddinFramework
DemoMacroFeature/SampleMacroFeature/SampleMacroFeature.cs
DemoMacroFeature/SampleMacroFeature/SampleMacroFeature.cs
using System.Numerics; using System.Runtime.InteropServices; using SolidworksAddinFramework; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swpublished; namespace DemoMacroFeatures.SampleMacroFeature { [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ISwComFeature))] public class SampleMacroFeature : MacroFeatureBase<SampleMacroFeature,SampleMacroFeatureDataBase> { public SampleMacroFeature() : base("Alpha Split", swMacroFeatureOptions_e.swMacroFeatureByDefault) { } protected override PropertyManagerPageBase GetPropertyManagerPage() => new SamplePropertyPage(this); protected override object Regenerate(IModeler modeler) { var body = (IBody2)Database.Body.GetSingleObject(ModelDoc); if (body == null) return null; body = (IBody2)body.Copy(); SwFeatureData.EnableMultiBodyConsume = true; var splitBodies = SplitBodies(modeler, body, Database); if (splitBodies == null) return "There was some error"; foreach (var splitBody in splitBodies) { SwFeatureData.AddIdsToBody(splitBody); } return splitBodies; } public static IBody2[] SplitBodies(IModeler modeler, IBody2 body, SampleMacroFeatureDataBase database) { var box = body.GetBodyBoxTs(); var center = box.Center; var axisX = Vector3.UnitX; // Find the point to cut the object center.X = (float) (database.Alpha*box.P0.X + (1 - database.Alpha)*box.P1.X); var sheet = modeler.CreateSheet(center, axisX, box.P0, box.P1); var cutResult = body.Cut(sheet); return cutResult.Error == 0 ? cutResult.Bodies : null; } protected override object Security() { return null; } public static void AddMacroFeature(ISldWorks app) { var moddoc = (IModelDoc2) app.ActiveDoc; var macroFeature = new SampleMacroFeature(); macroFeature.Edit(app, moddoc, null); } } }
using System.Numerics; using System.Runtime.InteropServices; using SolidworksAddinFramework; using SolidWorks.Interop.sldworks; using SolidWorks.Interop.swconst; using SolidWorks.Interop.swpublished; namespace DemoMacroFeatures.SampleMacroFeature { [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(ISwComFeature))] public class SampleMacroFeature : MacroFeatureBase<SampleMacroFeature,SampleMacroFeatureDataBase> { private SampleMacroFeature() : base("Alpha Split", swMacroFeatureOptions_e.swMacroFeatureByDefault) { } protected override PropertyManagerPageBase GetPropertyManagerPage() => new SamplePropertyPage(this); protected override object Regenerate(IModeler modeler) { var body = (IBody2)Database.Body.GetSingleObject(ModelDoc); if (body == null) return null; body = (IBody2)body.Copy(); SwFeatureData.EnableMultiBodyConsume = true; var splitBodies = SplitBodies(modeler, body, Database); if (splitBodies == null) return "There was some error"; foreach (var splitBody in splitBodies) { SwFeatureData.AddIdsToBody(splitBody); } return splitBodies; } public static IBody2[] SplitBodies(IModeler modeler, IBody2 body, SampleMacroFeatureDataBase database) { var box = body.GetBodyBoxTs(); var center = box.Center; var axisX = Vector3.UnitX; // Find the point to cut the object center.X = (float) (database.Alpha*box.P0.X + (1 - database.Alpha)*box.P1.X); var sheet = modeler.CreateSheet(center, axisX, box.P0, box.P1); var cutResult = body.Cut(sheet); return cutResult.Error == 0 ? cutResult.Bodies : null; } protected override object Security() { return null; } public static void AddMacroFeature(ISldWorks app) { var moddoc = (IModelDoc2) app.ActiveDoc; var macroFeature = new SampleMacroFeature(); macroFeature.Edit(app, moddoc, null); } } }
mit
C#
dc5c430c41374884dedf4db52b0542dc7452d4bb
Add missing property to Animation
MrRoundRobin/telegram.bot,TelegramBots/telegram.bot
src/Telegram.Bot/Types/Animation.cs
src/Telegram.Bot/Types/Animation.cs
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Telegram.Bot.Types { /// <summary> /// This object represents an animation file to be displayed in the message containing a <see cref="Game"/>. /// </summary> [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class Animation { /// <summary> /// Unique file identifier. /// </summary> [JsonProperty(Required = Required.Always)] public string FileId { get; set; } /// <summary> /// Unique identifier for this file, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file. /// </summary> [JsonProperty(Required = Required.Always)] public string FileUniqueId { get; set; } /// <summary> /// Video width as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Width { get; set; } /// <summary> /// Video height as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Height { get; set; } /// <summary> /// Duration of the video in seconds as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Duration { get; set; } /// <summary> /// Animation thumbnail as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public PhotoSize Thumb { get; set; } /// <summary> /// Original animation filename as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string FileName { get; set; } /// <summary> /// MIME type of the file as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string MimeType { get; set; } /// <summary> /// File size. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int FileSize { get; set; } } }
using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Telegram.Bot.Types { /// <summary> /// This object represents an animation file to be displayed in the message containing a <see cref="Game"/>. /// </summary> [JsonObject(MemberSerialization.OptIn, NamingStrategyType = typeof(SnakeCaseNamingStrategy))] public class Animation { /// <summary> /// Unique file identifier. /// </summary> [JsonProperty(Required = Required.Always)] public string FileId { get; set; } /// <summary> /// Video width as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Width { get; set; } /// <summary> /// Video height as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Height { get; set; } /// <summary> /// Duration of the video in seconds as defined by sender /// </summary> [JsonProperty(Required = Required.Always)] public int Duration { get; set; } /// <summary> /// Animation thumbnail as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public PhotoSize Thumb { get; set; } /// <summary> /// Original animation filename as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string FileName { get; set; } /// <summary> /// MIME type of the file as defined by sender. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public string MimeType { get; set; } /// <summary> /// File size. /// </summary> [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)] public int FileSize { get; set; } } }
mit
C#
19c778885085eae99df7d8d6a49d74729ab7cf5d
Rename property to MySqlException.Number.
gitsno/MySqlConnector,mysql-net/MySqlConnector,mysql-net/MySqlConnector,gitsno/MySqlConnector
src/MySql.Data/MySqlClient/MySqlException.cs
src/MySql.Data/MySqlClient/MySqlException.cs
using System; using System.Data.Common; namespace MySql.Data.MySqlClient { public sealed class MySqlException : DbException { public int Number { get; } public string SqlState { get; } internal MySqlException(string message, Exception innerException) : this(0, null, message, innerException) { } internal MySqlException(int errorNumber, string sqlState, string message) : this(errorNumber, sqlState, message, null) { } internal MySqlException(int errorNumber, string sqlState, string message, Exception innerException) : base(message, innerException) { Number = errorNumber; SqlState = sqlState; } } }
using System; using System.Data.Common; namespace MySql.Data.MySqlClient { public sealed class MySqlException : DbException { public int ErrorNumber { get; } public string SqlState { get; } internal MySqlException(string message, Exception innerException) : this(0, null, message, innerException) { } internal MySqlException(int errorNumber, string sqlState, string message) : this(errorNumber, sqlState, message, null) { } internal MySqlException(int errorNumber, string sqlState, string message, Exception innerException) : base(message, innerException) { ErrorNumber = errorNumber; SqlState = sqlState; } } }
mit
C#
06ae422aa8b704ad81115c7c9c91a7f6d5942418
add a link to our privacy policy
agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov
WebAPI.API/Views/Shared/_Navigation.cshtml
WebAPI.API/Views/Shared/_Navigation.cshtml
<ul class="nav nav-pills nav-stacked"> <li class="nav-header">Endpoints <li class="active"><a href="#geocoding">Geocoding</a> <li><a href="#search">Searching</a> <li><a href="#info">SGID Information</a> <li class="nav-header">Resources <li>@Html.ActionLink("Console", "Dashboard", new { Controller = "Go" }) <li>@Html.ActionLink("Register", "Register", new { Controller = "Go" }) <li class="nav-header">Help <li>@Html.ActionLink("Getting Started Guide", "Startup", new { Controller = "Go" }) <li><a href="https://github.com/agrc/GeocodingSample">Sample Usage</a> <li><a href="https://github.com/agrc/api.mapserv.utah.gov/issues/new">Report an Issue</a> <li><a href="https://github.com/agrc/api.mapserv.utah.gov/blob/master/readme.md#privacy-policy">Privacy Policy</a> <li class="nav-header">About <li><a href="@Url.Action("Index", "ChangeLog")"> <i class="glyphicon glyphicon-barcode"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a> <li class="nav-header">&copy; AGRC @DateTime.Now.Year </ul> <p> <img src="@Url.Content("~/Content/images/ravendb-small.png")" alt="ravendb logo"/> </p>
<ul class="nav nav-pills nav-stacked"> <li class="nav-header">Endpoints <li class="active"><a href="#geocoding">Geocoding</a> <li><a href="#search">Searching</a> <li><a href="#info">SGID Information</a> <li class="nav-header">Resources <li>@Html.ActionLink("Console", "Dashboard", new { Controller = "Go" }) <li>@Html.ActionLink("Register", "Register", new { Controller = "Go" }) <li class="nav-header">Help <li>@Html.ActionLink("Getting Started Guide", "Startup", new { Controller = "Go" }) <li><a href="https://github.com/agrc/GeocodingSample">Sample Usage</a> <li><a href="https://github.com/agrc/api.mapserv.utah.gov/issues/new">Report an Issue</a> <li class="nav-header">About <li><a href="@Url.Action("Index", "ChangeLog")"> <i class="glyphicon glyphicon-barcode"></i> @ViewContext.Controller.GetType().Assembly.GetName().Version.ToString()</a> <li class="nav-header">&copy; AGRC @DateTime.Now.Year </ul> <p> <img src="@Url.Content("~/Content/images/ravendb-small.png")" alt="ravendb logo"/> </p>
mit
C#
5ebf3fbf3c85537aa23572ec68f47a42240cbd9d
Update Arg.cs
ipjohnson/Grace
src/Grace/DependencyInjection/Arg.cs
src/Grace/DependencyInjection/Arg.cs
namespace Grace.DependencyInjection { /// <summary> /// Arg helper /// </summary> public class Arg { /// <summary> /// Any arguement of type T /// </summary> /// <typeparam name="T">type of arg</typeparam> /// <returns>default T value</returns> public static T Any<T>() { return default(T); } } }
namespace Grace.DependencyInjection { /// <summary> /// Arg helper /// </summary> public class Arg { /// <summary> /// Any arguement of type T /// </summary> /// <typeparam name="T">type of arg</typeparam> /// <returns>default T value</returns> public static T Any<T>() { return default(T); } } }
mit
C#
4d76dc49c60deeb38b7270ff0a143653dd369379
Use file scoped namespaces
carbon/Amazon
src/Amazon.Elb/Actions/DescribeRulesRequest.cs
src/Amazon.Elb/Actions/DescribeRulesRequest.cs
#nullable disable namespace Amazon.Elb; public class DescribeRulesRequest : IElbRequest { public string Action => "DescribeRules"; public string ListenerArn { get; init; } public string[] RuleArns { get; init; } }
#nullable disable using System.ComponentModel.DataAnnotations; namespace Amazon.Elb { public class DescribeRulesRequest : IElbRequest { public string Action => "DescribeRules"; public string ListenerArn { get; init; } public string[] RuleArns { get; init; } } }
mit
C#
ba5fa7094f37182f0f6aac23ec95c2cfa952e18d
Add RaiseCanExecuteChanged
meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework,meziantou/Meziantou.Framework
src/Meziantou.Framework.WPF/DelegateCommand.cs
src/Meziantou.Framework.WPF/DelegateCommand.cs
using System; using System.Windows.Input; using System.Windows.Threading; namespace Meziantou.Framework.WPF { public sealed class DelegateCommand : ICommand { private readonly Action<object> _execute; private readonly Func<object, bool> _canExecute; private readonly Dispatcher _dispatcher; public event EventHandler CanExecuteChanged; public DelegateCommand(Action execute) : this(WrapAction(execute)) { } public DelegateCommand(Action execute, Func<bool> canExecute) : this(WrapAction(execute), WrapAction(canExecute)) { } public DelegateCommand(Action<object> execute) : this(execute, canExecute: null) { } public DelegateCommand(Action<object> execute, Func<object, bool> canExecute) { _execute = execute; _canExecute = canExecute; _dispatcher = Dispatcher.CurrentDispatcher; } public bool CanExecute(object parameter) { return _canExecute?.Invoke(parameter) ?? true; } public void Execute(object parameter) { _execute?.Invoke(parameter); } public void RaiseCanExecuteChanged() { if (_dispatcher != null) { _dispatcher.Invoke(() => CanExecuteChanged?.Invoke(this, EventArgs.Empty)); } else { CanExecuteChanged?.Invoke(this, EventArgs.Empty); } } private static Action<object> WrapAction(Action action) { if (action == null) return null; return _ => action(); } private static Func<object, bool> WrapAction(Func<bool> action) { if (action == null) return null; return _ => action(); } } }
using System; using System.Windows.Input; namespace Meziantou.Framework.WPF { public sealed class DelegateCommand : ICommand { private readonly Action<object> _execute; private readonly Func<object, bool> _canExecute; public event EventHandler CanExecuteChanged; public DelegateCommand(Action execute) : this(WrapAction(execute)) { } public DelegateCommand(Action execute, Func<bool> canExecute) : this(WrapAction(execute), WrapAction(canExecute)) { } public DelegateCommand(Action<object> execute) : this(execute, null) { } public DelegateCommand(Action<object> execute, Func<object, bool> canExecute) { _execute = execute; _canExecute = canExecute; } public bool CanExecute(object parameter) { return _canExecute?.Invoke(parameter) ?? true; } public void Execute(object parameter) { _execute?.Invoke(parameter); } private static Action<object> WrapAction(Action action) { if (action == null) return null; return _ => action(); } private static Func<object, bool> WrapAction(Func<bool> action) { if (action == null) return null; return _ => action(); } } }
mit
C#
60f922ce1b67f434d6d6afbeaa68fa52866283a4
Add ignore_case and expand properties to synonym filter
UdiBen/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,joehmchan/elasticsearch-net,alanprot/elasticsearch-net,abibell/elasticsearch-net,junlapong/elasticsearch-net,jonyadamit/elasticsearch-net,ststeiger/elasticsearch-net,faisal00813/elasticsearch-net,adam-mccoy/elasticsearch-net,LeoYao/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,NickCraver/NEST,NickCraver/NEST,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,RossLieberman/NEST,DavidSSL/elasticsearch-net,starckgates/elasticsearch-net,elastic/elasticsearch-net,jonyadamit/elasticsearch-net,amyzheng424/elasticsearch-net,gayancc/elasticsearch-net,adam-mccoy/elasticsearch-net,mac2000/elasticsearch-net,robrich/elasticsearch-net,alanprot/elasticsearch-net,ststeiger/elasticsearch-net,robrich/elasticsearch-net,NickCraver/NEST,Grastveit/NEST,faisal00813/elasticsearch-net,abibell/elasticsearch-net,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,UdiBen/elasticsearch-net,starckgates/elasticsearch-net,UdiBen/elasticsearch-net,tkirill/elasticsearch-net,SeanKilleen/elasticsearch-net,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,ststeiger/elasticsearch-net,LeoYao/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,junlapong/elasticsearch-net,alanprot/elasticsearch-net,CSGOpenSource/elasticsearch-net,robertlyson/elasticsearch-net,wawrzyn/elasticsearch-net,abibell/elasticsearch-net,RossLieberman/NEST,robertlyson/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,faisal00813/elasticsearch-net,alanprot/elasticsearch-net,DavidSSL/elasticsearch-net,cstlaurent/elasticsearch-net,mac2000/elasticsearch-net,wawrzyn/elasticsearch-net,DavidSSL/elasticsearch-net,KodrAus/elasticsearch-net,wawrzyn/elasticsearch-net,cstlaurent/elasticsearch-net,SeanKilleen/elasticsearch-net,Grastveit/NEST,amyzheng424/elasticsearch-net,TheFireCookie/elasticsearch-net,tkirill/elasticsearch-net,geofeedia/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,amyzheng424/elasticsearch-net,robrich/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,Grastveit/NEST,junlapong/elasticsearch-net,geofeedia/elasticsearch-net,elastic/elasticsearch-net,cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,gayancc/elasticsearch-net
src/Nest/Domain/Settings/SynonymTokenFilter.cs
src/Nest/Domain/Settings/SynonymTokenFilter.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } [JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)] public bool? IgnoreCase { get; set; } [JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)] public bool? Expand { get; set; } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } } }
apache-2.0
C#
a3bfd2ad567e6286d74daa9a43b1dc7debb0919c
Add tokenizer option to SynonymTokenFilter
robertlyson/elasticsearch-net,mac2000/elasticsearch-net,junlapong/elasticsearch-net,starckgates/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net,mac2000/elasticsearch-net,SeanKilleen/elasticsearch-net,alanprot/elasticsearch-net,geofeedia/elasticsearch-net,DavidSSL/elasticsearch-net,ststeiger/elasticsearch-net,gayancc/elasticsearch-net,abibell/elasticsearch-net,faisal00813/elasticsearch-net,amyzheng424/elasticsearch-net,geofeedia/elasticsearch-net,mac2000/elasticsearch-net,alanprot/elasticsearch-net,KodrAus/elasticsearch-net,LeoYao/elasticsearch-net,joehmchan/elasticsearch-net,faisal00813/elasticsearch-net,junlapong/elasticsearch-net,azubanov/elasticsearch-net,geofeedia/elasticsearch-net,Grastveit/NEST,starckgates/elasticsearch-net,CSGOpenSource/elasticsearch-net,Grastveit/NEST,tkirill/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,jonyadamit/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,tkirill/elasticsearch-net,abibell/elasticsearch-net,UdiBen/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,alanprot/elasticsearch-net,alanprot/elasticsearch-net,wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,amyzheng424/elasticsearch-net,CSGOpenSource/elasticsearch-net,RossLieberman/NEST,wawrzyn/elasticsearch-net,cstlaurent/elasticsearch-net,NickCraver/NEST,robrich/elasticsearch-net,TheFireCookie/elasticsearch-net,Grastveit/NEST,KodrAus/elasticsearch-net,azubanov/elasticsearch-net,starckgates/elasticsearch-net,SeanKilleen/elasticsearch-net,DavidSSL/elasticsearch-net,jonyadamit/elasticsearch-net,NickCraver/NEST,ststeiger/elasticsearch-net,joehmchan/elasticsearch-net,wawrzyn/elasticsearch-net,UdiBen/elasticsearch-net,abibell/elasticsearch-net,gayancc/elasticsearch-net,adam-mccoy/elasticsearch-net,gayancc/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,LeoYao/elasticsearch-net,robrich/elasticsearch-net,cstlaurent/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,amyzheng424/elasticsearch-net,RossLieberman/NEST,adam-mccoy/elasticsearch-net,robertlyson/elasticsearch-net,joehmchan/elasticsearch-net,ststeiger/elasticsearch-net,NickCraver/NEST,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,DavidSSL/elasticsearch-net,junlapong/elasticsearch-net
src/Nest/Domain/Settings/SynonymTokenFilter.cs
src/Nest/Domain/Settings/SynonymTokenFilter.cs
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } [JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)] public bool? IgnoreCase { get; set; } [JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)] public bool? Expand { get; set; } [JsonProperty("tokenizer", NullValueHandling = NullValueHandling.Ignore)] public string Tokenizer { get; set; } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Nest { public class SynonymTokenFilter : TokenFilterSettings { public SynonymTokenFilter() : base("synonym") { } [JsonProperty("synonyms_path", NullValueHandling = NullValueHandling.Ignore)] public string SynonymsPath { get; set; } [JsonProperty("format", NullValueHandling=NullValueHandling.Ignore)] public string Format { get; set; } [JsonProperty("synonyms", NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<string> Synonyms { get; set; } [JsonProperty("ignore_case", NullValueHandling = NullValueHandling.Ignore)] public bool? IgnoreCase { get; set; } [JsonProperty("expand", NullValueHandling = NullValueHandling.Ignore)] public bool? Expand { get; set; } } }
apache-2.0
C#
dc2ae0489610ce436f0147e52716905073b2dc63
arrange test similar like the other tests
valit-stack/Valit,valit-stack/Valit
tests/Valit.Tests/MessageProvider/CustomMessageProvider_Tests.cs
tests/Valit.Tests/MessageProvider/CustomMessageProvider_Tests.cs
using System.Collections.Generic; using Xunit; using Shouldly; namespace Valit.Tests.MessageProvider { public class CustomMessageProvider_Tests { [Fact] public void CustomMessageProvider_Adds_Proper_Messages() { var result = ValitRules<Model> .Create() .WithMessageProvider(new CustomMessageProvider()) .Ensure(m => m.Value, _ => _ .MaxLength(10) .WithMessageKey(1) .MinLength(5) .WithMessageKey(2) .Matches(@"^\d") .WithMessageKey(3)) .For(_model) .Validate(); result.Succeeded.ShouldBe(false); result.ErrorCodes.ShouldBeEmpty(); result.ErrorMessages.ShouldNotBeEmpty(); result.ErrorMessages.ShouldContain("One"); result.ErrorMessages.ShouldNotContain("Two"); result.ErrorMessages.ShouldContain("Three"); } #region ARRANGE public CustomMessageProvider_Tests() { _model = new Model(); } private readonly Model _model; class Model { public string Value => "This text has 28 characters!"; } #endregion } class CustomMessageProvider : IValitMessageProvider<int> { private IDictionary<int, string> _messages = new Dictionary<int, string> { [1] = "One", [2] = "Two", [3] = "Three", }; public string GetByKey(int key) { if (_messages.TryGetValue(key, out var message)) return message; return string.Empty; } } }
using System.Collections.Generic; using Xunit; using Shouldly; namespace Valit.Tests.MessageProvider { public class CustomMessageProvider_Tests { [Fact] public void CustomMessageProvider_Adds_Proper_Messages() { var result = ValitRules<Model> .Create() .WithMessageProvider(new CustomMessageProvider()) .Ensure(m => m.Value, _ => _ .MaxLength(10) .WithMessageKey(1) .MinLength(5) .WithMessageKey(2) .Matches(@"^\d") .WithMessageKey(3)) .For(_model) .Validate(); result.Succeeded.ShouldBe(false); result.ErrorCodes.ShouldBeEmpty(); result.ErrorMessages.ShouldNotBeEmpty(); result.ErrorMessages.ShouldContain("One"); result.ErrorMessages.ShouldNotContain("Two"); result.ErrorMessages.ShouldContain("Three"); } Model _model => new Model(); class Model { public string Value => "This text has 28 characters!"; } } class CustomMessageProvider : IValitMessageProvider<int> { private IDictionary<int, string> _messages = new Dictionary<int, string> { [1] = "One", [2] = "Two", [3] = "Three", }; public string GetByKey(int key) { if (_messages.TryGetValue(key, out var message)) return message; return string.Empty; } } }
mit
C#
733397fbf6968a9f8acce20f71ed9ea6a063e761
Convert shift-jis to UTF-8
ytabuchi/XamarinNativeHandsOn
Finish/XN_ListView/XN_ListView.Droid/CustomListAdapter.cs
Finish/XN_ListView/XN_ListView.Droid/CustomListAdapter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace XN_ListView.Droid { class CustomListAdapter : BaseAdapter<TableItem> { Activity _context; List<TableItem> _items; public CustomListAdapter(Activity context, List<TableItem> items) { _context = context; _items = items; } public override TableItem this[int position] { get { return _items[position]; } } public override int Count { get { return _items.Count; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var item = _items[position]; View view = convertView; if (view == null) view = _context.LayoutInflater.Inflate(Resource.Layout.CustomView, null); //BaseAdapter<T> の対応するプロパティを割り当て view.FindViewById<TextView>(Resource.Id.mainText).Text = item.Main; view.FindViewById<TextView>(Resource.Id.subText).Text = item.Sub; view.FindViewById<ImageView>(Resource.Id.imageView).SetImageResource(item.ImageResourceId); return view; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace XN_ListView.Droid { class CustomListAdapter : BaseAdapter<TableItem> { Activity _context; List<TableItem> _items; public CustomListAdapter(Activity context, List<TableItem> items) { _context = context; _items = items; } public override TableItem this[int position] { get { return _items[position]; } } public override int Count { get { return _items.Count; } } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var item = _items[position]; View view = convertView; if (view == null) view = _context.LayoutInflater.Inflate(Resource.Layout.CustomView, null); //BaseAdapter<T>̑ΉvpeB蓖 view.FindViewById<TextView>(Resource.Id.mainText).Text = item.Main; view.FindViewById<TextView>(Resource.Id.subText).Text = item.Sub; view.FindViewById<ImageView>(Resource.Id.imageView).SetImageResource(item.ImageResourceId); return view; } } }
mit
C#
489caebf5996f1ca676e7d1700e44da8fd21110e
Move bind `LoadComplete` code out of constructor
UselessToucan/osu,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu
osu.Game/Overlays/News/NewsHeader.cs
osu.Game/Overlays/News/NewsHeader.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Framework.Graphics; namespace osu.Game.Overlays.News { public class NewsHeader : BreadcrumbControlOverlayHeader { private const string front_page_string = "frontpage"; public Action ShowFrontPage; private readonly Bindable<string> article = new Bindable<string>(null); public NewsHeader() { TabControl.AddItem(front_page_string); article.BindValueChanged(onArticleChanged, true); } protected override void LoadComplete() { base.LoadComplete(); Current.BindValueChanged(e => { if (e.NewValue == front_page_string) ShowFrontPage?.Invoke(); }); } public void SetFrontPage() => article.Value = null; public void SetArticle(string slug) => article.Value = slug; private void onArticleChanged(ValueChangedEvent<string> e) { if (e.OldValue != null) TabControl.RemoveItem(e.OldValue); if (e.NewValue != null) { TabControl.AddItem(e.NewValue); Current.Value = e.NewValue; } else { Current.Value = front_page_string; } } protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/news"); protected override OverlayTitle CreateTitle() => new NewsHeaderTitle(); private class NewsHeaderTitle : OverlayTitle { public NewsHeaderTitle() { Title = "news"; Description = "get up-to-date on community happenings"; IconTexture = "Icons/Hexacons/news"; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Framework.Graphics; namespace osu.Game.Overlays.News { public class NewsHeader : BreadcrumbControlOverlayHeader { private const string front_page_string = "frontpage"; public Action ShowFrontPage; private readonly Bindable<string> article = new Bindable<string>(null); public NewsHeader() { TabControl.AddItem(front_page_string); Current.BindValueChanged(e => { if (e.NewValue == front_page_string) ShowFrontPage?.Invoke(); }); article.BindValueChanged(onArticleChanged, true); } public void SetFrontPage() => article.Value = null; public void SetArticle(string slug) => article.Value = slug; private void onArticleChanged(ValueChangedEvent<string> e) { if (e.OldValue != null) TabControl.RemoveItem(e.OldValue); if (e.NewValue != null) { TabControl.AddItem(e.NewValue); Current.Value = e.NewValue; } else { Current.Value = front_page_string; } } protected override Drawable CreateBackground() => new OverlayHeaderBackground(@"Headers/news"); protected override OverlayTitle CreateTitle() => new NewsHeaderTitle(); private class NewsHeaderTitle : OverlayTitle { public NewsHeaderTitle() { Title = "news"; Description = "get up-to-date on community happenings"; IconTexture = "Icons/Hexacons/news"; } } } }
mit
C#
3eba7167eea417ddf376695da48a8baf29fbed58
Add linq reference for pre .net 4 builds.
ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog
Take2/NuLog/FallbackLoggers/StandardFallbackLoggerBase.cs
Take2/NuLog/FallbackLoggers/StandardFallbackLoggerBase.cs
/* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.Dispatchers; using NuLog.LogEvents; using System; #if PRENET4 using System.Linq; #endif namespace NuLog.FallbackLoggers { /// <summary> /// The core/basic functionality of the standard fallback logger implementation. /// </summary> public abstract class StandardFallbackLoggerBase : IFallbackLogger { public abstract void Log(Exception exception, ITarget target, ILogEvent logEvent); public abstract void Log(string message, params object[] args); protected virtual string FormatMessage(Exception exception, ITarget target, ILogEvent logEvent) { return FormatMessage("Failure writing to target \"{0}\" of type {1} | {2} | {3} | {4} | {5}", target.Name, target.GetType().FullName, JoinTags(logEvent), GetMessage(logEvent), GetExceptionMessage(logEvent), exception); } protected virtual string FormatMessage(string message, params object[] args) { var formatted = args != null && args.Length > 0 ? string.Format(message, args) : message; return string.Format("{0:yyyy-MM-dd hh:mm:ss.fff} | {1}", DateTime.Now, formatted); } private static string GetMessage(ILogEvent logEvent) { return logEvent is LogEvent ? ((LogEvent)logEvent).Message : logEvent.ToString(); } private static string JoinTags(ILogEvent logEvent) { #if PRENET4 return logEvent.Tags != null ? string.Join(",", logEvent.Tags.ToArray()) : string.Empty; #else return logEvent.Tags != null ? string.Join(",", logEvent.Tags) : string.Empty; #endif } private static string GetExceptionMessage(ILogEvent logEvent) { var castEvent = logEvent as LogEvent; if (castEvent != null) { var exception = castEvent.Exception; return string.Format("LogEvent Exception: \"{0}\"", exception != null ? exception.Message : string.Empty); } else { return string.Empty; } } } }
/* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using NuLog.Dispatchers; using NuLog.LogEvents; using System; namespace NuLog.FallbackLoggers { /// <summary> /// The core/basic functionality of the standard fallback logger implementation. /// </summary> public abstract class StandardFallbackLoggerBase : IFallbackLogger { public abstract void Log(Exception exception, ITarget target, ILogEvent logEvent); public abstract void Log(string message, params object[] args); protected virtual string FormatMessage(Exception exception, ITarget target, ILogEvent logEvent) { return FormatMessage("Failure writing to target \"{0}\" of type {1} | {2} | {3} | {4} | {5}", target.Name, target.GetType().FullName, JoinTags(logEvent), GetMessage(logEvent), GetExceptionMessage(logEvent), exception); } protected virtual string FormatMessage(string message, params object[] args) { var formatted = args != null && args.Length > 0 ? string.Format(message, args) : message; return string.Format("{0:yyyy-MM-dd hh:mm:ss.fff} | {1}", DateTime.Now, formatted); } private static string GetMessage(ILogEvent logEvent) { return logEvent is LogEvent ? ((LogEvent)logEvent).Message : logEvent.ToString(); } private static string JoinTags(ILogEvent logEvent) { #if PRENET4 return logEvent.Tags != null ? string.Join(",", logEvent.Tags.ToArray()) : string.Empty; #else return logEvent.Tags != null ? string.Join(",", logEvent.Tags) : string.Empty; #endif } private static string GetExceptionMessage(ILogEvent logEvent) { var castEvent = logEvent as LogEvent; if (castEvent != null) { var exception = castEvent.Exception; return string.Format("LogEvent Exception: \"{0}\"", exception != null ? exception.Message : string.Empty); } else { return string.Empty; } } } }
mit
C#
a947ad6755ae34fb114d94129b46525170abd33e
Fix missing object reference error.
DerTraveler/unity-hex-map
Assets/HexMap/HexMap.cs
Assets/HexMap/HexMap.cs
/* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData = new List<HexData>(); public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } }
/* Copyright (c) 2016 Kevin Fischer * * This Source Code Form is subject to the terms of the MIT License. * If a copy of the license was not distributed with this file, * You can obtain one at https://opensource.org/licenses/MIT. */ using UnityEngine; using System.Collections.Generic; using System.Collections.ObjectModel; namespace HexMapEngine { public class HexMap : ScriptableObject { List<HexData> _hexData; public ReadOnlyCollection<HexData> HexData { get { return _hexData.AsReadOnly(); } } Dictionary<Hex, HexData> _map; public void SetHexData(List<HexData> hexData) { _hexData = hexData; _map = new Dictionary<Hex, HexData>(); foreach (HexData data in hexData) { _map.Add(data.position, data); } } public HexData Get(Hex position) { HexData result; _map.TryGetValue(position, out result); return result; } } }
mit
C#
9e24c5f47c657ec9c0ef0c77307104c19f20b04b
Update DateTimeExtensions.cs
keith-hall/Extensions,keith-hall/Extensions
src/DateTimeExtensions.cs
src/DateTimeExtensions.cs
using System; using System.Globalization; using System.Threading; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with <see cref="DateTime" />s. /// </summary> public static class DateTimeExtensions { /// <summary> /// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in ISO-8601 format. /// </summary> /// <param name="dt">The date to convert.</param> /// <param name="withT">Whether or not to include the 'T' in the output. If false, a space will be used instead.</param> /// <returns>An ISO-8601 formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns> public static string ToISO8601String(this DateTime dt, bool withT) { return dt.ToString( dt.ToSortableDateTime() .Replace(@" ", withT ? @"'T'" : @" ") + @"'" + TimeZoneString(dt) + @"'" , CultureInfo.InvariantCulture); } /// <summary> /// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in a universal sortable format. /// </summary> /// <param name="dt">The date to convert.</param> /// <returns>A sortable formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns> public static string ToSortableDateTime (this DateTime dt) { return dt.ToString( Thread.CurrentThread.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern .Replace(@"Z'", @".'fff") ); } /// <summary> /// Gets the local time zone offset <see cref="String"/> from UTC for the specified <see cref="DateTime"/>. /// </summary> /// <param name="dt">The date to get the local timezone offset <see cref="String"/> for.</param> /// <returns>A <see cref="String"/> representation of the local timezone offset for the specified <see cref="DateTime"/>.</returns> public static string TimeZoneString (this DateTime dt) { if (dt.Kind == DateTimeKind.Utc) return @"Z"; var diff = System.TimeZoneInfo.Local.BaseUtcOffset; var hours = diff.Hours; if (System.TimeZoneInfo.Local.IsDaylightSavingTime(dt)) hours += 1; return (hours > 0 ? @"+" : string.Empty) + hours.ToString(@"00") + @":" + diff.Minutes.ToString(@"00"); } /// <summary> /// Convert the specified <see cref="DateTime"/> from UTC to the Local timezone. /// </summary> /// <param name="dt">The date to convert to local time.</param> /// <returns>The specified UTC <see cref="DateTime"/> converted to the Local timezone.</returns> public static DateTime FromUniversalTime (this DateTime dt) { if (dt.Kind == DateTimeKind.Local) return dt; return System.TimeZoneInfo.ConvertTimeFromUtc(dt, System.TimeZoneInfo.Local); } } }
using System; using System.Globalization; using System.Threading; namespace HallLibrary.Extensions { /// <summary> /// Contains extension methods for working with <see cref="DateTime" />s. /// </summary> public static class DateTimeExtensions { /// <summary> /// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in ISO-8601 format. /// </summary> /// <param name="dt">The date to convert.</param> /// <param name="withT">Whether or not to include the 'T' in the output. If false, a space will be used instead.</param> /// <returns>An ISO-8601 formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns> public static string ToISO8601String(this DateTime dt, bool withT) { return dt.ToString( dt.ToSortableDateTime() .Replace(@" ", withT ? @"'T'" : @" ") + @"'" + TimeZoneString(dt) + @"'" , CultureInfo.InvariantCulture); } /// <summary> /// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in a universal sortable format. /// </summary> /// <param name="dt">The date to convert.</param> /// <returns>A sortable formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns> public static string ToSortableDateTime (this DateTime dt) { return Thread.CurrentThread.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern .Replace(@"Z'", @".'fff"); } /// <summary> /// Gets the local time zone offset <see cref="String"/> from UTC for the specified <see cref="DateTime"/>. /// </summary> /// <param name="dt">The date to get the local timezone offset <see cref="String"/> for.</param> /// <returns>A <see cref="String"/> representation of the local timezone offset for the specified <see cref="DateTime"/>.</returns> public static string TimeZoneString (this DateTime dt) { if (dt.Kind == DateTimeKind.Utc) return @"Z"; var diff = System.TimeZoneInfo.Local.BaseUtcOffset; var hours = diff.Hours; if (System.TimeZoneInfo.Local.IsDaylightSavingTime(dt)) hours += 1; return (hours > 0 ? @"+" : string.Empty) + hours.ToString(@"00") + @":" + diff.Minutes.ToString(@"00"); } /// <summary> /// Convert the specified <see cref="DateTime"/> from UTC to the Local timezone. /// </summary> /// <param name="dt">The date to convert to local time.</param> /// <returns>The specified UTC <see cref="DateTime"/> converted to the Local timezone.</returns> public static DateTime FromUniversalTime (this DateTime dt) { if (dt.Kind == DateTimeKind.Local) return dt; return System.TimeZoneInfo.ConvertTimeFromUtc(dt, System.TimeZoneInfo.Local); } } }
apache-2.0
C#
e426c0fa04d5a6ab8fe94a554202c752e3b2e83b
Set IsBusy immediately, so there is no chance to run the command more than once.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { IsBusy = true; try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
using AvalonStudio.Extensibility; using ReactiveUI; using Splat; using System; using System.Linq; using System.Reactive; using System.Reactive.Linq; using System.Threading; using WalletWasabi.Gui.Helpers; using WalletWasabi.Logging; using WalletWasabi.Wallets; namespace WalletWasabi.Gui.Controls.WalletExplorer { public class ClosedWalletViewModel : WalletViewModelBase { public ClosedWalletViewModel(Wallet wallet) : base(wallet) { OpenWalletCommand = ReactiveCommand.CreateFromTask(async () => { try { var global = Locator.Current.GetService<Global>(); if (!await global.WaitForInitializationCompletedAsync(CancellationToken.None)) { return; } await global.WalletManager.StartWalletAsync(Wallet); } catch (Exception e) { NotificationHelpers.Error($"Error loading Wallet: {Title}"); Logger.LogError(e.Message); } }, this.WhenAnyValue(x => x.IsBusy).Select(x => !x)); } public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; } } }
mit
C#
c0e9a1989c0ef3338aa37efa829ac185dee598f7
Update Config.cs
ianmartinez/Language-Pad
src/LangPadData/Config.cs
src/LangPadData/Config.cs
using System; using System.Collections.Generic; using System.IO; namespace LangPadData { public static class Config { private static readonly string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); private static readonly string AppFolder = Path.Combine(AppData, "LangPad"); private static readonly string SettingsFilePath = Path.Combine(AppFolder, "LangPad.config"); private static Dictionary<string, string> Settings; public static bool HasLoaded => Settings != null; public static void LoadSettingsFile() { // Create config folder, if it doesn't exist if (!Directory.Exists(AppFolder)) Directory.CreateDirectory(AppFolder); // Create settings file, if it doesn't exist if (!File.Exists(SettingsFilePath)) File.WriteAllText(SettingsFilePath, ""); // Load settings Settings = KeyValue.ReadFile(SettingsFilePath); } public static void SaveSettingsFile() { var lines = new List<KvLine>(); lines.Add(new KvLine(KvLineType.Comment, "LangPad Configuration")); foreach (var setting in Settings) lines.Add(new KvLine(KvLineType.KeyValue, setting.Key, setting.Value)); KeyValue.WriteFile(SettingsFilePath, lines); } public static string Test { get => KeyValue.Search(Settings, "Test", "testvalue"); set { Settings["Test"] = value; SaveSettingsFile(); } } } }
using System; using System.Collections.Generic; using System.IO; namespace LangPadData { public static class Config { private static string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); private static string AppFolder = Path.Combine(AppData, "LangPad"); private static string SettingsFilePath = Path.Combine(AppFolder, "LangPad.config"); private static Dictionary<string, string> Settings; public static bool HasLoaded => Settings != null; public static void LoadSettingsFile() { // Create config folder, if it doesn't exist if (!Directory.Exists(AppFolder)) Directory.CreateDirectory(AppFolder); // Create settings file, if it doesn't exist if (!File.Exists(SettingsFilePath)) File.WriteAllText(SettingsFilePath, ""); // Load settings Settings = KeyValue.ReadFile(SettingsFilePath); } public static void SaveSettingsFile() { var lines = new List<KvLine>(); lines.Add(new KvLine(KvLineType.Comment, "LangPad Configuration")); foreach (var setting in Settings) lines.Add(new KvLine(KvLineType.KeyValue, setting.Key, setting.Value)); KeyValue.WriteFile(SettingsFilePath, lines); } public static string Test { get => KeyValue.Search(Settings, "Test", "testvalue"); set { Settings["Test"] = value; SaveSettingsFile(); } } } }
mit
C#
5456853702b473167dd9fcf8cf568fda6674f54a
Remove commented AssemblyVersion attributes to get GitVersionTask working
ekblom/noterium
src/Noterium/Properties/AssemblyInfo.cs
src/Noterium/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Noterium")] [assembly: AssemblyDescription("Main executable for Noterium")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Viktor Ekblom")] [assembly: AssemblyProduct("Noterium")] [assembly: AssemblyCopyright("Copyright © 2018")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Noterium")] [assembly: AssemblyDescription("Main executable for Noterium")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Viktor Ekblom")] [assembly: AssemblyProduct("Noterium")] [assembly: AssemblyCopyright("Copyright © 2018")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")]
mit
C#
767f2900f9faeff247d48a4b4a96c91a846b339a
Add support for creating a bounded channel in helper
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/SignalRSamples/ObservableExtensions.cs
samples/SignalRSamples/ObservableExtensions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable, int? maxBufferSize = null) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is bounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended and isn't shown here. var channel = maxBufferSize != null ? Channel.CreateBounded<T>(maxBufferSize.Value) : Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Reactive.Linq; using System.Threading.Channels; namespace SignalRSamples { public static class ObservableExtensions { public static ChannelReader<T> AsChannelReader<T>(this IObservable<T> observable) { // This sample shows adapting an observable to a ChannelReader without // back pressure, if the connection is slower than the producer, memory will // start to increase. // If the channel is unbounded, TryWrite will return false and effectively // drop items. // The other alternative is to use a bounded channel, and when the limit is reached // block on WaitToWriteAsync. This will block a thread pool thread and isn't recommended var channel = Channel.CreateUnbounded<T>(); var disposable = observable.Subscribe( value => channel.Writer.TryWrite(value), error => channel.Writer.TryComplete(error), () => channel.Writer.TryComplete()); // Complete the subscription on the reader completing channel.Reader.Completion.ContinueWith(task => disposable.Dispose()); return channel.Reader; } } }
apache-2.0
C#
5a74e8dd400131b40f3fcda7eb2e4eb5e43203b5
Add scheduling of events to occur later on the timeline
bwatts/Totem,bwatts/Totem
src/Totem/Runtime/Timeline/ITimeline.cs
src/Totem/Runtime/Timeline/ITimeline.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, Many<Event> events); void AppendLater(DateTime when, Many<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Totem.Runtime.Timeline { /// <summary> /// Describes a series of domain events /// </summary> public interface ITimeline : IFluent { void Append(TimelinePosition cause, IReadOnlyList<Event> events); Task<TFlow> MakeRequest<TFlow>(TimelinePosition cause, Event e) where TFlow : RequestFlow; } }
mit
C#
5ab6e46a5e760a61431c770017ad1b3c7e1f131b
remove litter
os2kitos/kitos,os2kitos/kitos,os2kitos/kitos,os2kitos/kitos
Tests.Integration.Presentation.Web/ItSystem/ItInterfaceUsageTests.cs
Tests.Integration.Presentation.Web/ItSystem/ItInterfaceUsageTests.cs
using System.Net; using System.Threading.Tasks; using Core.DomainModel.Organization; using Presentation.Web.Models; using Tests.Integration.Presentation.Web.Tools; using Xunit; namespace Tests.Integration.Presentation.Web.ItSystem { public class ItInterfaceUsageTests : WithAutoFixture { [Theory] [InlineData(OrganizationRole.GlobalAdmin)] [InlineData(OrganizationRole.User)] public async Task Api_User_Can_Get_It_Interface_Usage(OrganizationRole role) { //Arrange await InterfaceHelper.CreateItInterfaceUsageAsync( TestEnvironment.DefaultItSystemId, TestEnvironment.DefaultItInterfaceId, TestEnvironment.DefaultItSystemId, TestEnvironment.DefaultOrganizationId, TestEnvironment.DefaultContractId); var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/ItInterfaceUsage?usageId={TestEnvironment.DefaultItSystemId}&sysId={TestEnvironment.DefaultItSystemId}&interfaceId={TestEnvironment.DefaultItInterfaceId}"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync<ItInterfaceUsageDTO>(); //Assert Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); Assert.Equal(TestEnvironment.DefaultItSystemId, response.ItSystemUsageId); Assert.Equal(TestEnvironment.DefaultItSystemId, response.ItSystemId); Assert.Equal(TestEnvironment.DefaultItInterfaceId, response.ItInterfaceId); Assert.Equal(TestEnvironment.DefaultContractId, response.ItContractId); } } } }
using System.Net; using System.Threading.Tasks; using Core.DomainModel.Organization; using Presentation.Web.Models; using Tests.Integration.Presentation.Web.Tools; using Xunit; namespace Tests.Integration.Presentation.Web.ItSystem { public class ItInterfaceUsageTests : WithAutoFixture { [Theory] [InlineData(OrganizationRole.GlobalAdmin)] [InlineData(OrganizationRole.User)] public async Task Api_User_Can_Get_It_Interface_Usage(OrganizationRole role) { //Arrange await InterfaceHelper.CreateItInterfaceUsageAsync( TestEnvironment.DefaultItSystemId, TestEnvironment.DefaultItInterfaceId, TestEnvironment.DefaultItSystemId, TestEnvironment.DefaultOrganizationId, TestEnvironment.DefaultContractId); var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/ItInterfaceUsage?usageId={TestEnvironment.DefaultItSystemId}&sysId={TestEnvironment.DefaultItSystemId}&interfaceId={TestEnvironment.DefaultItInterfaceId}"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { var response = await httpResponse.ReadResponseBodyAsKitosApiResponseAsync<ItInterfaceUsageDTO>(); //Assert Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); Assert.Equal(TestEnvironment.DefaultItSystemId, response.ItSystemUsageId); Assert.Equal(TestEnvironment.DefaultItSystemId, response.ItSystemId); Assert.Equal(TestEnvironment.DefaultItInterfaceId, response.ItInterfaceId); Assert.Equal(TestEnvironment.DefaultContractId, response.ItContractId); } } [Theory] [InlineData(OrganizationRole.GlobalAdmin)] public async Task Api_User_Can_Get_It_Interface_Usages(OrganizationRole role) { //Arrange var token = await HttpApi.GetTokenAsync(role); var url = TestEnvironment.CreateUrl($"api/ItInterfaceUsage?usageId={TestEnvironment.DefaultItSystemId}"); //Act using (var httpResponse = await HttpApi.GetWithTokenAsync(url, token.Token)) { //Assert Assert.Equal(HttpStatusCode.OK, httpResponse.StatusCode); } } } }
mpl-2.0
C#
dea556b283001d8b647ca7ddc0127e10e147d973
Fix error descriptor to border color converter.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Converters/ErrorDescriptorToBorderColorConverter.cs
WalletWasabi.Gui/Converters/ErrorDescriptorToBorderColorConverter.cs
using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using WalletWasabi.Models; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Converters { public class ErrorDescriptorToBorderColorConverter : IValueConverter { private ErrorDescriptor UndefinedExceptionToErrorDescriptor(Exception ex) { var newErrDescMessage = ExceptionExtensions.ToTypeMessageString(ex); return new ErrorDescriptor(ErrorSeverity.Warning, newErrDescMessage); } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var descriptors = ErrorDescriptors.Create(); if (value is IEnumerable<object> rawObj) { foreach (var error in rawObj.OfType<ErrorDescriptor>()) { descriptors.Add(error); } foreach (var ex in rawObj.OfType<Exception>()) { descriptors.Add(UndefinedExceptionToErrorDescriptor(ex)); } } else if (value is Exception ex) { descriptors.Add(UndefinedExceptionToErrorDescriptor(ex)); } else { return null; } return GetColorFromDescriptors(descriptors); } private SolidColorBrush GetColorFromDescriptors(ErrorDescriptors descriptors) { if (!descriptors.HasErrors) { return null; } var highPrioError = descriptors.OrderByDescending(p => p.Severity).FirstOrDefault(); if (ErrorSeverityColorConverter.ErrorSeverityColors.TryGetValue(highPrioError.Severity, out var brush)) { return brush; } else { return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
using Avalonia.Data.Converters; using Avalonia.Media; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using WalletWasabi.Models; using WalletWasabi.Logging; namespace WalletWasabi.Gui.Converters { public class ErrorDescriptorToBorderColorConverter : IValueConverter { private ErrorDescriptor UndefinedExceptionToErrorDescriptor(Exception ex) { var newErrDescMessage = ExceptionExtensions.ToTypeMessageString(ex); return new ErrorDescriptor(ErrorSeverity.Warning, newErrDescMessage); } public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { var descriptors = new ErrorDescriptors(); if (value is IEnumerable<object> rawObj) { foreach (var error in rawObj.OfType<ErrorDescriptor>()) { descriptors.Add(error); } foreach (var ex in rawObj.OfType<Exception>()) { descriptors.Add(UndefinedExceptionToErrorDescriptor(ex)); } } else if (value is Exception ex) { descriptors.Add(UndefinedExceptionToErrorDescriptor(ex)); } else { return null; } return GetColorFromDescriptors(descriptors); } private SolidColorBrush GetColorFromDescriptors(ErrorDescriptors descriptors) { if (!descriptors.HasErrors) { return null; } var highPrioError = descriptors.OrderByDescending(p => p.Severity).FirstOrDefault(); if (ErrorSeverityColorConverter.ErrorSeverityColors.TryGetValue(highPrioError.Severity, out var brush)) { return brush; } else { return null; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } }
mit
C#
bd14f260217f1f6fef23e6bcc2c76e83adda601a
Change comments header
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/WpfMinesweeper/InputBox.xaml.cs
src2/WpfMinesweeper/InputBox.xaml.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InputBox.xaml.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // Interaction logic for InputBox.xaml // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System; using System.Windows; /// <summary> /// Interaction logic for InputBox.xaml /// </summary> public partial class InputBox : Window { /// <summary> /// The player name delegate. /// </summary> private readonly Action<string> playerNameDelegate; /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="playerNameDelegate"> /// The player name delegate. /// </param> public InputBox(Action<string> playerNameDelegate) { this.InitializeComponent(); this.playerNameDelegate = playerNameDelegate; } /// <summary> /// The cancel button click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void CancelButtonClick(object sender, RoutedEventArgs e) { this.Close(); } /// <summary> /// The ok button_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void OkButtonClick(object sender, RoutedEventArgs e) { // Input validations this.playerNameDelegate(this.NameTextBox.Text); this.Close(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="InputBox.xaml.cs" company=""> // // </copyright> // <summary> // Interaction logic for InputBox.xaml // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System; using System.Windows; /// <summary> /// Interaction logic for InputBox.xaml /// </summary> public partial class InputBox : Window { /// <summary> /// The player name delegate. /// </summary> private readonly Action<string> playerNameDelegate; /// <summary> /// Initializes a new instance of the <see cref="InputBox"/> class. /// </summary> /// <param name="playerNameDelegate"> /// The player name delegate. /// </param> public InputBox(Action<string> playerNameDelegate) { this.InitializeComponent(); this.playerNameDelegate = playerNameDelegate; } /// <summary> /// The cancel button click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void CancelButtonClick(object sender, RoutedEventArgs e) { this.Close(); } /// <summary> /// The ok button_ click. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The e. /// </param> private void OkButtonClick(object sender, RoutedEventArgs e) { // Input validations this.playerNameDelegate(this.NameTextBox.Text); this.Close(); } } }
mit
C#
43d2cdbe1d757d39b486f717b52258f0953e2b89
Fix assembly version for Shimmer
flagbug/Espera,punker76/Espera
Espera/GlobalAssemblyInfo.cs
Espera/GlobalAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.6")] [assembly: AssemblyFileVersion("1.7.6")] [assembly: AssemblyInformationalVersion("1.7.6")]
using System.Reflection; [assembly: AssemblyProduct("Espera")] [assembly: AssemblyCopyright("Copyright © 2013 Dennis Daume")] [assembly: AssemblyVersion("1.7.0.6")] [assembly: AssemblyFileVersion("1.7.0.6")]
mit
C#
80f320bb3349564340686b3c2d8808186b780f7a
Add workaround example for how to use parameterized type matchers
Moq/moq4
tests/Moq.Tests/CustomTypeMatchersFixture.cs
tests/Moq.Tests/CustomTypeMatchersFixture.cs
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using Xunit; namespace Moq.Tests { public class CustomTypeMatchersFixture { [Fact] public void Setup_with_custom_type_matcher() { var invocationCount = 0; var mock = new Mock<IX>(); mock.Setup(x => x.Method<IntOrString>()).Callback(() => invocationCount++); mock.Object.Method<bool>(); mock.Object.Method<int>(); mock.Object.Method<int>(); mock.Object.Method<object>(); mock.Object.Method<string>(); Assert.Equal(3, invocationCount); } [Fact] public void Verify_with_custom_type_matcher() { var mock = new Mock<IX>(); mock.Object.Method<bool>(); mock.Object.Method<int>(); mock.Object.Method<int>(); mock.Object.Method<object>(); mock.Object.Method<string>(); mock.Verify(x => x.Method<IntOrString>(), Times.Exactly(3)); } [Fact] public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Setup() { var mock = new Mock<IX>(); Action setup = () => mock.Setup(x => x.Method<Picky>()); var ex = Assert.Throws<ArgumentException>(setup); Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message); } [Fact] public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Verify() { var mock = new Mock<IX>(); Action verify = () => mock.Verify(x => x.Method<Picky>(), Times.Never); var ex = Assert.Throws<ArgumentException>(verify); Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message); } [Fact] public void Can_use_type_matcher_derived_from_one_having_a_parameterized_constructor() { var mock = new Mock<IX>(); mock.Object.Method<bool>(); mock.Object.Method<int>(); mock.Object.Method<object>(); mock.Object.Method<string>(); mock.Object.Method<string>(); mock.Verify(x => x.Method<PickyIntOrString>(), Times.Exactly(3)); } public interface IX { void Method<T>(); } public sealed class IntOrString : ITypeMatcher { public bool Matches(Type typeArgument) { return typeArgument == typeof(int) || typeArgument == typeof(string); } } public sealed class PickyIntOrString : Picky { public PickyIntOrString() : base(typeof(int), typeof(string)) { } } public class Picky : ITypeMatcher { private readonly Type[] types; public Picky(params Type[] types) { this.types = types; } public bool Matches(Type typeArgument) { return Array.IndexOf(this.types, typeArgument) >= 0; } } } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using Xunit; namespace Moq.Tests { public class CustomTypeMatchersFixture { [Fact] public void Setup_with_custom_type_matcher() { var invocationCount = 0; var mock = new Mock<IX>(); mock.Setup(x => x.Method<IntOrString>()).Callback(() => invocationCount++); mock.Object.Method<bool>(); mock.Object.Method<int>(); mock.Object.Method<int>(); mock.Object.Method<object>(); mock.Object.Method<string>(); Assert.Equal(3, invocationCount); } [Fact] public void Verify_with_custom_type_matcher() { var mock = new Mock<IX>(); mock.Object.Method<bool>(); mock.Object.Method<int>(); mock.Object.Method<int>(); mock.Object.Method<object>(); mock.Object.Method<string>(); mock.Verify(x => x.Method<IntOrString>(), Times.Exactly(3)); } [Fact] public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Setup() { var mock = new Mock<IX>(); Action setup = () => mock.Setup(x => x.Method<Picky>()); var ex = Assert.Throws<ArgumentException>(setup); Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message); } [Fact] public void Cannot_use_type_matcher_with_parameterized_constructor_directly_in_Verify() { var mock = new Mock<IX>(); Action verify = () => mock.Verify(x => x.Method<Picky>(), Times.Never); var ex = Assert.Throws<ArgumentException>(verify); Assert.Contains("Picky does not have a default (public parameterless) constructor", ex.Message); } public interface IX { void Method<T>(); } public sealed class IntOrString : ITypeMatcher { public bool Matches(Type typeArgument) { return typeArgument == typeof(int) || typeArgument == typeof(string); } } public class Picky : ITypeMatcher { private readonly Type[] types; public Picky(params Type[] types) { this.types = types; } public bool Matches(Type typeArgument) { return Array.IndexOf(this.types, typeArgument) >= 0; } } } }
bsd-3-clause
C#
d85f57dabd9bf2b85fa04e8c026d20bab60ee98b
add cdr
corvusalba/my-little-lispy,corvusalba/my-little-lispy
src/MyLittleLispy.Runtime/BuiltinsModule.cs
src/MyLittleLispy.Runtime/BuiltinsModule.cs
using System.Collections.Generic; namespace MyLittleLispy.Runtime { public class BuiltinsModule : IModule { private readonly IEnumerable<string> _builtins = new[] { "(define (<= x y) (or (< x y) (= x y)))", "(define (>= x y) (or (> x y) (= x y)))", "(define (xor x y) (and (or x y) (not (and x y))))" }; public void Import(Parser parser, Context context) { context.Bind("halt", new Lambda(new string[] { "code" }, new ClrLambdaBody( c => { throw new HaltException(c.Lookup("code").To<int>()); })) ); context.Bind("+", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Add(c.Lookup("b")))) ); context.Bind("-", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Substract(c.Lookup("b")))) ); context.Bind("*", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Multiple(c.Lookup("b")))) ); context.Bind("/", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Divide(c.Lookup("b")))) ); context.Bind("=", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Equal(c.Lookup("b")))) ); context.Bind("<", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Lesser(c.Lookup("b")))) ); context.Bind(">", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Greater(c.Lookup("b")))) ); context.Bind("and", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").And(c.Lookup("b")))) ); context.Bind("or", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Or(c.Lookup("b")))) ); context.Bind("not", new Lambda(new[] {"a"}, new ClrLambdaBody( c => c.Lookup("a").Not())) ); context.Bind("car", new Lambda(new[] {"a"}, new ClrLambdaBody( c => c.Lookup("a").Car())) ); context.Bind("cdr", new Lambda(new[] {"a"}, new ClrLambdaBody( c => c.Lookup("a").Cdr())) ); foreach (var define in _builtins) { parser.Parse(define).Eval(context); } } } }
using System.Collections.Generic; namespace MyLittleLispy.Runtime { public class BuiltinsModule : IModule { private readonly IEnumerable<string> _builtins = new[] { "(define (<= x y) (or (< x y) (= x y)))", "(define (>= x y) (or (> x y) (= x y)))", "(define (xor x y) (and (or x y) (not (and x y))))" }; public void Import(Parser parser, Context context) { context.Bind("halt", new Lambda(new string[] { "code" }, new ClrLambdaBody( c => { throw new HaltException(c.Lookup("code").To<int>()); })) ); context.Bind("+", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Add(c.Lookup("b")))) ); context.Bind("-", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Substract(c.Lookup("b")))) ); context.Bind("*", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Multiple(c.Lookup("b")))) ); context.Bind("/", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Divide(c.Lookup("b")))) ); context.Bind("=", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Equal(c.Lookup("b")))) ); context.Bind("<", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Lesser(c.Lookup("b")))) ); context.Bind(">", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Greater(c.Lookup("b")))) ); context.Bind("and", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").And(c.Lookup("b")))) ); context.Bind("or", new Lambda(new[] {"a", "b"}, new ClrLambdaBody( c => c.Lookup("a").Or(c.Lookup("b")))) ); context.Bind("not", new Lambda(new[] {"a"}, new ClrLambdaBody( c => c.Lookup("a").Not())) ); context.Bind("car", new Lambda(new[] {"a"}, new ClrLambdaBody( c => c.Lookup("a").Car())) ); foreach (var define in _builtins) { parser.Parse(define).Eval(context); } } } }
mit
C#
6d7e9bdc1305464931c3e204fb8e8fe6666d928a
Fix scheme
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/AdminController.cs
Battery-Commander.Web/Controllers/AdminController.cs
using BatteryCommander.Web.Models; using FluentScheduler; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Jobs() { return View(JobManager.AllSchedules); } public async Task<IActionResult> Users() { var soldiers_with_access = await db .Soldiers .Include(soldier => soldier.Unit) .Where(soldier => soldier.CanLogin) .Where(soldier => !String.IsNullOrWhiteSpace(soldier.CivilianEmail)) .Select(soldier => new { Uri = Url.RouteUrl("Soldier.Details", new { soldier.Id }, Request.Scheme), Unit = soldier.Unit.Name, soldier.FirstName, soldier.LastName, soldier.CivilianEmail }) .ToListAsync(); return Json(soldiers_with_access); } } }
using BatteryCommander.Web.Models; using FluentScheduler; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class AdminController : Controller { private readonly Database db; public AdminController(Database db) { this.db = db; } public IActionResult Index() { return View(); } public IActionResult Backup() { var data = System.IO.File.ReadAllBytes("Data.db"); var mimeType = "application/octet-stream"; return File(data, mimeType); } public IActionResult Jobs() { return View(JobManager.AllSchedules); } public async Task<IActionResult> Users() { var soldiers_with_access = await db .Soldiers .Include(soldier => soldier.Unit) .Where(soldier => soldier.CanLogin) .Where(soldier => !String.IsNullOrWhiteSpace(soldier.CivilianEmail)) .Select(soldier => new { Uri = Url.RouteUrl("Soldier.Details", new { soldier.Id }, Url.RequestContext.HttpContext.Request.Url.Scheme), Unit = soldier.Unit.Name, soldier.FirstName, soldier.LastName, soldier.CivilianEmail }) .ToListAsync(); return Json(soldiers_with_access); } } }
mit
C#
cc55ef3156c79dafbc3b02d1008bbd03c9b8e095
Update BookLesson.cshtml
DavidVeksler/SmallTalk,DavidVeksler/SmallTalk,DavidVeksler/SmallTalk
Apps/SmallTalk.Web/Views/Home/BookLesson.cshtml
Apps/SmallTalk.Web/Views/Home/BookLesson.cshtml
 <body> <div id="fullscreen_bg" class="fullscreen_bg"/> <center> <p style="color:white; font-weight:bold; margin-top:50px; font-size:50px;">Match!</p> <br> <p style="color:white; font-weight:bold; margin-top:30px; font-size:24px;">-Mentor Name- would like to be your mentor!</p> <br> <p style="color:white; font-weight:bold; margin-top:30px; font-size:24px;">Your lesson will be in:</p><label>location</label> <p style="color:white; font-weight:bold; margin-top:10px; margin-bottom: 0px; font-size:24px;">At </p> <label>time</label> <a class="btn btn-primary btn-lg btn-block" type="button" style="margin-top:50px;">Continue to unit lesson</a> </center> </div> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>

mit
C#
a403c5acb85035e89631cb82c2d0aa6c40c065af
order front-end lists by name alphabetically for now
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/FilterListService/FilterListService.cs
src/FilterLists.Services/FilterListService/FilterListService.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using FilterLists.Data; using FilterLists.Data.Entities; using FilterLists.Services.FilterListService.Models; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.FilterListService { public class FilterListService { private readonly FilterListsDbContext filterListsDbContext; public FilterListService(FilterListsDbContext filterListsDbContext) { this.filterListsDbContext = filterListsDbContext; } public async Task<IEnumerable<FilterListSummaryDto>> GetAllSummariesAsync() { return await filterListsDbContext.Set<FilterList>().AsNoTracking().OrderBy(x => x.Name) .ProjectTo<FilterListSummaryDto>().ToListAsync(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using FilterLists.Data; using FilterLists.Data.Entities; using FilterLists.Services.FilterListService.Models; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.FilterListService { public class FilterListService { private readonly FilterListsDbContext filterListsDbContext; public FilterListService(FilterListsDbContext filterListsDbContext) { this.filterListsDbContext = filterListsDbContext; } public async Task<IEnumerable<FilterListSummaryDto>> GetAllSummariesAsync() { return await filterListsDbContext.Set<FilterList>().AsNoTracking().ProjectTo<FilterListSummaryDto>() .ToListAsync(); } } }
mit
C#
8dfea75ae4612f5b83116313237a9ef7e1f972d7
remove emoji and yaml support from markdig pipeline
mike-ward/Markdown-Edit,punker76/Markdown-Edit
src/MarkdownEdit/MarkdownConverters/MarkdigMarkdownConverter.cs
src/MarkdownEdit/MarkdownConverters/MarkdigMarkdownConverter.cs
using Markdig; namespace MarkdownEdit.MarkdownConverters { public class MarkdigMarkdownConverter : IMarkdownConverter { public string ConvertToHtml(string markdown) { var pipeline = new MarkdownPipelineBuilder() .UseAdvancedExtensions() .Build(); return Markdown.ToHtml(markdown, pipeline); } } }
using Markdig; namespace MarkdownEdit.MarkdownConverters { public class MarkdigMarkdownConverter : IMarkdownConverter { public string ConvertToHtml(string markdown) { var pipeline = new MarkdownPipelineBuilder() .UseEmojiAndSmiley() .UseYamlFrontMatter() .UseAdvancedExtensions() .Build(); return Markdown.ToHtml(markdown, pipeline); } } }
mit
C#
9967bb85ea6f6425a14863c1fafc8c29b4696ec6
Add base class to error controller so that it can find Base SupportUserBanner child action
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Web/Controllers/ErrorController.cs
src/SFA.DAS.EmployerAccounts.Web/Controllers/ErrorController.cs
using System.Net; using System.Web.Mvc; using SFA.DAS.Authentication; using SFA.DAS.EmployerAccounts.Interfaces; using SFA.DAS.EmployerAccounts.Web.ViewModels; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : BaseController { public ErrorController( IAuthenticationService owinWrapper, IMultiVariantTestingService multiVariantTestingService, ICookieStorageService<FlashMessageViewModel> flashMessage) : base(owinWrapper, multiVariantTestingService, flashMessage) { } [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }
using System.Net; using System.Web.Mvc; namespace SFA.DAS.EmployerAccounts.Web.Controllers { public class ErrorController : Controller { [Route("accessdenied")] public ActionResult AccessDenied() { Response.StatusCode = (int)HttpStatusCode.Forbidden; return View(); } [Route("error")] public ActionResult Error() { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return View(); } [Route("notfound")] public ActionResult NotFound() { Response.StatusCode = (int)HttpStatusCode.NotFound; return View(); } } }
mit
C#
0851f9e608746abd1a71e79f00d0230a46fd3ee6
Remove DiscoveryPort from INetworkProvider
hach-que/Dx
Dx.Runtime/Processing/Interfaces/INetworkProvider.cs
Dx.Runtime/Processing/Interfaces/INetworkProvider.cs
using System.Net; namespace Dx.Runtime { public interface INetworkProvider { /// <summary> /// The node this network provider is associated with. /// </summary> ILocalNode Node { get; } /// <summary> /// The network identifier. /// </summary> /// <remarks>The implementation of this property should be read-only, to be set by the class internally when Join is called.</remarks> ID ID { get; } /// <summary> /// The messaging port that the TCP network (IStorageProvider) is listening on. /// </summary> int MessagingPort { get; } /// <summary> /// The IP address that processing and storage services should bind on. /// </summary> IPAddress IPAddress { get; } /// <summary> /// Whether this node was the first node to join the network. This should return /// the same value regardless of new nodes joining the network. /// </summary> bool IsFirst { get; } /// <summary> /// Joins the network with the specified ID. /// </summary> /// <param name="id">The network ID.</param> void Join(ID id); /// <summary> /// Leaves the network. /// </summary> void Leave(); } }
using System.Net; namespace Dx.Runtime { public interface INetworkProvider { /// <summary> /// The node this network provider is associated with. /// </summary> ILocalNode Node { get; } /// <summary> /// The network identifier. /// </summary> /// <remarks>The implementation of this property should be read-only, to be set by the class internally when Join is called.</remarks> ID ID { get; } /// <summary> /// The discovery port that the UDP network (INetworkProvider) is listening on. /// </summary> int DiscoveryPort { get; } /// <summary> /// The messaging port that the TCP network (IStorageProvider) is listening on. /// </summary> int MessagingPort { get; } /// <summary> /// The IP address that processing and storage services should bind on. /// </summary> IPAddress IPAddress { get; } /// <summary> /// Whether this node was the first node to join the network. This should return /// the same value regardless of new nodes joining the network. /// </summary> bool IsFirst { get; } /// <summary> /// Joins the network with the specified ID. /// </summary> /// <param name="id">The network ID.</param> void Join(ID id); /// <summary> /// Leaves the network. /// </summary> void Leave(); } }
mit
C#
c3513df1aa4835e770a95b1b0f51a7dbb70f4b2f
Fix Corrupted Config File Issue
TrueCommerce/CloudFtpBridge,TrueCommerce/CloudFtpBridge
src/Tc.Psg.CloudFtpBridge/Configuration/CloudFtpBridgeConfig.cs
src/Tc.Psg.CloudFtpBridge/Configuration/CloudFtpBridgeConfig.cs
using System.Collections.Generic; using System.IO; using System.Reflection; using Newtonsoft.Json; namespace Tc.Psg.CloudFtpBridge.Configuration { public class CloudFtpBridgeConfig { public CloudFtpBridgeConfig() { Companies = new List<CompanyConfig>(); PollingInterval = 30; } public List<CompanyConfig> Companies { get; set; } public bool DebugEnabled { get; set; } public int PollingInterval { get; set; } // seconds public static string GetDefaultConfigFileName() { FileInfo assemblyFileInfo = new FileInfo(Assembly.GetEntryAssembly().Location); return Path.Combine(assemblyFileInfo.DirectoryName, "CloudFtpBridgeConfig.json"); } public static CloudFtpBridgeConfig Load() { return LoadFrom(GetDefaultConfigFileName()); } public static CloudFtpBridgeConfig LoadFrom(string path) { CloudFtpBridgeConfig config = new CloudFtpBridgeConfig(); if (!File.Exists(path)) { config.SaveTo(path); } using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); config = JsonConvert.DeserializeObject<CloudFtpBridgeConfig>(json); } return config; } public void Save() { SaveTo(GetDefaultConfigFileName()); } public void SaveTo(string path) { using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write)) using (StreamWriter writer = new StreamWriter(stream)) { string json = JsonConvert.SerializeObject(this, Formatting.Indented); writer.Write(json); } } } }
using System.Collections.Generic; using System.IO; using System.Reflection; using Newtonsoft.Json; namespace Tc.Psg.CloudFtpBridge.Configuration { public class CloudFtpBridgeConfig { public CloudFtpBridgeConfig() { Companies = new List<CompanyConfig>(); PollingInterval = 30; } public List<CompanyConfig> Companies { get; set; } public bool DebugEnabled { get; set; } public int PollingInterval { get; set; } // seconds public static string GetDefaultConfigFileName() { FileInfo assemblyFileInfo = new FileInfo(Assembly.GetEntryAssembly().Location); return Path.Combine(assemblyFileInfo.DirectoryName, "CloudFtpBridgeConfig.json"); } public static CloudFtpBridgeConfig Load() { return LoadFrom(GetDefaultConfigFileName()); } public static CloudFtpBridgeConfig LoadFrom(string path) { CloudFtpBridgeConfig config = new CloudFtpBridgeConfig(); if (!File.Exists(path)) { config.SaveTo(path); } using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read)) using (StreamReader reader = new StreamReader(stream)) { string json = reader.ReadToEnd(); config = JsonConvert.DeserializeObject<CloudFtpBridgeConfig>(json); } return config; } public void Save() { SaveTo(GetDefaultConfigFileName()); } public void SaveTo(string path) { using (FileStream stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) using (StreamWriter writer = new StreamWriter(stream)) { string json = JsonConvert.SerializeObject(this, Formatting.Indented); writer.Write(json); } } } }
mit
C#
e41fb55e327a4102a6456d895596a34185051414
Fix SQ warning
steven-r/Oberon0Compiler
oberon0/Expressions/Operations/OpUnaryMinus.cs
oberon0/Expressions/Operations/OpUnaryMinus.cs
#region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="OpUnaryMinus.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler/OpUnaryMinus.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; /// <summary> /// Handle "~". /// </summary> /// <seealso cref="IArithmeticOperation" /> /// <remarks>This function is some kind of exception as - usually takes one parameter. The second is handled as a dummy</remarks> [ArithmeticOperation(OberonGrammarLexer.MINUS, BaseType.IntType, BaseType.AnyType, BaseType.IntType)] [ArithmeticOperation(OberonGrammarLexer.MINUS, BaseType.DecimalType, BaseType.AnyType, BaseType.DecimalType)] [UsedImplicitly] internal class OpUnaryMinus : BinaryOperation { protected override Expression BinaryOperate( BinaryExpression bin, Block block, IArithmeticOpMetadata operationParameters) { if (bin.LeftHandSide.IsConst) { switch (bin.LeftHandSide.TargetType.BaseType) { case BaseType.IntType: ConstantIntExpression leftInt = (ConstantIntExpression)bin.LeftHandSide; leftInt.Value = -(int)leftInt.Value; return leftInt; case BaseType.DecimalType: ConstantDoubleExpression leftDouble = (ConstantDoubleExpression)bin.LeftHandSide; leftDouble.Value = -(decimal)leftDouble.Value; return leftDouble; } } return bin; // expression remains the same } } }
#region copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="OpUnaryMinus.cs" company="Stephen Reindl"> // Copyright (c) Stephen Reindl. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // </copyright> // <summary> // Part of oberon0 - Oberon0Compiler/OpUnaryMinus.cs // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace Oberon0.Compiler.Expressions.Operations { using JetBrains.Annotations; using Oberon0.Compiler.Definitions; using Oberon0.Compiler.Expressions.Constant; using Oberon0.Compiler.Expressions.Operations.Internal; using Oberon0.Compiler.Types; /// <summary> /// Handle "~". /// </summary> /// <seealso cref="IArithmeticOperation" /> /// <remarks>This function is some kind of exception as - usually takes one parameter. The second is handled as a dummy</remarks> [ArithmeticOperation(OberonGrammarLexer.MINUS, BaseType.IntType, BaseType.AnyType, BaseType.IntType)] [ArithmeticOperation(OberonGrammarLexer.MINUS, BaseType.DecimalType, BaseType.AnyType, BaseType.DecimalType)] [UsedImplicitly] internal class OpUnaryMinus : BinaryOperation { protected override Expression BinaryOperate( BinaryExpression e, Block block, IArithmeticOpMetadata operationParameters) { if (e.LeftHandSide.IsConst) { switch (e.LeftHandSide.TargetType.BaseType) { case BaseType.IntType: ConstantIntExpression leftInt = (ConstantIntExpression)e.LeftHandSide; leftInt.Value = -(int)leftInt.Value; return leftInt; case BaseType.DecimalType: ConstantDoubleExpression leftDouble = (ConstantDoubleExpression)e.LeftHandSide; leftDouble.Value = -(decimal)leftDouble.Value; return leftDouble; } } return e; // expression remains the same } } }
mit
C#
b5ec101cc8af2a4b3313ba7466b79b5fa6961c95
add a comment about deprecating IRegionModule
bravelittlescientist/opensim-performance,RavenB/opensim,cdbean/CySim,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TechplexEngineer/Aurora-Sim,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,cdbean/CySim,cdbean/CySim,TomDataworks/opensim,ft-/opensim-optimizations-wip-tests,AlexRa/opensim-mods-Alex,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,RavenB/opensim,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,justinccdev/opensim,RavenB/opensim,BogusCurry/arribasim-dev,allquixotic/opensim-autobackup,TomDataworks/opensim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,allquixotic/opensim-autobackup,AlexRa/opensim-mods-Alex,justinccdev/opensim,M-O-S-E-S/opensim,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,cdbean/CySim,TechplexEngineer/Aurora-Sim,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,AlexRa/opensim-mods-Alex,TomDataworks/opensim,rryk/omp-server,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,justinccdev/opensim,ft-/arribasim-dev-extras,RavenB/opensim,justinccdev/opensim,ft-/opensim-optimizations-wip,N3X15/VoxelSim,ft-/arribasim-dev-tests,OpenSimian/opensimulator,BogusCurry/arribasim-dev,RavenB/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,N3X15/VoxelSim,bravelittlescientist/opensim-performance,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,N3X15/VoxelSim,allquixotic/opensim-autobackup,Michelle-Argus/ArribasimExtract,AlexRa/opensim-mods-Alex,BogusCurry/arribasim-dev,rryk/omp-server,RavenB/opensim,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,OpenSimian/opensimulator,rryk/omp-server,bravelittlescientist/opensim-performance,rryk/omp-server,OpenSimian/opensimulator,ft-/arribasim-dev-extras,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,allquixotic/opensim-autobackup,TechplexEngineer/Aurora-Sim,N3X15/VoxelSim,OpenSimian/opensimulator,M-O-S-E-S/opensim,N3X15/VoxelSim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,TomDataworks/opensim,QuillLittlefeather/opensim-1,cdbean/CySim,OpenSimian/opensimulator,TomDataworks/opensim,justinccdev/opensim,Michelle-Argus/ArribasimExtract,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-extras,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,RavenB/opensim,AlexRa/opensim-mods-Alex,TechplexEngineer/Aurora-Sim,BogusCurry/arribasim-dev,TomDataworks/opensim,justinccdev/opensim,rryk/omp-server,TomDataworks/opensim,bravelittlescientist/opensim-performance,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,cdbean/CySim,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-extras,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip,BogusCurry/arribasim-dev,allquixotic/opensim-autobackup
OpenSim/Region/Framework/Interfaces/IRegionModule.cs
OpenSim/Region/Framework/Interfaces/IRegionModule.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Interfaces { /// <summary> /// DEPRECATED! Use INonSharedRegionModule or ISharedRegionModule instead /// </summary> public interface IRegionModule { void Initialise(Scene scene, IConfigSource source); void PostInitialise(); void Close(); string Name { get; } bool IsSharedModule { get; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.Framework.Interfaces { public interface IRegionModule { void Initialise(Scene scene, IConfigSource source); void PostInitialise(); void Close(); string Name { get; } bool IsSharedModule { get; } } }
bsd-3-clause
C#
142f7ee4d0ffc9e562541b8d60c5d4ac1aec9407
Bump to version 3.0.0-beta2
Silv3rPRO/proshine
PROShine/App.xaml.cs
PROShine/App.xaml.cs
using System; using System.Reflection; using System.Windows; namespace PROShine { public partial class App : Application { public static string Name { get; private set; } public static string Version { get; private set; } public static string Author { get; private set; } public static string Description { get; private set; } public static bool IsBeta { get; private set; } public static void InitializeVersion() { Assembly assembly = typeof(App).Assembly; AssemblyName assemblyName = assembly.GetName(); Name = assemblyName.Name; Version = assemblyName.Version.ToString(3) + "-beta2"; IsBeta = true; Author = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute), false)).Company; Description = ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute), false)).Description; } } }
using System; using System.Reflection; using System.Windows; namespace PROShine { public partial class App : Application { public static string Name { get; private set; } public static string Version { get; private set; } public static string Author { get; private set; } public static string Description { get; private set; } public static bool IsBeta { get; private set; } public static void InitializeVersion() { Assembly assembly = typeof(App).Assembly; AssemblyName assemblyName = assembly.GetName(); Name = assemblyName.Name; Version = assemblyName.Version.ToString() + "-beta1"; IsBeta = true; Author = ((AssemblyCompanyAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyCompanyAttribute), false)).Company; Description = ((AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(assembly, typeof(AssemblyDescriptionAttribute), false)).Description; } } }
mit
C#
6a6677493d0a2e3e0b526e8b4f279b1dfdfd2d0c
bump to release 0.3
Zutatensuppe/DiabloInterface,Zutatensuppe/DiabloInterface
src/DiabloInterface/Properties/AssemblyInfo.cs
src/DiabloInterface/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("DiabloInterface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DiabloInterface")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("25bb3310-9bd7-4234-af7d-9f7fb6870a20")] [assembly: AssemblyVersion("0.3.0")] [assembly: AssemblyInformationalVersion("0.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DiabloInterface")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DiabloInterface")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("25bb3310-9bd7-4234-af7d-9f7fb6870a20")] [assembly: AssemblyVersion("0.3.0")] [assembly: AssemblyInformationalVersion("0.3.0.PR.3")]
mit
C#
f73ca34efefce32d27ea23dbb61d5385deb69bf9
Update ByteArrayBuilder.cs
PowerMogli/Rabbit.Db
src/Micro+/Materialization/ByteArrayBuilder.cs
src/Micro+/Materialization/ByteArrayBuilder.cs
using System; using System.Collections.Generic; using System.Text; namespace MicroORM.Materialization { internal class ByteArrayBuilder : IDisposable { List<byte> _byteValues = new List<byte>(); StringBuilder _stringValues = new StringBuilder(); internal void Append(string value) { _stringValues.AppendFormat("|{0}|", value); } internal void Append(byte[] value) { _byteValues.AddRange(value); } internal byte[] ToByteArray() { _byteValues.AddRange(new UTF8Encoding().GetBytes(_stringValues.ToString())); return _byteValues.ToArray(); } public void Dispose() { _byteValues.Clear(); _stringValues.Clear(); } } }
using System.Collections.Generic; using System.Text; namespace MicroORM.Materialization { internal class ByteArrayBuilder { List<byte> _byteValues = new List<byte>(); StringBuilder _stringValues = new StringBuilder(); internal void Append(string value) { _stringValues.AppendFormat("|{0}|", value); } internal void Append(byte[] value) { _byteValues.AddRange(value); } internal byte[] ToByteArray() { _byteValues.AddRange(new UTF8Encoding().GetBytes(_stringValues.ToString())); return _byteValues.ToArray(); } } }
apache-2.0
C#
69748447c371f648949ac8c3766e1fd3b186a3a3
Add throw if not latest version to database status object
phoenixwebgroup/DotNetMongoMigrations,phoenixwebgroup/DotNetMongoMigrations
src/MongoMigrations/DatabaseMigrationStatus.cs
src/MongoMigrations/DatabaseMigrationStatus.cs
namespace MongoMigrations { using System; using System.Linq; using MongoDB.Driver; public class DatabaseMigrationStatus { private readonly MigrationRunner _Runner; public string VersionCollectionName = "DatabaseVersion"; public DatabaseMigrationStatus(MigrationRunner runner) { _Runner = runner; } public virtual MongoCollection<AppliedMigration> GetMigrationsApplied() { return _Runner.Database.GetCollection<AppliedMigration>(VersionCollectionName); } public virtual bool IsNotLatestVersion() { return _Runner.MigrationLocator.LatestVersion() != GetVersion(); } public virtual void ThrowIfNotLatestVersion() { if (!IsNotLatestVersion()) { return; } var databaseVersion = GetVersion(); var migrationVersion = _Runner.MigrationLocator.LatestVersion(); throw new ApplicationException("Database is not the expected version, database is at version: " + databaseVersion + ", migrations are at version: " + migrationVersion); } public virtual MigrationVersion GetVersion() { var lastAppliedMigration = GetLastAppliedMigration(); return lastAppliedMigration == null ? MigrationVersion.Default() : lastAppliedMigration.Version; } public virtual AppliedMigration GetLastAppliedMigration() { return GetMigrationsApplied() .FindAll() .ToList() // in memory but this will never get big enough to matter .OrderByDescending(v => v.Version) .FirstOrDefault(); } public virtual AppliedMigration StartMigration(Migration migration) { var appliedMigration = new AppliedMigration(migration); GetMigrationsApplied().Insert(appliedMigration); return appliedMigration; } public virtual void CompleteMigration(AppliedMigration appliedMigration) { appliedMigration.CompletedOn = DateTime.Now; GetMigrationsApplied().Save(appliedMigration); } public virtual void MarkUpToVersion(MigrationVersion version) { _Runner.MigrationLocator.GetAllMigrations() .Where(m => m.Version <= version) .ToList() .ForEach(m => MarkVersion(m.Version)); } public virtual void MarkVersion(MigrationVersion version) { var appliedMigration = AppliedMigration.MarkerOnly(version); GetMigrationsApplied().Insert(appliedMigration); } } }
namespace MongoMigrations { using System; using System.Linq; using MongoDB.Driver; public class DatabaseMigrationStatus { private readonly MigrationRunner _Runner; public string VersionCollectionName = "DatabaseVersion"; public DatabaseMigrationStatus(MigrationRunner runner) { _Runner = runner; } public virtual MongoCollection<AppliedMigration> GetMigrationsApplied() { return _Runner.Database.GetCollection<AppliedMigration>(VersionCollectionName); } public virtual bool IsNotLatestVersion() { return _Runner.MigrationLocator.LatestVersion() > GetVersion(); } public virtual MigrationVersion GetVersion() { var lastAppliedMigration = GetLastAppliedMigration(); return lastAppliedMigration == null ? MigrationVersion.Default() : lastAppliedMigration.Version; } public virtual AppliedMigration GetLastAppliedMigration() { return GetMigrationsApplied() .FindAll() .ToList() // in memory but this will never get big enough to matter .OrderByDescending(v => v.Version) .FirstOrDefault(); } public virtual AppliedMigration StartMigration(Migration migration) { var appliedMigration = new AppliedMigration(migration); GetMigrationsApplied().Insert(appliedMigration); return appliedMigration; } public virtual void CompleteMigration(AppliedMigration appliedMigration) { appliedMigration.CompletedOn = DateTime.Now; GetMigrationsApplied().Save(appliedMigration); } public virtual void MarkUpToVersion(MigrationVersion version) { _Runner.MigrationLocator.GetAllMigrations() .Where(m => m.Version <= version) .ToList() .ForEach(m => MarkVersion(m.Version)); } public virtual void MarkVersion(MigrationVersion version) { var appliedMigration = AppliedMigration.MarkerOnly(version); GetMigrationsApplied().Insert(appliedMigration); } } }
mit
C#
cd20643648630f587d6670437f05e242508145ba
Fix a typo in xml comment
sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore,sergeysolovev/webpack-aspnetcore
src/Webpack.AspNetCore/Static/StaticOptions.cs
src/Webpack.AspNetCore/Static/StaticOptions.cs
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.StaticFiles; using System; namespace Webpack.AspNetCore.Static { /// <summary> /// Represents a limited set of options from <see cref="StaticFileOptions" /> /// <see cref="SharedOptionsBase.FileProvider" /> is excluded /// </summary> public class StaticOptions { public StaticOptions() { ManifestPath = new PathString("/dist/manifest.json"); UseStaticFileMiddleware = true; OnPrepareResponse = _ => { }; } /// <summary> /// The asset manifest path within the application's web root path /// Default: /dist/manifest.json /// </summary> public PathString ManifestPath { get; set; } /// <summary> /// Determines whether to use <see cref="Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware"/> /// to serve static assets from the root of <see cref="ManifestPath"/>. /// Default: <c>true</c> /// </summary> public bool UseStaticFileMiddleware { get; set; } /// <summary> /// The relative request path that maps to static resources. /// </summary> public PathString RequestPath { get; set; } /// <summary> /// Used to map files to content-types. /// </summary> public IContentTypeProvider ContentTypeProvider { get; set; } /// <summary> /// The default content type for a request if the ContentTypeProvider cannot determine one. /// None is provided by default, so the client must determine the format themselves. /// http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7 /// </summary> public string DefaultContentType { get; set; } /// <summary> /// If the file is not a recognized content-type should it be served? /// Default: false. /// </summary> public bool ServeUnknownFileTypes { get; set; } /// <summary> /// Called after the status code and headers have been set, but before the body has been written. /// This can be used to add or change the response headers. /// </summary> public Action<StaticFileResponseContext> OnPrepareResponse { get; set; } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.StaticFiles; using System; namespace Webpack.AspNetCore.Static { /// <summary> /// Represents a limited set of options from <see cref="StaticFileOptions" /> /// <see cref="SharedOptionsBase.FileProvider" /> is excluded /// </summary> public class StaticOptions { public StaticOptions() { ManifestPath = new PathString("/dist/manifest.json"); UseStaticFileMiddleware = true; OnPrepareResponse = _ => { }; } /// <summary> /// The asset manifest path within the application's web root path /// Default: /manifest.json /// </summary> public PathString ManifestPath { get; set; } /// <summary> /// Determines whether to use <see cref="Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware"/> /// to serve static assets from the root of <see cref="ManifestPath"/>. /// Default: <c>true</c> /// </summary> public bool UseStaticFileMiddleware { get; set; } /// <summary> /// The relative request path that maps to static resources. /// </summary> public PathString RequestPath { get; set; } /// <summary> /// Used to map files to content-types. /// </summary> public IContentTypeProvider ContentTypeProvider { get; set; } /// <summary> /// The default content type for a request if the ContentTypeProvider cannot determine one. /// None is provided by default, so the client must determine the format themselves. /// http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html#sec7 /// </summary> public string DefaultContentType { get; set; } /// <summary> /// If the file is not a recognized content-type should it be served? /// Default: false. /// </summary> public bool ServeUnknownFileTypes { get; set; } /// <summary> /// Called after the status code and headers have been set, but before the body has been written. /// This can be used to add or change the response headers. /// </summary> public Action<StaticFileResponseContext> OnPrepareResponse { get; set; } } }
mit
C#
181dbd3794bde263664402ba6ca03501bd065107
Fix incorrect access of `options`
peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework
osu.Framework/Platform/Linux/LinuxGameHost.cs
osu.Framework/Platform/Linux/LinuxGameHost.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using SDL2; using osu.Framework.Input; using osu.Framework.Platform.Linux.SDL2; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { /// <summary> /// If SDL disables the compositor. /// </summary> /// <remarks> /// On Linux, SDL will disable the compositor by default. /// Since not all applications want to do that, we can specify it manually. /// </remarks> public readonly bool BypassCompositor; internal LinuxGameHost(string gameName, HostOptions options) : base(gameName, options) { BypassCompositor = Options.BypassCompositor; } protected override void SetupForRun() { SDL.SDL_SetHint(SDL.SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, BypassCompositor ? "1" : "0"); base.SetupForRun(); } protected override IWindow CreateWindow() => new SDL2DesktopWindow(); public override IEnumerable<string> UserStoragePaths { get { string xdg = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); if (!string.IsNullOrEmpty(xdg)) yield return xdg; yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".local", "share"); foreach (string path in base.UserStoragePaths) yield return path; } } public override Clipboard GetClipboard() => new SDL2Clipboard(); protected override ReadableKeyCombinationProvider CreateReadableKeyCombinationProvider() => new LinuxReadableKeyCombinationProvider(); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.IO; using SDL2; using osu.Framework.Input; using osu.Framework.Platform.Linux.SDL2; namespace osu.Framework.Platform.Linux { public class LinuxGameHost : DesktopGameHost { /// <summary> /// If SDL disables the compositor. /// </summary> /// <remarks> /// On Linux, SDL will disable the compositor by default. /// Since not all applications want to do that, we can specify it manually. /// </remarks> public readonly bool BypassCompositor; internal LinuxGameHost(string gameName, HostOptions options) : base(gameName, options) { BypassCompositor = options.BypassCompositor; } protected override void SetupForRun() { SDL.SDL_SetHint(SDL.SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, BypassCompositor ? "1" : "0"); base.SetupForRun(); } protected override IWindow CreateWindow() => new SDL2DesktopWindow(); public override IEnumerable<string> UserStoragePaths { get { string xdg = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); if (!string.IsNullOrEmpty(xdg)) yield return xdg; yield return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), ".local", "share"); foreach (string path in base.UserStoragePaths) yield return path; } } public override Clipboard GetClipboard() => new SDL2Clipboard(); protected override ReadableKeyCombinationProvider CreateReadableKeyCombinationProvider() => new LinuxReadableKeyCombinationProvider(); } }
mit
C#
266f7ad13e9ffa5e08c88517feaec32c831ff4f2
Enable JS in the browser so the user can authorize the app
jamesqo/Repository,jamesqo/Repository,jamesqo/Repository
Repository/SignInActivity.cs
Repository/SignInActivity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); // GitHub needs JS enabled to un-grey the authorization button _signInWebView.Settings.JavaScriptEnabled = true; var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Webkit; using Android.Widget; using Repository.Internal; using static Repository.Internal.Verify; namespace Repository { [Activity(Label = "Sign In")] public class SignInActivity : Activity { private sealed class LoginSuccessListener : WebViewClient { private readonly string _callbackUrl; internal LoginSuccessListener(string callbackUrl) { _callbackUrl = NotNull(callbackUrl); } public override void OnPageFinished(WebView view, string url) { if (url.StartsWith(_callbackUrl, StringComparison.Ordinal)) { // TODO: Start some activity? } } } private WebView _signInWebView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.SignIn); _signInWebView = FindViewById<WebView>(Resource.Id.SignInWebView); var url = NotNull(Intent.Extras.GetString(Strings.SignIn_Url)); _signInWebView.LoadUrl(url); var callbackUrl = NotNull(Intent.Extras.GetString(Strings.SignIn_CallbackUrl)); _signInWebView.SetWebViewClient(new LoginSuccessListener(callbackUrl)); } } }
mit
C#
3d4f816e3cfaf0b16c34c665048eb24d02a101dc
Add OpenAPI response types.
JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders,JasonGT/NorthwindTraders
Northwind.Web/Controllers/ProductsController.cs
Northwind.Web/Controllers/ProductsController.cs
using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Northwind.Application.Products.Commands; using Northwind.Application.Products.Models; using Northwind.Application.Products.Queries; namespace Northwind.Web.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : BaseController { // GET: api/Products [HttpGet] public async Task<ProductsListViewModel> GetProducts() { return await Mediator.Send(new GetAllProductsQuery()); } // GET: api/Products/5 [HttpGet("{id}")] [ProducesResponseType(typeof(ProductViewModel), (int)HttpStatusCode.OK)] public async Task<IActionResult> GetProduct(int id) { return Ok(await Mediator.Send(new GetProductQuery(id))); } // POST: api/Products [HttpPost] [ProducesResponseType(typeof(ProductDto), (int)HttpStatusCode.OK)] public async Task<IActionResult> PostProduct([FromBody] CreateProductCommand command) { var newProduct = await Mediator.Send(command); return CreatedAtAction("GetProduct", new { id = newProduct.ProductId }, newProduct); } // PUT: api/Products/5 [HttpPut("{id}")] [ProducesResponseType(typeof(ProductDto), (int)HttpStatusCode.OK)] public async Task<IActionResult> PutProduct([FromBody] UpdateProductCommand command) { return Ok(await Mediator.Send(command)); } // DELETE: api/Products/5 [HttpDelete("{id}")] [ProducesResponseType((int)HttpStatusCode.NoContent)] public async Task<IActionResult> DeleteProduct(int id) { await Mediator.Send(new DeleteProductCommand(id)); return NoContent(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Northwind.Application.Products.Commands; using Northwind.Application.Products.Models; using Northwind.Application.Products.Queries; namespace Northwind.Web.Controllers { [Route("api/[controller]")] [ApiController] public class ProductsController : BaseController { // GET: api/Products [HttpGet] public async Task<ProductsListViewModel> GetProducts() { return await Mediator.Send(new GetAllProductsQuery()); } // GET: api/Products/5 [HttpGet("{id}")] public async Task<IActionResult> GetProduct(int id) { return Ok(await Mediator.Send(new GetProductQuery(id))); } // POST: api/Products [HttpPost] public async Task<IActionResult> PostProduct([FromBody] CreateProductCommand command) { var newProduct = await Mediator.Send(command); return CreatedAtAction("GetProduct", new { id = newProduct.ProductId }, newProduct); } // PUT: api/Products/5 [HttpPut("{id}")] public async Task<IActionResult> PutProduct([FromBody] UpdateProductCommand command) { return Ok(await Mediator.Send(command)); } // DELETE: api/Products/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteProduct(int id) { await Mediator.Send(new DeleteProductCommand(id)); return NoContent(); } } }
mit
C#
d2285d9421f48cf06fa502e723078342a54aadd3
Update Program.cs
chinaboard/PureCat
PureCat.Demo/Program.cs
PureCat.Demo/Program.cs
using PureCat.Context; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PureCat.Demo { class Program { static Random _rand = new Random(); static void Main(string[] args) { PureCat.Initialize(); while (true) { var a = DateTime.Now.Second; Console.WriteLine(DateTime.Now); var context = PureCat.DoTransaction("Do", nameof(DoTest), DoTest); var b = DateTime.Now.Second; PureCat.DoTransaction("Do", nameof(Add), () => Add(a, b, context)); } } static CatContext DoTest() { var times = _rand.Next(1000); Thread.Sleep(times); PureCat.LogEvent("Do", nameof(DoTest), "0", $"sleep {times}"); return PureCat.LogRemoteCallClient("callAdd"); } static void Add(int a, int b, CatContext context = null) { PureCat.LogRemoteCallServer(context); PureCat.LogEvent("Do", nameof(Add), "0", $"{a} + {b} = {a + b}"); } } }
using PureCat.Context; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace PureCat.Demo { class Program { static Random _rand = new Random(); static void Main(string[] args) { PureCat.Initialize(new Configuration.ClientConfig(new Configuration.Domain("PureCat.Demo"), new Configuration.Server("10.14.40.4"))); while (true) { var a = DateTime.Now.Second; Console.WriteLine(DateTime.Now); var context = PureCat.DoTransaction("Do", nameof(DoTest), DoTest); var b = DateTime.Now.Second; PureCat.DoTransaction("Do", nameof(Add), () => Add(a, b, context)); } } static CatContext DoTest() { var times = _rand.Next(1000); Thread.Sleep(times); PureCat.LogEvent("Do", nameof(DoTest), "0", $"sleep {times}"); return PureCat.LogRemoteCallClient("callAdd"); } static void Add(int a, int b, CatContext context = null) { PureCat.LogRemoteCallServer(context); PureCat.LogEvent("Do", nameof(Add), "0", $"{a} + {b} = {a + b}"); } } }
mit
C#
9109f92b4beede59cf5a8a995123c6ed5224c64c
Fix sources visual desync.
chocolatey/ChocolateyGUI,chocolatey/ChocolateyGUI,gep13/ChocolateyGUI,gep13/ChocolateyGUI,gep13/ChocolateyGUI,chocolatey/ChocolateyGUI,gep13/ChocolateyGUI,chocolatey/ChocolateyGUI,digital-carver/ChocolateyGUI,gep13/ChocolateyGUI,chocolatey/ChocolateyGUI
Source/ChocolateyGui/Views/SettingsView.xaml.cs
Source/ChocolateyGui/Views/SettingsView.xaml.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="SettingsView.xaml.cs"> // Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- using Caliburn.Micro; using ChocolateyGui.Models.Messages; namespace ChocolateyGui.Views { /// <summary> /// Interaction logic for SettingsView.xaml /// </summary> public partial class SettingsView : IHandle<SourcesUpdatedMessage> { public SettingsView(IEventAggregator eventAggregator) { eventAggregator.Subscribe(this); InitializeComponent(); } public void Handle(SourcesUpdatedMessage message) { SourcesGrid.Items.Refresh(); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="SettingsView.xaml.cs"> // Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace ChocolateyGui.Views { /// <summary> /// Interaction logic for SettingsView.xaml /// </summary> public partial class SettingsView { public SettingsView() { InitializeComponent(); } } }
apache-2.0
C#
fd7398c3bf8d499617d59afd129d6fa6f692f3b9
fix scheduler migration
thinking-home/system,thinking-home/system,thinking-home/system
ThinkingHome.Plugins.Scheduler/Model/Migrations/Migration01.cs
ThinkingHome.Plugins.Scheduler/Model/Migrations/Migration01.cs
using System.Data; using ThinkingHome.Migrator.Framework; using ThinkingHome.Migrator.Framework.Extensions; namespace ThinkingHome.Plugins.Scheduler.Model.Migrations { [Migration(1)] public class Migration01 : Migration { public override void Apply() { Database.AddTable("Scheduler_SchedulerEvent", new Column("Id", DbType.Guid, ColumnProperty.PrimaryKey), new Column("Name", DbType.String.WithSize(int.MaxValue), ColumnProperty.NotNull), new Column("EventAlias", DbType.String.WithSize(int.MaxValue), ColumnProperty.NotNull), new Column("Hours", DbType.Int32, ColumnProperty.NotNull), new Column("Minutes", DbType.Int32, ColumnProperty.NotNull), new Column("Enabled", DbType.Boolean, ColumnProperty.NotNull) ); } public override void Revert() { Database.RemoveTable("Scheduler_SchedulerEvent"); } } }
using System.Data; using ThinkingHome.Migrator.Framework; using ThinkingHome.Migrator.Framework.Extensions; namespace ThinkingHome.Plugins.Scheduler.Model.Migrations { [Migration(1)] public class Migration01 : Migration { public override void Apply() { Database.AddTable("Scheduler_SchedulerEvent", new Column("Id", DbType.Guid, ColumnProperty.PrimaryKey), new Column("Name", DbType.String.WithSize(int.MaxValue), ColumnProperty.NotNull), new Column("EventAlias", DbType.String.WithSize(int.MaxValue), ColumnProperty.NotNull), new Column("Hours", DbType.Int32, ColumnProperty.NotNull), new Column("Minutes", DbType.Int32, ColumnProperty.NotNull), new Column("Enabled", DbType.Boolean, ColumnProperty.NotNull) ); } public override void Revert() { Database.RemoveTable("Scripts_UserScript"); } } }
mit
C#
7e929d1c78175c9d416e2c47dcc0334b0ecbf0ab
clear password when dialog closed just in case .
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/AddWallet/Common/EnterPasswordViewModel.cs
WalletWasabi.Fluent/AddWallet/Common/EnterPasswordViewModel.cs
using ReactiveUI; using System; using System.Reactive.Linq; using System.Windows.Input; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Fluent.AddWallet.CreateWallet; using WalletWasabi.Fluent.ViewModels; using WalletWasabi.Fluent.ViewModels.Dialogs; using WalletWasabi.Gui; using WalletWasabi.Gui.Validation; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Models; using WalletWasabi.Userfacing; namespace WalletWasabi.Fluent.AddWallet.Common { public class EnterPasswordViewModel : DialogViewModelBase<string> { private IScreen _screen; private string _password; private string _confirmPassword; public EnterPasswordViewModel(IScreen screen) { _screen = screen; this.ValidateProperty(x => x.Password, ValidatePassword); this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword); var continueCommandCanExecute = this.WhenAnyValue( x => x.Password, x => x.ConfirmPassword, (password, confirmPassword) => { // This will fire validations before return canExecute value. this.RaisePropertyChanged(nameof(Password)); this.RaisePropertyChanged(nameof(ConfirmPassword)); return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any); }) .ObserveOn(RxApp.MainThreadScheduler); ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute); CancelCommand = ReactiveCommand.Create(() => Close(null!)); } public string Password { get => _password; set => this.RaiseAndSetIfChanged(ref _password, value); } public string ConfirmPassword { get => _confirmPassword; set => this.RaiseAndSetIfChanged(ref _confirmPassword, value); } public ICommand ContinueCommand { get; } public ICommand CancelCommand { get; } protected override void OnDialogClosed() { Password = ""; ConfirmPassword = ""; } private void ValidateConfirmPassword(IValidationErrors errors) { if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword) { errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage); } } private void ValidatePassword(IValidationErrors errors) { if (PasswordHelper.IsTrimable(Password, out _)) { errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage); } if (PasswordHelper.IsTooLong(Password, out _)) { errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage); } } } }
using ReactiveUI; using System; using System.Reactive.Linq; using System.Windows.Input; using WalletWasabi.Blockchain.Keys; using WalletWasabi.Fluent.AddWallet.CreateWallet; using WalletWasabi.Fluent.ViewModels; using WalletWasabi.Fluent.ViewModels.Dialogs; using WalletWasabi.Gui; using WalletWasabi.Gui.Validation; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Models; using WalletWasabi.Userfacing; namespace WalletWasabi.Fluent.AddWallet.Common { public class EnterPasswordViewModel : DialogViewModelBase<string> { private IScreen _screen; private string _password; private string _confirmPassword; public EnterPasswordViewModel(IScreen screen) { _screen = screen; this.ValidateProperty(x => x.Password, ValidatePassword); this.ValidateProperty(x => x.ConfirmPassword, ValidateConfirmPassword); var continueCommandCanExecute = this.WhenAnyValue( x => x.Password, x => x.ConfirmPassword, (password, confirmPassword) => { // This will fire validations before return canExecute value. this.RaisePropertyChanged(nameof(Password)); this.RaisePropertyChanged(nameof(ConfirmPassword)); return (string.IsNullOrEmpty(password) && string.IsNullOrEmpty(confirmPassword)) || (!string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(confirmPassword) && !Validations.Any); }) .ObserveOn(RxApp.MainThreadScheduler); ContinueCommand = ReactiveCommand.Create(() => Close(Password), continueCommandCanExecute); CancelCommand = ReactiveCommand.Create(() => Close(null!)); } public string Password { get => _password; set => this.RaiseAndSetIfChanged(ref _password, value); } public string ConfirmPassword { get => _confirmPassword; set => this.RaiseAndSetIfChanged(ref _confirmPassword, value); } public ICommand ContinueCommand { get; } public ICommand CancelCommand { get; } protected override void OnDialogClosed() { } private void ValidateConfirmPassword(IValidationErrors errors) { if (!string.IsNullOrEmpty(ConfirmPassword) && Password != ConfirmPassword) { errors.Add(ErrorSeverity.Error, PasswordHelper.MatchingMessage); } } private void ValidatePassword(IValidationErrors errors) { if (PasswordHelper.IsTrimable(Password, out _)) { errors.Add(ErrorSeverity.Error, PasswordHelper.WhitespaceMessage); } if (PasswordHelper.IsTooLong(Password, out _)) { errors.Add(ErrorSeverity.Error, PasswordHelper.PasswordTooLongMessage); } } } }
mit
C#
a967a89aaa2cf5a8cbe191dcfb0aa4f78b5d8549
Add the attribute needed, provided
Inumedia/SlackAPI
SlackAPI/Response.cs
SlackAPI/Response.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public string needed; public string provided; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SlackAPI { public abstract class Response { /// <summary> /// Should always be checked before trying to process a response. /// </summary> public bool ok; /// <summary> /// if ok is false, then this is the reason-code /// </summary> public string error; public void AssertOk() { if (!(ok)) throw new InvalidOperationException(string.Format("An error occurred: {0}", this.error)); } } }
mit
C#
cf5c96366d2dbd36d90276b0d3524641c05afeca
remove a few unused usings
jonsequitur/Alluvial
Alluvial.For.ItsDomainSql/AlluvialDistributorLeaseInitializer.cs
Alluvial.For.ItsDomainSql/AlluvialDistributorLeaseInitializer.cs
using System; using System.Data.Entity; using System.Threading.Tasks; using Alluvial.Distributors.Sql; using Microsoft.Its.Domain.Sql.Migrations; using Newtonsoft.Json; namespace Alluvial.For.ItsDomainSql { public class AlluvialDistributorLeaseInitializer<T> : IDbMigrator { private readonly Leasable<T>[] leasables; private readonly string pool; public AlluvialDistributorLeaseInitializer( Leasable<T>[] leasables, string pool) { if (leasables == null) { throw new ArgumentNullException(nameof(leasables)); } if (string.IsNullOrWhiteSpace(pool)) { throw new ArgumentException("Pool cannot be null, empty, or consist entirely of whitespace.", nameof(pool)); } this.leasables = leasables; this.pool = pool; } public MigrationResult Migrate(DbContext context) { Task.Run(async () => { var dbConnection = context.Database.Connection; await SqlBrokeredDistributorDatabase.InitializeSchema(dbConnection); await SqlBrokeredDistributorDatabase.RegisterLeasableResources( leasables, pool, dbConnection); }) .Wait(); return new MigrationResult { MigrationWasApplied = true, Log = $"Initialized leases in pool {pool}:\n\n" + JsonConvert.SerializeObject(leasables) }; } public string MigrationScope => $"Leases: {pool}"; public Version MigrationVersion => new Version("1.0.0"); } }
using System; using System.Data; using System.Data.Common; using System.Data.Entity; using System.Threading.Tasks; using Alluvial.Distributors.Sql; using Microsoft.Its.Domain.Sql.Migrations; using Newtonsoft.Json; namespace Alluvial.For.ItsDomainSql { public class AlluvialDistributorLeaseInitializer<T> : IDbMigrator { private readonly Leasable<T>[] leasables; private readonly string pool; public AlluvialDistributorLeaseInitializer( Leasable<T>[] leasables, string pool) { if (leasables == null) { throw new ArgumentNullException(nameof(leasables)); } if (string.IsNullOrWhiteSpace(pool)) { throw new ArgumentException("Pool cannot be null, empty, or consist entirely of whitespace.", nameof(pool)); } this.leasables = leasables; this.pool = pool; } public MigrationResult Migrate(DbContext context) { Task.Run(async () => { var dbConnection = context.Database.Connection; await SqlBrokeredDistributorDatabase.InitializeSchema(dbConnection); await SqlBrokeredDistributorDatabase.RegisterLeasableResources( leasables, pool, dbConnection); }) .Wait(); return new MigrationResult { MigrationWasApplied = true, Log = $"Initialized leases in pool {pool}:\n\n" + JsonConvert.SerializeObject(leasables) }; } public string MigrationScope => $"Leases: {pool}"; public Version MigrationVersion => new Version("1.0.0"); } }
mit
C#
5c591bcf8f3fa90a1277b6db0c6e7d1b00e73720
Update version
roberthardy/Synthesis,kamsar/Synthesis
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("ISITE Design")] [assembly: AssemblyProduct("Synthesis")] [assembly: AssemblyCopyright("Copyright © Kam Figy, ISITE Design")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("8.1.1.0")] [assembly: AssemblyFileVersion("8.1.1.0")] [assembly: AssemblyInformationalVersion("8.1.1")] [assembly: CLSCompliant(false)]
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("ISITE Design")] [assembly: AssemblyProduct("Synthesis")] [assembly: AssemblyCopyright("Copyright © Kam Figy, ISITE Design")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("8.1.0.0")] [assembly: AssemblyFileVersion("8.1.0.0")] [assembly: AssemblyInformationalVersion("8.1.0")] [assembly: CLSCompliant(false)]
mit
C#
c5ab46efd7b593afe0536c4fec1cb4376ff530e4
remove setup method
edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk
tests/HttpClientTest.cs
tests/HttpClientTest.cs
#if __MOBILE__ using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #endif using System; using System.Collections.Generic; using System.Threading.Tasks; using FHSDK; using FHSDK.FHHttpClient; using Newtonsoft.Json.Linq; using tests.Mocks; namespace tests { [TestClass] public class HttpClientTest { [TestMethod] public async Task ShouldSendAsync() { //given await FHClient.Init(); var mock = new MockHttpClient(); FHHttpClientFactory.Get = () => mock; const string method = "POST"; //when await FHHttpClient.SendAsync(new Uri("http://localhost/test"), method, new Dictionary<string, string>() {{"key", "value"}}, "request-data", TimeSpan.FromSeconds(20)); //then Assert.IsNotNull(mock.Request); Assert.AreEqual(method, mock.Request.Method.Method); Assert.IsTrue(mock.Request.Headers.Contains("key")); Assert.AreEqual("\"request-data\"", await mock.Request.Content.ReadAsStringAsync()); Assert.AreEqual(20, mock.Timeout.Seconds); } [TestMethod] public async Task ShouldPerformGet() { //given await FHClient.Init(); var mock = new MockHttpClient(); FHHttpClientFactory.Get = () => mock; const string method = "GET"; //when await FHHttpClient.SendAsync(new Uri("http://localhost/test"), method, null, JObject.Parse("{'key-data': 'value'}"), TimeSpan.FromSeconds(20)); //then Assert.IsNotNull(mock.Request); Assert.AreEqual("http://localhost/test?key-data=\"value\"", mock.Request.RequestUri.ToString()); } } }
#if __MOBILE__ using NUnit.Framework; using TestClass = NUnit.Framework.TestFixtureAttribute; using TestMethod = NUnit.Framework.TestAttribute; using TestInitialize = NUnit.Framework.SetUpAttribute; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; #endif using System; using System.Collections.Generic; using System.Threading.Tasks; using FHSDK; using FHSDK.FHHttpClient; using Newtonsoft.Json.Linq; using tests.Mocks; namespace tests { [TestClass] public class HttpClientTest { [TestInitialize] public async void Setup() { await FHClient.Init(); } [TestMethod] public async Task ShouldSendAsync() { //given var mock = new MockHttpClient(); FHHttpClientFactory.Get = () => mock; const string method = "POST"; //when await FHHttpClient.SendAsync(new Uri("http://localhost/test"), method, new Dictionary<string, string>() {{"key", "value"}}, "request-data", TimeSpan.FromSeconds(20)); //then Assert.IsNotNull(mock.Request); Assert.AreEqual(method, mock.Request.Method.Method); Assert.IsTrue(mock.Request.Headers.Contains("key")); Assert.AreEqual("\"request-data\"", await mock.Request.Content.ReadAsStringAsync()); Assert.AreEqual(20, mock.Timeout.Seconds); } [TestMethod] public async Task ShouldPerformGet() { //given var mock = new MockHttpClient(); FHHttpClientFactory.Get = () => mock; const string method = "GET"; //when await FHHttpClient.SendAsync(new Uri("http://localhost/test"), method, null, JObject.Parse("{'key-data': 'value'}"), TimeSpan.FromSeconds(20)); //then Assert.IsNotNull(mock.Request); Assert.AreEqual("http://localhost/test?key-data=\"value\"", mock.Request.RequestUri.ToString()); } } }
apache-2.0
C#
b911e3374f169b2a9127e8a2657edf3fd59da68c
Fix for #8
Excel-DNA/Samples
Ribbon/DataWriter.cs
Ribbon/DataWriter.cs
using System; using ExcelDna.Integration; using Microsoft.Office.Interop.Excel; namespace Ribbon { public class DataWriter { public static void WriteData() { Application xlApp = (Application)ExcelDnaUtil.Application; Workbook wb = xlApp.ActiveWorkbook; if (wb == null) return; Worksheet ws = wb.Worksheets.Add(Type: XlSheetType.xlWorksheet); ws.Range["A1"].Value = "Date"; ws.Range["B1"].Value = "Value"; Range headerRow = ws.Range["A1", "B1"]; headerRow.Font.Size = 12; headerRow.Font.Bold = true; // Generally it's faster to write an array to a range var values = new object[100, 2]; var startDate = new DateTime(2007, 1, 1); var rand = new Random(); for (int i = 0; i < 100; i++) { values[i, 0] = startDate.AddDays(i); values[i, 1] = rand.NextDouble(); } ws.Range["A2"].Resize[100, 2].Value = values; ws.Columns["A:A"].EntireColumn.AutoFit(); // Add a chart Range dataRange= ws.Range["A1:B101"]; dataRange.Select(); ws.Shapes.AddChart(XlChartType.xlLineMarkers).Select(); } } }
using System; using ExcelDna.Integration; using Microsoft.Office.Interop.Excel; namespace Ribbon { public class DataWriter { public static void WriteData() { Application xlApp = (Application)ExcelDnaUtil.Application; Workbook wb = xlApp.ActiveWorkbook; if (wb == null) return; Worksheet ws = wb.Worksheets.Add(Type: XlSheetType.xlWorksheet); ws.Range["A1"].Value = "Date"; ws.Range["B1"].Value = "Value"; Range headerRow = ws.Range["A1", "B1"]; headerRow.Font.Size = 12; headerRow.Font.Bold = true; // Generally it's faster to write an array to a range var values = new object[100, 2]; var startDate = new DateTime(2007, 1, 1); var rand = new Random(); for (int i = 0; i < 100; i++) { values[i, 0] = startDate.AddDays(i); values[i, 1] = rand.NextDouble(); } ws.Range["A2"].Resize[100, 2].Value = values; ws.Columns["A:A"].EntireColumn.AutoFit(); // Add a chart Range dataRange= ws.Range["A1:B101"]; dataRange.Select(); ws.Shapes.AddChart(XlChartType.xlLineMarkers).Select(); xlApp.ActiveChart.SetSourceData(Source: dataRange); } } }
mit
C#
3ae98611f2efd7c8fb7acc172f9252241dd5c918
Add simple RelativePosition and OffsetPosition checks to TestGetRootPartPosition
M-O-S-E-S/opensim,OpenSimian/opensimulator,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-tests,rryk/omp-server,rryk/omp-server,M-O-S-E-S/opensim,TomDataworks/opensim,justinccdev/opensim,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,justinccdev/opensim,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,OpenSimian/opensimulator,Michelle-Argus/ArribasimExtract,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,M-O-S-E-S/opensim,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-extras,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras,rryk/omp-server,BogusCurry/arribasim-dev,bravelittlescientist/opensim-performance,justinccdev/opensim,RavenB/opensim,ft-/arribasim-dev-tests,OpenSimian/opensimulator,rryk/omp-server,rryk/omp-server,M-O-S-E-S/opensim,QuillLittlefeather/opensim-1,TomDataworks/opensim,ft-/arribasim-dev-tests,TomDataworks/opensim,ft-/opensim-optimizations-wip-extras,QuillLittlefeather/opensim-1,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-extras,TomDataworks/opensim,ft-/opensim-optimizations-wip,justinccdev/opensim,bravelittlescientist/opensim-performance,Michelle-Argus/ArribasimExtract,bravelittlescientist/opensim-performance,TomDataworks/opensim,bravelittlescientist/opensim-performance,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip,bravelittlescientist/opensim-performance,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,Michelle-Argus/ArribasimExtract,justinccdev/opensim,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,OpenSimian/opensimulator,ft-/arribasim-dev-tests,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,BogusCurry/arribasim-dev,rryk/omp-server,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,justinccdev/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-tests,BogusCurry/arribasim-dev
OpenSim/Region/Framework/Scenes/Tests/SceneObjectSpatialTests.cs
OpenSim/Region/Framework/Scenes/Tests/SceneObjectSpatialTests.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Threading; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Spatial scene object tests (will eventually cover root and child part position, rotation properties, etc.) /// </summary> [TestFixture] public class SceneObjectSpatialTests { [Test] public void TestGetRootPartPosition() { TestHelpers.InMethod(); Scene scene = SceneHelpers.SetupScene(); UUID ownerId = TestHelpers.ParseTail(0x1); Vector3 partPosition = new Vector3(10, 20, 30); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, ownerId, "obj1", 0x10); so.AbsolutePosition = partPosition; scene.AddNewSceneObject(so, false); Assert.That(so.AbsolutePosition, Is.EqualTo(partPosition)); Assert.That(so.RootPart.AbsolutePosition, Is.EqualTo(partPosition)); Assert.That(so.RootPart.OffsetPosition, Is.EqualTo(Vector3.Zero)); Assert.That(so.RootPart.RelativePosition, Is.EqualTo(partPosition)); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Threading; using NUnit.Framework; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Region.Framework.Scenes; using OpenSim.Tests.Common; using OpenSim.Tests.Common.Mock; namespace OpenSim.Region.Framework.Scenes.Tests { /// <summary> /// Spatial scene object tests (will eventually cover root and child part position, rotation properties, etc.) /// </summary> [TestFixture] public class SceneObjectSpatialTests { [Test] public void TestGetRootPartPosition() { TestHelpers.InMethod(); Scene scene = SceneHelpers.SetupScene(); UUID ownerId = TestHelpers.ParseTail(0x1); Vector3 partPosition = new Vector3(10, 20, 30); SceneObjectGroup so = SceneHelpers.CreateSceneObject(1, ownerId, "obj1", 0x10); so.AbsolutePosition = partPosition; scene.AddNewSceneObject(so, false); Assert.That(so.AbsolutePosition, Is.EqualTo(partPosition)); Assert.That(so.RootPart.AbsolutePosition, Is.EqualTo(partPosition)); } } }
bsd-3-clause
C#
cb3ffde3bf4f4b725ab7167ce466657bf8ec03e0
Update BagPartSettings default display type, placeholder, and hint to Detail (#4385)
xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard
src/OrchardCore.Modules/OrchardCore.Flows/Views/BagPartSettings.Edit.cshtml
src/OrchardCore.Modules/OrchardCore.Flows/Views/BagPartSettings.Edit.cshtml
@model OrchardCore.Flows.ViewModels.BagPartSettingsViewModel <fieldset class="form-group"> <label asp-for="ContainedContentTypes">@T["Contained Content Types"]</label> <span class="hint">@T["The content types that this bag can contain, e.g. Slide for a Slide Show."]</span> @await Component.InvokeAsync("SelectContentTypes", new { selectedContentTypes = Model.ContainedContentTypes, htmlName = Html.NameFor(m => m.ContainedContentTypes) }) </fieldset> <fieldset class="form-group"> <div class="row col-sm-6"> <label asp-for="DisplayType">@T["Display Type"]</label> <input asp-for="DisplayType" placeholder="Detail" class="form-control medium" /> <span class="hint">@T["The display type to use when rendering the content items. Default is Detail."]</span> </div> </fieldset>
@model OrchardCore.Flows.ViewModels.BagPartSettingsViewModel <fieldset class="form-group"> <label asp-for="ContainedContentTypes">@T["Contained Content Types"]</label> <span class="hint">@T["The content types that this bag can contain, e.g. Slide for a Slide Show."]</span> @await Component.InvokeAsync("SelectContentTypes", new { selectedContentTypes = Model.ContainedContentTypes, htmlName = Html.NameFor(m => m.ContainedContentTypes) }) </fieldset> <fieldset class="form-group"> <div class="row col-sm-6"> <label asp-for="DisplayType">@T["Display Type"]</label> <input asp-for="DisplayType" placeholder="Summary" class="form-control medium" /> <span class="hint">@T["The display type to use when rendering the content items. Default is Summary."]</span> </div> </fieldset>
bsd-3-clause
C#
a76e40a75722be72cab9ce1eac66e6153aaffac2
Fix Socket span tests in light of ArraySegment->Span cast change (#25292)
ravimeda/corefx,zhenlan/corefx,ericstj/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,ptoonen/corefx,zhenlan/corefx,mmitche/corefx,zhenlan/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,Jiayili1/corefx,shimingsg/corefx,mmitche/corefx,ptoonen/corefx,shimingsg/corefx,ViktorHofer/corefx,mmitche/corefx,zhenlan/corefx,ravimeda/corefx,mmitche/corefx,Ermiar/corefx,Ermiar/corefx,ViktorHofer/corefx,ViktorHofer/corefx,axelheer/corefx,ericstj/corefx,ericstj/corefx,ravimeda/corefx,Ermiar/corefx,zhenlan/corefx,Ermiar/corefx,ptoonen/corefx,Ermiar/corefx,ericstj/corefx,zhenlan/corefx,wtgodbe/corefx,mmitche/corefx,ViktorHofer/corefx,wtgodbe/corefx,ptoonen/corefx,wtgodbe/corefx,ericstj/corefx,Jiayili1/corefx,ravimeda/corefx,BrennanConroy/corefx,axelheer/corefx,zhenlan/corefx,Jiayili1/corefx,ptoonen/corefx,ravimeda/corefx,BrennanConroy/corefx,wtgodbe/corefx,ravimeda/corefx,BrennanConroy/corefx,wtgodbe/corefx,wtgodbe/corefx,ravimeda/corefx,Jiayili1/corefx,axelheer/corefx,ptoonen/corefx,ViktorHofer/corefx,Ermiar/corefx,ericstj/corefx,Jiayili1/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,axelheer/corefx,Jiayili1/corefx,axelheer/corefx,Ermiar/corefx,axelheer/corefx
src/System.Net.Sockets/tests/FunctionalTests/SocketTestHelper.netcoreapp.cs
src/System.Net.Sockets/tests/FunctionalTests/SocketTestHelper.netcoreapp.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; namespace System.Net.Sockets.Tests { public class SocketHelperSpanSync : SocketHelperArraySync { public override bool ValidatesArrayArguments => false; public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Receive((Span<byte>)buffer, SocketFlags.None)); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Send((ReadOnlySpan<byte>)buffer, SocketFlags.None)); } public sealed class SocketHelperSpanSyncForceNonBlocking : SocketHelperSpanSync { public override bool ValidatesArrayArguments => false; public override Task<Socket> AcceptAsync(Socket s) => Task.Run(() => { s.ForceNonBlocking(true); Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return accepted; }); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Run(() => { s.ForceNonBlocking(true); s.Connect(endPoint); }); } public sealed class SocketHelperMemoryArrayTask : SocketHelperTask { public override bool ValidatesArrayArguments => false; public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => s.ReceiveAsync((Memory<byte>)buffer, SocketFlags.None).AsTask(); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => s.SendAsync((ReadOnlyMemory<byte>)buffer, SocketFlags.None).AsTask(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; namespace System.Net.Sockets.Tests { public class SocketHelperSpanSync : SocketHelperArraySync { public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Receive((Span<byte>)buffer, SocketFlags.None)); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => Task.Run(() => s.Send((ReadOnlySpan<byte>)buffer, SocketFlags.None)); } public sealed class SocketHelperSpanSyncForceNonBlocking : SocketHelperSpanSync { public override Task<Socket> AcceptAsync(Socket s) => Task.Run(() => { s.ForceNonBlocking(true); Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return accepted; }); public override Task ConnectAsync(Socket s, EndPoint endPoint) => Task.Run(() => { s.ForceNonBlocking(true); s.Connect(endPoint); }); } public sealed class SocketHelperMemoryArrayTask : SocketHelperTask { public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) => s.ReceiveAsync((Memory<byte>)buffer, SocketFlags.None).AsTask(); public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) => s.SendAsync((ReadOnlyMemory<byte>)buffer, SocketFlags.None).AsTask(); } }
mit
C#
67477a20a004c97d795e203f745acb2d7999214e
Update Setting Values for OAuth2 setting
CloudBreadProject/CloudBread-Unity-SDK
Assets/CloudBread/API/OAuth/OAuth2Setting.cs
Assets/CloudBread/API/OAuth/OAuth2Setting.cs
using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { private const string SettingAssetName = "CBOAuth2Setting"; private const string SettingsPath = "CloudBread/Resources"; private const string SettingsAssetExtension = ".asset"; // Facebook private bool _useFacebook = false; static public bool UseFacebook { get { return Instance._useFacebook; } set { Instance._useFacebook = value; } } private string _facebookRedirectAddress = ".auth/login/facebook"; static public string FacebookRedirectAddress { get { return Instance._facebookRedirectAddress; } set { Instance._facebookRedirectAddress = value; } } // GoogePlay public bool _useGooglePlay = false; static public bool UseGooglePlay { get { return instance._useGooglePlay; } set { Instance._useGooglePlay = value; } } public string _googleRedirectAddress = "aaaa"; static public string GoogleRedirectAddress { get { return instance._googleRedirectAddress; } set { Instance._googleRedirectAddress = value; } } // KaKao private bool _useKaKao = false; public bool UseKaKao { get { return Instance._useKaKao; } set { Instance._useKaKao = value; } } public static string KakaoRedirectAddress; private static OAuth2Setting instance = null; public static OAuth2Setting Instance { get { if (instance == null) { instance = Resources.Load(SettingAssetName) as OAuth2Setting; if (instance == null) { // If not found, autocreate the asset object. instance = ScriptableObject.CreateInstance<OAuth2Setting>(); #if UNITY_EDITOR string properPath = Path.Combine(Application.dataPath, SettingsPath); if (!Directory.Exists(properPath)) { Directory.CreateDirectory(properPath); } string fullPath = Path.Combine( Path.Combine("Assets", SettingsPath), SettingAssetName + SettingsAssetExtension); AssetDatabase.CreateAsset(instance, fullPath); #endif } } return instance; } } } }
using System; using UnityEngine; namespace CloudBread.OAuth { public class OAuth2Setting : ScriptableObject { static bool _useFacebook; static public string FaceBookRedirectAddress; static bool _useGooglePlay; public static string GooglePlayRedirectAddress; static bool _useKaKao; public static string KakaoRedirectAddress; public OAuth2Setting () { } } }
mit
C#
b5c409fc97448e0de788b5ffe31188e00fad8006
add DisallowMultipleComponent.
scienceagora4dim/Stereoscopic4D
Assets/Stereoscopic4D/Scripts/Transform4D.cs
Assets/Stereoscopic4D/Scripts/Transform4D.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Stereoscopic4D { /// <summary> /// This class extends GameObject to 4D transform /// </summary> [DisallowMultipleComponent] public class Transform4D : MonoBehaviour { /// <summary> /// w position. /// </summary> public float w; [Header("Rotation with W")] /// <summary> /// The XZ rotation. /// </summary> public float xz; /// <summary> /// The YZ rotation. /// </summary> public float yz; /// <summary> /// The XY rotation. /// </summary> public float xy; /// <summary> /// Gets or sets the 4D position. /// </summary> /// <value>The 4D position.</value> public Vector4 position { get { Vector3 pos = transform.position; return new Vector4 (pos.x, pos.y, pos.z, w); } set { transform.position = new Vector3 (value.x, value.y, value.z); w = value.w; } } /// <summary> /// Gets or sets the world rotation with w. /// </summary> /// <value>The local rotation with w.</value> public Quaternion rotationWithW { get { return Quaternion.Euler (xz, yz, xy); } set { Vector3 angles = value.eulerAngles; xz = angles.x; yz = angles.y; xy = angles.z; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Stereoscopic4D { /// <summary> /// This class extends GameObject to 4D transform /// </summary> public class Transform4D : MonoBehaviour { /// <summary> /// w position. /// </summary> public float w; [Header("Rotation with W")] /// <summary> /// The XZ rotation. /// </summary> public float xz; /// <summary> /// The YZ rotation. /// </summary> public float yz; /// <summary> /// The XY rotation. /// </summary> public float xy; /// <summary> /// Gets or sets the 4D position. /// </summary> /// <value>The 4D position.</value> public Vector4 position { get { Vector3 pos = transform.position; return new Vector4 (pos.x, pos.y, pos.z, w); } set { transform.position = new Vector3 (value.x, value.y, value.z); w = value.w; } } /// <summary> /// Gets or sets the world rotation with w. /// </summary> /// <value>The local rotation with w.</value> public Quaternion rotationWithW { get { return Quaternion.Euler (xz, yz, xy); } set { Vector3 angles = value.eulerAngles; xz = angles.x; yz = angles.y; xy = angles.z; } } } }
mit
C#
3f379bedf765233776c60a53bc42b8221a45dcfd
Use using
joelverhagen/tostorage
ToStorage/Program.cs
ToStorage/Program.cs
using System; using System.Threading.Tasks; using CommandLine; using Knapcode.ToStorage.AzureBlobStorage; using Knapcode.ToStorage.Core.AzureBlobStorage; namespace Knapcode.ToStorage { public class Program { public static int Main(string[] args) { return MainAsync(args).Result; } private static async Task<int> MainAsync(string[] args) { // parse options var result = Parser.Default.ParseArguments<Options>(args); if (result.Tag == ParserResultType.NotParsed) { return 1; } var options = result.MapResult(o => o, e => null); if ((options.Account == null || options.Key == null) && options.ConnectionString == null) { Console.WriteLine("Either a connection string must be specified, or the account and key."); return 1; } // build the implementation models var client = new Client(); using (var stdin = Console.OpenStandardInput()) { var request = new UploadRequest { Container = options.Container, ContentType = options.ContentType, PathFormat = options.PathFormat, UpdateLatest = options.UpdateLatest, Stream = stdin, Trace = Console.Out }; // upload if (options.ConnectionString != null) { await client.UploadAsync(options.ConnectionString, request).ConfigureAwait(false); } else { await client.UploadAsync(options.Account, options.Key, request).ConfigureAwait(false); } } return 0; } } }
using System; using System.Threading.Tasks; using CommandLine; using Knapcode.ToStorage.Core.AzureBlobStorage; namespace Knapcode.ToStorage { public class Program { public static int Main(string[] args) { return MainAsync(args).Result; } private static async Task<int> MainAsync(string[] args) { // parse options var result = Parser.Default.ParseArguments<AzureBlobStorage.Options>(args); if (result.Tag == ParserResultType.NotParsed) { return 1; } var options = result.MapResult(o => o, e => null); if ((options.Account == null || options.Key == null) && options.ConnectionString == null) { Console.WriteLine("Either a connection string must be specified, or the account and key."); return 1; } // build the implementation models var client = new Client(); using (var stdin = Console.OpenStandardInput()) { var request = new UploadRequest { Container = options.Container, ContentType = options.ContentType, PathFormat = options.PathFormat, UpdateLatest = options.UpdateLatest, Stream = stdin, Trace = Console.Out }; // upload if (options.ConnectionString != null) { await client.UploadAsync(options.ConnectionString, request).ConfigureAwait(false); } else { await client.UploadAsync(options.Account, options.Key, request).ConfigureAwait(false); } } return 0; } } }
mit
C#
1036740ad5ecab18919e9a786b2656c4bce97a1c
fix "Operation not supported" on http send async
yar229/WebDavMailRuCloud
WDMRC.Console/ProxyFabric.cs
WDMRC.Console/ProxyFabric.cs
using System; using System.Net; using System.Net.Http; using System.Text.RegularExpressions; using MihaZupan; namespace YaR.CloudMailRu.Console { class ProxyFabric { public IWebProxy Get(string proxyAddress, string proxyUser, string proxyPassword) { if (string.IsNullOrEmpty(proxyAddress)) #if NET461 return WebRequest.DefaultWebProxy; #else return HttpClient.DefaultProxy; #endif var match = Regex.Match(proxyAddress, @"\A\s*(?<type>(socks|https|http)) :// (?<address>\S*?) : (?<port>\d+) \s* \Z", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); if (!match.Success) throw new ArgumentException("Not supported proxy type"); string type = match.Groups["type"].Value; string address = match.Groups["address"].Value; int port = int.Parse(match.Groups["port"].Value); var proxy = type == "socks" ? string.IsNullOrEmpty(proxyUser) ? (IWebProxy)new HttpToSocks5Proxy(address, port) : new HttpToSocks5Proxy(address, port, proxyUser, proxyPassword) : new WebProxy(new Uri(proxyAddress)) { UseDefaultCredentials = string.IsNullOrEmpty(proxyUser), Credentials = new NetworkCredential {UserName = proxyUser, Password = proxyPassword} }; return proxy; } } }
using System; using System.Net; using System.Text.RegularExpressions; using MihaZupan; namespace YaR.CloudMailRu.Console { class ProxyFabric { public IWebProxy Get(string proxyAddress, string proxyUser, string proxyPassword) { if (string.IsNullOrEmpty(proxyAddress)) return WebRequest.DefaultWebProxy; var match = Regex.Match(proxyAddress, @"\A\s*(?<type>(socks|https|http)) :// (?<address>\S*?) : (?<port>\d+) \s* \Z", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline); if (!match.Success) throw new ArgumentException("Not supported proxy type"); string type = match.Groups["type"].Value; string address = match.Groups["address"].Value; int port = int.Parse(match.Groups["port"].Value); var proxy = type == "socks" ? string.IsNullOrEmpty(proxyUser) ? (IWebProxy)new HttpToSocks5Proxy(address, port) : new HttpToSocks5Proxy(address, port, proxyUser, proxyPassword) : new WebProxy(new Uri(proxyAddress)) { UseDefaultCredentials = string.IsNullOrEmpty(proxyUser), Credentials = new NetworkCredential {UserName = proxyUser, Password = proxyPassword} }; return proxy; } } }
mit
C#
30b39070bdf6781d3cb01cf8390ec4da874c43c2
Update comments
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/ConsoleMinesweeper/Models/ConsoleTimer.cs
src2/ConsoleMinesweeper/Models/ConsoleTimer.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConsoleTimer.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The console timer. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleMinesweeper.Models { using System; using System.Threading; using Minesweeper.Models.Interfaces; /// <summary> /// The console timer. /// </summary> public class ConsoleTimer : IMinesweeperTimer { /// <summary> /// The console timer. /// </summary> private Timer consoleTimer; /// <summary> /// The tick event. /// </summary> public event EventHandler TickEvent; /// <summary> /// The start. /// </summary> public void Start() { this.consoleTimer = new Timer(this.TimerCallback, null, 0, 1000); } /// <summary> /// The stop. /// </summary> public void Stop() { } /// <summary> /// The timer callback. /// </summary> /// <param name="o"> /// The o. /// </param> private void TimerCallback(object o) { if (this.TickEvent != null) { this.TickEvent.Invoke(this, new EventArgs()); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ConsoleTimer.cs" company=""> // // </copyright> // <summary> // The console timer. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleMinesweeper.Models { using System; using System.Threading; using Minesweeper.Models.Interfaces; /// <summary> /// The console timer. /// </summary> public class ConsoleTimer : IMinesweeperTimer { /// <summary> /// The console timer. /// </summary> private Timer consoleTimer; /// <summary> /// The tick event. /// </summary> public event EventHandler TickEvent; /// <summary> /// The start. /// </summary> public void Start() { this.consoleTimer = new Timer(this.TimerCallback, null, 0, 1000); } /// <summary> /// The stop. /// </summary> public void Stop() { } /// <summary> /// The timer callback. /// </summary> /// <param name="o"> /// The o. /// </param> private void TimerCallback(object o) { if (this.TickEvent != null) { this.TickEvent.Invoke(this, new EventArgs()); } } } }
mit
C#
df1e4cd1d803ff43071f5912ee9f020fa40a871a
Change icon classes.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/IconClasses.cs
source/Nuke.Common/IconClasses.cs
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.IO; using Nuke.Common.Tools.CoverallsNet; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitReleaseManager; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.Npm; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.TestCloud; using Nuke.Common.Tools.VsTest; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(CoverallsNetTasks), "stats-growth")] [assembly: IconClass(typeof(DefaultSettings), "equalizer")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitReleaseManagerTasks), "tree7")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "sword")] [assembly: IconClass(typeof(NpmTasks), "box")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "stats-growth")] [assembly: IconClass(typeof(SerializationTasks), "transmission2")] [assembly: IconClass(typeof(TestCloudTasks), "bug2")] [assembly: IconClass(typeof(TextTasks), "file-text3")] [assembly: IconClass(typeof(VsTestTasks), "bug2")] [assembly: IconClass(typeof(XmlTasks), "file-empty2")] [assembly: IconClass(typeof(XunitTasks), "bug2")] #if !NETCORE [assembly: IconClass(typeof(FtpTasks), "sphere2")] [assembly: IconClass(typeof(HttpTasks), "sphere2")] #endif
// Copyright Matthias Koch 2017. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common; using Nuke.Common.Git; using Nuke.Common.IO; using Nuke.Common.Tools.DocFx; using Nuke.Common.Tools.DotCover; using Nuke.Common.Tools.DotNet; using Nuke.Common.Tools.DupFinder; using Nuke.Common.Tools.GitLink; using Nuke.Common.Tools.GitVersion; using Nuke.Common.Tools.InspectCode; using Nuke.Common.Tools.MSBuild; using Nuke.Common.Tools.NuGet; using Nuke.Common.Tools.Nunit; using Nuke.Common.Tools.OpenCover; using Nuke.Common.Tools.Paket; using Nuke.Common.Tools.ReportGenerator; using Nuke.Common.Tools.Xunit; using Nuke.Core.Execution; [assembly: IconClass(typeof(DefaultSettings), "equalizer")] [assembly: IconClass(typeof(DocFxTasks), "books")] [assembly: IconClass(typeof(DotCoverTasks), "shield2")] [assembly: IconClass(typeof(DotNetTasks), "fire")] [assembly: IconClass(typeof(DupFinderTasks), "code")] [assembly: IconClass(typeof(GitLinkTasks), "link")] [assembly: IconClass(typeof(GitRepository), "git")] [assembly: IconClass(typeof(GitVersionTasks), "podium")] [assembly: IconClass(typeof(InspectCodeTasks), "code")] [assembly: IconClass(typeof(MSBuildTasks), "download2")] [assembly: IconClass(typeof(NuGetTasks), "box")] [assembly: IconClass(typeof(NunitTasks), "bug2")] [assembly: IconClass(typeof(OpenCoverTasks), "shield2")] [assembly: IconClass(typeof(PaketTasks), "box")] [assembly: IconClass(typeof(ReportGeneratorTasks), "flag3")] [assembly: IconClass(typeof(SerializationTasks), "barcode")] [assembly: IconClass(typeof(TextTasks), "file-text3")] [assembly: IconClass(typeof(XmlTasks), "file-empty2")] [assembly: IconClass(typeof(XunitTasks), "bug2")] #if !NETCORE [assembly: IconClass(typeof(FtpTasks), "sphere2")] [assembly: IconClass(typeof(HttpTasks), "sphere2")] #endif
mit
C#
f5464285fb247db01cdeedc913443e89046a89fc
Fix missed RelocatedType annotation
ViktorHofer/corefx,wtgodbe/corefx,ptoonen/corefx,BrennanConroy/corefx,shimingsg/corefx,ptoonen/corefx,ptoonen/corefx,wtgodbe/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,ViktorHofer/corefx,BrennanConroy/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,ptoonen/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,ViktorHofer/corefx,wtgodbe/corefx,ViktorHofer/corefx,shimingsg/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,BrennanConroy/corefx,wtgodbe/corefx,ptoonen/corefx,ptoonen/corefx,ViktorHofer/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx
src/Common/src/CoreLib/System/Security/Principal/IPrincipal.cs
src/Common/src/CoreLib/System/Security/Principal/IPrincipal.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // All roles will implement this interface // using System; namespace System.Security.Principal { #if PROJECTN [Internal.Runtime.CompilerServices.RelocatedType("System.Security.Principal")] #endif public interface IPrincipal { // Retrieve the identity object IIdentity Identity { get; } // Perform a check for a specific role bool IsInRole(string role); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // All roles will implement this interface // using System; namespace System.Security.Principal { public interface IPrincipal { // Retrieve the identity object IIdentity Identity { get; } // Perform a check for a specific role bool IsInRole(string role); } }
mit
C#
3669e5f4de6ef9a43ca45e071e8c6a513d4111f9
Fix invalid JSON caused by localized decimal mark
zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype
src/Glimpse.Common/Internal/Serialization/TimeSpanConverter.cs
src/Glimpse.Common/Internal/Serialization/TimeSpanConverter.cs
using System; using System.Globalization; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString(CultureInfo.InvariantCulture)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } }
using System; using Newtonsoft.Json; namespace Glimpse.Internal { public class TimeSpanConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var result = 0.0; var convertedNullable = value as TimeSpan?; if (convertedNullable.HasValue) { result = Math.Round(convertedNullable.Value.TotalMilliseconds, 2); } writer.WriteRawValue(result.ToString()); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value; } public override bool CanConvert(Type objectType) { return objectType == typeof(TimeSpan) || objectType == typeof(TimeSpan?); } } }
mit
C#
aee9ec768e038976dfb1d2bf27cfbf14324bba3a
Update BasketController.cs
dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,BillWagner/eShopOnContainers,albertodall/eShopOnContainers,TypeW/eShopOnContainers,BillWagner/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,BillWagner/eShopOnContainers,BillWagner/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,BillWagner/eShopOnContainers,andrelmp/eShopOnContainers
src/Services/Basket/Basket.API/Controllers/BasketController.cs
src/Services/Basket/Basket.API/Controllers/BasketController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.AspNetCore.Authorization; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers { [Route("/")] [Authorize] public class BasketController : Controller { private IBasketRepository _repository; public BasketController(IBasketRepository repository) { _repository = repository; } // GET api/values/5 [HttpGet("{id}")] public async Task<IActionResult> Get(string id) { var basket = await _repository.GetBasketAsync(id); return Ok(basket); } // POST api/values [HttpPost] public async Task<IActionResult> Post([FromBody]CustomerBasket value) { var basket = await _repository.UpdateBasketAsync(value); return Ok(basket); } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(string id) { _repository.DeleteBasketAsync(id); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.eShopOnContainers.Services.Basket.API.Model; using Microsoft.AspNetCore.Authorization; namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers { //TODO NOTE: Right now this is a very chunky API, as the app evolves it is possible we would //want to make the actions more fine grained, add basket item as an action for example. //If this is the case we should also investigate changing the serialization format used for Redis, //using a HashSet instead of a simple string. [Route("/")] [Authorize] public class BasketController : Controller { private IBasketRepository _repository; public BasketController(IBasketRepository repository) { _repository = repository; } // GET api/values/5 [HttpGet("{id}")] public async Task<IActionResult> Get(string id) { var basket = await _repository.GetBasketAsync(id); return Ok(basket); } // POST api/values [HttpPost] public async Task<IActionResult> Post([FromBody]CustomerBasket value) { var basket = await _repository.UpdateBasketAsync(value); return Ok(basket); } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(string id) { _repository.DeleteBasketAsync(id); } } }
mit
C#
5c70fadaaecf9010e838efd2c06ed2d08b71d76d
Fix FMC values
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Vehicle.cs
Battery-Commander.Web/Models/Vehicle.cs
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } // Notes, What's broken about it? [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required, StringLength(10)] public String Bumper { get; set; } [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // public String Registration { get; set; } // public String Serial { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? // LIN? // Fuel Card? Towbar? Water Buffalo? // Fuel Level? // Driver, A-Driver, Passengers, Assigned Section? public enum VehicleType : byte { HMMWV = 0, LMTV } public enum VehicleStatus : byte { Unknown = 0, FMC = 1, NMC = byte.MaxValue } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } // Notes, What's broken about it? [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required, StringLength(10)] public String Bumper { get; set; } [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // public String Registration { get; set; } // public String Serial { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? // LIN? // Fuel Card? Towbar? Water Buffalo? // Fuel Level? // Driver, A-Driver, Passengers, Assigned Section? public enum VehicleType : byte { HMMWV = 0, LMTV } public enum VehicleStatus : byte { Unknown = byte.MinValue, FMC = 0, NMC = byte.MaxValue } } }
mit
C#
b0f7b9b0bbc54e40eb9adc7380afb25cfd3f1bc5
Set properties so that title displays correctly for nunitlite
OmicronPersei/nunit,agray/nunit,nivanov1984/nunit,ggeurts/nunit,Suremaker/nunit,Green-Bug/nunit,appel1/nunit,agray/nunit,mikkelbu/nunit,OmicronPersei/nunit,ChrisMaddock/nunit,agray/nunit,mjedrzejek/nunit,mikkelbu/nunit,danielmarbach/nunit,JustinRChou/nunit,jadarnel27/nunit,ChrisMaddock/nunit,danielmarbach/nunit,nunit/nunit,nivanov1984/nunit,mjedrzejek/nunit,danielmarbach/nunit,Suremaker/nunit,ggeurts/nunit,Green-Bug/nunit,jnm2/nunit,jadarnel27/nunit,nunit/nunit,NikolayPianikov/nunit,NikolayPianikov/nunit,JustinRChou/nunit,jnm2/nunit,appel1/nunit,Green-Bug/nunit
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // 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.Reflection; // // Common Information for the NUnit assemblies // [assembly: AssemblyCompany("NUnit Software")] [assembly: AssemblyProduct("NUnit 3")] [assembly: AssemblyCopyright("Copyright (C) 2016 Charlie Poole")] [assembly: AssemblyTrademark("NUnit is a trademark of NUnit Software")] #if PORTABLE [assembly: AssemblyMetadata("PCL", "True")] #endif #if DEBUG #if NET_4_5 [assembly: AssemblyConfiguration(".NET 4.5 Debug")] #elif NET_4_0 [assembly: AssemblyConfiguration(".NET 4.0 Debug")] #elif NET_3_5 [assembly: AssemblyConfiguration(".NET 3.5 Debug")] #elif NET_2_0 [assembly: AssemblyConfiguration(".NET 2.0 Debug")] #elif NETSTANDARD1_6 [assembly: AssemblyConfiguration("NetStandard 1.6 Debug")] #elif PORTABLE [assembly: AssemblyConfiguration("Portable Debug")] #else [assembly: AssemblyConfiguration("Debug")] #endif #else #if NET_4_5 [assembly: AssemblyConfiguration(".NET 4.5")] #elif NET_4_0 [assembly: AssemblyConfiguration(".NET 4.0")] #elif NET_3_5 [assembly: AssemblyConfiguration(".NET 3.5")] #elif NET_2_0 [assembly: AssemblyConfiguration(".NET 2.0")] #elif NETSTANDARD1_6 [assembly: AssemblyConfiguration("NetStandard 1.6")] #elif PORTABLE [assembly: AssemblyConfiguration("Portable")] #else [assembly: AssemblyConfiguration("")] #endif #endif
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // 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.Reflection; // // Common Information for the NUnit assemblies // [assembly: AssemblyCompany("NUnit Software")] [assembly: AssemblyProduct("NUnit 3")] [assembly: AssemblyCopyright("Copyright (C) 2016 Charlie Poole")] [assembly: AssemblyTrademark("NUnit is a trademark of NUnit Software")] #if PORTABLE [assembly: AssemblyMetadata("PCL", "True")] #endif #if DEBUG #if NET_4_5 [assembly: AssemblyConfiguration(".NET 4.5 Debug")] #elif NET_4_0 [assembly: AssemblyConfiguration(".NET 4.0 Debug")] #elif NET_2_0 [assembly: AssemblyConfiguration(".NET 2.0 Debug")] #elif PORTABLE [assembly: AssemblyConfiguration("Portable Debug")] #else [assembly: AssemblyConfiguration("Debug")] #endif #else #if NET_4_5 [assembly: AssemblyConfiguration(".NET 4.5")] #elif NET_4_0 [assembly: AssemblyConfiguration(".NET 4.0")] #elif NET_2_0 [assembly: AssemblyConfiguration(".NET 2.0")] #elif PORTABLE [assembly: AssemblyConfiguration("Portable")] #else [assembly: AssemblyConfiguration("")] #endif #endif
mit
C#
d403c72fcf934da32d1db5d287a54406df512881
Add members property to collection
digirati-co-uk/iiif-model
Digirati.IIIF/Model/Types/Collection.cs
Digirati.IIIF/Model/Types/Collection.cs
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } [JsonProperty(Order = 111, PropertyName = "members")] public IIIFPresentationBase[] Members { get; set; } public override string Type { get { return "sc:Collection"; } } } }
using Newtonsoft.Json; namespace Digirati.IIIF.Model.Types { public class Collection : IIIFPresentationBase { [JsonProperty(Order = 100, PropertyName = "collections")] public Collection[] Collections { get; set; } [JsonProperty(Order = 101, PropertyName = "manifests")] public Manifest[] Manifests { get; set; } public override string Type { get { return "sc:Collection"; } } } }
mit
C#
ec1dc60bd66132d983535b907a79806097f44810
Change namespace
mstrother/BmpListener
BmpListener.ConsoleExample/Program.cs
BmpListener.ConsoleExample/Program.cs
using System; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; namespace BmpListener.ConsoleExample { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new TestConverter()); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }
using System; using System.Net; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; namespace BmpListener { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new TestConverter()); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }
mit
C#
cb11393bf380ae1b99839f1a204e122ac48c7a9f
Add new class for implementing Instance property.
exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml,exKAZUu/Code2Xml
Code2Xml.Core/CodeToXmls/CodeToXml.cs
Code2Xml.Core/CodeToXmls/CodeToXml.cs
#region License // Copyright (C) 2009-2013 Kazunori Sakamoto // // 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.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Text; using System.Xml.Linq; using Paraiba.Text; namespace Code2Xml.Core.CodeToXmls { public abstract class CodeToXml<TCodeToXml> : CodeToXml where TCodeToXml : CodeToXml, new() { private static TCodeToXml _instance; public static TCodeToXml Instance { get { return (_instance = _instance ?? new TCodeToXml()); } } } [ContractClass(typeof(CodeToXmlContract))] public abstract class CodeToXml { public const bool DefaultThrowingParseError = false; public abstract string ParserName { get; } public abstract IEnumerable<string> TargetExtensions { get; } public XElement GenerateFromFile( string path, Encoding encoding, bool throwingParseError) { Contract.Requires(path != null); using (var reader = new StreamReader(path, encoding)) { return Generate(reader, throwingParseError); } } public XElement GenerateFromFile(string path, bool throwingParseError) { Contract.Requires(path != null); return Generate(GuessEncoding.ReadAllText(path), throwingParseError); } public abstract XElement Generate( TextReader reader, bool throwingParseError); public virtual XElement Generate(string code, bool throwingParseError) { Contract.Requires(code != null); using (var reader = new StringReader(code)) { return Generate(reader, throwingParseError); } } public XElement GenerateFromFile(string path, Encoding encoding) { Contract.Requires(path != null); return GenerateFromFile(path, encoding, DefaultThrowingParseError); } public XElement GenerateFromFile(string path) { Contract.Requires(path != null); return GenerateFromFile(path, DefaultThrowingParseError); } public XElement Generate(TextReader reader) { Contract.Requires(reader != null); return Generate(reader, DefaultThrowingParseError); } public XElement Generate(string code) { Contract.Requires(code != null); return Generate(code, DefaultThrowingParseError); } } }
#region License // Copyright (C) 2011-2012 Kazunori Sakamoto // // 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.Collections.Generic; using System.Diagnostics.Contracts; using System.IO; using System.Text; using System.Xml.Linq; using Paraiba.Text; namespace Code2Xml.Core.CodeToXmls { [ContractClass(typeof(CodeToXmlContract))] public abstract class CodeToXml { public const bool DefaultThrowingParseError = false; public abstract string ParserName { get; } public abstract IEnumerable<string> TargetExtensions { get; } public XElement GenerateFromFile( string path, Encoding encoding, bool throwingParseError) { Contract.Requires(path != null); using (var reader = new StreamReader(path, encoding)) { return Generate(reader, throwingParseError); } } public XElement GenerateFromFile(string path, bool throwingParseError) { Contract.Requires(path != null); return Generate(GuessEncoding.ReadAllText(path), throwingParseError); } public abstract XElement Generate( TextReader reader, bool throwingParseError); public virtual XElement Generate(string code, bool throwingParseError) { Contract.Requires(code != null); using (var reader = new StringReader(code)) { return Generate(reader, throwingParseError); } } public XElement GenerateFromFile(string path, Encoding encoding) { Contract.Requires(path != null); return GenerateFromFile(path, encoding, DefaultThrowingParseError); } public XElement GenerateFromFile(string path) { Contract.Requires(path != null); return GenerateFromFile(path, DefaultThrowingParseError); } public XElement Generate(TextReader reader) { Contract.Requires(reader != null); return Generate(reader, DefaultThrowingParseError); } public XElement Generate(string code) { Contract.Requires(code != null); return Generate(code, DefaultThrowingParseError); } } }
apache-2.0
C#
113153e6a34becbae3934939172511b2f8ee591a
Fix remaining filter tests
peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,ppy/osu
osu.Game/Tests/Visual/OnlinePlay/TestRoomManager.cs
osu.Game/Tests/Visual/OnlinePlay/TestRoomManager.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Rooms; using osu.Game.Rulesets; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Tests.Visual.OnlinePlay { /// <summary> /// A very simple <see cref="RoomManager"/> for use in online play test scenes. /// </summary> public class TestRoomManager : RoomManager { public Action<Room, string> JoinRoomRequested; private int currentRoomId; public override void JoinRoom(Room room, string password = null, Action<Room> onSuccess = null, Action<string> onError = null) { JoinRoomRequested?.Invoke(room, password); base.JoinRoom(room, password, onSuccess, onError); } public void AddRooms(int count, RulesetInfo ruleset = null, bool withPassword = false) { for (int i = 0; i < count; i++) { var room = new Room { RoomID = { Value = -currentRoomId }, Name = { Value = $@"Room {currentRoomId}" }, Host = { Value = new APIUser { Username = @"Host" } }, EndDate = { Value = DateTimeOffset.Now + TimeSpan.FromSeconds(10) }, Category = { Value = i % 2 == 0 ? RoomCategory.Spotlight : RoomCategory.Normal }, }; if (withPassword) room.Password.Value = @"password"; if (ruleset != null) { room.PlaylistItemStats.Value = new Room.RoomPlaylistItemStats { RulesetIDs = new[] { ruleset.OnlineID }, }; room.Playlist.Add(new PlaylistItem(new BeatmapInfo { Metadata = new BeatmapMetadata() }) { RulesetID = ruleset.OnlineID, }); } CreateRoom(room); currentRoomId++; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Game.Beatmaps; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Rooms; using osu.Game.Rulesets; using osu.Game.Screens.OnlinePlay.Components; namespace osu.Game.Tests.Visual.OnlinePlay { /// <summary> /// A very simple <see cref="RoomManager"/> for use in online play test scenes. /// </summary> public class TestRoomManager : RoomManager { public Action<Room, string> JoinRoomRequested; private int currentRoomId; public override void JoinRoom(Room room, string password = null, Action<Room> onSuccess = null, Action<string> onError = null) { JoinRoomRequested?.Invoke(room, password); base.JoinRoom(room, password, onSuccess, onError); } public void AddRooms(int count, RulesetInfo ruleset = null, bool withPassword = false) { for (int i = 0; i < count; i++) { var room = new Room { RoomID = { Value = -currentRoomId }, Name = { Value = $@"Room {currentRoomId}" }, Host = { Value = new APIUser { Username = @"Host" } }, EndDate = { Value = DateTimeOffset.Now + TimeSpan.FromSeconds(10) }, Category = { Value = i % 2 == 0 ? RoomCategory.Spotlight : RoomCategory.Normal }, }; if (withPassword) room.Password.Value = @"password"; if (ruleset != null) { room.Playlist.Add(new PlaylistItem(new BeatmapInfo { Metadata = new BeatmapMetadata() }) { RulesetID = ruleset.OnlineID, }); } CreateRoom(room); currentRoomId++; } } } }
mit
C#
612dfe57fdabf3f6a99f3ce0a7a2e073e908ed70
Remove unnecessary using's, add comment
EasyPeasyLemonSqueezy/MadCat
MadCat/NutPackerLib/OriginalNameAttribute.cs
MadCat/NutPackerLib/OriginalNameAttribute.cs
using System; namespace NutPackerLib { /// <summary> /// Original name of something. /// </summary> public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NutPackerLib { public class OriginalNameAttribute : Attribute { public string Name { get; private set; } public OriginalNameAttribute(string name) { Name = name; } } }
mit
C#
f48663d30b18b5a87ab9fe9417d2e203f7391143
handle duplicate{user|role|permission}Exceptions
Pondidum/Magistrate,Pondidum/Magistrate,Pondidum/Magistrate,Pondidum/Magistrate
Magistrate/Api/ExceptionHandlerMiddleware.cs
Magistrate/Api/ExceptionHandlerMiddleware.cs
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Magistrate.Domain; using Microsoft.Owin; using Newtonsoft.Json; using Owin.Routing; using Serilog; namespace Magistrate.Api { public class ExceptionHandlerMiddleware : OwinMiddleware { private static readonly ILogger Log = Serilog.Log.ForContext<ExceptionHandlerMiddleware>(); private readonly JsonSerializerSettings _jsonSettings; private readonly Dictionary<Type, Func<IOwinContext, Exception, Task>> _handlers; public ExceptionHandlerMiddleware(OwinMiddleware next, JsonSerializerSettings jsonSettings) : base(next) { _jsonSettings = jsonSettings; _handlers = new Dictionary<Type, Func<IOwinContext, Exception, Task>>(); Register<DuplicatePermissionException>(async (context, ex) => { context.Response.StatusCode = 409; // 409:Conflict await context.WriteJson(new { Message = ex.Message }, _jsonSettings); }); Register<DuplicateRoleException>(async (context, ex) => { context.Response.StatusCode = 409; // 409:Conflict await context.WriteJson(new { Message = ex.Message }, _jsonSettings); }); Register<DuplicateUserException>(async (context, ex) => { context.Response.StatusCode = 409; // 409:Conflict await context.WriteJson(new { Message = ex.Message }, _jsonSettings); }); } private void Register<TException>(Func<IOwinContext, TException, Task> apply) where TException : Exception { _handlers[typeof(TException)] = (context, ex) => apply(context, (TException)ex); } public override async Task Invoke(IOwinContext context) { try { await Next.Invoke(context); } catch (Exception ex) { Log.Error(ex, ex.ToString()); Func<IOwinContext, Exception, Task> handler; if (_handlers.TryGetValue(ex.GetType(), out handler)) { await handler(context, ex); } else { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.WriteJson(ex, _jsonSettings); } } } } }
using System; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Magistrate.Domain; using Microsoft.Owin; using Newtonsoft.Json; using Owin.Routing; using Serilog; namespace Magistrate.Api { public class ExceptionHandlerMiddleware : OwinMiddleware { private static readonly ILogger Log = Serilog.Log.ForContext<ExceptionHandlerMiddleware>(); private readonly JsonSerializerSettings _jsonSettings; private readonly Dictionary<Type, Func<IOwinContext, Exception, Task>> _handlers; public ExceptionHandlerMiddleware(OwinMiddleware next, JsonSerializerSettings jsonSettings) : base(next) { _jsonSettings = jsonSettings; _handlers = new Dictionary<Type, Func<IOwinContext, Exception, Task>>(); Register<DuplicatePermissionException>(async (context, ex) => { context.Response.StatusCode = 409; // 409:Conflict await context.WriteJson(new { Message = ex.Message }, _jsonSettings); }); } private void Register<TException>(Func<IOwinContext, TException, Task> apply) where TException : Exception { _handlers[typeof(TException)] = (context, ex) => apply(context, (TException)ex); } public override async Task Invoke(IOwinContext context) { try { await Next.Invoke(context); } catch (Exception ex) { Log.Error(ex, ex.ToString()); Func<IOwinContext, Exception, Task> handler; if (_handlers.TryGetValue(ex.GetType(), out handler)) { await handler(context, ex); } else { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; await context.WriteJson(ex, _jsonSettings); } } } } }
lgpl-2.1
C#
14ab24f8f256689b131f958e119238e859d3a217
Fix typo
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mastorm/MODiX
Modix/Services/Wikipedia/WikipediaService.cs
Modix/Services/Wikipedia/WikipediaService.cs
using Modix.Services.Wikipedia; using Newtonsoft.Json; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class WikipediaService { private const string WikipediaApiScheme = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles={0}&redirects="; public async Task<WikipediaResponse> GetWikipediaResultsAsync(string phrase) { string query = string.Join(" ", phrase); query = WebUtility.UrlEncode(query); var client = new HttpClient(); var response = await client.GetAsync(string.Format(WikipediaApiScheme, query)); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Wikipedia API."); } var jsonResponse = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<WikipediaResponse>(jsonResponse); } } }
using Modix.Services.Wikipedia; using Newtonsoft.Json; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Modix.Services.StackExchange { public class WikipediaService { private const string WikipediaApiScheme = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exlimit=max&explaintext&exintro&titles={0}&redirects="; public async Task<WikipediaResponse> GetWikipediaResultsAsync(string phrase) { string query = string.Join(" ", phrase); query = WebUtility.UrlEncode(query); var client = new HttpClient(); var response = await client.GetAsync(string.Format(WikipediaApiScheme, query)); if (!response.IsSuccessStatusCode) { throw new WebException("Something failed while querying the Stack Exchange API."); } var jsonResponse = await response.Content.ReadAsStringAsync(); return JsonConvert.DeserializeObject<WikipediaResponse>(jsonResponse); } } }
mit
C#
031f9c553032df0e65b48b94945fecf8f35e5cf8
Use gate request for parsing qs.
CrankyTRex/JabbRMirror,LookLikeAPro/JabbR,meebey/JabbR,CrankyTRex/JabbRMirror,fuzeman/vox,meebey/JabbR,huanglitest/JabbRTest2,ajayanandgit/JabbR,18098924759/JabbR,huanglitest/JabbRTest2,CrankyTRex/JabbRMirror,borisyankov/JabbR,lukehoban/JabbR,fuzeman/vox,LookLikeAPro/JabbR,e10/JabbR,yadyn/JabbR,M-Zuber/JabbR,lukehoban/JabbR,18098924759/JabbR,JabbR/JabbR,yadyn/JabbR,AAPT/jean0226case1322,JabbR/JabbR,borisyankov/JabbR,M-Zuber/JabbR,mzdv/JabbR,timgranstrom/JabbR,huanglitest/JabbRTest2,LookLikeAPro/JabbR,lukehoban/JabbR,SonOfSam/JabbR,yadyn/JabbR,mzdv/JabbR,meebey/JabbR,AAPT/jean0226case1322,fuzeman/vox,borisyankov/JabbR,SonOfSam/JabbR,ajayanandgit/JabbR,timgranstrom/JabbR,e10/JabbR
JabbR/Middleware/ImageProxyHandler.cs
JabbR/Middleware/ImageProxyHandler.cs
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Cache; using System.Threading.Tasks; using JabbR.ContentProviders; using JabbR.Infrastructure; using Owin.Types; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; /// <summary> /// Proxies images through the jabbr server to avoid mixed mode https. /// </summary> public class ImageProxyHandler { private readonly AppFunc _next; private readonly string _path; public ImageProxyHandler(AppFunc next, string path) { _next = next; _path = path; } public async Task Invoke(IDictionary<string, object> env) { var httpRequest = new Gate.Request(env); if (!httpRequest.Path.StartsWith(_path)) { await _next(env); return; } var httpResponse = new OwinResponse(env); string url; Uri uri; if (!httpRequest.Query.TryGetValue("url", out url) || String.IsNullOrEmpty(url) || !ImageContentProvider.IsValidImagePath(url) || !Uri.TryCreate(url, UriKind.Absolute, out uri)) { httpResponse.StatusCode = 404; await TaskAsyncHelper.Empty; return; } var request = (HttpWebRequest)WebRequest.Create(url); request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default); var response = (HttpWebResponse)await request.GetResponseAsync(); httpResponse.SetHeader("ContentType", response.ContentType); httpResponse.StatusCode = (int)response.StatusCode; using (response) { using (Stream stream = response.GetResponseStream()) { await stream.CopyToAsync(httpResponse.Body); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Cache; using System.Threading.Tasks; using JabbR.ContentProviders; using JabbR.Infrastructure; using Owin.Types; namespace JabbR.Middleware { using AppFunc = Func<IDictionary<string, object>, Task>; /// <summary> /// Proxies images through the jabbr server to avoid mixed mode https. /// </summary> public class ImageProxyHandler { private readonly AppFunc _next; private readonly string _path; public ImageProxyHandler(AppFunc next, string path) { _next = next; _path = path; } public async Task Invoke(IDictionary<string, object> env) { var httpRequest = new OwinRequest(env); if (!httpRequest.Path.StartsWith(_path)) { await _next(env); return; } var httpResponse = new OwinResponse(env); var qs = new QueryStringCollection(httpRequest.QueryString); string url = qs["url"]; Uri uri; if (String.IsNullOrEmpty(url) || !ImageContentProvider.IsValidImagePath(url) || !Uri.TryCreate(url, UriKind.Absolute, out uri)) { httpResponse.StatusCode = 404; await TaskAsyncHelper.Empty; return; } var request = (HttpWebRequest)WebRequest.Create(url); request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default); var response = (HttpWebResponse)await request.GetResponseAsync(); httpResponse.SetHeader("ContentType", response.ContentType); httpResponse.StatusCode = (int)response.StatusCode; using (response) { using (Stream stream = response.GetResponseStream()) { await stream.CopyToAsync(httpResponse.Body); } } } } }
mit
C#
6f90fce7a710f300aa2f18d66eb32e20512998cb
Fix Warning (which was reported as Error)
littlesmilelove/NLog,hubo0831/NLog,BrutalCode/NLog,kevindaub/NLog,bjornbouetsmith/NLog,UgurAldanmaz/NLog,luigiberrettini/NLog,NLog/NLog,luigiberrettini/NLog,ie-zero/NLog,tetrodoxin/NLog,bjornbouetsmith/NLog,sean-gilliam/NLog,UgurAldanmaz/NLog,MartinTherriault/NLog,nazim9214/NLog,kevindaub/NLog,ie-zero/NLog,snakefoot/NLog,BrutalCode/NLog,nazim9214/NLog,304NotModified/NLog,littlesmilelove/NLog,hubo0831/NLog,MartinTherriault/NLog,tetrodoxin/NLog
src/NLog/Internal/MySmtpClient.cs
src/NLog/Internal/MySmtpClient.cs
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.Internal { using System.Net.Mail; /// <summary> /// Supports mocking of SMTP Client code. /// </summary> /// <remarks> /// Disabled Error CS0618 'SmtpClient' is obsolete: 'SmtpClient and its network of types are poorly designed, /// we strongly recommend you use https://github.com/jstedfast/MailKit and https://github.com/jstedfast/MimeKit instead' /// </remarks> #pragma warning disable 618 internal class MySmtpClient : SmtpClient, ISmtpClient #pragma warning restore 618 { #if NET3_5 || MONO /// <summary> /// Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the <see cref="T:System.Net.Mail.SmtpClient"/> class. /// </summary> public void Dispose() { // dispose was added in .NET Framework 4.0, previous frameworks don't need it but adding it here to make the // user experience the same across all } #endif } } #endif
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT namespace NLog.Internal { using System.Net.Mail; /// <summary> /// Supports mocking of SMTP Client code. /// </summary> internal class MySmtpClient : SmtpClient, ISmtpClient { #if NET3_5 || MONO /// <summary> /// Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of the <see cref="T:System.Net.Mail.SmtpClient"/> class. /// </summary> public void Dispose() { // dispose was added in .NET Framework 4.0, previous frameworks don't need it but adding it here to make the // user experience the same across all } #endif } } #endif
bsd-3-clause
C#
4ef3c9a3266adc9822ad34e66f80be20f1b3b497
Fix B19.
neitsa/PrepareLanding,neitsa/PrepareLanding
src/Patches/PatchGenerateWorld.cs
src/Patches/PatchGenerateWorld.cs
using System; using Harmony; using RimWorld.Planet; namespace PrepareLanding.Patches { [HarmonyPatch(typeof(WorldGenerator), "GenerateWorld")] public static class PatchGenerateWorld { public static event Action WorldAboutToBeGenerated = delegate { }; [HarmonyPrefix] public static bool GenerateWorldPrefix() { WorldAboutToBeGenerated?.Invoke(); return true; } public static event Action WorldGenerated = delegate { }; [HarmonyPostfix] public static void GenerateWorldPostFix() { WorldGenerated?.Invoke(); } } }
using System; using Harmony; using RimWorld.Planet; namespace PrepareLanding.Patches { [HarmonyPatch(typeof(WorldGenerator), "GenerateWorld")] public static class PatchGenerateWorld { public static event Action WorldAboutToBeGenerated = delegate { }; [HarmonyPrefix] public static void GenerateWorldPrefix() { WorldAboutToBeGenerated?.Invoke(); } public static event Action WorldGenerated = delegate { }; [HarmonyPostfix] public static void GenerateWorldPostFix() { WorldGenerated?.Invoke(); } } }
mit
C#
5e15f1c5dda597577d26293ea97b405f9bd0bfe5
Improve code
sakapon/KLibrary.Linq
KLibrary4/Linq/Linq/GroupingHelper.cs
KLibrary4/Linq/Linq/GroupingHelper.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace KLibrary.Linq { public static class GroupingHelper { public static IEnumerable<IGrouping<TKey, TSource>> GroupBySequentially<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var queue = new Queue<TSource>(); var currentKey = default(TKey); var comparer = EqualityComparer<TKey>.Default; foreach (var item in source) { var key = keySelector(item); if (!comparer.Equals(key, currentKey)) { if (queue.Count != 0) { yield return new Grouping<TKey, TSource>(currentKey, queue.ToArray()); queue.Clear(); } currentKey = key; } queue.Enqueue(item); } if (queue.Count != 0) { yield return new Grouping<TKey, TSource>(currentKey, queue.ToArray()); } } } public class Grouping<TKey, TElement> : IGrouping<TKey, TElement> { public TKey Key { get; } protected IEnumerable<TElement> Values { get; } public Grouping(TKey key, IEnumerable<TElement> values) { Key = key; Values = values; } public IEnumerator<TElement> GetEnumerator() => Values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace KLibrary.Linq { public static class GroupingHelper { public static IEnumerable<IGrouping<TKey, TSource>> GroupBySequentially<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (keySelector == null) throw new ArgumentNullException(nameof(keySelector)); var queue = new Queue<TSource>(); var currentKey = default(TKey); var comparer = EqualityComparer<TKey>.Default; foreach (var item in source) { var key = keySelector(item); if (!comparer.Equals(key, currentKey)) { if (queue.Count != 0) { yield return new Grouping<TKey, TSource>(currentKey, queue.ToArray()); queue.Clear(); } currentKey = key; } queue.Enqueue(item); } if (queue.Count != 0) { yield return new Grouping<TKey, TSource>(currentKey, queue.ToArray()); queue.Clear(); } } } public class Grouping<TKey, TElement> : IGrouping<TKey, TElement> { public TKey Key { get; } protected IEnumerable<TElement> Values { get; } public Grouping(TKey key, IEnumerable<TElement> values) { Key = key; Values = values; } public IEnumerator<TElement> GetEnumerator() => Values.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
mit
C#
c2cf324ef6aa018edc8564552ae00b6f57338da1
Add missing newline to end of Program.cs
portaljacker/portalbot
src/portalbot/Program.cs
src/portalbot/Program.cs
using Discord; using Discord.Commands; using Discord.WebSocket; using System; using System.Reflection; using System.Threading.Tasks; namespace portalbot { class Program { private CommandService _commands; private DiscordSocketClient _client; private DependencyMap _map; static void Main(string[] args) => new Program().Run().GetAwaiter().GetResult(); public async Task Run() { string token = Environment.GetEnvironmentVariable("DISCORD_BOT_TOKEN"); _client = new DiscordSocketClient(); _commands = new CommandService(); _map = new DependencyMap(); _map.Add(_client); _map.Add(_commands); _map.Add(new Random()); await InstallCommands(); /*_client.MessageReceived += async (message) => { if (message.Content == "!ping") await message.Channel.SendMessageAsync("pong"); };//*/ await _client.LoginAsync(TokenType.Bot, token); await _client.ConnectAsync(); // Block this task until the program is exited. await Task.Delay(-1); } public async Task InstallCommands() { _client.MessageReceived += HandleCommand; await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); } public async Task HandleCommand(SocketMessage messageParam) { var message = messageParam as SocketUserMessage; if (message == null) return; int argPos = 0; if (!message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) return; var context = new CommandContext(_client, message); var result = await _commands.ExecuteAsync(context, argPos, _map); if (!result.IsSuccess) await context.Channel.SendMessageAsync(result.ErrorReason); } } }
using Discord; using Discord.Commands; using Discord.WebSocket; using System; using System.Reflection; using System.Threading.Tasks; namespace portalbot { class Program { private CommandService _commands; private DiscordSocketClient _client; private DependencyMap _map; static void Main(string[] args) => new Program().Run().GetAwaiter().GetResult(); public async Task Run() { string token = Environment.GetEnvironmentVariable("DISCORD_BOT_TOKEN"); _client = new DiscordSocketClient(); _commands = new CommandService(); _map = new DependencyMap(); _map.Add(_client); _map.Add(_commands); _map.Add(new Random()); await InstallCommands(); /*_client.MessageReceived += async (message) => { if (message.Content == "!ping") await message.Channel.SendMessageAsync("pong"); };//*/ await _client.LoginAsync(TokenType.Bot, token); await _client.ConnectAsync(); // Block this task until the program is exited. await Task.Delay(-1); } public async Task InstallCommands() { _client.MessageReceived += HandleCommand; await _commands.AddModulesAsync(Assembly.GetEntryAssembly()); } public async Task HandleCommand(SocketMessage messageParam) { var message = messageParam as SocketUserMessage; if (message == null) return; int argPos = 0; if (!message.HasCharPrefix('!', ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) return; var context = new CommandContext(_client, message); var result = await _commands.ExecuteAsync(context, argPos, _map); if (!result.IsSuccess) await context.Channel.SendMessageAsync(result.ErrorReason); } } }
mit
C#
69dda669b4e63e3cf0630beb91ee8cdcc1ef4b0c
Change creation of MaintenanceTimer in ConnectionFactory so its no marked as not in use.
mongodb-csharp/mongodb-csharp,zh-huan/mongodb,samus/mongodb-csharp
MongoDBDriver/Connection/ConnectionFactory.cs
MongoDBDriver/Connection/ConnectionFactory.cs
using System; using System.Collections.Generic; using System.Threading; namespace MongoDB.Driver.Connection { public static class ConnectionFactory { private static readonly TimeSpan MaintenaceWakeup = TimeSpan.FromSeconds(30); private static readonly Timer MaintenanceTimer = new Timer(o => OnMaintenaceWakeup()); private static readonly Dictionary<string,ConnectionPool> Pools = new Dictionary<string, ConnectionPool>(); private static readonly object SyncObject = new object(); /// <summary> /// Initializes the <see cref="ConnectionFactory"/> class. /// </summary> static ConnectionFactory() { MaintenanceTimer.Change(MaintenaceWakeup, MaintenaceWakeup); } /// <summary> /// Gets the pool count. /// </summary> /// <value>The pool count.</value> public static int PoolCount { get { lock(SyncObject) return Pools.Count; } } /// <summary> /// Called when [maintenace wakeup]. /// </summary> private static void OnMaintenaceWakeup() { lock(SyncObject) { foreach(var pool in Pools.Values) pool.Cleanup(); } } /// <summary> /// Gets the connection. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> public static Connection GetConnection(string connectionString) { if(connectionString == null) throw new ArgumentNullException("connectionString"); ConnectionPool pool; lock(SyncObject) { if(!Pools.TryGetValue(connectionString, out pool)) Pools.Add(connectionString, pool = new ConnectionPool(connectionString)); } return new Connection(pool); } } }
using System; using System.Collections.Generic; using System.Threading; namespace MongoDB.Driver.Connection { public static class ConnectionFactory { private static readonly TimeSpan MaintenaceWakeup = TimeSpan.FromSeconds(30); private static readonly Timer MaintenanceTimer; private static readonly Dictionary<string,ConnectionPool> Pools = new Dictionary<string, ConnectionPool>(); private static readonly object SyncObject = new object(); /// <summary> /// Initializes the <see cref="ConnectionFactory"/> class. /// </summary> static ConnectionFactory() { MaintenanceTimer = new Timer(o => OnMaintenaceWakeup(), null, MaintenaceWakeup, MaintenaceWakeup); } /// <summary> /// Gets the pool count. /// </summary> /// <value>The pool count.</value> public static int PoolCount { get { lock(SyncObject) return Pools.Count; } } /// <summary> /// Called when [maintenace wakeup]. /// </summary> private static void OnMaintenaceWakeup() { lock(SyncObject) { foreach(var pool in Pools.Values) pool.Cleanup(); } } /// <summary> /// Gets the connection. /// </summary> /// <param name="connectionString">The connection string.</param> /// <returns></returns> public static Connection GetConnection(string connectionString) { if(connectionString == null) throw new ArgumentNullException("connectionString"); ConnectionPool pool; lock(SyncObject) { if(!Pools.TryGetValue(connectionString, out pool)) Pools.Add(connectionString, pool = new ConnectionPool(connectionString)); } return new Connection(pool); } } }
apache-2.0
C#
088342a3198645996377e571233f144cb1fa2774
Increase project version number to 0.14.0
atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.14.0")] [assembly: AssemblyFileVersion("0.14.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.13.0")] [assembly: AssemblyFileVersion("0.13.0")]
apache-2.0
C#
7a60bc03477c59a1bb1bc0b4e2cd112f397a6b93
remove obsolete security assertion
spring-projects/spring-net-codeconfig,spring-projects/spring-net-codeconfig
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.431 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: CLSCompliantAttribute(false)] [assembly: ComVisibleAttribute(false)] [assembly: AllowPartiallyTrustedCallersAttribute()] [assembly: AssemblyCompanyAttribute("http://www.springframework.net")] [assembly: AssemblyCopyrightAttribute("Copyright 2010-2011 Spring.NET Framework Team.")] [assembly: AssemblyTrademarkAttribute("Apache License, Version 2.0")] [assembly: AssemblyCultureAttribute("")] [assembly: AssemblyVersionAttribute("1.0.0.4132")] [assembly: AssemblyFileVersionAttribute("1.0.0.4132")] [assembly: AssemblyConfigurationAttribute("net-4.0.win32; dev")] [assembly: AssemblyInformationalVersionAttribute("1.0.0.4132")] [assembly: AssemblyDelaySignAttribute(false)]
#region License /* * Copyright 2010-2011 the original author or 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 System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: CLSCompliantAttribute(false)] [assembly: ComVisibleAttribute(false)] [assembly: AllowPartiallyTrustedCallersAttribute()] [assembly: AssemblyCompanyAttribute("http://www.springframework.net")] [assembly: AssemblyCopyrightAttribute("Copyright 2010-2011 Spring.NET Framework Team.")] [assembly: AssemblyTrademarkAttribute("Apache License, Version 2.0")] [assembly: AssemblyCultureAttribute("")] [assembly: AssemblyVersionAttribute("1.0.0.4111")] [assembly: AssemblyFileVersionAttribute("1.0.0.4111")] [assembly: AssemblyConfigurationAttribute("net-4.0.win32; release")] [assembly: AssemblyInformationalVersionAttribute("1.0.0.4111; net-4.0.win32; release")] [assembly: AssemblyDelaySignAttribute(false)]
apache-2.0
C#
4daeca013588066a09d7fb6ecf8a2300d1dd9533
Increase project version to 0.16.0
atata-framework/atata-sample-app-tests
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.16.0")] [assembly: AssemblyFileVersion("0.16.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("Copyright © Yevgeniy Shunevych 2017")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("0.15.0")] [assembly: AssemblyFileVersion("0.15.0")]
apache-2.0
C#
235e4736d81750878bbe15cbab86a3dc7b5e6f74
tidy up whitespace in email
PandaWood/ExceptionReporter.NET,PandaWood/ExceptionReporter.NET,PandaWood/ExceptionReporter.NET
src/ExceptionReporter/Mail/EmailTextBuilder.cs
src/ExceptionReporter/Mail/EmailTextBuilder.cs
using System.Text; namespace ExceptionReporting.Mail { /// <summary> /// textual content for email introduction /// </summary> public class EmailTextBuilder { public string CreateIntro(bool takeScreenshot) { var s = new StringBuilder() .AppendLine("The email is ready to be sent.") .AppendLine("Information relating to the error is included. Please feel free to add any relevant information or attach any files."); if (takeScreenshot) { s.AppendLine("A screenshot, taken at the time of the exception, is attached.") .AppendLine("You may delete the attachment before sending if you prefer.") .AppendLine(); } return s.ToString(); } } }
using System.Text; namespace ExceptionReporting.Mail { /// <summary> /// textual content for email introduction /// </summary> public class EmailTextBuilder { public string CreateIntro(bool takeScreenshot) { var s = new StringBuilder("The email is ready to be sent.") .AppendLine("Information relating to the error is included. Please feel free to add any relevant information or attach any files."); if (takeScreenshot) { s.AppendLine("A screenshot, taken at the time of the exception, is attached") .AppendLine("You may delete the attachment before sending if you prefer.") .AppendLine(); } return s.ToString(); } } }
mit
C#
da4dff171e9c02f3d194d807979f20cb6905b999
Tweak text on homepage
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/Views/Home/Index.cshtml
src/LondonTravel.Site/Views/Home/Index.cshtml
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status of travel in London. </p> <p> <a class="btn btn-primary" id="link-install" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa">Install »</a> </p> </div>
@inject SiteOptions Options @{ ViewBag.Title = "Home"; } <div class="jumbotron"> <h1>London Travel</h1> <p class="lead"> An Amazon Alexa skill for checking the status for travel in London. </p> <p> <a class="btn btn-primary" id="link-install" href="@Options?.ExternalLinks?.Skill" rel="noopener" target="_blank" title="Install London Travel for Amazon Alexa">Install »</a> </p> </div>
apache-2.0
C#
52f826b7775602b9aee809da35225bc8967b8ccb
bump to version 1.3.8
Terradue/DotNetTep,Terradue/DotNetTep
Terradue.Tep/Properties/AssemblyInfo.cs
Terradue.Tep/Properties/AssemblyInfo.cs
/*! \namespace Terradue.Tep @{ Terradue.Tep Software Package provides with all the functionalities specific to the TEP. \xrefitem sw_version "Versions" "Software Package Version" 1.3.8 \xrefitem sw_link "Links" "Software Package List" [Terradue.Tep](https://git.terradue.com/sugar/Terradue.Tep) \xrefitem sw_license "License" "Software License" [AGPL](https://git.terradue.com/sugar/Terradue.Tep/LICENSE) \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch \xrefitem sw_req "Require" "Software Dependencies" \ref ServiceStack \xrefitem sw_req "Require" "Software Dependencies" \ref log4net \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Portal \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Authentication.Umsso \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Cloud \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Github \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Metadata.EarthObservation \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.News \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenNebula \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.GeoJson \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.RdfEO \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Tumblr \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Twitter \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Ogc.OwsContext \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.WebService.Model \ingroup Tep @} */ /*! \defgroup Tep Tep Modules @{ This is a super component that encloses all Thematic Exploitation Platform related functional components. Their main functionnalities are targeted to enhance the basic \ref Core functionalities for the thematic usage of the plaform. @} */ using System.Reflection; using System.Runtime.CompilerServices; using NuGet4Mono.Extensions; [assembly: AssemblyTitle("Terradue.Tep")] [assembly: AssemblyDescription("Terradue Tep .Net library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Terradue")] [assembly: AssemblyProduct("Terradue.Tep")] [assembly: AssemblyCopyright("Terradue")] [assembly: AssemblyAuthors("Enguerran Boissier")] [assembly: AssemblyProjectUrl("https://git.terradue.com/sugar/Terradue.Tep")] [assembly: AssemblyLicenseUrl("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.8")] [assembly: AssemblyInformationalVersion("1.3.8")] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
/*! \namespace Terradue.Tep @{ Terradue.Tep Software Package provides with all the functionalities specific to the TEP. \xrefitem sw_version "Versions" "Software Package Version" 1.3.7 \xrefitem sw_link "Links" "Software Package List" [Terradue.Tep](https://git.terradue.com/sugar/Terradue.Tep) \xrefitem sw_license "License" "Software License" [AGPL](https://git.terradue.com/sugar/Terradue.Tep/LICENSE) \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch \xrefitem sw_req "Require" "Software Dependencies" \ref ServiceStack \xrefitem sw_req "Require" "Software Dependencies" \ref log4net \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Portal \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Authentication.Umsso \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Cloud \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Github \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.Metadata.EarthObservation \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.News \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenNebula \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.GeoJson \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.RdfEO \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Tumblr \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.OpenSearch.Twitter \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Ogc.OwsContext \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.ServiceModel.Syndication \xrefitem sw_req "Require" "Software Dependencies" \ref Terradue.WebService.Model \ingroup Tep @} */ /*! \defgroup Tep Tep Modules @{ This is a super component that encloses all Thematic Exploitation Platform related functional components. Their main functionnalities are targeted to enhance the basic \ref Core functionalities for the thematic usage of the plaform. @} */ using System.Reflection; using System.Runtime.CompilerServices; using NuGet4Mono.Extensions; [assembly: AssemblyTitle("Terradue.Tep")] [assembly: AssemblyDescription("Terradue Tep .Net library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Terradue")] [assembly: AssemblyProduct("Terradue.Tep")] [assembly: AssemblyCopyright("Terradue")] [assembly: AssemblyAuthors("Enguerran Boissier")] [assembly: AssemblyProjectUrl("https://git.terradue.com/sugar/Terradue.Tep")] [assembly: AssemblyLicenseUrl("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.7")] [assembly: AssemblyInformationalVersion("1.3.7")] [assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
agpl-3.0
C#
9a8faab6792d67c8db5efd94dd831c121cde4048
Add CountryCode field.
jcheng31/WundergroundAutocomplete.NET
WundergroundClient/Autocomplete/City.cs
WundergroundClient/Autocomplete/City.cs
using System; namespace WundergroundClient.Autocomplete { class City : AutocompleteResponseObject { public String Country; /// <summary> /// Corresponds to the "zmw" field used in links. /// </summary> public String Identifier; /// <summary> /// The Olson-format time zone. /// e.g. America/Argentina/La_Rioja /// </summary> public String TimeZone; /// <summary> /// Abbreviated time zone. /// e.g. ART /// </summary> public String ShortTimeZone; public double Latitude; public double Longitude; /// <summary> /// The latitude and longitude of this city, separated /// by a space. /// </summary> public String LatitudeLongitude; /// <summary> /// The country code this city is in. /// /// Note: Wunderground uses different country codes than /// the standard ISO. Check http://www.wunderground.com/weather/api/d/docs?d=resources/country-to-iso-matching /// for mapping between this field and the ISO specification. /// </summary> public String CountryCode; } }
using System; namespace WundergroundClient.Autocomplete { class City : AutocompleteResponseObject { public String Country; /// <summary> /// Corresponds to the "zmw" field used in links. /// </summary> public String Identifier; /// <summary> /// The Olson-format time zone. /// e.g. America/Argentina/La_Rioja /// </summary> public String TimeZone; /// <summary> /// Abbreviated time zone. /// e.g. ART /// </summary> public String ShortTimeZone; public double Latitude; public double Longitude; /// <summary> /// The latitude and longitude of this city, separated /// by a space. /// </summary> public String LatitudeLongitude; } }
mit
C#
00b17402814209cc0f54abd211ec051a92f1cbd4
Add spaces into displayed Palette Insight Agent service name
palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent,palette-software/PaletteInsightAgent
PaletteInsightAgentService/Service.cs
PaletteInsightAgentService/Service.cs
using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "Palette Insight Agent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }
using Topshelf; namespace PaletteInsightAgentService { /// <summary> /// Service layer that wraps the PaletteInsightAgentLib. Topshelf keeps this pretty thin for us. /// </summary> internal class PaletteInsightAgentService { // Service name & description. private const string ServiceName = "PaletteInsightAgent"; private const string ServiceDisplayname = "PaletteInsightAgent"; private const string ServiceDescription = "Tableau Server performance monitor"; // Service recovery attempt timings, in minutes. private const int RecoveryFirstAttempt = 0; private const int RecoverySecondAttempt = 1; private const int RecoveryThirdAttempt = 5; // Service recovery reset period, in days. private const int RecoveryResetPeriod = 1; /// <summary> /// Main entry point for the service layer. /// </summary> public static void Main() { // configure service parameters HostFactory.Run(hostConfigurator => { hostConfigurator.SetServiceName(ServiceName); hostConfigurator.SetDescription(ServiceDescription); hostConfigurator.SetDisplayName(ServiceDisplayname); hostConfigurator.Service(() => new PaletteInsightAgentServiceBootstrapper()); hostConfigurator.RunAsLocalSystem(); hostConfigurator.StartAutomaticallyDelayed(); hostConfigurator.UseNLog(); hostConfigurator.EnableServiceRecovery(r => { r.RestartService(RecoveryFirstAttempt); r.RestartService(RecoverySecondAttempt); r.RestartService(RecoveryThirdAttempt); r.OnCrashOnly(); r.SetResetPeriod(RecoveryResetPeriod); }); }); } } }
mit
C#
773295649f7a06996f7f35980f86a8cd31e78857
Add COMException to be caught when calling ManagementEventWatcher.Stop
emoacht/Monitorian
Source/Monitorian.Core/Models/Watcher/BrightnessWatcher.cs
Source/Monitorian.Core/Models/Watcher/BrightnessWatcher.cs
using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Monitorian.Core.Models.Monitor; namespace Monitorian.Core.Models.Watcher { internal class BrightnessWatcher : IDisposable { private ManagementEventWatcher _watcher; private Action<string, int> _onBrightnessChanged; public BrightnessWatcher() { } /// <summary> /// Subscribes to brightness changed event. /// </summary> /// <param name="onBrightnessChanged">Action to be invoked when brightness changed</param> /// <param name="onError">Action to be invoked when error occurred</param> /// <returns>True if successfully subscribes</returns> public bool Subscribe(Action<string, int> onBrightnessChanged, Action<string> onError) { (_watcher, var message) = MSMonitor.StartBrightnessEventWatcher(); if (_watcher is null) { if (!string.IsNullOrEmpty(message)) onError?.Invoke(message); return false; } this._onBrightnessChanged = onBrightnessChanged ?? throw new ArgumentNullException(nameof(onBrightnessChanged)); _watcher.EventArrived += OnEventArrived; return true; } private void OnEventArrived(object sender, EventArrivedEventArgs e) { var (instanceName, brightness) = MSMonitor.ParseBrightnessEventArgs(e); _onBrightnessChanged?.Invoke(instanceName, brightness); } #region IDisposable private bool _isDisposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { // Free any other managed objects here. try { if (_watcher is not null) { _watcher.EventArrived -= OnEventArrived; _watcher.Stop(); // This may throw InvalidCastException or COMException. _watcher.Dispose(); } } catch (Exception ex) when (ex is InvalidCastException or COMException) { } } // Free any unmanaged objects here. _isDisposed = true; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Text; using System.Threading.Tasks; using Monitorian.Core.Models.Monitor; namespace Monitorian.Core.Models.Watcher { internal class BrightnessWatcher : IDisposable { private ManagementEventWatcher _watcher; private Action<string, int> _onBrightnessChanged; public BrightnessWatcher() { } /// <summary> /// Subscribes to brightness changed event. /// </summary> /// <param name="onBrightnessChanged">Action to be invoked when brightness changed</param> /// <param name="onError">Action to be invoked when error occurred</param> /// <returns>True if successfully subscribes</returns> public bool Subscribe(Action<string, int> onBrightnessChanged, Action<string> onError) { (_watcher, var message) = MSMonitor.StartBrightnessEventWatcher(); if (_watcher is null) { if (!string.IsNullOrEmpty(message)) onError?.Invoke(message); return false; } this._onBrightnessChanged = onBrightnessChanged ?? throw new ArgumentNullException(nameof(onBrightnessChanged)); _watcher.EventArrived += OnEventArrived; return true; } private void OnEventArrived(object sender, EventArrivedEventArgs e) { var (instanceName, brightness) = MSMonitor.ParseBrightnessEventArgs(e); _onBrightnessChanged?.Invoke(instanceName, brightness); } #region IDisposable private bool _isDisposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_isDisposed) return; if (disposing) { // Free any other managed objects here. try { if (_watcher is not null) { _watcher.EventArrived -= OnEventArrived; _watcher.Stop(); // This may throw InvalidCastException. _watcher.Dispose(); } } catch (InvalidCastException) { } } // Free any unmanaged objects here. _isDisposed = true; } #endregion } }
mit
C#
004b50fca6518643f0e55ac0b0784c868f2c77be
Remove extra newline
wlindley/bantam-unity
Assets/Bantam/Scripts/Runtime/Context.cs
Assets/Bantam/Scripts/Runtime/Context.cs
using System.Collections.Generic; namespace Bantam.Unity { public abstract class Context { private readonly List<Factory> factories = new List<Factory>(); public abstract void Init(); public virtual T GetInstance<T>(string id="") where T : class { var type = typeof(T); var numFactories = factories.Count; for (var i = 0; i < numFactories; i++) { var instance = factories[i].Build(type, id); if (null != instance) return instance as T; } return null; } public virtual void Inject<T>(out T injectee, string id="") where T : class { injectee = GetInstance<T>(id); } public virtual void BindSingleton<T>(string id="") where T : class, new() { factories.Add(new SingletonFactory<T>(id)); } public virtual void BindTransient<T>(string id="") where T : class, new() { factories.Add(new TransientFactory<T>(id)); } public virtual void BindInstance<T>(T instance, string id="") where T : class { factories.Add(new InstanceFactory<T>(instance, id)); } public virtual void BindCustom(Factory factory) { factories.Add(factory); } } }
using System.Collections.Generic; namespace Bantam.Unity { public abstract class Context { private readonly List<Factory> factories = new List<Factory>(); public abstract void Init(); public virtual T GetInstance<T>(string id="") where T : class { var type = typeof(T); var numFactories = factories.Count; for (var i = 0; i < numFactories; i++) { var instance = factories[i].Build(type, id); if (null != instance) return instance as T; } return null; } public virtual void Inject<T>(out T injectee, string id="") where T : class { injectee = GetInstance<T>(id); } public virtual void BindSingleton<T>(string id="") where T : class, new() { factories.Add(new SingletonFactory<T>(id)); } public virtual void BindTransient<T>(string id="") where T : class, new() { factories.Add(new TransientFactory<T>(id)); } public virtual void BindInstance<T>(T instance, string id="") where T : class { factories.Add(new InstanceFactory<T>(instance, id)); } public virtual void BindCustom(Factory factory) { factories.Add(factory); } } }
mit
C#
3abada74d41b2ec5885e3735d422433d667dbf50
Update HelpCommand.cs
nguerrera/cli,livarcocc/cli-1,mlorbetske/cli,weshaggard/cli,svick/cli,svick/cli,jonsequitur/cli,AbhitejJohn/cli,weshaggard/cli,blackdwarf/cli,EdwardBlair/cli,naamunds/cli,EdwardBlair/cli,Faizan2304/cli,ravimeda/cli,harshjain2/cli,livarcocc/cli-1,naamunds/cli,blackdwarf/cli,harshjain2/cli,livarcocc/cli-1,mlorbetske/cli,mlorbetske/cli,MichaelSimons/cli,svick/cli,AbhitejJohn/cli,mlorbetske/cli,Faizan2304/cli,ravimeda/cli,jonsequitur/cli,dasMulli/cli,johnbeisner/cli,Faizan2304/cli,MichaelSimons/cli,nguerrera/cli,blackdwarf/cli,weshaggard/cli,weshaggard/cli,harshjain2/cli,MichaelSimons/cli,jonsequitur/cli,dasMulli/cli,nguerrera/cli,johnbeisner/cli,dasMulli/cli,MichaelSimons/cli,naamunds/cli,AbhitejJohn/cli,AbhitejJohn/cli,EdwardBlair/cli,weshaggard/cli,ravimeda/cli,nguerrera/cli,naamunds/cli,MichaelSimons/cli,naamunds/cli,blackdwarf/cli,johnbeisner/cli,jonsequitur/cli
src/dotnet/commands/dotnet-help/HelpCommand.cs
src/dotnet/commands/dotnet-help/HelpCommand.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Help { public class HelpCommand { private const string UsageText = @"Usage: dotnet [host-options] [command] [arguments] [common-options] Arguments: [command] The command to execute [arguments] Arguments to pass to the command [host-options] Options specific to dotnet (host) [common-options] Options common to all commands Common options: -v|--verbose Enable verbose output -h|--help Show help Host options (passed before the command): -v|--verbose Enable verbose output --version Display .NET CLI Version Number --info Display .NET CLI Info Commands: new Initialize a basic .NET project restore Restore dependencies specified in the .NET project build Builds a .NET project publish Publishes a .NET project for deployment (including the runtime) run Compiles and immediately executes a .NET project test Runs unit tests using the test runner specified in the project pack Creates a NuGet package"; public static int Run(string[] args) { if (args.Length == 0) { PrintHelp(); return 0; } else { return Cli.Program.Main(new[] { args[0], "--help" }); } } public static void PrintHelp() { PrintVersionHeader(); Reporter.Output.WriteLine(UsageText); } public static void PrintVersionHeader() { var versionString = string.IsNullOrEmpty(Product.Version) ? string.Empty : $" ({Product.Version})"; Reporter.Output.WriteLine(Product.LongName + versionString); } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Reflection; using Microsoft.DotNet.Cli.Utils; namespace Microsoft.DotNet.Tools.Help { public class HelpCommand { private const string UsageText = @"Usage: dotnet [host-options] [command] [arguments] [common-options] Arguments: [command] The command to execute [arguments] Arguments to pass to the command [host-options] Options specific to dotnet (host) [common-options] Options common to all commands Common options: -v|--verbose Enable verbose output -h|--help Show help Host options (passed before the command): -v|--verbose Enable verbose output --version Display .NET CLI Version Number --info Display .NET CLI Info Common Commands: new Initialize a basic .NET project restore Restore dependencies specified in the .NET project build Builds a .NET project publish Publishes a .NET project for deployment (including the runtime) run Compiles and immediately executes a .NET project test Runs unit tests using the test runner specified in the project pack Creates a NuGet package"; public static int Run(string[] args) { if (args.Length == 0) { PrintHelp(); return 0; } else { return Cli.Program.Main(new[] { args[0], "--help" }); } } public static void PrintHelp() { PrintVersionHeader(); Reporter.Output.WriteLine(UsageText); } public static void PrintVersionHeader() { var versionString = string.IsNullOrEmpty(Product.Version) ? string.Empty : $" ({Product.Version})"; Reporter.Output.WriteLine(Product.LongName + versionString); } } }
mit
C#
167ac7ea08bf376e49e45155003ac85370097be1
Fix for Bug Command Line Output in OptionSets file is incorrect #26
daryllabar/DLaB.Xrm.XrmToolBoxTools
DLaB.CrmSvcUtilExtensions/OptionSet/CustomCodeGenerationService.cs
DLaB.CrmSvcUtilExtensions/OptionSet/CustomCodeGenerationService.cs
using Microsoft.Crm.Services.Utility; namespace DLaB.CrmSvcUtilExtensions.OptionSet { public class CustomCodeGenerationService : BaseCustomCodeGenerationService { public CustomCodeGenerationService(ICodeGenerationService service) : base(service) {} protected override string CommandLineText => ConfigHelper.GetAppSettingOrDefault("OptionSetCommandLineText", string.Empty); protected override bool CreateOneFilePerCodeUnit => ConfigHelper.GetAppSettingOrDefault("CreateOneFilePerOptionSet", false); protected override CodeUnit SplitByCodeUnit => CodeUnit.Enum; } }
using Microsoft.Crm.Services.Utility; namespace DLaB.CrmSvcUtilExtensions.OptionSet { public class CustomCodeGenerationService : BaseCustomCodeGenerationService { public CustomCodeGenerationService(ICodeGenerationService service) : base(service) {} protected override bool CreateOneFilePerCodeUnit { get { return ConfigHelper.GetAppSettingOrDefault("CreateOneFilePerOptionSet", false); } } protected override CodeUnit SplitByCodeUnit { get { return CodeUnit.Enum; } } } }
mit
C#
a6da86e32d1d4a7f74dd4ccbed654943cef8ffba
Fix for buildtypeid case mismatch
ericdc1/DTMF,ericdc1/DTMF,ericdc1/DTMF
Source/DTMF.Website/Logic/TeamCity.cs
Source/DTMF.Website/Logic/TeamCity.cs
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.ToLower().Contains(appName.ToLower()))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
using System.Linq; using System.Text; using TeamCitySharp; using TeamCitySharp.Locators; namespace DTMF.Logic { public class TeamCity { public static bool IsRunning(StringBuilder sb, string appName) { //remove prefix and suffixes from app names so same app can go to multiple places appName = appName.Replace(".Production", ""); appName = appName.Replace(".Development", ""); appName = appName.Replace(".Staging", ""); appName = appName.Replace(".Test", ""); //skip if not configured if (System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"] == string.Empty) return false; //Check for running builds var client = new TeamCityClient(System.Configuration.ConfigurationManager.AppSettings["TeamCityServer"]); client.ConnectAsGuest(); var builds = client.Builds.ByBuildLocator(BuildLocator.RunningBuilds()); if (builds.Any(f=>f.BuildTypeId.Contains(appName))) { Utilities.AppendAndSend(sb, "Build in progress. Sync disabled"); //foreach (var build in builds) //{ // Utilities.AppendAndSend(sb, "<li>" + build.BuildTypeId + " running</li>"); //} return true; } return false; } } }
mit
C#