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
92b2bb48bba14ad7b2ebb7633f65c8be8f8b4fdf
Discard button should return to the List view.
alastairs/cgowebsite,alastairs/cgowebsite
src/CGO.Web/Views/Concerts/_ConcertEditForm.cshtml
src/CGO.Web/Views/Concerts/_ConcertEditForm.cshtml
@model CGO.Web.ViewModels.ConcertViewModel @{ Html.EnableClientValidation(); } @using (Html.BeginForm()) { @Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following mistakes:") <fieldset> <legend>Concert details</legend> <h2>Basic Details</h2> <p></p> <p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p> <p> <label for="Date" style="display: inline">Start date and time:&nbsp;</label> @Html.EditorFor(c => c.Date, "Date") @Html.EditorFor(c => c.StartTime, "Time") @Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime) </p> <p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p> <script type="text/javascript"> //$("#Location").typeahead() </script> <h2>Marketing details</h2> <p></p> <div class="wmd-panel"> <div id="wmd-button-bar"></div> @Html.TextAreaFor(c => c.Description, new { id = "wmd-input", @class = "wmd-input", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br /> </div> <div id="wmd-preview" class="wmd-panel wmd-preview"></div> <p>&nbsp;</p> <p> <label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" /> </p> <p>&nbsp;</p> <p> @Html.HiddenFor(c => c.IsPublished) <input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#IsPublished').val(true);$(this).submit();" /> <input type="submit" value="Save for later" class="btn" onclick="$('#IsPublished').val(false);$(this).submit();" /> <a href="@Url.Action("List")" class="btn">Discard</a> </p> </fieldset> } @Html.Partial("_MarkdownEditor")
@model CGO.Web.ViewModels.ConcertViewModel @{ Html.EnableClientValidation(); } @using (Html.BeginForm()) { @Html.ValidationSummary(false, "Oh dear, the violas made a boo-boo. Please go back and fix the following mistakes:") <fieldset> <legend>Concert details</legend> <h2>Basic Details</h2> <p></p> <p>@Html.TextBoxFor(c => c.Title, new { placeholder = "Enter title" }) @Html.ValidationMessageFor(c => c.Title)</p> <p> <label for="Date" style="display: inline">Start date and time:&nbsp;</label> @Html.EditorFor(c => c.Date, "Date") @Html.EditorFor(c => c.StartTime, "Time") @Html.ValidationMessageFor(c => c.Date) @Html.ValidationMessageFor(c => c.StartTime) </p> <p>@Html.TextBoxFor(c => c.Location, new { placeholder = "Enter venue " }) @Html.ValidationMessageFor(c => c.Location)</p> <script type="text/javascript"> //$("#Location").typeahead() </script> <h2>Marketing details</h2> <p></p> <div class="wmd-panel"> <div id="wmd-button-bar"></div> @Html.TextAreaFor(c => c.Description, new { id = "wmd-input", @class = "wmd-input", placeholder = "Provide a description of the concert, including things like the pieces being played, the composers, the soloists for the concert, etc." })<br /> </div> <div id="wmd-preview" class="wmd-panel wmd-preview"></div> <p>&nbsp;</p> <p> <label for="PosterImage" style="display: inline">Upload poster image: </label><input type="file" name="PosterImage" id="PosterImage" /> </p> <p>&nbsp;</p> <p> @Html.HiddenFor(c => c.IsPublished) <input type="submit" value="Publish Concert" class="btn btn-primary" onclick="$('#IsPublished').val(true);$(this).submit();" /> <input type="submit" value="Save for later" class="btn" onclick="$('#IsPublished').val(false);$(this).submit();" /> <input type="reset" value="Discard" class="btn" /> </p> </fieldset> } @Html.Partial("_MarkdownEditor")
mit
C#
99f679a016f3492c2af9191cb041385c0f4eab4d
convert TODO to issue #134
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Api/Controllers/ListsController.cs
src/FilterLists.Api/Controllers/ListsController.cs
using FilterLists.Services.Contracts; using Microsoft.AspNetCore.Mvc; namespace FilterLists.Api.Controllers { [Route("v1/[controller]")] [Produces("application/json")] public class ListsController : Controller { private readonly IFilterListService filterListService; public ListsController(IFilterListService filterListService) { this.filterListService = filterListService; } /// <summary> /// Get Lists /// </summary> /// <returns>All FilterLists</returns> [HttpGet] public IActionResult Get() { return Json(filterListService.GetAll()); } } }
using FilterLists.Services.Contracts; using Microsoft.AspNetCore.Mvc; namespace FilterLists.Api.Controllers { //TODO: migrate controllers to separate projects by version, use dependency injection //TODO: automate URL versioning [Route("v1/[controller]")] [Produces("application/json")] public class ListsController : Controller { private readonly IFilterListService filterListService; public ListsController(IFilterListService filterListService) { this.filterListService = filterListService; } /// <summary> /// Get Lists /// </summary> /// <returns>All FilterLists</returns> [HttpGet] public IActionResult Get() { return Json(filterListService.GetAll()); } } }
mit
C#
410aac59d56872b7bc7559b22fb8ef111baafab6
Fix linker crash
jamesmontemagno/Hanselman.Forms,jamesmontemagno/Hanselman.Forms,jamesmontemagno/Hanselman.Forms
src/Hanselman/Views/Videos/VideoSeriesPage.xaml.cs
src/Hanselman/Views/Videos/VideoSeriesPage.xaml.cs
using System.Linq; using Hanselman.Helpers; using Hanselman.Models; using Hanselman.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; // mattleibow cheered 33 on November 22nd 2019 namespace Hanselman.Views { [Preserve(AllMembers =true)] public partial class VideoSeriesPage : ContentPage { VideoSeriesViewModel VM => (VideoSeriesViewModel)BindingContext; public VideoSeriesPage(VideoSeries series) { InitializeComponent(); BindingContext = new VideoSeriesViewModel(series); } public VideoSeriesPage() { InitializeComponent(); BindingContext = new VideoSeriesViewModel(); } void SetSpan() { var gil = (GridItemsLayout)CollectionViewVideos.ItemsLayout; gil.Span = (int)Application.Current.Resources["VideoSpan"]; } void App_SpanChanged(object sender, System.EventArgs e) => SetSpan(); protected override void OnDisappearing() { base.OnDisappearing(); App.SpanChanged -= App_SpanChanged; } protected override void OnAppearing() { base.OnAppearing(); if (VM.Episodes.Count == 0) VM.LoadEpisodesCommand.Execute(null); SetSpan(); App.SpanChanged += App_SpanChanged; } async void CollectionViewVideos_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.CurrentSelection.FirstOrDefault() is VideoFeedItem item && item != null) { await Navigation.PushAsync(new VideoDetailsPage(item)); ((CollectionView)sender).SelectedItem = null; } } } }
using System.Linq; using Hanselman.Models; using Hanselman.ViewModels; using Xamarin.Forms; using Xamarin.Forms.Xaml; // mattleibow cheered 33 on November 22nd 2019 namespace Hanselman.Views { public partial class VideoSeriesPage : ContentPage { VideoSeriesViewModel VM => (VideoSeriesViewModel)BindingContext; public VideoSeriesPage(VideoSeries series) { InitializeComponent(); BindingContext = new VideoSeriesViewModel(series); } public VideoSeriesPage() { InitializeComponent(); BindingContext = new VideoSeriesViewModel(); } void SetSpan() { var gil = (GridItemsLayout)CollectionViewVideos.ItemsLayout; gil.Span = (int)Application.Current.Resources["VideoSpan"]; } void App_SpanChanged(object sender, System.EventArgs e) => SetSpan(); protected override void OnDisappearing() { base.OnDisappearing(); App.SpanChanged -= App_SpanChanged; } protected override void OnAppearing() { base.OnAppearing(); if (VM.Episodes.Count == 0) VM.LoadEpisodesCommand.Execute(null); SetSpan(); App.SpanChanged += App_SpanChanged; } async void CollectionViewVideos_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (e.CurrentSelection.FirstOrDefault() is VideoFeedItem item && item != null) { await Navigation.PushAsync(new VideoDetailsPage(item)); ((CollectionView)sender).SelectedItem = null; } } } }
mit
C#
c32eafd0aadc2f8dd82f4235c65038773c4e75e9
remove unused constant
ginach/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Helpers/EtagHelper.cs
src/Microsoft.Graph/Requests/Helpers/EtagHelper.cs
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph { using System; /// <summary> /// Helper class to extract @odata.etag property and to specify If-Match headers for requests. /// </summary> public static class EtagHelper { /// <summary> /// Name of the OData etag property. /// </summary> public const string ODataEtagPropertyName = "@odata.etag"; /// <summary> /// Returns the etag of an entity. /// </summary> /// <param name="entity">The entity that contains an etag.</param> /// <returns>Etag value if present, null otherwise.</returns> public static string GetEtag(this Entity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } entity.AdditionalData.TryGetValue(ODataEtagPropertyName, out object etag); return etag as string; } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph { using System; /// <summary> /// Helper class to extract @odata.etag property and to specify If-Match headers for requests. /// </summary> public static class EtagHelper { /// <summary> /// Name of the OData etag property. /// </summary> public const string ODataEtagPropertyName = "@odata.etag"; private const string IfMatchHeaderName = "If-Match"; /// <summary> /// Returns the etag of an entity. /// </summary> /// <param name="entity">The entity that contains an etag.</param> /// <returns>Etag value if present, null otherwise.</returns> public static string GetEtag(this Entity entity) { if (entity == null) { throw new ArgumentNullException(nameof(entity)); } entity.AdditionalData.TryGetValue(ODataEtagPropertyName, out object etag); return etag as string; } } }
mit
C#
8c7beeb9ec4f9e89e17fb8cb6db380eb9f9e3b97
fix version
Fody/Obsolete
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("4.3.1")] [assembly: AssemblyFileVersion("4.3.1")]
using System.Reflection; [assembly: AssemblyTitle("Obsolete")] [assembly: AssemblyProduct("Obsolete")] [assembly: AssemblyVersion("4.3.0")] [assembly: AssemblyFileVersion("4.3.0")]
mit
C#
e11ee872090c06b447b889855027da2935f5e84a
Change chart fields
helgitrump/CPUMonitor
CPUMonitor/MainForm.Designer.cs
CPUMonitor/MainForm.Designer.cs
/* * Created by SharpDevelop. * User: user * Date: 12.07.2017 * Time: 16:30 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ namespace CPUMonitor { partial class MainForm { /// <summary> /// Designer variable used to keep track of non-visual components. /// </summary> private System.ComponentModel.IContainer components = null; private System.Windows.Forms.DataVisualization.Charting.Chart chartCPU; /// <summary> /// Disposes resources used by the form. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// This method is required for Windows Forms designer support. /// Do not change the method contents inside the source code editor. The Forms designer might /// not be able to load this method if it was changed manually. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); this.chartCPU = new System.Windows.Forms.DataVisualization.Charting.Chart(); ((System.ComponentModel.ISupportInitialize)(this.chartCPU)).BeginInit(); this.SuspendLayout(); // // chartCPU // chartArea1.Name = "ChartArea1"; this.chartCPU.ChartAreas.Add(chartArea1); legend1.Name = "Legend1"; this.chartCPU.Legends.Add(legend1); this.chartCPU.Location = new System.Drawing.Point(12, 12); this.chartCPU.Name = "chartCPU"; series1.ChartArea = "ChartArea1"; series1.Legend = "Legend1"; series1.Name = "CPU"; this.chartCPU.Series.Add(series1); this.chartCPU.Size = new System.Drawing.Size(534, 308); this.chartCPU.TabIndex = 0; this.chartCPU.Text = "chart1"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(558, 383); this.Controls.Add(this.chartCPU); this.Name = "MainForm"; this.Text = "CPUMonitor"; ((System.ComponentModel.ISupportInitialize)(this.chartCPU)).EndInit(); this.ResumeLayout(false); } } }
/* * Created by SharpDevelop. * User: user * Date: 12.07.2017 * Time: 16:30 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ namespace CPUMonitor { partial class MainForm { /// <summary> /// Designer variable used to keep track of non-visual components. /// </summary> private System.ComponentModel.IContainer components = null; private System.Windows.Forms.DataVisualization.Charting.Chart chart1; /// <summary> /// Disposes resources used by the form. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } /// <summary> /// This method is required for Windows Forms designer support. /// Do not change the method contents inside the source code editor. The Forms designer might /// not be able to load this method if it was changed manually. /// </summary> private void InitializeComponent() { System.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); ((System.ComponentModel.ISupportInitialize)(this.chart1)).BeginInit(); this.SuspendLayout(); // // chart1 // chartArea1.Name = "ChartArea1"; this.chart1.ChartAreas.Add(chartArea1); legend1.Name = "Legend1"; this.chart1.Legends.Add(legend1); this.chart1.Location = new System.Drawing.Point(12, 12); this.chart1.Name = "chart1"; series1.ChartArea = "ChartArea1"; series1.Legend = "Legend1"; series1.Name = "Series1"; this.chart1.Series.Add(series1); this.chart1.Size = new System.Drawing.Size(534, 308); this.chart1.TabIndex = 0; this.chart1.Text = "chart1"; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(558, 383); this.Controls.Add(this.chart1); this.Name = "MainForm"; this.Text = "CPUMonitor"; ((System.ComponentModel.ISupportInitialize)(this.chart1)).EndInit(); this.ResumeLayout(false); } } }
mit
C#
6d6b9d489c0b46ae65dba0d7dd04be8a2d891c9b
Comment out redis queue tests for now.
adamzolotarev/Exceptionless,exceptionless/Exceptionless,adamzolotarev/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,adamzolotarev/Exceptionless,exceptionless/Exceptionless
Source/Api.Tests/Queue/RedisQueueTests.cs
Source/Api.Tests/Queue/RedisQueueTests.cs
//using System; //using Exceptionless.Core; //using Exceptionless.Core.Queues; //using StackExchange.Redis; //namespace Exceptionless.Api.Tests.Queue { // public class RedisQueueTests : InMemoryQueueTests { // private ConnectionMultiplexer _muxer; // protected override IQueue<SimpleWorkItem> GetQueue(int retries, TimeSpan? workItemTimeout, TimeSpan? retryDelay) { // //if (!Settings.Current.UseAzureServiceBus) // // return; // if (_muxer == null) // _muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString()); // return new RedisQueue<SimpleWorkItem>(_muxer, workItemTimeout: workItemTimeout, retries: 1); // } // } //}
using System; using Exceptionless.Core; using Exceptionless.Core.Queues; using StackExchange.Redis; namespace Exceptionless.Api.Tests.Queue { public class RedisQueueTests : InMemoryQueueTests { private ConnectionMultiplexer _muxer; protected override IQueue<SimpleWorkItem> GetQueue(int retries, TimeSpan? workItemTimeout, TimeSpan? retryDelay) { //if (!Settings.Current.UseAzureServiceBus) // return; if (_muxer == null) _muxer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionInfo.ToString()); return new RedisQueue<SimpleWorkItem>(_muxer, workItemTimeout: workItemTimeout, retries: 1); } } }
apache-2.0
C#
adf0d67493ae76def97a25e2d7ac90968ff9ffb1
Remove TvSeasonEpisode ShowId
LordMike/TMDbLib
TMDbLib/Objects/Search/TvSeasonEpisode.cs
TMDbLib/Objects/Search/TvSeasonEpisode.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; using TMDbLib.Objects.General; using TMDbLib.Objects.TvShows; namespace TMDbLib.Objects.Search { public class TvSeasonEpisode { [JsonProperty("air_date")] public DateTime? AirDate { get; set; } [JsonProperty("crew")] public List<Crew> Crew { get; set; } [JsonProperty("episode_number")] public int EpisodeNumber { get; set; } [JsonProperty("guest_stars")] public List<Cast> GuestStars { get; set; } [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("overview")] public string Overview { get; set; } [JsonProperty("production_code")] public string ProductionCode { get; set; } [JsonProperty("season_number")] public int SeasonNumber { get; set; } [JsonProperty("still_path")] public string StillPath { get; set; } [JsonProperty("vote_average")] public double VoteAverage { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using TMDbLib.Objects.General; using TMDbLib.Objects.TvShows; namespace TMDbLib.Objects.Search { public class TvSeasonEpisode { [JsonProperty("air_date")] public DateTime? AirDate { get; set; } [JsonProperty("crew")] public List<Crew> Crew { get; set; } [JsonProperty("episode_number")] public int EpisodeNumber { get; set; } [JsonProperty("guest_stars")] public List<Cast> GuestStars { get; set; } [JsonProperty("id")] public int Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("overview")] public string Overview { get; set; } [JsonProperty("production_code")] public string ProductionCode { get; set; } [JsonProperty("season_number")] public int SeasonNumber { get; set; } [JsonProperty("show_id")] public int ShowId { get; set; } [JsonProperty("still_path")] public string StillPath { get; set; } [JsonProperty("vote_average")] public double VoteAverage { get; set; } [JsonProperty("vote_count")] public int VoteCount { get; set; } } }
mit
C#
8a74d07b9cd174b08f5541f63d39d6f07fe2b146
Introduce EiB to FileSize
GGG-KILLER/GUtils.NET
GUtils.IO/FileSize.cs
GUtils.IO/FileSize.cs
using System; namespace GUtils.IO { public static class FileSize { public const Int64 KiB = 1 << 10; public const Int64 MiB = 1 << 20; public const Int64 GiB = 1 << 30; public const Int64 TiB = 1 << 40; public const Int64 PiB = 1 << 50; public const Int64 EiB = 1 << 60; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB" }; public static String Format ( Int64 Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / Math.Pow ( 1024, i )} {_suffixes[i]}"; } public static String Format ( Double Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / Math.Pow ( 1024, i )} {_suffixes[i]}"; } public static String Format ( Int64 Size, Int32 decimals ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Math.Round ( Size / Math.Pow ( 1024, i ), decimals )} {_suffixes[i]}"; } public static String Format ( Double Size, Int32 decimals ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Math.Round ( Size / Math.Pow ( 1024, i ), decimals )} {_suffixes[i]}"; } } }
using System; namespace GUtils.IO { public static class FileSize { public const Int64 KiB = 1024; public const Int64 MiB = 1024 * KiB; public const Int64 GiB = 1024 * MiB; public const Int64 TiB = 1024 * GiB; public const Int64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( Int64 Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / Math.Pow ( 1024, i )} {_suffixes[i]}"; } public static String Format ( Double Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / Math.Pow ( 1024, i )} {_suffixes[i]}"; } public static String Format ( Int64 Size, Int32 decimals ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Math.Round ( Size / Math.Pow ( 1024, i ), decimals )} {_suffixes[i]}"; } public static String Format ( Double Size, Int32 decimals ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Math.Round ( Size / Math.Pow ( 1024, i ), decimals )} {_suffixes[i]}"; } } }
mit
C#
d33eab2a4eb8a5be22e2dd1c757461459a874b39
Add DarkGray code
Test20130521/ConsoleApplication61
ConsoleApplication61/Program.cs
ConsoleApplication61/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication61 { class Program { static void Main(string[] args) { } void M1() { var currentGroupId = GetGroup("A"); F1(currentGroupId); F2(currentGroupId); var groupB = GetGroup("B"); F3(groupB); } private int GetGroup(string p0) { throw new NotImplementedException(); } void F1(int groupId){} void F2(int groupId){} void F3(int groupId){} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication61 { class Program { static void Main(string[] args) { } } }
mit
C#
e17985be0008a00cb9db74ac18b20ea02f62e9a6
use extension method to grab lessons in wand shop
StefanoFiumara/Harry-Potter-Unity
Assets/Scripts/HarryPotterUnity/Cards/Charms/Locations/WandShop.cs
Assets/Scripts/HarryPotterUnity/Cards/Charms/Locations/WandShop.cs
using System.Collections.Generic; using System.Linq; using HarryPotterUnity.Enums; using HarryPotterUnity.Utils; namespace HarryPotterUnity.Cards.Charms.Locations { public class WandShop : BaseLocation { private IEnumerable<BaseLesson> AllLessons { get { return Player.InPlay.LessonsOfType(LessonTypes.Charms) .Concat(Player.OppositePlayer.InPlay.LessonsOfType(LessonTypes.Charms)) .Cast<BaseLesson>(); } } public override void OnEnterInPlayAction() { foreach (var lesson in AllLessons) { lesson.AmountLessonsProvided = 2; } Player.OnCardPlayedEvent += DoubleLessonsProvided; Player.OppositePlayer.OnCardPlayedEvent += DoubleLessonsProvided; } public override void OnExitInPlayAction() { foreach (var lesson in AllLessons) { lesson.AmountLessonsProvided = 1; } Player.OnCardPlayedEvent -= DoubleLessonsProvided; Player.OppositePlayer.OnCardPlayedEvent -= DoubleLessonsProvided; } private void DoubleLessonsProvided(BaseCard card, List<BaseCard> targets) { var lesson = card as BaseLesson; if (lesson != null && lesson.LessonType == LessonTypes.Charms) { lesson.AmountLessonsProvided = 2; } } } }
using System.Collections.Generic; using System.Linq; using HarryPotterUnity.Enums; namespace HarryPotterUnity.Cards.Charms.Locations { public class WandShop : BaseLocation { private IEnumerable<BaseLesson> AllLessons { get { return Player.InPlay.Lessons.Cast<BaseLesson>() .Concat(Player.OppositePlayer.InPlay.Lessons.Cast<BaseLesson>()) .Where(c => c.LessonType == LessonTypes.Charms); } } public override void OnEnterInPlayAction() { foreach (var lesson in AllLessons) { lesson.AmountLessonsProvided = 2; } Player.OnCardPlayedEvent += DoubleLessonsProvided; Player.OppositePlayer.OnCardPlayedEvent += DoubleLessonsProvided; } public override void OnExitInPlayAction() { foreach (var lesson in AllLessons) { lesson.AmountLessonsProvided = 1; } Player.OnCardPlayedEvent -= DoubleLessonsProvided; Player.OppositePlayer.OnCardPlayedEvent -= DoubleLessonsProvided; } private void DoubleLessonsProvided(BaseCard card, List<BaseCard> targets) { var lesson = card as BaseLesson; if (lesson != null && lesson.LessonType == LessonTypes.Charms) { lesson.AmountLessonsProvided = 2; } } } }
mit
C#
d190d4d0ff414a8ab39bb82f5be57c8c0273cb90
Fix commit.
yasotidev/BoomerDoukala,yasotidev/BoomerDoukala
DoukalaTemplate/Src/Client/www/Web/Doukala/Models/Compagny.cs
DoukalaTemplate/Src/Client/www/Web/Doukala/Models/Compagny.cs
namespace Doukala.Models { public class Compagny { public byte[] LogoAvatar { get; set; } public string Logo { get; set; } public string Nom { get; set; } public string Description { get; set; } public virtual Address Address { get; set; } public string Activity { get; set; } public string CodeNaf { get; set; } public string SiretNumber { get; set; } public string IntraCommunityVat { get; set; } public string Email { get; set; } public string WebSite { get; set; } public virtual Manager Manager { get; set; } } }
namespace Doukala.Models { public class Compagny : DomainObject { public byte[] LogoAvatar { get; set; } public string Logo { get; set; } public string Nom { get; set; } public string Description { get; set; } public virtual Address Address { get; set; } public string Activity { get; set; } public string CodeNaf { get; set; } public string SiretNumber { get; set; } public string IntraCommunityVat { get; set; } public string Email { get; set; } public string WebSite { get; set; } public virtual Manager Manager { get; set; } } }
agpl-3.0
C#
ea600b6b11b2eb3f66b2b14a68aa63141cb7691f
clean formatting
timba/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,timba/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,ZocDoc/ServiceStack,NServiceKit/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit
tests/ServiceStack.Razor.Tests/HelloRequest.cs
tests/ServiceStack.Razor.Tests/HelloRequest.cs
using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface; namespace ServiceStack.Razor.Tests { public class HelloRequest { public string Name { get; set; } } public class HelloResponse { public string Result { get; set; } } //https://github.com/ServiceStack/ServiceStack/wiki/New-Api public class HelloService : ServiceInterface.Service, IAny<HelloRequest> { //public HelloResponse Any( Hello h ) //{ // //return new HelloResponse { Result = "Hello, " + h.Name }; // return h; //} public object Any(HelloRequest request) { //return new HelloResponse { Result = "Hello, " + request.Name }; return new { Foo = "foo", Password = "pwd", Pw2 = "222", FooMasta = new { Charisma = 10, Mula = 10000000000, Car = "911Turbo" } }; } } public class FooRequest { public string WhatToSay { get; set; } } public class FooResponse { public string FooSaid { get; set; } } public class DefaultViewFooRequest { public string WhatToSay { get; set; } } public class DefaultViewFooResponse { public string FooSaid { get; set; } } public class FooController : ServiceInterface.Service, IGet<FooRequest>, IPost<FooRequest> { public object Get(FooRequest request) { return new FooResponse { FooSaid = string.Format("GET: {0}", request.WhatToSay) }; } public object Post(FooRequest request) { return new FooResponse { FooSaid = string.Format("POST: {0}", request.WhatToSay) }; } [DefaultView("DefaultViewFoo")] public object Get(DefaultViewFooRequest request) { if (request.WhatToSay == "redirect") { return HttpResult.Redirect("/"); } return new DefaultViewFooResponse { FooSaid = string.Format("GET: {0}", request.WhatToSay) }; } } }
using ServiceStack.Common.Web; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface; namespace ServiceStack.Razor.Tests { public class HelloRequest { public string Name { get; set; } } public class HelloResponse { public string Result { get; set; } } //https://github.com/ServiceStack/ServiceStack/wiki/New-Api public class HelloService : ServiceInterface.Service, IAny<HelloRequest> { //public HelloResponse Any( Hello h ) //{ // //return new HelloResponse { Result = "Hello, " + h.Name }; // return h; //} public object Any( HelloRequest request ) { //return new HelloResponse { Result = "Hello, " + request.Name }; return new { Foo = "foo", Password = "pwd", Pw2 = "222", FooMasta = new { Charisma = 10, Mula = 10000000000, Car = "911Turbo" } }; } } public class FooRequest { public string WhatToSay { get; set; } } public class FooResponse { public string FooSaid { get; set; } } public class DefaultViewFooRequest { public string WhatToSay { get; set; } } public class DefaultViewFooResponse { public string FooSaid { get; set; } } public class FooController : ServiceInterface.Service, IGet<FooRequest>, IPost<FooRequest> { public object Get( FooRequest request ) { return new FooResponse { FooSaid = string.Format( "GET: {0}", request.WhatToSay ) }; } public object Post( FooRequest request ) { return new FooResponse { FooSaid = string.Format( "POST: {0}", request.WhatToSay ) }; } [DefaultView("DefaultViewFoo")] public object Get(DefaultViewFooRequest request) { if (request.WhatToSay == "redirect") { return HttpResult.Redirect("/"); } return new DefaultViewFooResponse { FooSaid = string.Format("GET: {0}", request.WhatToSay) }; } } }
bsd-3-clause
C#
8b455d840fd414a6b64bfc32b752420b161d57be
Add IArchiveReader to Autofac configuration.
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Util/ArkadeAutofacModule.cs
src/Arkivverket.Arkade/Util/ArkadeAutofacModule.cs
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Identify; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<ArchiveExtractor>().As<IArchiveExtractor>(); builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<ArchiveExtractionReader>().AsSelf(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<TestEngine>().AsSelf().SingleInstance(); builder.RegisterType<ArchiveContentReader>().As<IArchiveContentReader>(); } } }
using Arkivverket.Arkade.Core; using Arkivverket.Arkade.Identify; using Autofac; namespace Arkivverket.Arkade.Util { public class ArkadeAutofacModule : Module { protected override void Load(ContainerBuilder builder) { builder.RegisterType<ArchiveExtractor>().As<IArchiveExtractor>(); builder.RegisterType<TarCompressionUtility>().As<ICompressionUtility>(); builder.RegisterType<ArchiveExtractionReader>().AsSelf(); builder.RegisterType<ArchiveIdentifier>().As<IArchiveIdentifier>(); builder.RegisterType<TestEngine>().AsSelf().SingleInstance(); } } }
agpl-3.0
C#
404ab23b804ed26aeb7c6623fdf739266ddac620
duplicate binding prevention
army-of-two/when-its-done,army-of-two/when-its-done,army-of-two/when-its-done
WhenItsDone/Clients/WhenItsDone.WebFormsClient/App_Start/NinjectBindingsModules/MVPBindingsModule.cs
WhenItsDone/Clients/WhenItsDone.WebFormsClient/App_Start/NinjectBindingsModules/MVPBindingsModule.cs
using System; using System.Linq; using Ninject; using Ninject.Extensions.Factory; using Ninject.Modules; using WebFormsMvp; using WebFormsMvp.Binder; using WhenItsDone.WebFormsClient.App_Start.Factories; namespace WhenItsDone.WebFormsClient.App_Start.NinjectBindingsModules { public class MVPBindingsModule : NinjectModule { public override void Load() { this.Bind<IPresenter>().ToMethod(ctx => { var requestedType = (Type)ctx.Parameters.First().GetValue(ctx, null); var parameters = ctx.Parameters.ToList(); if (parameters.Count < 3) { throw new ArgumentException("Expected at least 3 parameters."); } var viewType = (Type)parameters[1]; if (viewType == null) { throw new ArgumentNullException("Invalid view type."); } var view = (IView)parameters[2]; if (view == null) { view = (IView)ctx.Kernel.Get(viewType); } var bindingExists = this.Kernel.GetBindings(viewType).Any(); if (bindingExists) { this.Rebind(viewType).ToMethod(context => view); } else { this.Bind(viewType).ToMethod(context => view); } return (IPresenter)ctx.Kernel.Get(requestedType); }) .NamedLikeFactoryMethod((ICustomPresenterFactory factory) => factory.CreatePresenter(null, null, null)); this.Kernel.Bind<IPresenterFactory>().To<WebFormsMvpPresenterFactory>().InSingletonScope(); } } }
using System; using System.Linq; using Ninject; using Ninject.Extensions.Factory; using Ninject.Modules; using WebFormsMvp; using WebFormsMvp.Binder; using WhenItsDone.WebFormsClient.App_Start.Factories; namespace WhenItsDone.WebFormsClient.App_Start.NinjectBindingsModules { public class MVPBindingsModule : NinjectModule { public override void Load() { this.Bind<IPresenter>().ToMethod(ctx => { var requestedType = (Type)ctx.Parameters.First().GetValue(ctx, null); var parameters = ctx.Parameters.ToList(); if (parameters.Count < 3) { throw new ArgumentException("Expected at least 3 parameters."); } var view = (IView)parameters[2]; if (view == null) { var viewType = (Type)parameters[1]; if (viewType == null) { throw new ArgumentNullException("Invalid view type."); } view = (IView)ctx.Kernel.Get(viewType); } this.Bind(typeof(IView)).ToMethod(context => view); return (IPresenter)ctx.Kernel.Get(requestedType); }) .NamedLikeFactoryMethod((ICustomPresenterFactory factory) => factory.CreatePresenter(null, null, null)); this.Kernel.Bind<IPresenterFactory>().To<WebFormsMvpPresenterFactory>().InSingletonScope(); } } }
mit
C#
7c70439f4c74e084f3beb51739e8032f83090835
Put on Pair
theraot/Theraot
Core/Theraot/Threading/Needles/DefaultNeedle.cs
Core/Theraot/Threading/Needles/DefaultNeedle.cs
using System; using System.Collections.Generic; namespace Theraot.Threading.Needles { [global::System.Diagnostics.DebuggerNonUserCode] [global::System.ComponentModel.ImmutableObject(true)] public sealed class DefaultNeedle<T> : IReadOnlyNeedle<T> { private static readonly DefaultNeedle<T> _instance = new DefaultNeedle<T>(); private DefaultNeedle() { //Empty } [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "By Design")] public static DefaultNeedle<T> Instance { get { return _instance; } } bool IReadOnlyNeedle<T>.IsAlive { get { return true; } } public T Value { get { return default(T); } } public static explicit operator T(DefaultNeedle<T> needle) { if (needle == null) { throw new ArgumentNullException("needle"); } else { return needle.Value; } } [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "By Design")] public static bool operator !=(DefaultNeedle<T> left, DefaultNeedle<T> right) { return false; } [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", Justification = "By Design")] public static bool operator ==(DefaultNeedle<T> left, DefaultNeedle<T> right) { return true; } public override bool Equals(object obj) { return obj is EmptyReadOnlyNeedle<T>; } public override int GetHashCode() { return EqualityComparer<T>.Default.GetHashCode(default(T)); } public override string ToString() { return Value.ToString(); } } }
namespace Theraot.Threading.Needles { [global::System.Diagnostics.DebuggerNonUserCode] [global::System.ComponentModel.ImmutableObject(true)] public sealed class DefaultNeedle<T> : INeedle<T> { private static readonly DefaultNeedle<T> _instance = new DefaultNeedle<T>(); private DefaultNeedle() { //Empty } [global::System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes", Justification = "By Design")] public static DefaultNeedle<T> Instance { get { return _instance; } } public bool IsAlive { get { return true; } } public T Value { get { return default(T); } set { //Empty } } public override bool Equals(object obj) { if (obj is DefaultNeedle<T>) { return true; } else { return false; } } public override int GetHashCode() { return base.GetHashCode(); } void INeedle<T>.Release() { //Empty } } }
mit
C#
3085815422cbee41bef3487e50a855cbb79532dc
Fix analytics fields names
sitereactor/kudu,barnyp/kudu,bbauya/kudu,MavenRain/kudu,mauricionr/kudu,MavenRain/kudu,badescuga/kudu,shrimpy/kudu,juvchan/kudu,sitereactor/kudu,puneet-gupta/kudu,kenegozi/kudu,shrimpy/kudu,MavenRain/kudu,juvchan/kudu,mauricionr/kudu,kenegozi/kudu,YOTOV-LIMITED/kudu,juoni/kudu,puneet-gupta/kudu,uQr/kudu,kali786516/kudu,dev-enthusiast/kudu,shrimpy/kudu,oliver-feng/kudu,bbauya/kudu,dev-enthusiast/kudu,chrisrpatterson/kudu,sitereactor/kudu,shibayan/kudu,kali786516/kudu,projectkudu/kudu,shibayan/kudu,shibayan/kudu,mauricionr/kudu,bbauya/kudu,kenegozi/kudu,badescuga/kudu,kali786516/kudu,duncansmart/kudu,mauricionr/kudu,YOTOV-LIMITED/kudu,EricSten-MSFT/kudu,barnyp/kudu,puneet-gupta/kudu,badescuga/kudu,YOTOV-LIMITED/kudu,projectkudu/kudu,duncansmart/kudu,uQr/kudu,projectkudu/kudu,YOTOV-LIMITED/kudu,chrisrpatterson/kudu,duncansmart/kudu,kenegozi/kudu,oliver-feng/kudu,kali786516/kudu,juoni/kudu,EricSten-MSFT/kudu,sitereactor/kudu,chrisrpatterson/kudu,shrimpy/kudu,oliver-feng/kudu,juvchan/kudu,duncansmart/kudu,oliver-feng/kudu,dev-enthusiast/kudu,juvchan/kudu,projectkudu/kudu,EricSten-MSFT/kudu,barnyp/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,chrisrpatterson/kudu,sitereactor/kudu,juoni/kudu,dev-enthusiast/kudu,bbauya/kudu,shibayan/kudu,puneet-gupta/kudu,badescuga/kudu,barnyp/kudu,MavenRain/kudu,uQr/kudu,juoni/kudu,projectkudu/kudu,badescuga/kudu,juvchan/kudu,uQr/kudu,shibayan/kudu,EricSten-MSFT/kudu
Kudu.Core/Tracing/Analytics.cs
Kudu.Core/Tracing/Analytics.cs
using System; using System.Text; using Kudu.Contracts.Settings; using Kudu.Contracts.Tracing; namespace Kudu.Core.Tracing { public class Analytics : IAnalytics { private readonly SiteExtensionLogManager _siteExtensionLogManager; private readonly IDeploymentSettingsManager _settings; public Analytics(IDeploymentSettingsManager settings, ITracer tracer, string directoryPath) { _settings = settings; _siteExtensionLogManager = new SiteExtensionLogManager(tracer, directoryPath); } public void ProjectDeployed(string projectType, string result, string error, long deploymentDurationInMilliseconds, string siteMode) { var o = new KuduSiteExtensionLogEvent("SiteDeployed"); o["SiteType"] = projectType; o["ScmType"] = _settings.GetValue(SettingsKeys.ScmType); o["Result"] = result; o["Error"] = error; o["Latency"] = deploymentDurationInMilliseconds; o["SiteMode"] = siteMode; _siteExtensionLogManager.Log(o); } public void JobStarted(string jobName, string scriptExtension, string jobType, string siteMode, string error) { var o = new KuduSiteExtensionLogEvent("JobStarted"); o["JobName"] = jobName; o["ScriptExtension"] = scriptExtension; o["JobType"] = jobType; o["SiteMode"] = siteMode; o["Error"] = error; _siteExtensionLogManager.Log(o); } public void UnexpectedException(Exception exception) { var strb = new StringBuilder(); strb.AppendLine(exception.ToString()); var aggregate = exception as AggregateException; if (aggregate != null) { foreach (var inner in aggregate.Flatten().InnerExceptions) { strb.AppendLine(inner.ToString()); } } var o = new KuduSiteExtensionLogEvent("UnexpectedException"); o["Error"] = strb.ToString(); _siteExtensionLogManager.Log(o); } } }
using System; using System.Text; using Kudu.Contracts.Settings; using Kudu.Contracts.Tracing; namespace Kudu.Core.Tracing { public class Analytics : IAnalytics { private readonly SiteExtensionLogManager _siteExtensionLogManager; private readonly IDeploymentSettingsManager _settings; public Analytics(IDeploymentSettingsManager settings, ITracer tracer, string directoryPath) { _settings = settings; _siteExtensionLogManager = new SiteExtensionLogManager(tracer, directoryPath); } public void ProjectDeployed(string projectType, string result, string error, long deploymentDurationInMilliseconds, string siteMode) { var o = new KuduSiteExtensionLogEvent("SiteDeployed"); o["SiteType"] = projectType; o["ScmType"] = _settings.GetValue(SettingsKeys.ScmType); o["Result"] = result; o["Error"] = error; o["Latency"] = deploymentDurationInMilliseconds; o["SiteMode"] = siteMode; _siteExtensionLogManager.Log(o); } public void JobStarted(string jobName, string scriptExtension, string jobType, string siteMode, string error) { var o = new KuduSiteExtensionLogEvent("JobStarted"); o["WebJobsName"] = jobName; o["ScriptExtension"] = scriptExtension; o["WebJobsType"] = jobType; o["SiteMode"] = siteMode; o["Error"] = error; _siteExtensionLogManager.Log(o); } public void UnexpectedException(Exception exception) { var strb = new StringBuilder(); strb.AppendLine(exception.ToString()); var aggregate = exception as AggregateException; if (aggregate != null) { foreach (var inner in aggregate.Flatten().InnerExceptions) { strb.AppendLine(inner.ToString()); } } var o = new KuduSiteExtensionLogEvent("UnexpectedException"); o["Error"] = strb.ToString(); _siteExtensionLogManager.Log(o); } } }
apache-2.0
C#
3249b1269540ea276c3a0c28af207a3cf9830365
Remove shared state
Haacked/Scientist.net
src/Scientist/Internals/InMemoryResultPublisher.cs
src/Scientist/Internals/InMemoryResultPublisher.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GitHub.Internals { public class InMemoryResultPublisher : IResultPublisher { readonly Task _completed = Task.FromResult(0); readonly ConcurrentDictionary<int, ConcurrentBag<object>> _results = new ConcurrentDictionary<int, ConcurrentBag<object>>(); static int GetKey<T, TClean>() { if (typeof(T) == typeof(TClean)) { return typeof(T).TypeHandle.GetHashCode(); } else { return typeof(T).TypeHandle.GetHashCode() ^ typeof(TClean).TypeHandle.GetHashCode(); } } public Task Publish<T, TClean>(Result<T, TClean> result) { _results.AddOrUpdate( GetKey<T, TClean>(), key => new ConcurrentBag<object> { result }, (key, value) => { value.Add(result); return value; }); return _completed; } /// <summary> /// Gets the results of a specific type from the publisher. /// </summary> /// <typeparam name="T">The type of result to get.</typeparam> /// <typeparam name="TClean">the type of cleaned result to get.</typeparam> /// <returns>All results that have the type provided, and have been published.</returns> public IEnumerable<Result<T, TClean>> Results<T, TClean>() { ConcurrentBag<object> bag; // Try to get the list of results. if (_results.TryGetValue(GetKey<T, TClean>(), out bag)) { return bag.Cast<Result<T, TClean>>(); } // Otherwise return nothing. else { return new Result<T, TClean>[0]; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GitHub.Internals { public class InMemoryResultPublisher : IResultPublisher { readonly static Task _completed = Task.FromResult(0); readonly static ConcurrentDictionary<int, ConcurrentBag<object>> _results = new ConcurrentDictionary<int, ConcurrentBag<object>>(); static int GetKey<T, TClean>() { if (typeof(T) == typeof(TClean)) { return typeof(T).TypeHandle.GetHashCode(); } else { return typeof(T).TypeHandle.GetHashCode() ^ typeof(TClean).TypeHandle.GetHashCode(); } } public Task Publish<T, TClean>(Result<T, TClean> result) { _results.AddOrUpdate( GetKey<T, TClean>(), key => new ConcurrentBag<object> { result }, (key, value) => { value.Add(result); return value; }); return _completed; } /// <summary> /// Gets the results of a specific type from the publisher. /// </summary> /// <typeparam name="T">The type of result to get.</typeparam> /// <typeparam name="TClean">the type of cleaned result to get.</typeparam> /// <returns>All results that have the type provided, and have been published.</returns> public IEnumerable<Result<T, TClean>> Results<T, TClean>() { ConcurrentBag<object> bag; // Try to get the list of results. if (_results.TryGetValue(GetKey<T, TClean>(), out bag)) { return bag.Cast<Result<T, TClean>>(); } // Otherwise return nothing. else { return new Result<T, TClean>[0]; } } } }
mit
C#
150b466d8aea4bb864f5d26de45f3584a9ee5ff4
Tweak ObservableTraceListener.
JohanLarsson/Gu.Wpf.FlipView
Gu.Wpf.FlipView.Demo/ObservableTraceListener.cs
Gu.Wpf.FlipView.Demo/ObservableTraceListener.cs
namespace Gu.Wpf.FlipView.Demo { using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; public class ObservableTraceListener : System.Diagnostics.TraceListener { public static readonly ObservableTraceListener Instance = new ObservableTraceListener(); private readonly StringBuilder StringBuilder = new StringBuilder(); private ObservableTraceListener() { Register(PresentationTraceSources.AnimationSource); Register(PresentationTraceSources.DataBindingSource); Register(PresentationTraceSources.DocumentsSource); Register(PresentationTraceSources.DependencyPropertySource); Register(PresentationTraceSources.FreezableSource); Register(PresentationTraceSources.HwndHostSource); Register(PresentationTraceSources.MarkupSource); Register(PresentationTraceSources.NameScopeSource); Register(PresentationTraceSources.ResourceDictionarySource); Register(PresentationTraceSources.RoutedEventSource); Register(PresentationTraceSources.ShellSource); void Register(TraceSource source) { source.Listeners.Add(this); source.Switch.Level = SourceLevels.Warning | SourceLevels.Error; } } public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public static void Initialize() { // NOP ctor runs } public override void Write(string message) { this.StringBuilder.Append(message); } public override void WriteLine(string message) { this.StringBuilder.Append(message); this.Messages.Add(this.StringBuilder.ToString()); this.StringBuilder.Clear(); } } }
namespace Gu.Wpf.FlipView.Demo { using System.Collections.ObjectModel; using System.Diagnostics; public class ObservableTraceListener : System.Diagnostics.TraceListener { public static readonly ObservableTraceListener Instance = new ObservableTraceListener(); private ObservableTraceListener() { PresentationTraceSources.Refresh(); Register(PresentationTraceSources.AnimationSource); Register(PresentationTraceSources.DataBindingSource); Register(PresentationTraceSources.DocumentsSource); Register(PresentationTraceSources.DependencyPropertySource); Register(PresentationTraceSources.FreezableSource); Register(PresentationTraceSources.HwndHostSource); Register(PresentationTraceSources.MarkupSource); Register(PresentationTraceSources.NameScopeSource); Register(PresentationTraceSources.ResourceDictionarySource); Register(PresentationTraceSources.RoutedEventSource); Register(PresentationTraceSources.ShellSource); void Register(TraceSource source) { source.Listeners.Add(this); source.Switch.Level = SourceLevels.Warning | SourceLevels.Error; } } public ObservableCollection<string> Messages { get; } = new ObservableCollection<string>(); public static void Initialize() { // NOP ctor runs } public override void Write(string message) { } public override void WriteLine(string message) { this.Messages.Add(message); } } }
mit
C#
0bfbd5788d9afb78d92c78318968b2db3233d6af
refactor cli to get aguments
stefbast/PackageUseScrutiniser
PackageUseScrutiniser.Cli/Program.cs
PackageUseScrutiniser.Cli/Program.cs
using System; using System.Collections.Generic; using System.IO; using PackageUseScrutiniser.Core; namespace PackageUseScrutiniser.Cli { internal static class Program { static void Main(string[] args) { if (args.Length == 0 || args[0] == "--help" || args.Length > 2) { PrintHelp(); return; } var path = GetPath(args); if (!Directory.Exists(path)) { Console.WriteLine("Path {0} does not exist", path); return; } var packageId = GetPackageId(args); var packageFinder = new PackageFinder(); foreach (var package in packageFinder.GetPackages(packageId, path)) { Console.WriteLine(package); } } private static string GetPath(string[] args) { if (args.Length >= 2) { return args[1]; } return Directory.GetCurrentDirectory(); } private static string GetPackageId(IList<string> args) { if (args.Count >= 1) { return args[0]; } return null; } private static void PrintHelp() { Console.WriteLine("usage: pus <package id> [<path>]"); Console.WriteLine("\tIf no path is defined, uses the current path."); } } }
using System; using System.Collections.Generic; using System.IO; using PackageUseScrutiniser.Core; namespace PackageUseScrutiniser.Cli { class Program { static void Main(string[] args) { IEnumerable<string> packages = new List<string>(); var packageFinder = new PackageFinder(); switch (args.Length) { case 1: if (args[0] == "--help") { PrintHelp(); } packages = packageFinder.GetPackages(Directory.GetCurrentDirectory(), args[0]); break; case 2: packages = packageFinder.GetPackages(args[0], args[1]); break; default: PrintHelp(); break; } foreach (var package in packages) { Console.WriteLine(package); } } private static void PrintHelp() { Console.WriteLine("usage: pus <package id> [<path>]"); Console.WriteLine("\tIf no path is defined, uses the current path."); } } }
mit
C#
72287a9f0a3c969431d4452ba20bc6f7e7a56c04
Update version number
kungfux/business-accounting
BusinessAccounting/BusinessAccounting/Properties/AssemblyInfo.cs
BusinessAccounting/BusinessAccounting/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; 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("Business Accounting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alexander Fuks")] [assembly: AssemblyProduct("Business Accounting")] [assembly: AssemblyCopyright("Copyright © Alexander Fuks 2014-2019")] [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.*")] [assembly: AssemblyVersion("1.4.1.0")] [assembly: AssemblyFileVersion("1.4.1.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; 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("Business Accounting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Alexander Fuks")] [assembly: AssemblyProduct("Business Accounting")] [assembly: AssemblyCopyright("Copyright © Alexander Fuks 2014-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
apache-2.0
C#
4d5a80dabf65ce2dea636018fffbeefec5cb35c3
Fix not pasting stats with no boss name available.
Gl0/CasualMeter,lunyx/CasualMeter
CasualMeter.Common/Formatters/DamageTrackerFormatter.cs
CasualMeter.Common/Formatters/DamageTrackerFormatter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class DamageTrackerFormatter : Formatter { public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty)); placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration))); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CasualMeter.Common.Helpers; using Tera.DamageMeter; namespace CasualMeter.Common.Formatters { public class DamageTrackerFormatter : Formatter { public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers) { var placeHolders = new List<KeyValuePair<string, object>>(); placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name)); placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration))); Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value); FormatProvider = formatHelpers.CultureInfo; } } }
mit
C#
4a89ded6914907573c87b25cb1838eed0a6c7d85
Support to specify UTC and offset separately to setCurrentTimeAsync
naotaco/kz-remote-api,jocieldo/kz-remote-api,kazyx/kz-remote-api
Project/Api/SystemApiClient.cs
Project/Api/SystemApiClient.cs
using System; using System.Threading.Tasks; namespace Kazyx.RemoteApi.System { public class SystemApiClient : ApiClient { /// <summary> /// /// </summary> /// <param name="endpoint">Endpoint URL of system service.</param> public SystemApiClient(Uri endpoint) : base(endpoint) { } public async Task SetCurrentTimeAsync(DateTimeOffset UtcTime, int OffsetInMinute) { var req = new TimeOffset { DateTime = UtcTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), TimeZoneOffsetMinute = OffsetInMinute, DstOffsetMinute = 0 }; await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req)); } } }
using System; using System.Threading.Tasks; namespace Kazyx.RemoteApi.System { public class SystemApiClient : ApiClient { /// <summary> /// /// </summary> /// <param name="endpoint">Endpoint URL of system service.</param> public SystemApiClient(Uri endpoint) : base(endpoint) { } public async Task SetCurrentTimeAsync(DateTimeOffset time) { var req = new TimeOffset { DateTime = time.ToString("yyyy-MM-ddThh:mm:ssZ"), TimeZoneOffsetMinute = (int)(time.Offset.TotalMinutes), DstOffsetMinute = 0 }; await NoValue(RequestGenerator.Serialize("setCurrentTime", ApiVersion.V1_0, req)); } } }
mit
C#
01ce10023a27ca1e60a5669590a81b3294669f5d
Disable Manage Packages menu when project selected.
mrward/monodevelop-nuget-extensions,mrward/monodevelop-nuget-extensions
src/MonoDevelop.PackageManagement.Extensions/MonoDevelop.PackageManagement/ManagePackagesHandler2.cs
src/MonoDevelop.PackageManagement.Extensions/MonoDevelop.PackageManagement/ManagePackagesHandler2.cs
// // ManagePackagesHandler.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using ICSharpCode.PackageManagement; using MonoDevelop.Components.Commands; using MonoDevelop.Ide; using MonoDevelop.PackageManagement.Commands; namespace MonoDevelop.PackageManagement { public class ManagePackagesHandler2 : PackagesCommandHandler { protected override void Run () { try { ManagePackagesViewModel2 viewModel = CreateViewModel (); IPackageManagementEvents packageEvents = PackageManagementServices.PackageManagementEvents; var dialog = new ManagePackagesDialog2 (viewModel, packageEvents); MessageService.ShowCustomDialog (dialog); } catch (Exception ex) { MessageService.ShowException (ex); } } ManagePackagesViewModel2 CreateViewModel () { var packageEvents = new ThreadSafePackageManagementEvents (PackageManagementServices.PackageManagementEvents); var viewModels = new PackagesViewModels2 ( PackageManagementServices.Solution, PackageManagementServices.RegisteredPackageRepositories, packageEvents, PackageManagementServices.PackageActionRunner, new PackageManagementTaskFactory()); return new ManagePackagesViewModel2 ( viewModels, new ManagePackagesViewTitle (PackageManagementServices.Solution), packageEvents); } protected override void Update (CommandInfo info) { info.Enabled = !IsDotNetProjectSelected (); } } }
// // ManagePackagesHandler.cs // // Author: // Matt Ward <ward.matt@gmail.com> // // Copyright (C) 2013 Matthew Ward // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using ICSharpCode.PackageManagement; using MonoDevelop.Ide; using MonoDevelop.PackageManagement.Commands; namespace MonoDevelop.PackageManagement { public class ManagePackagesHandler2 : PackagesCommandHandler { protected override void Run () { try { ManagePackagesViewModel2 viewModel = CreateViewModel (); IPackageManagementEvents packageEvents = PackageManagementServices.PackageManagementEvents; var dialog = new ManagePackagesDialog2 (viewModel, packageEvents); MessageService.ShowCustomDialog (dialog); } catch (Exception ex) { MessageService.ShowException (ex); } } ManagePackagesViewModel2 CreateViewModel () { var packageEvents = new ThreadSafePackageManagementEvents (PackageManagementServices.PackageManagementEvents); var viewModels = new PackagesViewModels2 ( PackageManagementServices.Solution, PackageManagementServices.RegisteredPackageRepositories, packageEvents, PackageManagementServices.PackageActionRunner, new PackageManagementTaskFactory()); return new ManagePackagesViewModel2 ( viewModels, new ManagePackagesViewTitle (PackageManagementServices.Solution), packageEvents); } } }
mit
C#
281c9c7ae9ccc0abaa3e02ecfd0c5e73f27e45d1
disable file watcher
danisein/Wox,danisein/Wox,yozora-hitagi/Saber,Launchify/Launchify,Megasware128/Wox,medoni/Wox,yozora-hitagi/Saber,JohnTheGr8/Wox,Launchify/Launchify,zlphoenix/Wox,medoni/Wox,zlphoenix/Wox,Megasware128/Wox,JohnTheGr8/Wox
Plugins/Wox.Plugin.Program/FileChangeWatcher.cs
Plugins/Wox.Plugin.Program/FileChangeWatcher.cs
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Wox.Infrastructure.Logger; using Wox.Plugin.Program.Programs; namespace Wox.Plugin.Program { //internal static class FileChangeWatcher //{ // private static readonly List<string> WatchedPath = new List<string>(); // // todo remove previous watcher events // public static void AddAll(List<UnregisteredPrograms> sources, string[] suffixes) // { // foreach (var s in sources) // { // if (Directory.Exists(s.Location)) // { // AddWatch(s.Location, suffixes); // } // } // } // public static void AddWatch(string path, string[] programSuffixes, bool includingSubDirectory = true) // { // if (WatchedPath.Contains(path)) return; // if (!Directory.Exists(path)) // { // Log.Warn($"FileChangeWatcher: {path} doesn't exist"); // return; // } // WatchedPath.Add(path); // foreach (string fileType in programSuffixes) // { // FileSystemWatcher watcher = new FileSystemWatcher // { // Path = path, // IncludeSubdirectories = includingSubDirectory, // Filter = $"*.{fileType}", // EnableRaisingEvents = true // }; // watcher.Changed += FileChanged; // watcher.Created += FileChanged; // watcher.Deleted += FileChanged; // watcher.Renamed += FileChanged; // } // } // private static void FileChanged(object source, FileSystemEventArgs e) // { // Task.Run(() => // { // Main.IndexPrograms(); // }); // } //} }
using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Wox.Infrastructure.Logger; using Wox.Plugin.Program.ProgramSources; namespace Wox.Plugin.Program { internal static class FileChangeWatcher { private static readonly List<string> WatchedPath = new List<string>(); // todo remove previous watcher events public static void AddAll(List<UnregisteredPrograms> sources, string[] suffixes) { foreach (var s in sources) { if (Directory.Exists(s.Location)) { AddWatch(s.Location, suffixes); } } } public static void AddWatch(string path, string[] programSuffixes, bool includingSubDirectory = true) { if (WatchedPath.Contains(path)) return; if (!Directory.Exists(path)) { Log.Warn($"FileChangeWatcher: {path} doesn't exist"); return; } WatchedPath.Add(path); foreach (string fileType in programSuffixes) { FileSystemWatcher watcher = new FileSystemWatcher { Path = path, IncludeSubdirectories = includingSubDirectory, Filter = $"*.{fileType}", EnableRaisingEvents = true }; watcher.Changed += FileChanged; watcher.Created += FileChanged; watcher.Deleted += FileChanged; watcher.Renamed += FileChanged; } } private static void FileChanged(object source, FileSystemEventArgs e) { Task.Run(() => { Main.IndexPrograms(); }); } } }
mit
C#
40d933471f84a5b34603e4551b13af2deaca7733
Update Index.cshtml
ravi-msi/practicegit,ravi-msi/practicegit,ravi-msi/practicegit
PracticeGit/PracticeGit/Views/Home/Index.cshtml
PracticeGit/PracticeGit/Views/Home/Index.cshtml
<div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p>ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301870">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301871">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301872">Learn more &raquo;</a></p> </div> </div> <div class="row"> New row -- added text </div>
<div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p>ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301870">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301871">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301872">Learn more &raquo;</a></p> </div> </div> <div class="row"> New row </div>
mit
C#
02768e1b8516d7e85488ad93268f20a109f2eacc
update version
prodot/ReCommended-Extension
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
Sources/ReCommendedExtension/Properties/AssemblyInfo.cs
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.0.1.0")] [assembly: AssemblyFileVersion("4.0.1")]
using System.Reflection; using ReCommendedExtension; // 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(ZoneMarker.ExtensionName)] [assembly: AssemblyDescription(ZoneMarker.ExtensionDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("prodot GmbH")] [assembly: AssemblyProduct(ZoneMarker.ExtensionId)] [assembly: AssemblyCopyright("© 2012-2020 prodot GmbH")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0")]
apache-2.0
C#
c079409597d05ce9b4b41e8b40f5c365da1a369f
remove unid check
JackCeparou/JackCeparouCompass
Items/RamaladniDropFixPlugin.cs
Items/RamaladniDropFixPlugin.cs
namespace Turbo.Plugins.Jack.Items { using System.Linq; using Turbo.Plugins.Default; using Turbo.Plugins.Jack.TextToSpeech; public class RamaladniDropFixPlugin : BasePlugin, IAfterCollectHandler { public SoundAlert<IItem> SoundAlert { get; private set; } public RamaladniDropFixPlugin() { Enabled = true; SoundAlert = SoundAlertFactory.Create<IItem>((item) => item.SnoItem.NameLocalized); } public void AfterCollect() { var gifts = Hud.Game.Items.Where(item => item.SnoItem.Sno == 1844495708 && item.Location == ItemLocation.Floor && item.LastSpeak == null /*&& item.Unidentified/*.*/); foreach (var gift in gifts) { SoundAlertManagerPlugin.Register<IItem>(gift, SoundAlert); } } } }
namespace Turbo.Plugins.Jack.Items { using System.Linq; using Turbo.Plugins.Default; using Turbo.Plugins.Jack.TextToSpeech; public class RamaladniDropFixPlugin : BasePlugin, IAfterCollectHandler { public SoundAlert<IItem> SoundAlert { get; private set; } public RamaladniDropFixPlugin() { Enabled = true; SoundAlert = SoundAlertFactory.Create<IItem>((item) => item.SnoItem.NameLocalized); } public void AfterCollect() { var gifts = Hud.Game.Items.Where(item => item.SnoItem.Sno == 1844495708 && item.Location == ItemLocation.Floor && item.LastSpeak == null && item.Unidentified/*.*/); foreach (var gift in gifts) { SoundAlertManagerPlugin.Register<IItem>(gift, SoundAlert); } } } }
mit
C#
9c38d78eacc40ace221eb0410c7c7e40b17ce75e
rename tuple test for starmap
jmrnilsson/itertools
Itertools/Tests/StarmapTests.cs
Itertools/Tests/StarmapTests.cs
using System; using System.Linq; using Xunit; namespace Itertools.Tests { internal delegate dynamic Area(string name, int width, decimal height); public class StarmapTests { [Fact] public void StarmapFor2Tuple() { var iterable0 = new[] {Tuple.Create(1, "first"), Tuple.Create(3, "second")}; var actual = Itertools.Starmap((a, b) => $"{a}{b}", iterable0); Assert.StrictEqual("1first3second", string.Join("", actual)); } [Fact] public void Starmap3Tuple() { Func<string, int, decimal, dynamic> action = (name, width, height) => new { name, area = width * height }; var iterable0 = new[] {Tuple.Create("A", 101, 1.2m), Tuple.Create("B", 3, .3m)}; var actual = Itertools.Starmap(action, iterable0).ToList(); Assert.Equal("A", actual[0].name); Assert.Equal(101 * 1.2m, actual[0].area); Assert.Equal("B", actual[1].name); Assert.Equal(3 * .3m, actual[1].area); } } }
using System; using System.Linq; using Xunit; namespace Itertools.Tests { internal delegate dynamic Area(string name, int width, decimal height); public class StarmapTests { [Fact] public void Starmap() { var iterable0 = new[] {Tuple.Create(1, "first"), Tuple.Create(3, "second")}; var actual = Itertools.Starmap((a, b) => $"{a}{b}", iterable0); Assert.StrictEqual("1first3second", string.Join("", actual)); } [Fact] public void StarmapWithLambda() { Func<string, int, decimal, dynamic> action = (name, width, height) => new { name, area = width * height }; var iterable0 = new[] {Tuple.Create("A", 101, 1.2m), Tuple.Create("B", 3, .3m)}; var actual = Itertools.Starmap(action, iterable0).ToList(); Assert.Equal("A", actual[0].name); Assert.Equal(101 * 1.2m, actual[0].area); Assert.Equal("B", actual[1].name); Assert.Equal(3 * .3m, actual[1].area); } } }
mit
C#
ee45e781521fe1419804a655ffbe619209e38de2
revert test config
NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework,NakedObjectsGroup/NakedObjectsFramework
Spa2/NakedObjects.Spa.Selenium.Test/tests/TestConfig.cs
Spa2/NakedObjects.Spa.Selenium.Test/tests/TestConfig.cs
 namespace NakedObjects.Selenium { public static class TestConfig { //public const string BaseUrl = "http://localhost:49998/"; public const string BaseUrl = "http://nakedobjectstest2.azurewebsites.net/"; } }
 namespace NakedObjects.Selenium { public static class TestConfig { public const string BaseUrl = "http://localhost:49998/"; //public const string BaseUrl = "http://nakedobjectstest2.azurewebsites.net/"; } }
apache-2.0
C#
0f83308f7b1c18ebca3c89333954e26e34be2b56
Update osu!taiko TestSceneInputDrum with InputDrum changes for touch controls
ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneInputDrum.cs
osu.Game.Rulesets.Taiko.Tests/Skinning/TestSceneInputDrum.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Taiko.UI; using osuTK; namespace osu.Game.Rulesets.Taiko.Tests.Skinning { [TestFixture] public class TestSceneInputDrum : TaikoSkinnableTestScene { [BackgroundDependencyLoader] private void load() { var playfield = new TaikoPlayfield(); var beatmap = CreateWorkingBeatmap(new TaikoRuleset().RulesetInfo).GetPlayableBeatmap(new TaikoRuleset().RulesetInfo); foreach (var h in beatmap.HitObjects) playfield.Add(h); SetContents(_ => new TaikoInputManager(new TaikoRuleset().RulesetInfo) { RelativeSizeAxes = Axes.Both, Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200), Child = new InputDrum() } }); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Taiko.UI; using osuTK; namespace osu.Game.Rulesets.Taiko.Tests.Skinning { [TestFixture] public class TestSceneInputDrum : TaikoSkinnableTestScene { [BackgroundDependencyLoader] private void load() { var playfield = new TaikoPlayfield(); var beatmap = CreateWorkingBeatmap(new TaikoRuleset().RulesetInfo).GetPlayableBeatmap(new TaikoRuleset().RulesetInfo); foreach (var h in beatmap.HitObjects) playfield.Add(h); SetContents(_ => new TaikoInputManager(new TaikoRuleset().RulesetInfo) { RelativeSizeAxes = Axes.Both, Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(200), Child = new InputDrum(playfield.HitObjectContainer) } }); } } }
mit
C#
781064ba9693c72adda2d84f8a81deba782f9888
create list marker based on its level
peppy/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Graphics/Containers/Markdown/OsuMarkdownListItem.cs
osu.Game/Graphics/Containers/Markdown/OsuMarkdownListItem.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osuTK; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownListItem : CompositeDrawable { private readonly int level; private const float default_left_padding = 20; [Resolved] private IMarkdownTextComponent parentTextComponent { get; set; } public FillFlowContainer Content { get; } public OsuMarkdownListItem(int level) { this.level = level; AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; Padding = new MarginPadding { Left = default_left_padding }; InternalChildren = new Drawable[] { Content = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Spacing = new Vector2(10, 10), } }; } [BackgroundDependencyLoader] private void load() { var marker = parentTextComponent.CreateSpriteText(); marker.Text = createTextMarker(); marker.Font = OsuFont.GetFont(size: marker.Font.Size / 2); marker.Origin = Anchor.Centre; marker.X = -default_left_padding / 2; marker.Y = marker.Font.Size; AddInternal(marker); } private string createTextMarker() { switch (level) { case 1: return "●"; case 2: return "○"; default: return "■"; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Containers.Markdown; using osuTK; namespace osu.Game.Graphics.Containers.Markdown { public class OsuMarkdownListItem : CompositeDrawable { private readonly int level; private const float default_left_padding = 20; [Resolved] private IMarkdownTextComponent parentTextComponent { get; set; } public FillFlowContainer Content { get; } public OsuMarkdownListItem(int level) { this.level = level; AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; Padding = new MarginPadding { Left = default_left_padding }; InternalChildren = new Drawable[] { Content = new FillFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Direction = FillDirection.Vertical, Spacing = new Vector2(10, 10), } }; } [BackgroundDependencyLoader] private void load() { var marker = parentTextComponent.CreateSpriteText(); marker.Text = "●"; marker.Font = OsuFont.GetFont(size: marker.Font.Size / 2); marker.Origin = Anchor.Centre; marker.X = -default_left_padding / 2; marker.Y = marker.Font.Size; AddInternal(marker); } } }
mit
C#
59e5b937c6d3fa2a9d644081793791f46da5cfdb
Update RuleUpdater.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/RuleUpdater.cs
ProcessBlockUtil/RuleUpdater.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Version message. */ Console.WriteLine("AC PBU RuleUpdater V1.0.1"); Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung"); Console.WriteLine(" "); Console.WriteLine("The process is starting, please make sure the program running."); /* Stop The Service. */ Console.WriteLine("Stopping Service...."); ServiceController pbuSC = new ServiceController("pbuService"); pbuSC.Stop(); pbuSC.WaitForStatus(ServiceControllerStatus.Stopped); /* Obtain some path. */ String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete and copy Exist file. */ if(File.Exists(userProfile + "\\ACRules.txt")){ File.Copy(userProfile + "\\ACRules.txt", userProfile + "\\ACRules_Backup.txt"); File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Console.WriteLine("Restarting Service...."); pbuSC.Start(); pbuSC.WaitForStatus(ServiceControllerStatus.Running); } } }
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Diagnostics; using System.ServiceProcess; using System.Threading; using NetUtil; namespace ACProcessBlockUtil { class RuleUpdater { public static void Main(String[] a){ /* Version message. */ Console.WriteLine("AC PBU RuleUpdater V1.0.1"); Console.WriteLine("Copyright (C) 2011-2014 AC Inc. (Andy Cheung"); Console.WriteLine(" "); Console.WriteLine("The process is starting, please make sure the program running."); /* Stop The Service. */ Console.WriteLine("Stopping Service...."); ServiceController pbuSC = new ServiceController("pbuService"); pbuSC.Stop(); pbuSC.WaitForStatus(ServiceControllerStatus.Stopped); /* Obtain some path. */ String userProfile = Environment.GetEnvironmentVariable("UserProfile"); String systemRoot = Environment.GetEnvironmentVariable("SystemRoot"); /* Delete and copy Exist file. */ if(File.Exists(userProfile + "\\ACRules.txt")){ File.Delete(userProfile + "\\ACRules.txt"); } /* Download File. */ NetUtil.writeToFile("http://win120a.github.io/Api/PBURules.txt", userProfile + "\\ACRules.txt"); /* Restart the Service. */ Console.WriteLine("Restarting Service...."); pbuSC.Start(); pbuSC.WaitForStatus(ServiceControllerStatus.Running); } } }
apache-2.0
C#
e42a85ea334d07ae9c04c03c61e4e77066f353cf
Add more checks to TwitterRespository's AnyTwitterAuthenticationSettingsAreNotSet method which not only check against the default values provided for each authentication credential ("[twitterconsumerkey]", etc...), but also checks for string.Empty for OAuthToken and OAuthSecret
MisterJames/allReady,VishalMadhvani/allReady,BillWagner/allReady,enderdickerson/allReady,binaryjanitor/allReady,chinwobble/allReady,c0g1t8/allReady,chinwobble/allReady,colhountech/allReady,bcbeatty/allReady,bcbeatty/allReady,dpaquette/allReady,mipre100/allReady,forestcheng/allReady,MisterJames/allReady,jonatwabash/allReady,dpaquette/allReady,shanecharles/allReady,gitChuckD/allReady,anobleperson/allReady,c0g1t8/allReady,HamidMosalla/allReady,chinwobble/allReady,jonatwabash/allReady,GProulx/allReady,HTBox/allReady,shanecharles/allReady,forestcheng/allReady,HTBox/allReady,stevejgordon/allReady,chinwobble/allReady,GProulx/allReady,HTBox/allReady,stevejgordon/allReady,JowenMei/allReady,mipre100/allReady,dpaquette/allReady,mgmccarthy/allReady,jonatwabash/allReady,gitChuckD/allReady,enderdickerson/allReady,anobleperson/allReady,VishalMadhvani/allReady,shanecharles/allReady,c0g1t8/allReady,GProulx/allReady,arst/allReady,binaryjanitor/allReady,colhountech/allReady,JowenMei/allReady,arst/allReady,HamidMosalla/allReady,enderdickerson/allReady,HamidMosalla/allReady,HamidMosalla/allReady,pranap/allReady,arst/allReady,gitChuckD/allReady,bcbeatty/allReady,HTBox/allReady,binaryjanitor/allReady,stevejgordon/allReady,pranap/allReady,colhountech/allReady,enderdickerson/allReady,jonatwabash/allReady,BillWagner/allReady,pranap/allReady,binaryjanitor/allReady,shanecharles/allReady,VishalMadhvani/allReady,bcbeatty/allReady,VishalMadhvani/allReady,anobleperson/allReady,forestcheng/allReady,arst/allReady,JowenMei/allReady,BillWagner/allReady,BillWagner/allReady,MisterJames/allReady,mipre100/allReady,GProulx/allReady,MisterJames/allReady,JowenMei/allReady,mgmccarthy/allReady,mgmccarthy/allReady,stevejgordon/allReady,dpaquette/allReady,pranap/allReady,mgmccarthy/allReady,forestcheng/allReady,colhountech/allReady,c0g1t8/allReady,anobleperson/allReady,gitChuckD/allReady,mipre100/allReady
AllReadyApp/Web-App/AllReady/Providers/ExternalUserInformationProviders/Providers/TwitterRepository.cs
AllReadyApp/Web-App/AllReady/Providers/ExternalUserInformationProviders/Providers/TwitterRepository.cs
using System.Linq; using System.Threading.Tasks; using LinqToTwitter; using Microsoft.Extensions.Options; namespace AllReady.Providers.ExternalUserInformationProviders.Providers { public class TwitterRepository : ITwitterRepository { private readonly IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings; public TwitterRepository(IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings) { this.twitterAuthenticationSettings = twitterAuthenticationSettings; } public async Task<Account> GetTwitterAccount(string userId, string screenName) { if (AnyTwitterAuthenticationSettingsAreNotSet()) { return null; } var authTwitter = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey, ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret, OAuthToken = twitterAuthenticationSettings.Value.OAuthToken, OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret, UserID = ulong.Parse(userId), ScreenName = screenName } }; await authTwitter.AuthorizeAsync(); var twitterContext = new TwitterContext(authTwitter); //VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work var account = await (from acct in twitterContext.Account where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true) select acct).SingleOrDefaultAsync(); return account; } private bool AnyTwitterAuthenticationSettingsAreNotSet() { return twitterAuthenticationSettings.Value.ConsumerKey == "[twitterconsumerkey]" || twitterAuthenticationSettings.Value.ConsumerSecret == "[twitterconsumersecret]" || twitterAuthenticationSettings.Value.OAuthToken == "[twitteroauthtoken]" || twitterAuthenticationSettings.Value.OAuthSecret == "[twitteroauthsecret]" || twitterAuthenticationSettings.Value.OAuthToken == string.Empty || twitterAuthenticationSettings.Value.OAuthSecret == string.Empty; } } }
using System.Linq; using System.Threading.Tasks; using LinqToTwitter; using Microsoft.Extensions.Options; namespace AllReady.Providers.ExternalUserInformationProviders.Providers { public class TwitterRepository : ITwitterRepository { private readonly IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings; public TwitterRepository(IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings) { this.twitterAuthenticationSettings = twitterAuthenticationSettings; } public async Task<Account> GetTwitterAccount(string userId, string screenName) { if (AnyTwitterAuthenticationSettingsAreNotSet()) { return null; } var authTwitter = new SingleUserAuthorizer { CredentialStore = new SingleUserInMemoryCredentialStore { ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey, ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret, OAuthToken = twitterAuthenticationSettings.Value.OAuthToken, OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret, UserID = ulong.Parse(userId), ScreenName = screenName } }; await authTwitter.AuthorizeAsync(); var twitterCtx = new TwitterContext(authTwitter); //VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work var account = await (from acct in twitterCtx.Account where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true) select acct).SingleOrDefaultAsync(); return account; } private bool AnyTwitterAuthenticationSettingsAreNotSet() { return twitterAuthenticationSettings.Value.ConsumerKey == "[twitterconsumerkey]" || twitterAuthenticationSettings.Value.ConsumerSecret == "[twitterconsumersecret]" || twitterAuthenticationSettings.Value.OAuthToken == "[twitteroauthtoken]" || twitterAuthenticationSettings.Value.OAuthSecret == "[twitteroauthsecret]"; } } }
mit
C#
709bde80b97e32ba655ba5148c16f0d90a4aec77
Fix unit test
mono/mono-addins,mono/mono-addins
Test/UnitTests/ExtensionModel/GlobalInfoConditionAttribute.cs
Test/UnitTests/ExtensionModel/GlobalInfoConditionAttribute.cs
// // GlobalInfoConditionAttribute.cs // // Copyright (c) Microsoft Corp. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Mono.Addins; namespace SimpleApp { public class GlobalInfoConditionAttribute : CustomConditionAttribute { public GlobalInfoConditionAttribute ([NodeAttribute("value")]string value) { this.Value = value; } [NodeAttribute("value")] public string Value { get; set; } } }
// // GlobalInfoConditionAttribute.cs // // Copyright (c) Microsoft Corp. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Mono.Addins; namespace SimpleApp { public class GlobalInfoConditionAttribute : CustomConditionAttribute { public GlobalInfoConditionAttribute ([NodeAttribute("value")]string value) { } [NodeAttribute("value")] public string Value { get; set; } } }
mit
C#
06e2e109732d76a75620b1ad941a196cce97f5f0
Update OrganizationXrmUtility.cs
saeid64/TFSHelper
Tosan.TeamFoundation.Plugin/Utility/OrganizationXrmUtility.cs
Tosan.TeamFoundation.Plugin/Utility/OrganizationXrmUtility.cs
using System; using System.Configuration; using System.Runtime.Caching; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Services; using Microsoft.Xrm.Sdk; namespace Tosan.TeamFoundation.Plugin.Core.Utility { class OrganizationXrmUtility { internal static IOrganizationService GetOrganizationService() { try { var connection = new CrmConnection(new ConnectionStringSettings("xrm", @"")) { ServiceUri = new Uri(@"") }; var myObjectCache = MemoryCache.Default; var myServiceCache = new OrganizationServiceCache(myObjectCache, connection); return new CachedOrganizationService(connection, myServiceCache); } catch (Exception) { throw; } } } }
using System; using System.Configuration; using System.Runtime.Caching; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Services; using Microsoft.Xrm.Sdk; namespace Tosan.TeamFoundation.Plugin.Core.Utility { class OrganizationXrmUtility { internal static IOrganizationService GetOrganizationService() { try { var connection = new CrmConnection(new ConnectionStringSettings("xrm", @"Url=https://crm2011.tosanltd.com/Tosan;Domain=tosanltd.com; Username=tfs; Password=hsb_1234;")) { ServiceUri = new Uri(@"https://crm2011.tosanltd.com/Tosan/XRMServices/2011/Organization.svc") }; var myObjectCache = MemoryCache.Default; var myServiceCache = new OrganizationServiceCache(myObjectCache, connection); return new CachedOrganizationService(connection, myServiceCache); } catch (Exception) { throw; } } } }
apache-2.0
C#
1d5e4eda7ef073781ae98c3a15ee0113b71e5e42
Trim down data returned from API
kgiszewski/Archetype,tomfulton/Archetype,kjac/Archetype,kgiszewski/Archetype,kipusoep/Archetype,Nicholas-Westby/Archetype,Nicholas-Westby/Archetype,tomfulton/Archetype,kjac/Archetype,kgiszewski/Archetype,imulus/Archetype,tomfulton/Archetype,kjac/Archetype,kipusoep/Archetype,imulus/Archetype,Nicholas-Westby/Archetype,kipusoep/Archetype,imulus/Archetype
app/Umbraco/Umbraco.Archetype/Api/ArchetypeDataTypeController.cs
app/Umbraco/Umbraco.Archetype/Api/ArchetypeDataTypeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; using AutoMapper; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Mapping; using Umbraco.Web.Mvc; using Umbraco.Web.Editors; namespace Archetype.Umbraco.Api { [PluginController("ArchetypeApi")] public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController { //pulled from the Core public object GetById(int id) { var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id); if (dataType == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } var dataTypeDisplay = Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType); return new { selectedEditor = dataTypeDisplay.SelectedEditor, preValues = dataTypeDisplay.PreValues }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; using AutoMapper; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Models.Mapping; using Umbraco.Web.Mvc; using Umbraco.Web.Editors; namespace Archetype.Umbraco.Api { [PluginController("ArchetypeApi")] public class ArchetypeDataTypeController : UmbracoAuthorizedJsonController { //pulled from the Core public DataTypeDisplay GetById(int id) { var dataType = Services.DataTypeService.GetDataTypeDefinitionById(id); if (dataType == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<IDataTypeDefinition, DataTypeDisplay>(dataType); } } }
mit
C#
3a4b42ba9cd96b3ceaa585297eff41fe91b44871
Rollback mistakenly committed commented lines
couchbase/couchbase-lite-net,couchbase/couchbase-lite-net,couchbase/couchbase-lite-net
src/Couchbase.Lite.Tests.iOS/AppDelegate.cs
src/Couchbase.Lite.Tests.iOS/AppDelegate.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Foundation; using UIKit; using Xunit.Runner; using Xunit.Runners.UI; using Xunit.Sdk; namespace Couchbase.Lite.Tests.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : RunnerAppDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Couchbase.Lite.Support.iOS.Activate(); // We need this to ensure the execution assembly is part of the app bundle AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly); // tests can be inside the main assembly AddTestAssembly(Assembly.GetExecutingAssembly()); AutoStart = true; TerminateAfterExecution = true; using (var str = GetType().Assembly.GetManifestResourceStream("result_ip")) using (var sr = new StreamReader(str)) { Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345); } return base.FinishedLaunching(app, options); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Foundation; using UIKit; using Xunit.Runner; using Xunit.Runners.UI; using Xunit.Sdk; namespace Couchbase.Lite.Tests.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : RunnerAppDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { Couchbase.Lite.Support.iOS.Activate(); // We need this to ensure the execution assembly is part of the app bundle AddExecutionAssembly(typeof(ExtensibilityPointFactory).Assembly); // tests can be inside the main assembly AddTestAssembly(Assembly.GetExecutingAssembly()); //AutoStart = true; //TerminateAfterExecution = true; //using (var str = GetType().Assembly.GetManifestResourceStream("result_ip")) //using (var sr = new StreamReader(str)) { // Writer = new TcpTextWriter(sr.ReadToEnd().TrimEnd(), 12345); //} return base.FinishedLaunching(app, options); } } }
apache-2.0
C#
654368ad5866fa0f7b57d933ff80afc9c6764ce9
Use Application Insights
duracellko/planningpoker4azure,duracellko/planningpoker4azure,duracellko/planningpoker4azure
src/Duracellko.PlanningPoker.Web/Program.cs
src/Duracellko.PlanningPoker.Web/Program.cs
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace Duracellko.PlanningPoker.Web { public static class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseApplicationInsights() .UseStartup<Startup>(); } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace Duracellko.PlanningPoker.Web { public static class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
mit
C#
7e126fc997d1b7a9282124550445f60857488492
Add accelerometer controls
theDrake/unity-experiments
SpaceShooter/Assets/Scripts/PlayerController.cs
SpaceShooter/Assets/Scripts/PlayerController.cs
using UnityEngine; using System.Collections; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public class PlayerController : MonoBehaviour { public float speed, tilt, fireRate; public Boundary boundary; public GameObject shot; public Transform shotSpawn; private float lastShotTime; private Rigidbody rb; private Quaternion calibrationQuaternion; void Start() { rb = GetComponent<Rigidbody>(); CalibrateAccelerometer(); } void Update() { if (Input.GetButton("Fire1") && Time.time > lastShotTime + fireRate) { Instantiate(shot, shotSpawn.position, shotSpawn.rotation); GetComponent<AudioSource>().Play(); lastShotTime = Time.time; } } void FixedUpdate() { //float moveHorizontal = Input.GetAxis("Horizontal"); //float moveVertical = Input.GetAxis("Vertical"); //Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); Vector3 acceleration = calibrationQuaternion * Input.acceleration; Vector3 movement = new Vector3(acceleration.x, 0.0f, acceleration.y); rb.velocity = movement * speed; rb.position = new Vector3 ( Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax) ); rb.rotation = Quaternion.Euler ( 0.0f, 0.0f, rb.velocity.x * tilt ); } void CalibrateAccelerometer() { Vector3 accelerationSnapshot = Input.acceleration; Quaternion rotateQuaternion = Quaternion.FromToRotation(new Vector3(0.0f, 0.0f, -1.0f), accelerationSnapshot); calibrationQuaternion = Quaternion.Inverse(rotateQuaternion); } }
using UnityEngine; using System.Collections; [System.Serializable] public class Boundary { public float xMin, xMax, zMin, zMax; } public class PlayerController : MonoBehaviour { public float speed, tilt, fireRate; public Boundary boundary; public GameObject shot; public Transform shotSpawn; private float lastShotTime; private Rigidbody rb; void Start() { rb = GetComponent<Rigidbody>(); } void Update() { if (Input.GetButton("Fire1") && Time.time > lastShotTime + fireRate) { Instantiate(shot, shotSpawn.position, shotSpawn.rotation); GetComponent<AudioSource>().Play(); lastShotTime = Time.time; } } void FixedUpdate() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); rb.velocity = movement * speed; rb.position = new Vector3 ( Mathf.Clamp(rb.position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(rb.position.z, boundary.zMin, boundary.zMax) ); rb.rotation = Quaternion.Euler ( 0.0f, 0.0f, rb.velocity.x * tilt ); } }
mit
C#
bd85eab3e37627572be2c851ad97a23af53db566
Bump version to 0.10.1
whampson/bft-spec,whampson/cascara
Src/WHampson.Cascara/Properties/AssemblyInfo.cs
Src/WHampson.Cascara/Properties/AssemblyInfo.cs
#region License /* Copyright (c) 2017 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WHampson.Cascara")] [assembly: AssemblyDescription("Binary File Template parser.")] [assembly: AssemblyProduct("WHampson.Cascara")] [assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")] [assembly: AssemblyFileVersion("0.10.1")] [assembly: AssemblyVersion("0.10.1")] [assembly: AssemblyInformationalVersion("0.10.1")]
#region License /* Copyright (c) 2017 Wes Hampson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #endregion using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WHampson.Cascara")] [assembly: AssemblyDescription("Binary File Template parser.")] [assembly: AssemblyProduct("WHampson.Cascara")] [assembly: AssemblyCopyright("Copyright (c) 2017 Wes Hampson")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2cc76928-f34e-4a9b-8623-1ccc543005c0")] [assembly: AssemblyFileVersion("0.10.0")] [assembly: AssemblyVersion("0.10.0")] [assembly: AssemblyInformationalVersion("0.10.0")]
mit
C#
a791a7d67cde677c7c9fd8a26692f7ff9ee0b1ec
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.TimeZoneInformation/ValuesOut.cs
RegistryPlugin.TimeZoneInformation/ValuesOut.cs
using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TimeZoneInformation { public class ValuesOut:IValueOut { public ValuesOut(string valueName, string valueData, string valueDataRaw) { ValueName = valueName; ValueData = valueData; ValueDataRaw = valueDataRaw; } public string ValueName { get; } public string ValueData { get; } public string ValueDataRaw { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => ValueData; public string BatchValueData2 => ValueDataRaw; public string BatchValueData3 => string.Empty; } }
using RegistryPluginBase.Interfaces; namespace RegistryPlugin.TimeZoneInformation { public class ValuesOut:IValueOut { public ValuesOut(string valueName, string valueData, string valueDataRaw) { ValueName = valueName; ValueData = valueData; ValueDataRaw = valueDataRaw; } public string ValueName { get; } public string ValueData { get; } public string ValueDataRaw { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => ValueData; public string BatchValueData2 => ValueDataRaw; public string BatchValueData3 => string.Empty; } }
mit
C#
d94315ee3f320c4edcc562c642dabcd63ecceebd
Fix potential crash from unsafe drawable mutation in scoreboard update code
NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu
osu.Game/Screens/OnlinePlay/Match/Components/MatchLeaderboard.cs
osu.Game/Screens/OnlinePlay/Match/Components/MatchLeaderboard.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.API; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Leaderboards; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Match.Components { public class MatchLeaderboard : Leaderboard<MatchLeaderboardScope, APIUserScoreAggregate> { [Resolved(typeof(Room), nameof(Room.RoomID))] private Bindable<long?> roomId { get; set; } [BackgroundDependencyLoader] private void load() { roomId.BindValueChanged(id => { if (id.NewValue == null) return; SetScores(null); RefetchScores(); }, true); } protected override bool IsOnlineScope => true; protected override APIRequest FetchScores(CancellationToken cancellationToken) { if (roomId.Value == null) return null; var req = new GetRoomLeaderboardRequest(roomId.Value ?? 0); req.Success += r => Schedule(() => { if (cancellationToken.IsCancellationRequested) return; SetScores(r.Leaderboard, r.UserScore); }); return req; } protected override LeaderboardScore CreateDrawableScore(APIUserScoreAggregate model, int index) => new MatchLeaderboardScore(model, index); protected override LeaderboardScore CreateDrawableTopScore(APIUserScoreAggregate model) => new MatchLeaderboardScore(model, model.Position, false); } public enum MatchLeaderboardScope { Overall } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Threading; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Online.API; using osu.Game.Online.API.Requests.Responses; using osu.Game.Online.Leaderboards; using osu.Game.Online.Rooms; namespace osu.Game.Screens.OnlinePlay.Match.Components { public class MatchLeaderboard : Leaderboard<MatchLeaderboardScope, APIUserScoreAggregate> { [Resolved(typeof(Room), nameof(Room.RoomID))] private Bindable<long?> roomId { get; set; } [BackgroundDependencyLoader] private void load() { roomId.BindValueChanged(id => { if (id.NewValue == null) return; SetScores(null); RefetchScores(); }, true); } protected override bool IsOnlineScope => true; protected override APIRequest FetchScores(CancellationToken cancellationToken) { if (roomId.Value == null) return null; var req = new GetRoomLeaderboardRequest(roomId.Value ?? 0); req.Success += r => { if (cancellationToken.IsCancellationRequested) return; SetScores(r.Leaderboard, r.UserScore); }; return req; } protected override LeaderboardScore CreateDrawableScore(APIUserScoreAggregate model, int index) => new MatchLeaderboardScore(model, index); protected override LeaderboardScore CreateDrawableTopScore(APIUserScoreAggregate model) => new MatchLeaderboardScore(model, model.Position, false); } public enum MatchLeaderboardScope { Overall } }
mit
C#
254b273c70ffc5226220be02028bb86e26d09a35
Revert "revert logging config causing bug"
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
api/FilterLists.Api/Startup.cs
api/FilterLists.Api/Startup.cs
using FilterLists.Api.DependencyInjection.Extensions; using FilterLists.Data.DependencyInjection.Extensions; using FilterLists.Services.DependencyInjection.Extensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace FilterLists.Api { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", false, true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true) .AddEnvironmentVariables(); Configuration = builder.Build(); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.RegisterFilterListsRepositories(Configuration); services.RegisterFilterListsServices(); services.RegisterFilterListsApi(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); } } }
using FilterLists.Api.DependencyInjection.Extensions; using FilterLists.Data.DependencyInjection.Extensions; using FilterLists.Services.DependencyInjection.Extensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace FilterLists.Api { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", false, true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.RegisterFilterListsRepositories(Configuration); services.RegisterFilterListsServices(); services.RegisterFilterListsApi(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); //TODO: maybe move to Startup() per Scott Allen loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); } } }
mit
C#
e1f0bc5598f8d7bccd8deb30990b23e61231e0f8
Fix display issue on edit page
jugglingnutcase/Wollump
Wollump/web/views/edit.cshtml
Wollump/web/views/edit.cshtml
@{ Layout = "_Layout.cshtml"; } @section title { Edit @Model.Name } @section styles { <style> .page-content { width: 100%; height: 400px; } </style> } @section content { <div class="pure-g-r"> <div class="pure-u-1"> <form class="pure-form pure-form-stacked" method="post" action="/edit/@Model.Name"> <fieldset> <legend>Edit @Model.Name</legend> <div class="pure-g-r"> <div class="pure-u-1-2"> <label for="content">Content</label><br /> <textarea class="page-content" name="content">@Model.Content</textarea> </div> </div> <div class="pure-g-r"> <div class="pure-u-1-2"> <label> Edit Summary <small>(Briefly describe the changes you have made)</small><br /> <input type="text" class="text" name="message" /> </label> </div> </div> <button type="submit" class="pure-button pure-button-primary">Save page</button> </fieldset> </form> </div> </div> }
@{ Layout = "_Layout.cshtml"; } @section title { Edit @Model.Name } @section styles { <style> .page-content { width: 100%; height: 400px; } </style> } @section content { <div class="pure-g-r"> <div class="pure-u-1-1"> <form class="pure-form pure-form-stacked" method="post" action="/edit/@Model.Name"> <fieldset> <legend>Edit @Model.Name</legend> <div class="pure-g-r"> <div class="pure-u-1-2"> <label for="content">Content</label><br /> <textarea class="page-content" name="content">@Model.Content</textarea> </div> </div> <div class="pure-g-r"> <div class="pure-u-1-2"> <label> Edit Summary <small>(Briefly describe the changes you have made)</small><br /> <input type="text" class="text" name="message" /> </label> </div> </div> <button type="submit" class="pure-button pure-button-primary">Save page</button> </fieldset> </form> </div> </div> }
mit
C#
d1113b26d1c7544b57e85e1dee08c358b90d42ee
Improve exception messages
rvernagus/NBenchmarker
src/NBenchmarker/NBenchmarker/BenchmarkResult.cs
src/NBenchmarker/NBenchmarker/BenchmarkResult.cs
using System; namespace NBenchmarker { public class BenchmarkResult { private TimeSpan _elapsedTime; private int _numberOfIterations; public BenchmarkResult(string trialName) { this.TrialName = trialName; this.ElapsedTime = TimeSpan.Zero; this.NumberOfIterations = 0; } public string TrialName { get; private set; } public TimeSpan ElapsedTime { get { return _elapsedTime; } set { if (value < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("value", value, "ElapsedTime cannot be less than TimeSpan.Zero"); } else { _elapsedTime = value; } } } public int NumberOfIterations { get { return _numberOfIterations; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", value, "NumberOfIterations cannot be less than 0"); } else { _numberOfIterations = value; } } } public TimeSpan IterationAverageDuration { get { var avgTicks = this.ElapsedTime.Ticks / this.NumberOfIterations; return TimeSpan.FromTicks(avgTicks); } } } }
using System; namespace NBenchmarker { public class BenchmarkResult { private TimeSpan _elapsedTime; private int _numberOfIterations; public BenchmarkResult(string trialName) { this.TrialName = trialName; this.ElapsedTime = TimeSpan.Zero; this.NumberOfIterations = 0; } public string TrialName { get; private set; } public TimeSpan ElapsedTime { get { return _elapsedTime; } set { if (value < TimeSpan.Zero) { throw new ArgumentOutOfRangeException("value"); } else { _elapsedTime = value; } } } public int NumberOfIterations { get { return _numberOfIterations; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } else { _numberOfIterations = value; } } } public TimeSpan IterationAverageDuration { get { var avgTicks = this.ElapsedTime.Ticks / this.NumberOfIterations; return TimeSpan.FromTicks(avgTicks); } } } }
mit
C#
87858d128da48a38ca469fb1e634ad027a869563
fix typo
seekasia-oss/jobstreet-ad-posting-api-client
src/SEEK.AdPostingApi.Client/RequestException.cs
src/SEEK.AdPostingApi.Client/RequestException.cs
using System; using System.Runtime.Serialization; namespace SEEK.AdPostingApi.Client { [Serializable] public class RequestException : Exception { public RequestException(string requestId, int statusCode, string message) : base(message) { this.RequestId = requestId; this.StatusCode = statusCode; } public RequestException(SerializationInfo info, StreamingContext context) : base(info, context) { this.RequestId = (string)info.GetValue(nameof(this.RequestId), typeof(string)); this.StatusCode = (int)info.GetValue(nameof(this.StatusCode), typeof(int)); } public string RequestId { get; } public int StatusCode { get; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(this.RequestId), this.RequestId); info.AddValue(nameof(this.StatusCode), this.StatusCode); base.GetObjectData(info, context); } } }
using System; using System.Runtime.Serialization; namespace SEEK.AdPostingApi.Client { [Serializable] public class RequestException : Exception { public RequestException(string requestId, int statusCode, string message) : base(message) { this.RequestId = requestId; this.StatusCode = statusCode; } public RequestException(SerializationInfo info, StreamingContext context) : base() { this.RequestId = (string)info.GetValue(nameof(this.RequestId), typeof(string)); this.StatusCode = (int)info.GetValue(nameof(this.StatusCode), typeof(int)); } public string RequestId { get; } public int StatusCode { get; } public override void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue(nameof(this.RequestId), this.RequestId); info.AddValue(nameof(this.StatusCode), this.StatusCode); base.GetObjectData(info, context); } } }
mit
C#
0b6b557a5a2ef96672b8924bc666913cab20e788
Change ProcessorInfo to CPU
zarlo/Cosmos,zarlo/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos
source/Cosmos.Core_Plugs/System/Diagnostics/StopwatchImpl.cs
source/Cosmos.Core_Plugs/System/Diagnostics/StopwatchImpl.cs
using IL2CPU.API; using IL2CPU.API.Attribs; using System; using System.Diagnostics; using Cosmos.Core; namespace Cosmos.Core_Plugs.System.Diagnostics { [Plug(Target = typeof(global::System.Diagnostics.Stopwatch))] public class StopwatchImpl { public static long GetTimestamp() { if (Stopwatch.IsHighResolution) // see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx for more details return (long)(CPU.GetCPUUptime() / (double)CPU.GetCPUCycleSpeed() * 1000000d); else return DateTime.UtcNow.Ticks; } } }
using IL2CPU.API; using IL2CPU.API.Attribs; using System; using System.Diagnostics; using Cosmos.Core; namespace Cosmos.Core_Plugs.System.Diagnostics { [Plug(Target = typeof(global::System.Diagnostics.Stopwatch))] public class StopwatchImpl { public static long GetTimestamp() { if (Stopwatch.IsHighResolution) // see https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx for more details return (long)(ProcessorInformation.GetCycleCount() / (double)ProcessorInformation.GetCycleRate() * 1000000d); else return DateTime.UtcNow.Ticks; } } }
bsd-3-clause
C#
bd607cc54c8cc8397d39ec9f41f202fc4b1dcfd4
Update WunderlistService.cs
marska/wundercal
src/Wundercal/Services/WunderlistService.cs
src/Wundercal/Services/WunderlistService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Wundercal.Services.Dto; namespace Wundercal.Services { public class WunderlistService : IWunderlistService { private readonly HttpClient _httpClient; public WunderlistService(string accessToken, string clientId) { var proxy = WebRequest.DefaultWebProxy; proxy.Credentials = CredentialCache.DefaultNetworkCredentials; var httpClientHandler = new HttpClientHandler() { Proxy = proxy }; _httpClient = new HttpClient(httpClientHandler) { BaseAddress = new Uri("https://a.wunderlist.com/api/v1/") }; _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Add("X-Access-Token", accessToken); _httpClient.DefaultRequestHeaders.Add("X-Client-ID", clientId); } public int CreateTask(int listId, string title, DateTime dueDate) { var param = JsonConvert.SerializeObject(new { list_id = listId, title = title, due_date = dueDate }); HttpContent content = new StringContent(param, Encoding.UTF8, "application/json"); var response = _httpClient.PostAsync("tasks", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception(response.StatusCode.ToString()); } var task = JsonConvert.DeserializeAnonymousType(response.Content.ReadAsStringAsync().Result, new {id = 0}); return task.id; } public int CreateReminder(int taskId, DateTime date) { var param = JsonConvert.SerializeObject(new { task_id = taskId, date = date }); HttpContent content = new StringContent(param, Encoding.UTF8, "application/json"); var response = _httpClient.PostAsync("reminders", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception(response.StatusCode.ToString()); } var reminder = JsonConvert.DeserializeAnonymousType(response.Content.ReadAsStringAsync().Result, new { id = 0 }); return reminder.id; } public int GetListId(string name) { var result = 0; var response = _httpClient.GetAsync("lists").Result; if (response.IsSuccessStatusCode) { var responseString = response.Content.ReadAsStringAsync().Result; var wunderlistLists = JsonConvert.DeserializeObject<List<WunderlistList>>(responseString); result = wunderlistLists.First(l => l.Title == name).Id; } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json; using Wundercal.Services.Dto; namespace Wundercal.Services { public class WunderlistService : IWunderlistService { private readonly HttpClient _httpClient = new HttpClient(); public WunderlistService(string accessToken, string clientId) { _httpClient.BaseAddress = new Uri("https://a.wunderlist.com/api/v1/"); _httpClient.DefaultRequestHeaders.Accept.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _httpClient.DefaultRequestHeaders.Add("X-Access-Token", accessToken); _httpClient.DefaultRequestHeaders.Add("X-Client-ID", clientId); } public int CreateTask(int listId, string title, DateTime dueDate) { var param = JsonConvert.SerializeObject(new { list_id = listId, title = title, due_date = dueDate }); HttpContent content = new StringContent(param, Encoding.UTF8, "application/json"); var response = _httpClient.PostAsync("tasks", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception(response.StatusCode.ToString()); } var task = JsonConvert.DeserializeAnonymousType(response.Content.ReadAsStringAsync().Result, new {id = 0}); return task.id; } public int CreateReminder(int taskId, DateTime date) { var param = JsonConvert.SerializeObject(new { task_id = taskId, date = date }); HttpContent content = new StringContent(param, Encoding.UTF8, "application/json"); var response = _httpClient.PostAsync("reminders", content).Result; if (!response.IsSuccessStatusCode) { throw new Exception(response.StatusCode.ToString()); } var reminder = JsonConvert.DeserializeAnonymousType(response.Content.ReadAsStringAsync().Result, new { id = 0 }); return reminder.id; } public int GetListId(string name) { var result = 0; var response = _httpClient.GetAsync("lists").Result; if (response.IsSuccessStatusCode) { var responseString = response.Content.ReadAsStringAsync().Result; var wunderlistLists = JsonConvert.DeserializeObject<List<WunderlistList>>(responseString); result = wunderlistLists.First(l => l.Title == name).Id; } return result; } } }
apache-2.0
C#
88e561c3aeda6199fea5f50d502752c6a424ff05
fix autolink attribute
lunet-io/markdig
src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs
src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using Markdig.Syntax.Inlines; namespace Markdig.Renderers.Html.Inlines { /// <summary> /// A HTML renderer for an <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Html.HtmlObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : HtmlObjectRenderer<AutolinkInline> { /// <summary> /// Gets or sets a value indicating whether to always add rel="nofollow" for links or not. /// </summary> public bool AutoRelNoFollow { get; set; } protected override void Write(HtmlRenderer renderer, AutolinkInline obj) { if (renderer.EnableHtmlForInline) { renderer.Write("<a href=\""); if (obj.IsEmail) { renderer.Write("mailto:"); } renderer.WriteEscapeUrl(obj.Url); renderer.Write('"'); renderer.WriteAttributes(obj); if (!obj.IsEmail && AutoRelNoFollow) { renderer.Write(" rel=\"nofollow\""); } renderer.Write(">"); } renderer.WriteEscape(obj.Url); if (renderer.EnableHtmlForInline) { renderer.Write("</a>"); } } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // This file is licensed under the BSD-Clause 2 license. // See the license.txt file in the project root for more information. using Markdig.Syntax.Inlines; namespace Markdig.Renderers.Html.Inlines { /// <summary> /// A HTML renderer for an <see cref="AutolinkInline"/>. /// </summary> /// <seealso cref="Markdig.Renderers.Html.HtmlObjectRenderer{Markdig.Syntax.Inlines.AutolinkInline}" /> public class AutolinkInlineRenderer : HtmlObjectRenderer<AutolinkInline> { /// <summary> /// Gets or sets a value indicating whether to always add rel="nofollow" for links or not. /// </summary> public bool AutoRelNoFollow { get; set; } protected override void Write(HtmlRenderer renderer, AutolinkInline obj) { if (renderer.EnableHtmlForInline) { renderer.Write("<a href=\""); if (obj.IsEmail) { renderer.Write("mailto:"); } renderer.WriteEscapeUrl(obj.Url); renderer.WriteAttributes(obj); if (!obj.IsEmail && AutoRelNoFollow) { renderer.Write(" rel=\"nofollow\""); } renderer.Write("\">"); } renderer.WriteEscape(obj.Url); if (renderer.EnableHtmlForInline) { renderer.Write("</a>"); } } } }
bsd-2-clause
C#
a5fb7e7bec003ce21e356781384c074ead32f989
create dictionary
volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,volkanceylan/Serenity
src/Serenity.Net.Data.Entity/Row/DefaultRowFieldsProvider.cs
src/Serenity.Net.Data.Entity/Row/DefaultRowFieldsProvider.cs
using Microsoft.Extensions.DependencyInjection; using Serenity.Reflection; using System; using System.Collections.Concurrent; namespace Serenity.Data { public class DefaultRowFieldsProvider : IRowFieldsProvider { private readonly IServiceProvider serviceProvider; private readonly ConcurrentDictionary<Type, RowFieldsBase> byType; public DefaultRowFieldsProvider(IServiceProvider serviceProvider) { this.byType = new ConcurrentDictionary<Type, RowFieldsBase>(); this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); } public RowFieldsBase Resolve(Type fieldsType) { return byType.GetOrAdd(fieldsType, CreateType); } private RowFieldsBase CreateType(Type fieldsType) { var annotationRegistry = serviceProvider.GetService<IAnnotationTypeRegistry>(); var connectionStrings = serviceProvider.GetService<IConnectionStrings>(); var fields = (RowFieldsBase)ActivatorUtilities.CreateInstance(serviceProvider, fieldsType); IAnnotatedType annotations = null; if (annotationRegistry != null && fieldsType.IsNested && typeof(IRow).IsAssignableFrom(fieldsType.DeclaringType)) { annotations = annotationRegistry.GetAnnotationTypesFor(fieldsType.DeclaringType) .GetAnnotatedType(); } var dialect = connectionStrings?.TryGetConnectionString(fields.ConnectionKey)? .Dialect ?? SqlSettings.DefaultDialect; fields.Initialize(annotations, dialect); return fields; } } }
using Microsoft.Extensions.DependencyInjection; using Serenity.Reflection; using System; using System.Collections.Concurrent; namespace Serenity.Data { public class DefaultRowFieldsProvider : IRowFieldsProvider { private readonly IServiceProvider serviceProvider; private readonly ConcurrentDictionary<Type, RowFieldsBase> byType; public DefaultRowFieldsProvider(IServiceProvider serviceProvider) { this.serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); } public RowFieldsBase Resolve(Type fieldsType) { return byType.GetOrAdd(fieldsType, CreateType); } private RowFieldsBase CreateType(Type fieldsType) { var annotationRegistry = serviceProvider.GetService<IAnnotationTypeRegistry>(); var connectionStrings = serviceProvider.GetService<IConnectionStrings>(); var fields = (RowFieldsBase)ActivatorUtilities.CreateInstance(serviceProvider, fieldsType); IAnnotatedType annotations = null; if (annotationRegistry != null && fieldsType.IsNested && typeof(IRow).IsAssignableFrom(fieldsType.DeclaringType)) { annotations = annotationRegistry.GetAnnotationTypesFor(fieldsType.DeclaringType) .GetAnnotatedType(); } var dialect = connectionStrings?.TryGetConnectionString(fields.ConnectionKey)? .Dialect ?? SqlSettings.DefaultDialect; fields.Initialize(annotations, dialect); return fields; } } }
mit
C#
eaf2b1d94df6eb7f02621243e81bb858b5953987
Remove line that shouldn't have been added yet
peppy/osu-new,DrabWeb/osu,naoey/osu,peppy/osu,ZLima12/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,Frontear/osuKyzer,smoogipoo/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,2yangk23/osu,naoey/osu,Nabile-Rahmani/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,UselessToucan/osu
osu.Game.Rulesets.Mania/Replays/ManiaFramedReplayInputHandler.cs
osu.Game.Rulesets.Mania/Replays/ManiaFramedReplayInputHandler.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Input; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Mania.Replays { internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler { private readonly ManiaRulesetContainer container; public ManiaFramedReplayInputHandler(Replay replay, ManiaRulesetContainer container) : base(replay) { this.container = container; } private ManiaPlayfield playfield; public override List<InputState> GetPendingStates() { var actions = new List<ManiaAction>(); if (playfield == null) playfield = (ManiaPlayfield)container.Playfield; int activeColumns = (int)(CurrentFrame.MouseX ?? 0); int counter = 0; while (activeColumns > 0) { if ((activeColumns & 1) > 0) actions.Add(playfield.Columns.ElementAt(counter).Action); counter++; activeColumns >>= 1; } return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Input; using osu.Game.Rulesets.Mania.UI; using osu.Game.Rulesets.Replays; namespace osu.Game.Rulesets.Mania.Replays { internal class ManiaFramedReplayInputHandler : FramedReplayInputHandler { private readonly ManiaRulesetContainer container; public ManiaFramedReplayInputHandler(Replay replay, ManiaRulesetContainer container) : base(replay) { this.container = container; } protected override bool AtImportantFrame => CurrentFrame.MouseX != PreviousFrame.MouseX; private ManiaPlayfield playfield; public override List<InputState> GetPendingStates() { var actions = new List<ManiaAction>(); if (playfield == null) playfield = (ManiaPlayfield)container.Playfield; int activeColumns = (int)(CurrentFrame.MouseX ?? 0); int counter = 0; while (activeColumns > 0) { if ((activeColumns & 1) > 0) actions.Add(playfield.Columns.ElementAt(counter).Action); counter++; activeColumns >>= 1; } return new List<InputState> { new ReplayState<ManiaAction> { PressedActions = actions } }; } } }
mit
C#
504b9878f1e5e5372ed8ba66a1d5d491bd15ae6f
Remove dead code
SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore
tests/SqlStreamStore.Http.Tests/HttpClientStreamStoreFixture.cs
tests/SqlStreamStore.Http.Tests/HttpClientStreamStoreFixture.cs
namespace SqlStreamStore { using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using SqlStreamStore.HAL; public class HttpClientStreamStoreFixture : StreamStoreAcceptanceTestFixture, IDisposable { private readonly InMemoryStreamStore _innerStreamStore; private readonly HttpMessageHandler _messageHandler; private readonly TestServer _server; public HttpClientStreamStoreFixture() { _innerStreamStore = new InMemoryStreamStore(() => GetUtcNow()); _server = new TestServer( new WebHostBuilder().Configure(builder => builder.UseSqlStreamStoreHal(_innerStreamStore))); _messageHandler = new RedirectingHandler { InnerHandler = _server.CreateHandler() }; } public override long MinPosition => 0; public override int MaxSubscriptionCount => 500; public override Task<IStreamStore> GetStreamStore() => Task.FromResult<IStreamStore>( new HttpClientSqlStreamStore( new HttpClientSqlStreamStoreSettings { GetUtcNow = () => GetUtcNow(), HttpMessageHandler = _messageHandler, BaseAddress = new UriBuilder().Uri })); void IDisposable.Dispose() { _server?.Dispose(); _messageHandler?.Dispose(); _innerStreamStore?.Dispose(); } } }
namespace SqlStreamStore { using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using SqlStreamStore.HAL; using MidFunc = System.Func< System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>, System.Func< System.Collections.Generic.IDictionary<string, object>, System.Threading.Tasks.Task>>; public class HttpClientStreamStoreFixture : StreamStoreAcceptanceTestFixture, IDisposable { private readonly InMemoryStreamStore _innerStreamStore; private readonly HttpMessageHandler _messageHandler; private readonly TestServer _server; public HttpClientStreamStoreFixture() { _innerStreamStore = new InMemoryStreamStore(() => GetUtcNow()); _server = new TestServer( new WebHostBuilder().Configure(builder => builder.UseSqlStreamStoreHal(_innerStreamStore))); _messageHandler = new RedirectingHandler { InnerHandler = _server.CreateHandler() }; } public override long MinPosition => 0; public override int MaxSubscriptionCount => 500; public override Task<IStreamStore> GetStreamStore() => Task.FromResult<IStreamStore>( new HttpClientSqlStreamStore( new HttpClientSqlStreamStoreSettings { GetUtcNow = () => GetUtcNow(), HttpMessageHandler = _messageHandler, BaseAddress = new UriBuilder().Uri })); void IDisposable.Dispose() { _server?.Dispose(); _messageHandler?.Dispose(); _innerStreamStore?.Dispose(); } } }
mit
C#
f11b04c7bce8711fe5e43bdfd6a45ed7481fe59d
Add ScanWindow for look(behind/ahead).
Nezaboodka/Nevod.TextParsing,Nezaboodka/Nevod.TextParsing
WordExtraction/WordExtractor.cs
WordExtraction/WordExtractor.cs
using System.Collections.Generic; namespace WordExtraction { class WordExtractor { class ScanWindow { public WordBreakPropertyType? Ahead { get; private set; } public WordBreakPropertyType? Current { get; private set; } public WordBreakPropertyType? Behind { get; private set; } public WordBreakPropertyType? BehindOfBehind { get; private set; } public void Add(WordBreakPropertyType? nextSymbolType) { BehindOfBehind = Behind; Behind = Current; Current = Ahead; Ahead = nextSymbolType; } public ScanWindow(WordBreakPropertyType? firstSymbolType, WordBreakPropertyType? nexSymbolType) { Add(firstSymbolType); Add(nexSymbolType); } } private const int CACHE_SIZE = 3; public static IEnumerable<string> GetWords(string text) { if (string.IsNullOrEmpty(text)) yield break; WordBreakPropertyType[] typesCache = new WordBreakPropertyType[CACHE_SIZE]; int i = 0; foreach (char c in text) { } yield return "word"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WordExtraction { class WordExtractor { public static IEnumerable<string> GetWords(string text) { yield return "word"; } } }
mit
C#
584e1e27a66c9dceb29ec52854fe5cda0e785ec9
Add dialog slot type
stoiveyp/Alexa.NET.Management
Alexa.NET.Management/InteractionModel/DialogSlot.cs
Alexa.NET.Management/InteractionModel/DialogSlot.cs
using Newtonsoft.Json; namespace Alexa.NET.Management.InteractionModel { public class DialogSlot { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("elicitationRequired",NullValueHandling = NullValueHandling.Ignore)] public bool ElicitationRequired { get; set; } [JsonProperty("confirmationRequired", NullValueHandling = NullValueHandling.Ignore)] public bool ConfirmationRequired { get; set; } [JsonProperty("prompts", NullValueHandling = NullValueHandling.Ignore)] public DialogSlotPrompts Prompts { get; set; } [JsonProperty("validations", NullValueHandling = NullValueHandling.Ignore)] public DialogSlotValidation[] Validations { get; set; } } }
using Newtonsoft.Json; namespace Alexa.NET.Management.InteractionModel { public class DialogSlot { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("elicitationRequired",NullValueHandling = NullValueHandling.Ignore)] public bool ElicitationRequired { get; set; } [JsonProperty("confirmationRequired", NullValueHandling = NullValueHandling.Ignore)] public bool ConfirmationRequired { get; set; } [JsonProperty("prompts", NullValueHandling = NullValueHandling.Ignore)] public DialogSlotPrompts Prompts { get; set; } [JsonProperty("validations", NullValueHandling = NullValueHandling.Ignore)] public DialogSlotValidation[] Validations { get; set; } } }
mit
C#
0ce6030b20075b0b2c380a9a85bcab7f0a7fc2a5
Update Feature1.cs
alokpro/GitTest1
ConsoleApplication1/ConsoleApplication1/Feature1.cs
ConsoleApplication1/ConsoleApplication1/Feature1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Feature1 { public int Add() { var x1 = 1; var x2 = 3; var sum = x1 + x2; return sum; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Feature1 { public int Add() { int x1 = 1; int x2 = 3; int sum = x1 + x2; return sum; } } }
mit
C#
55de2d4e21a13d9af03c5c493c30a94430fd507f
Fix issue: password change occurs only for default user.
enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api
Infopulse.EDemocracy.Web/Controllers/API/AccountController.cs
Infopulse.EDemocracy.Web/Controllers/API/AccountController.cs
using System.Linq; using Infopulse.EDemocracy.Data.Repositories; using Infopulse.EDemocracy.Web.Models; using Microsoft.AspNet.Identity; using System.Threading.Tasks; using System.Web.Http; using Infopulse.EDemocracy.Common.Operations; using Infopulse.EDemocracy.Web.CORS; using Infopulse.EDemocracy.Web.Resources; namespace Infopulse.EDemocracy.Web.Controllers.API { [CorsPolicyProvider] [RoutePrefix("api/Account")] public class AccountController : BaseApiController { private AuthRepository authRepository = null; public AccountController() { authRepository = new AuthRepository(); } // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(UserModel userModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await authRepository.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return errorResult; } return Ok(OperationResult.Success(1, "Ви зареєстровані")); } /// <summary> /// Changes current user password. /// </summary> /// <returns>Operation result.</returns> [HttpPost] [Authorize] public OperationResult ChangePassword(ChangePasswordModel passwordChanges) { var result = OperationExecuter.Execute(() => { var changePasswordResult = authRepository.ChangePassword(1, passwordChanges.CurrentPassword, passwordChanges.NewPassword); if (changePasswordResult.Succeeded) { return OperationResult.Success(GetSignedInUserId(), UserMessages.PasswordChanged_Success); } else { var errorMessage = changePasswordResult.Errors.Any() ? string.Join(". ", changePasswordResult.Errors) : UserMessages.PasswordChanged_Fail_WrongCurrentPassword; return OperationResult.Fail(-2, errorMessage); } }); return result; } protected override void Dispose(bool disposing) { if (disposing) { authRepository.Dispose(); } base.Dispose(disposing); } private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; } } }
using System.Linq; using Infopulse.EDemocracy.Data.Repositories; using Infopulse.EDemocracy.Web.Models; using Microsoft.AspNet.Identity; using System.Threading.Tasks; using System.Web.Http; using Infopulse.EDemocracy.Common.Operations; using Infopulse.EDemocracy.Web.CORS; using Infopulse.EDemocracy.Web.Resources; namespace Infopulse.EDemocracy.Web.Controllers.API { [CorsPolicyProvider] [RoutePrefix("api/Account")] public class AccountController : ApiController { private AuthRepository authRepository = null; public AccountController() { authRepository = new AuthRepository(); } // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(UserModel userModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await authRepository.RegisterUser(userModel); IHttpActionResult errorResult = GetErrorResult(result); if (errorResult != null) { return errorResult; } return Ok(OperationResult.Success(1, "Ви зареєстровані")); } /// <summary> /// Changes current user password. /// </summary> /// <returns>Operation result.</returns> [HttpPost] [Authorize] public OperationResult ChangePassword(ChangePasswordModel passwordChanges) { var result = OperationExecuter.Execute(() => { var changePasswordResult = authRepository.ChangePassword(1, passwordChanges.CurrentPassword, passwordChanges.NewPassword); if (changePasswordResult.Succeeded) { return OperationResult.Success(1, UserMessages.PasswordChanged_Success); } else { var errorMessage = changePasswordResult.Errors.Any() ? string.Join(". ", changePasswordResult.Errors) : UserMessages.PasswordChanged_Fail_WrongCurrentPassword; return OperationResult.Fail(-2, errorMessage); } }); return result; } protected override void Dispose(bool disposing) { if (disposing) { authRepository.Dispose(); } base.Dispose(disposing); } private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; } } }
cc0-1.0
C#
79bd13b79aeff351b07a5ccd0eb231aa0bd908a6
Update benchmark code
smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework
osu.Framework.Benchmarks/BenchmarkLocalisableDescription.cs
osu.Framework.Benchmarks/BenchmarkLocalisableDescription.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using BenchmarkDotNet.Attributes; using osu.Framework.Extensions; using osu.Framework.Localisation; namespace osu.Framework.Benchmarks { public class BenchmarkLocalisableDescription { private LocalisableString[] descriptions; [Params(1, 10, 100, 1000)] public int Times { get; set; } [GlobalSetup] public void SetUp() { descriptions = new LocalisableString[Times]; } [Benchmark] public LocalisableString[] GetLocalisableDescription() { for (int i = 0; i < Times; i++) descriptions[i] = TestLocalisableEnum.One.GetLocalisableDescription(); return descriptions; } private enum TestLocalisableEnum { [LocalisableDescription(typeof(TestStrings), nameof(TestStrings.One))] One, } private static class TestStrings { public static LocalisableString One => "1"; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using BenchmarkDotNet.Attributes; using osu.Framework.Extensions; using osu.Framework.Localisation; namespace osu.Framework.Benchmarks { public class BenchmarkLocalisableDescription { private LocalisableString[] descriptions; [Params(1, 10, 100, 1000)] public int Times { get; set; } [GlobalSetup] public void SetUp() { descriptions = new LocalisableString[Times]; } [Benchmark] public LocalisableString[] GetLocalisableDescription() { for (int i = 0; i < Times; i++) descriptions[i] = TestLocalisableEnum.One.GetLocalisableDescription(); return descriptions; } [LocalisableEnum(typeof(TestEnumLocalisationMapper))] private enum TestLocalisableEnum { One, } private class TestEnumLocalisationMapper : EnumLocalisationMapper<TestLocalisableEnum> { public override LocalisableString Map(TestLocalisableEnum value) { switch (value) { case TestLocalisableEnum.One: return "1"; default: throw new ArgumentOutOfRangeException(nameof(value)); } } } } }
mit
C#
6062bd303f7271897aa07165087c9178cef1e31f
fix bug for reporting viewer version 17.1.5.0
Ronglin-kooboo/DReportiing,Ronglin-kooboo/DReportiing,Ronglin-kooboo/DReportiing
DReporting/Web/Mvc/Controllers/PreviewController.cs
DReporting/Web/Mvc/Controllers/PreviewController.cs
using DevExpress.Web.Mvc; using DevExpress.XtraReports.UI; using DReporting.Web.Mvc.ViewModels; using System.Web; using System.Web.Mvc; namespace DReporting.Web.Mvc.Controllers { public class PreviewController : ControllerBase { public ActionResult Index(string templateId, string dataProviderId) { var args = HttpUtility.ParseQueryString(Request.Url.Query); args.Remove("TemplateID"); args.Remove("DataProviderID"); args.Remove("ReturnUrl"); var vm = VM(templateId, dataProviderId, args.ToString()); return View("Index", vm); } public ActionResult Callback(string templateId, string dataProviderId, string dataProviderArgs) { var vm = VM(templateId, dataProviderId, dataProviderArgs); return PartialView("Viewer", vm); } public ActionResult Export(string templateId, string dataProviderId, string dataProviderArgs) { var template = TemplateMgr.GetTemplate(templateId); if (!string.IsNullOrEmpty(dataProviderId)) { FillDataSource(template.XtraReport, dataProviderId, dataProviderArgs); } return DocumentViewerExtension.ExportTo(template.XtraReport); } private ViewerVM VM(string templateId, string dataProviderId, string dataProviderArgs) { var template = TemplateMgr.GetTemplate(templateId); if (!string.IsNullOrEmpty(dataProviderId)) { FillDataSource(template.XtraReport, dataProviderId, dataProviderArgs); } return new ViewerVM { TemplateID = templateId, TemplateName = template.TemplateName, DataProviderID = dataProviderId, DataProviderArgs = dataProviderArgs, XtraReport = template.XtraReport }; } private void FillDataSource(XtraReport xtraReport, string dataProviderId, string dataProviderArgs) { var query = HttpUtility.ParseQueryString(dataProviderArgs ?? string.Empty); var provider = DataProviderMgr.GetDataProvider(dataProviderId); xtraReport.DataSource = provider.Entity.GetDataSource(query, false); } } }
using DevExpress.Web.Mvc; using DevExpress.XtraReports.UI; using DReporting.Web.Mvc.ViewModels; using System.Web; using System.Web.Mvc; namespace DReporting.Web.Mvc.Controllers { public class PreviewController : ControllerBase { public ActionResult Index(string templateId, string dataProviderId) { var args = HttpUtility.ParseQueryString(Request.Url.Query); args.Remove("TemplateID"); args.Remove("DataProviderID"); args.Remove("ReturnUrl"); var vm = VM(templateId, dataProviderId, args.ToString()); return View("Index", vm); } public ActionResult Callback(string templateId, string dataProviderId, string dataProviderArgs) { var vm = VM(templateId, dataProviderId, dataProviderArgs); if (!string.IsNullOrEmpty(dataProviderId)) { FillDataSource(vm.XtraReport, dataProviderId, dataProviderArgs); } return PartialView("Viewer", vm); } public ActionResult Export(string templateId, string dataProviderId, string dataProviderArgs) { var template = TemplateMgr.GetTemplate(templateId); if (!string.IsNullOrEmpty(dataProviderId)) { FillDataSource(template.XtraReport, dataProviderId, dataProviderArgs); } return DocumentViewerExtension.ExportTo(template.XtraReport); } private ViewerVM VM(string templateId, string dataProviderId, string dataProviderArgs) { var template = TemplateMgr.GetTemplate(templateId); return new ViewerVM { TemplateID = templateId, TemplateName = template.TemplateName, DataProviderID = dataProviderId, DataProviderArgs = dataProviderArgs, XtraReport = template.XtraReport }; } private void FillDataSource(XtraReport xtraReport, string dataProviderId, string dataProviderArgs) { var query = HttpUtility.ParseQueryString(dataProviderArgs ?? string.Empty); var provider = DataProviderMgr.GetDataProvider(dataProviderId); xtraReport.DataSource = provider.Entity.GetDataSource(query, false); } } }
mit
C#
7fd8f41921250c0312bfcd5d4ec55e9beca74d8a
implement INotifyProperyChanged
kidchenko/windows-phone
DailyRitualsApp/DailyRitualsApp/DataModel/Ritual.cs
DailyRitualsApp/DailyRitualsApp/DataModel/Ritual.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using DailyRitualsApp.Commands; namespace DailyRitualsApp.DataModel { public class Ritual : INotifyPropertyChanged { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ObservableCollection<DateTime> Dates { get; set; } = new ObservableCollection<DateTime>(); [IgnoreDataMember] public ICommand CompletedCommand { get; set; } = new CompletedButtonClick(); public void AddDate() { Dates.Add(DateTime.Today); OnPropertyChanged("Dates"); } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; handler?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DailyRitualsApp.DataModel { public class Ritual { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ObservableCollection<DateTime> Dates { get; set; } } }
mit
C#
16f9cd6d803feac597d6632fe46b786d51d952da
add page param
Terradue/DotNetTep,Terradue/DotNetTep
Terradue.Tep/Terradue/Tep/WebServer/News/Discourse.Service.cs
Terradue.Tep/Terradue/Tep/WebServer/News/Discourse.Service.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ServiceStack.ServiceHost; using System.Net; namespace Terradue.Tep.WebServer.Services { [Api("Tep Terradue webserver")] [Restrict(EndpointAttributes.InSecure | EndpointAttributes.InternalNetworkAccess | EndpointAttributes.Json, EndpointAttributes.Secure | EndpointAttributes.External | EndpointAttributes.Json)] public class DiscourseServiceTep : ServiceStack.ServiceInterface.Service { public object Get(GetDiscourseTopicsPerCategory request){ return GetDiscourseRequest(string.Format("c/{0}.json?page={1}", request.catId, request.page)); } public object Get(GetDiscourseLatestTopicsPerCategory request){ return GetDiscourseRequest(string.Format("c/{0}/l/latest.json", request.catId)); } public object Get(GetDiscourseTopic request){ return GetDiscourseRequest(string.Format("t/{0}.json", request.topicId)); } private object GetDiscourseRequest(string query){ var discourseBaseUrl = "https://discuss.terradue.com"; var discourseUrl = string.Format("{0}/{1}", discourseBaseUrl, query); HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(discourseUrl); httprequest.Method = "GET"; httprequest.ContentType = "application/json"; httprequest.Accept = "application/json"; HttpWebResponse httpResponse = (HttpWebResponse)httprequest.GetResponse(); return httpResponse.GetResponseStream(); } } [Route("/discourse/c/{catId}/l/latest", "GET", Summary = "", Notes = "")] public class GetDiscourseLatestTopicsPerCategory { [ApiMember(Name="catId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int catId{ get; set; } } [Route("/discourse/c/{catId}", "GET", Summary = "", Notes = "")] public class GetDiscourseTopicsPerCategory { [ApiMember(Name="catId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int catId{ get; set; } [ApiMember(Name="page", Description = "request", ParameterType = "query", DataType = "int", IsRequired = false)] public int page{ get; set; } } [Route("/discourse/t/{topicId}", "GET", Summary = "", Notes = "")] public class GetDiscourseTopic { [ApiMember(Name="topicId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int topicId{ get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ServiceStack.ServiceHost; using System.Net; namespace Terradue.Tep.WebServer.Services { [Api("Tep Terradue webserver")] [Restrict(EndpointAttributes.InSecure | EndpointAttributes.InternalNetworkAccess | EndpointAttributes.Json, EndpointAttributes.Secure | EndpointAttributes.External | EndpointAttributes.Json)] public class DiscourseServiceTep : ServiceStack.ServiceInterface.Service { public object Get(GetDiscourseTopicsPerCategory request){ return GetDiscourseRequest(string.Format("c/{0}.json", request.catId)); } public object Get(GetDiscourseLatestTopicsPerCategory request){ return GetDiscourseRequest(string.Format("c/{0}/l/latest.json", request.catId)); } public object Get(GetDiscourseTopic request){ return GetDiscourseRequest(string.Format("t/{0}.json", request.topicId)); } private object GetDiscourseRequest(string query){ var discourseBaseUrl = "https://discuss.terradue.com"; var discourseUrl = string.Format("{0}/{1}", discourseBaseUrl, query); HttpWebRequest httprequest = (HttpWebRequest)WebRequest.Create(discourseUrl); httprequest.Method = "GET"; httprequest.ContentType = "application/json"; httprequest.Accept = "application/json"; HttpWebResponse httpResponse = (HttpWebResponse)httprequest.GetResponse(); return httpResponse.GetResponseStream(); } } [Route("/discourse/c/{catId}/l/latest", "GET", Summary = "", Notes = "")] public class GetDiscourseLatestTopicsPerCategory { [ApiMember(Name="catId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int catId{ get; set; } } [Route("/discourse/c/{catId}", "GET", Summary = "", Notes = "")] public class GetDiscourseTopicsPerCategory { [ApiMember(Name="catId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int catId{ get; set; } } [Route("/discourse/t/{topicId}", "GET", Summary = "", Notes = "")] public class GetDiscourseTopic { [ApiMember(Name="topicId", Description = "request", ParameterType = "query", DataType = "int", IsRequired = true)] public int topicId{ get; set; } } }
agpl-3.0
C#
8a86640de86f4d07db1b442d398d2caa7470c512
Fix bug when moving between pages executing on UI thread.
dsplaisted/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,BreeeZe/NuGetPackageExplorer
PackageViewModel/PackageChooser/QueryContextBase.cs
PackageViewModel/PackageChooser/QueryContextBase.cs
using System; using System.Collections.Generic; using System.Data.Services.Client; using System.Linq; using System.Threading.Tasks; namespace PackageExplorerViewModel { internal abstract class QueryContextBase<T> { private int? _totalItemCount; public int TotalItemCount { get { return _totalItemCount ?? 0; } } protected bool TotalItemCountReady { get { return _totalItemCount.HasValue; } } public IQueryable<T> Source { get; private set; } protected QueryContextBase(IQueryable<T> source) { Source = source; } protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query) { var dataServiceQuery = query as DataServiceQuery<T>; if (dataServiceQuery != null) { var queryResponse = (QueryOperationResponse<T>) await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute); try { _totalItemCount = (int)queryResponse.TotalCount; } catch (InvalidOperationException) { if (!TotalItemCountReady) { // the server doesn't return $inlinecount value, // fall back to using $count query _totalItemCount = Source.Count(); } } return queryResponse; } else { if (!TotalItemCountReady) { _totalItemCount = Source.Count(); } return query; } } } }
using System; using System.Collections.Generic; using System.Data.Services.Client; using System.Linq; using System.Threading.Tasks; namespace PackageExplorerViewModel { internal abstract class QueryContextBase<T> { private int? _totalItemCount; public int TotalItemCount { get { return _totalItemCount ?? 0; } } protected bool TotalItemCountReady { get { return _totalItemCount.HasValue; } } public IQueryable<T> Source { get; private set; } protected QueryContextBase(IQueryable<T> source) { Source = source; } protected async Task<IEnumerable<T>> LoadData(IQueryable<T> query) { var dataServiceQuery = query as DataServiceQuery<T>; if (!TotalItemCountReady && dataServiceQuery != null) { var queryResponse = (QueryOperationResponse<T>) await Task.Factory.FromAsync<IEnumerable<T>>(dataServiceQuery.BeginExecute(null, null), dataServiceQuery.EndExecute); try { _totalItemCount = (int)queryResponse.TotalCount; } catch (InvalidOperationException) { // the server doesn't return $inlinecount value, // fall back to using $count query _totalItemCount = Source.Count(); } return queryResponse; } else { if (!TotalItemCountReady) { _totalItemCount = Source.Count(); } return query; } } } }
mit
C#
b8c8073823a2349068afcf35fc9533f2c9e60857
Improve WebAssembly processing
Perfare/Il2CppDumper,Perfare/Il2CppDumper
Il2CppDumper/ExecutableFormats/WebAssemblyMemory.cs
Il2CppDumper/ExecutableFormats/WebAssemblyMemory.cs
using System.IO; namespace Il2CppDumper { public sealed class WebAssemblyMemory : Il2Cpp { public WebAssemblyMemory(Stream stream, bool is32Bit) : base(stream) { Is32Bit = is32Bit; } public override ulong MapVATR(ulong addr) { return addr; } public override bool PlusSearch(int methodCount, int typeDefinitionsCount) { var exec = new SearchSection { offset = 0, offsetEnd = (ulong)methodCount, //hack address = 0, addressEnd = (ulong)methodCount //hack }; var data = new SearchSection { offset = 1024, offsetEnd = Length, address = 1024, addressEnd = Length }; var bss = new SearchSection { offset = Length, offsetEnd = long.MaxValue, //hack address = Length, addressEnd = long.MaxValue //hack }; var plusSearch = new PlusSearch(this, methodCount, typeDefinitionsCount, maxMetadataUsages); plusSearch.SetSection(SearchSectionType.Exec, exec); plusSearch.SetSection(SearchSectionType.Data, data); plusSearch.SetSection(SearchSectionType.Bss, bss); var codeRegistration = plusSearch.FindCodeRegistration(); var metadataRegistration = plusSearch.FindMetadataRegistration(); return AutoPlusInit(codeRegistration, metadataRegistration); } public override bool Search() { return false; } public override bool SymbolSearch() { return false; } } }
using System.IO; namespace Il2CppDumper { public sealed class WebAssemblyMemory : Il2Cpp { public WebAssemblyMemory(Stream stream, bool is32Bit) : base(stream) { Is32Bit = is32Bit; } public override ulong MapVATR(ulong addr) { return addr; } public override bool PlusSearch(int methodCount, int typeDefinitionsCount) { var exec = new SearchSection { offset = 0, offsetEnd = (ulong)methodCount, //hack address = 0, addressEnd = (ulong)methodCount //hack }; var data = new SearchSection { offset = 1024, offsetEnd = Length, address = 1024, addressEnd = Length }; var bss = new SearchSection { offset = Length, offsetEnd = 1024 + 2159056, //STATICTOP address = Length, addressEnd = 1024 + 2159056 //STATICTOP }; var plusSearch = new PlusSearch(this, methodCount, typeDefinitionsCount, maxMetadataUsages); plusSearch.SetSection(SearchSectionType.Exec, exec); plusSearch.SetSection(SearchSectionType.Data, data); plusSearch.SetSection(SearchSectionType.Bss, bss); var codeRegistration = plusSearch.FindCodeRegistration(); var metadataRegistration = plusSearch.FindMetadataRegistration(); return AutoPlusInit(codeRegistration, metadataRegistration); } public override bool Search() { return false; } public override bool SymbolSearch() { return false; } } }
mit
C#
2572f25b2103b4b3a5241a21811c5344648f88ad
rename 'ElapsedTime' to 'Elapsed'
goncalopereira/statsd-csharp-client,bilal-fazlani/statsd-csharp-client,Pereingo/statsd-csharp-client,DarrellMozingo/statsd-csharp-client
src/StatsdClient/Stopwatch.cs
src/StatsdClient/Stopwatch.cs
using System; namespace StatsdClient { public interface IStopwatch { void Start(); void Stop(); TimeSpan Elapsed { get; } [Obsolete("use Elapsed property")] int ElapsedMilliseconds(); } public class Stopwatch : IStopwatch { private readonly System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch(); public void Start() { _stopwatch.Start(); } public void Stop() { _stopwatch.Stop(); } public TimeSpan Elapsed { get { return _stopwatch.Elapsed; } } [Obsolete("use Elapsed property")] public int ElapsedMilliseconds() { double milliseconds = Elapsed.TotalMilliseconds; if (milliseconds > int.MaxValue) { throw new InvalidOperationException("Please use new API 'Elapsed' instead of 'ElapsedMilliseconds()', as your value just overflowed for this old API"); } return (int)milliseconds; } } }
using System; namespace StatsdClient { public interface IStopwatch { void Start(); void Stop(); TimeSpan ElapsedTime { get; } [Obsolete("use ElapsedTime property")] int ElapsedMilliseconds(); } public class Stopwatch : IStopwatch { private readonly System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch(); public void Start() { _stopwatch.Start(); } public void Stop() { _stopwatch.Stop(); } public TimeSpan ElapsedTime { get { var milliseconds = (double)unchecked(_stopwatch.ElapsedMilliseconds); return TimeSpan.FromMilliseconds(milliseconds); } } [Obsolete("use ElapsedTime property")] public int ElapsedMilliseconds() { double milliseconds = ElapsedTime.TotalMilliseconds; if (milliseconds > int.MaxValue) { throw new InvalidOperationException("Please use new API 'ElapsedTime' instead of 'ElapsedMilliseconds()', as your value just overflowed for this old API"); } return (int)milliseconds; } } }
mit
C#
47ffa3b42888e9ffeb13105568cdb6f8fe6029c1
Fix for overallocation
PowerOfCode/lidgren-network-gen3,forestrf/lidgren-network-gen3,lidgren/lidgren-network-gen3,RainsSoft/lidgren-network-gen3,jbruening/lidgren-network-gen3,SacWebDeveloper/lidgren-network-gen3,dragutux/lidgren-network-gen3
Lidgren.Network/Encryption/NetCryptoProviderBase.cs
Lidgren.Network/Encryption/NetCryptoProviderBase.cs
using System; using System.IO; using System.Security.Cryptography; namespace Lidgren.Network { public abstract class NetCryptoProviderBase : NetEncryption { protected SymmetricAlgorithm m_algorithm; public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo) : base(peer) { m_algorithm = algo; m_algorithm.GenerateKey(); m_algorithm.GenerateIV(); } public override void SetKey(byte[] data, int offset, int count) { int len = m_algorithm.Key.Length; var key = new byte[len]; for (int i = 0; i < len; i++) key[i] = data[offset + (i % count)]; m_algorithm.Key = key; len = m_algorithm.IV.Length; key = new byte[len]; for (int i = 0; i < len; i++) key[len - 1 - i] = data[offset + (i % count)]; m_algorithm.IV = key; } public override bool Encrypt(NetOutgoingMessage msg) { int unEncLenBits = msg.LengthBits; var ms = new MemoryStream(); var cs = new CryptoStream(ms, m_algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(msg.m_data, 0, msg.LengthBytes); cs.Close(); // get results var arr = ms.ToArray(); ms.Close(); msg.EnsureBufferSize((arr.Length + 4) * 8); msg.LengthBits = 0; // reset write pointer msg.Write((uint)unEncLenBits); msg.Write(arr); msg.LengthBits = (arr.Length + 4) * 8; return true; } public override bool Decrypt(NetIncomingMessage msg) { int unEncLenBits = (int)msg.ReadUInt32(); var ms = new MemoryStream(msg.m_data, 4, msg.LengthBytes - 4); var cs = new CryptoStream(ms, m_algorithm.CreateDecryptor(), CryptoStreamMode.Read); var byteLen = NetUtility.BytesToHoldBits(unEncLenBits); var result = m_peer.GetStorage(byteLen); cs.Read(result, 0, byteLen); cs.Close(); // TODO: recycle existing msg msg.m_data = result; msg.m_bitLength = unEncLenBits; msg.m_readPosition = 0; return true; } } }
using System; using System.IO; using System.Security.Cryptography; namespace Lidgren.Network { public abstract class NetCryptoProviderBase : NetEncryption { protected SymmetricAlgorithm m_algorithm; public NetCryptoProviderBase(NetPeer peer, SymmetricAlgorithm algo) : base(peer) { m_algorithm = algo; m_algorithm.GenerateKey(); m_algorithm.GenerateIV(); } public override void SetKey(byte[] data, int offset, int count) { int len = m_algorithm.Key.Length; var key = new byte[len]; for (int i = 0; i < len; i++) key[i] = data[offset + (i % count)]; m_algorithm.Key = key; len = m_algorithm.IV.Length; key = new byte[len]; for (int i = 0; i < len; i++) key[len - 1 - i] = data[offset + (i % count)]; m_algorithm.IV = key; } public override bool Encrypt(NetOutgoingMessage msg) { int unEncLenBits = msg.LengthBits; var ms = new MemoryStream(); var cs = new CryptoStream(ms, m_algorithm.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(msg.m_data, 0, msg.LengthBytes); cs.Close(); // get results var arr = ms.ToArray(); ms.Close(); msg.EnsureBufferSize((arr.Length + 4) * 8); msg.LengthBits = 0; // reset write pointer msg.Write((uint)unEncLenBits); msg.Write(arr); msg.LengthBits = (arr.Length + 4) * 8; return true; } public override bool Decrypt(NetIncomingMessage msg) { int unEncLenBits = (int)msg.ReadUInt32(); var ms = new MemoryStream(msg.m_data, 4, msg.LengthBytes - 4); var cs = new CryptoStream(ms, m_algorithm.CreateDecryptor(), CryptoStreamMode.Read); var result = m_peer.GetStorage(unEncLenBits); cs.Read(result, 0, NetUtility.BytesToHoldBits(unEncLenBits)); cs.Close(); // TODO: recycle existing msg msg.m_data = result; msg.m_bitLength = unEncLenBits; msg.m_readPosition = 0; return true; } } }
mit
C#
525a87f07b1edd6ac03aee3a4de8c78a22a59aa9
Update Program.cs
vishipayyallore/CSharp-DotNet-Core-Samples
LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs
LearningDesignPatterns/Source/Alogithms/LogicPrograms/Program.cs
using LogicPrograms.Interfaces; using LogicPrograms.Logics; using System.Linq; using static System.Console; namespace LogicPrograms { class Program { static void Main(string[] args) { // Stair Case Program var number1 = 4; for(var index=1; index <= number1; index++) { WriteLine(string.Concat(Enumerable.Repeat("#", index)).PadLeft(number1)); } IMonthNames monthNames = new MonthNames(); for(var counter=1; counter <= 10; counter++) { monthNames.DisplayMonthNames(); } //------------------------------------------------------------------------------------------ var arrayItems = new int[] { 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0 }; var left = 0; var right = arrayItems.Length - 1; for(var index=0; index<arrayItems.Length; index++) { if(arrayItems[left] > arrayItems[right]) { var temp = arrayItems[left]; arrayItems[left] = arrayItems[right]; arrayItems[right] = temp; left++; right--; } } ISortBinaryArray sortBinaryArray = new SortBinaryArray(); sortBinaryArray.SortArray(arrayItems); //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ IMath math = new Math(); Write("\n\nEnter a number for finding Factorial: "); if (int.TryParse(ReadLine(), out int number)) { var factorial = math.GetFactorial(number); WriteLine($"Factorial: {factorial}"); } //------------------------------------------------------------------------------------------ WriteLine("\n\nPress any key ..."); ReadKey(); } } }
using LogicPrograms.Interfaces; using LogicPrograms.Logics; using static System.Console; namespace LogicPrograms { class Program { static void Main(string[] args) { IMonthNames monthNames = new MonthNames(); for(var counter=1; counter <= 10; counter++) { monthNames.DisplayMonthNames(); } //------------------------------------------------------------------------------------------ var arrayItems = new int[] { 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0 }; var left = 0; var right = arrayItems.Length - 1; for(var index=0; index<arrayItems.Length; index++) { if(arrayItems[left] > arrayItems[right]) { var temp = arrayItems[left]; arrayItems[left] = arrayItems[right]; arrayItems[right] = temp; left++; right--; } } ISortBinaryArray sortBinaryArray = new SortBinaryArray(); sortBinaryArray.SortArray(arrayItems); //------------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------------ IMath math = new Math(); Write("\n\nEnter a number for finding Factorial: "); if (int.TryParse(ReadLine(), out int number)) { var factorial = math.GetFactorial(number); WriteLine($"Factorial: {factorial}"); } //------------------------------------------------------------------------------------------ WriteLine("\n\nPress any key ..."); ReadKey(); } } }
apache-2.0
C#
14aff78be5e40a92f2c58431e2472d882f0488c5
use sealed for attribute class.
AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,grokys/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,akrisiun/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex
src/Avalonia.Styling/Controls/Metadata/PseudoClassesAttribute.cs
src/Avalonia.Styling/Controls/Metadata/PseudoClassesAttribute.cs
using System; using System.Collections.Generic; #nullable enable namespace Avalonia.Controls.Metadata { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public sealed class PseudoClassesAttribute : Attribute { public PseudoClassesAttribute(params string[] pseudoClasses) { PseudoClasses = pseudoClasses; } public IReadOnlyList<string> PseudoClasses { get; } } }
using System; using System.Collections.Generic; #nullable enable namespace Avalonia.Controls.Metadata { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] public class PseudoClassesAttribute : Attribute { public PseudoClassesAttribute(params string[] pseudoClasses) { PseudoClasses = pseudoClasses; } public IReadOnlyList<string> PseudoClasses { get; } } }
mit
C#
c3f249d1fad79f91127510b7ad25ecd1509f831e
Add the all-important = sign to make arg passing work
datalust/clef-tool
src/Datalust.ClefTool/Cli/Features/InvalidDataHandlingFeature.cs
src/Datalust.ClefTool/Cli/Features/InvalidDataHandlingFeature.cs
// Copyright 2016-2017 Datalust Pty Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Datalust.ClefTool.Pipe; namespace Datalust.ClefTool.Cli.Features { class InvalidDataHandlingFeature : CommandFeature { public InvalidDataHandling InvalidDataHandling { get; private set; } public override void Enable(OptionSet options) { options.Add("invalid-data=", "Specify how invalid data is handled: fail (default), ignore, or report", v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true)); } } }
// Copyright 2016-2017 Datalust Pty Ltd // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Datalust.ClefTool.Pipe; namespace Datalust.ClefTool.Cli.Features { class InvalidDataHandlingFeature : CommandFeature { public InvalidDataHandling InvalidDataHandling { get; private set; } public override void Enable(OptionSet options) { options.Add("invalid-data", "Specify how invalid data is handled: fail (default), ignore, or report", v => InvalidDataHandling = (InvalidDataHandling)Enum.Parse(typeof(InvalidDataHandling), v, ignoreCase: true)); } } }
apache-2.0
C#
32162a153e057cf8a69b946bed2fb88f2e50dfea
Make proeprty setters private if they are not being used
jaimalchohan/mini-web-deploy,jaimalchohan/mini-web-deploy
src/MiniWebDeploy.Deployer/Features/Discovery/AssemblyDetails.cs
src/MiniWebDeploy.Deployer/Features/Discovery/AssemblyDetails.cs
using System; namespace MiniWebDeploy.Deployer.Features.Discovery { public class AssemblyDetails { public string Path { get; private set; } public string BinaryPath { get; private set; } public Type InstallerType { get; private set; } public AssemblyDetails(string path, string binaryPath, Type installerType) { Path = path; BinaryPath = binaryPath; InstallerType = installerType; } } }
using System; namespace MiniWebDeploy.Deployer.Features.Discovery { public class AssemblyDetails { public string Path { get; set; } public string BinaryPath { get; set; } public Type InstallerType { get; set; } public AssemblyDetails(string path, string binaryPath, Type installerType) { Path = path; BinaryPath = binaryPath; InstallerType = installerType; } } }
mit
C#
dc51dd9ff6f76827cdca38b439d0889885280b5f
Format document
stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard
src/OrchardCore.Modules/OrchardCore.Admin/Admin/AdminSettings.cs
src/OrchardCore.Modules/OrchardCore.Admin/Admin/AdminSettings.cs
namespace OrchardCore.Admin.Models { public class AdminSettings { public bool DisplayMenuFilter { get; set; } } }
using System; namespace OrchardCore.Admin.Models { public class AdminSettings { public bool DisplayMenuFilter{ get; set; } } }
bsd-3-clause
C#
9d2defdb908bf83db763cd6f8a69e0cefa0d9b05
Add support for metadata on BankAccount creation
stripe/stripe-dotnet
src/Stripe.net/Services/BankAccounts/BankAccountCreateOptions.cs
src/Stripe.net/Services/BankAccounts/BankAccountCreateOptions.cs
namespace Stripe { using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; public class BankAccountCreateOptions : BaseOptions, IHasMetadata { /// <summary> /// A set of key/value pairs that you can attach to an object. It can be useful for storing /// additional information about the object in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// REQUIRED. Either a token, like the ones returned by /// <a href="https://stripe.com/docs/stripe.js">Stripe.js</a>, or a /// <see cref="SourceBankAccount"/> instance containing a user’s bank account /// details. /// </summary> [JsonProperty("source")] [JsonConverter(typeof(AnyOfConverter))] public AnyOf<string, SourceBankAccount> Source { get; set; } } }
namespace Stripe { using Newtonsoft.Json; using Stripe.Infrastructure; public class BankAccountCreateOptions : BaseOptions { /// <summary> /// REQUIRED. Either a token, like the ones returned by /// <a href="https://stripe.com/docs/stripe.js">Stripe.js</a>, or a /// <see cref="SourceBankAccount"/> instance containing a user’s bank account /// details. /// </summary> [JsonProperty("source")] [JsonConverter(typeof(AnyOfConverter))] public AnyOf<string, SourceBankAccount> Source { get; set; } } }
apache-2.0
C#
78670946e4387b24a3137a313536521b0982c727
Remove default to serialization mode to Assign when using constructor YamlMemberAttribute(string)
vasily-kirichenko/SharpYaml,SiliconStudio/SharpYaml,vasily-kirichenko/SharpYaml
YamlDotNet/Serialization/YamlMemberAttribute.cs
YamlDotNet/Serialization/YamlMemberAttribute.cs
using System; namespace YamlDotNet.Serialization { /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class YamlMemberAttribute : Attribute { private readonly SerializeMemberMode serializeMethod; private readonly string name; /// <summary> /// Initializes a new instance of the <see cref="YamlMemberAttribute"/> class. /// </summary> /// <param name="order">The order.</param> public YamlMemberAttribute(int order) { Order = order; } /// <summary> /// Initializes a new instance of the <see cref="YamlMemberAttribute"/> class. /// </summary> /// <param name="name">The name.</param> public YamlMemberAttribute(string name) { this.name = name; Order = -1; } /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> /// <param name="name">The name.</param> /// <param name="serializeMethod">The serialize method.</param> public YamlMemberAttribute(string name, SerializeMemberMode serializeMethod) { this.name = name; this.serializeMethod = serializeMethod; Order = -1; } /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> /// <param name="serializeMethod">The serialize method.</param> public YamlMemberAttribute(SerializeMemberMode serializeMethod) { this.serializeMethod = serializeMethod; Order = -1; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } } /// <summary> /// Gets the serialize method1. /// </summary> /// <value>The serialize method1.</value> public SerializeMemberMode SerializeMethod { get { return serializeMethod; } } /// <summary> /// Gets or sets the order. Default is -1 (default to alphabetical) /// </summary> /// <value>The order.</value> public int Order { get; set; } } }
using System; namespace YamlDotNet.Serialization { /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)] public sealed class YamlMemberAttribute : Attribute { private readonly SerializeMemberMode serializeMethod; private readonly string name; /// <summary> /// Initializes a new instance of the <see cref="YamlMemberAttribute"/> class. /// </summary> /// <param name="order">The order.</param> public YamlMemberAttribute(int order) { Order = order; } /// <summary> /// Initializes a new instance of the <see cref="YamlMemberAttribute"/> class. /// </summary> /// <param name="name">The name.</param> public YamlMemberAttribute(string name) { this.name = name; serializeMethod = SerializeMemberMode.Assign; Order = -1; } /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> /// <param name="name">The name.</param> /// <param name="serializeMethod">The serialize method.</param> public YamlMemberAttribute(string name, SerializeMemberMode serializeMethod) { this.name = name; this.serializeMethod = serializeMethod; Order = -1; } /// <summary> /// Specify the way to store a property or field of some class or structure. /// </summary> /// <param name="serializeMethod">The serialize method.</param> public YamlMemberAttribute(SerializeMemberMode serializeMethod) { this.serializeMethod = serializeMethod; Order = -1; } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return name; } } /// <summary> /// Gets the serialize method1. /// </summary> /// <value>The serialize method1.</value> public SerializeMemberMode SerializeMethod { get { return serializeMethod; } } /// <summary> /// Gets or sets the order. Default is -1 (default to alphabetical) /// </summary> /// <value>The order.</value> public int Order { get; set; } } }
mit
C#
0aa67318d3a336ab3e9818d31c9470d9e88f186e
Fix sendmessage in usable object controller
duaiwe/ld36
src/Assets/GameObjects/UsableObjComponent/UsableObjectCS.cs
src/Assets/GameObjects/UsableObjComponent/UsableObjectCS.cs
using UnityEngine; using System.Collections; /** * Using this component: * * 1. Implement the UsableObject interface (Assets/CommonScripts/UsableObject) on a script component of your game object. * 2. Add the UsableObjectTpl Prefab as a child of your game object. * 3. Adjust Position of Transform, Radius/Offset of Circile Collider, and Radius of Emission Shape as needed. */ public class UsableObjectCS : MonoBehaviour { public GameObject target; private ParticleSystem particles; void Start () { particles = GetComponent<ParticleSystem> (); Bounds spriteBounds = GetComponentInParent<SpriteRenderer> ().bounds; ParticleSystem.ShapeModule shape = particles.shape; shape.radius = spriteBounds.extents.x * 0.8f; GetComponent<BoxCollider2D> ().size = spriteBounds.size; GetComponent<BoxCollider2D> ().offset = new Vector2 (spriteBounds.extents.x, 0); } public void OnTriggerEnter2D (Collider2D other) { if (null != particles) { particles.Play (); } if (!UISystem.Instance.CutSceneDisplaying ()) { if (null != other.GetComponents<PlayerController> ()) { target.SendMessage ("Nearby", other.gameObject); } } } public void OnTriggerExit2D (Collider2D other) { if (null != particles) { particles.Stop (); } } public void Use (GameObject user) { if (!UISystem.Instance.CutSceneDisplaying ()) { target.SendMessage ("Use", user); } } }
using UnityEngine; using System.Collections; /** * Using this component: * * 1. Implement the UsableObject interface (Assets/CommonScripts/UsableObject) on a script component of your game object. * 2. Add the UsableObjectTpl Prefab as a child of your game object. * 3. Adjust Position of Transform, Radius/Offset of Circile Collider, and Radius of Emission Shape as needed. */ public class UsableObjectCS : MonoBehaviour { public GameObject target; private ParticleSystem particles; void Start () { particles = GetComponent<ParticleSystem> (); Bounds spriteBounds = GetComponentInParent<SpriteRenderer> ().bounds; ParticleSystem.ShapeModule shape = particles.shape; shape.radius = spriteBounds.extents.x * 0.8f; GetComponent<BoxCollider2D> ().size = spriteBounds.size; GetComponent<BoxCollider2D> ().offset = new Vector2 (spriteBounds.extents.x, 0); } public void OnTriggerEnter2D (Collider2D other) { if (null != particles) { particles.Play (); } if (!UISystem.Instance.CutSceneDisplaying ()) { if (null != other.GetComponents<PlayerController> ()) { target.SendMessage ("Nearby", other); } } } public void OnTriggerExit2D (Collider2D other) { if (null != particles) { particles.Stop (); } } public void Use (GameObject user) { if (!UISystem.Instance.CutSceneDisplaying ()) { target.SendMessage ("Use", user); } } }
mit
C#
e2410395c9359ba7f86f59d8d7d175e93db9ce12
update SettingTypesController
Doozie7/ExampleConfigServer
src/ConfigService.Api/Controllers/SettingTypesController.cs
src/ConfigService.Api/Controllers/SettingTypesController.cs
using ConfigService.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ConfigService.Api.Controllers { /// <summary> /// /// </summary> [Route("api/[controller]")] public class SettingTypesController : Controller { private readonly IRepository<SettingType> _repository; private readonly ILogger<SettingTypesController> _logger; /// <summary> /// /// </summary> /// <param name="repository"></param> /// <param name="logger"></param> public SettingTypesController(IRepository<SettingType> repository, ILogger<SettingTypesController> logger) { _repository = repository; _logger = logger; } /// <summary> /// /// </summary> /// <returns></returns> [HttpGet] public IActionResult Get() { return Ok(_repository.GetListOf(c => c.Enabled, c => c.Id)); } } }
using ConfigService.Model; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace ConfigService.Api.Controllers { /// <summary> /// /// </summary> [Route("api/[controller]")] public class SettingTypesController : Controller { private readonly IRepository<SettingType> _repository; private readonly ILogger<SettingTypesController> _logger; /// <summary> /// /// </summary> /// <param name="repository"></param> /// <param name="logger"></param> public SettingTypesController(IRepository<SettingType> repository, ILogger<SettingTypesController> logger) { _repository = repository; _logger = logger; } /// <summary> /// /// </summary> /// <returns></returns> [HttpGet] public IActionResult Get() { return Ok(_repository.GetListOf(c => c.Enabled == true, c => c.Id)); } } }
mit
C#
52150dc0d80d1c361fab2a582c1d508eeea5e9bc
Save bandwidth by passing $select=CurrentDivision in GetDivision()
exactonline/ClientSDK,exactonline/exactonline-api-dotnet-client,shtrip/exactonline-api-dotnet-client,PerplexWouter/exactonline-api-dotnet-client
src/ExactOnline.Client.Sdk/Controllers/ExactOnlineClient.cs
src/ExactOnline.Client.Sdk/Controllers/ExactOnlineClient.cs
using System; using System.Linq; using ExactOnline.Client.Models; using ExactOnline.Client.Sdk.Delegates; using ExactOnline.Client.Sdk.Helpers; namespace ExactOnline.Client.Sdk.Controllers { /// <summary> /// Front Controller for working with Exact Online Entities /// </summary> public class ExactOnlineClient { private readonly ApiConnector _apiConnector; private readonly string _exactOnlineApiUrl; // https://start.exactonline.nl/api/v1 private readonly ControllerList _controllers; private int _division; #region Constructors /// <summary> /// Create instance of ExactClient /// </summary> /// <param name="exactOnlineUrl">The Exact Online URL for your country</param> /// <param name="division">Division number</param> /// <param name="accesstokenDelegate">Delegate that will be executed the access token is expired</param> public ExactOnlineClient(string exactOnlineUrl, int division, AccessTokenManagerDelegate accesstokenDelegate) { // Set culture for correct deserializing of API Response (comma and points) _apiConnector = new ApiConnector(accesstokenDelegate); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); if (!exactOnlineUrl.EndsWith("/")) exactOnlineUrl += "/"; _exactOnlineApiUrl = exactOnlineUrl + "api/v1/"; _division = (division > 0) ? division : GetDivision(); string serviceRoot = _exactOnlineApiUrl + _division + "/"; _controllers = new ControllerList(_apiConnector, serviceRoot); } /// <summary> /// Create instance of ExactClient /// </summary> /// <param name="exactOnlineUrl">{URI}/</param> /// <param name="accesstokenDelegate">Valid oAuth AccessToken</param> public ExactOnlineClient(string exactOnlineUrl, AccessTokenManagerDelegate accesstokenDelegate) : this(exactOnlineUrl, 0, accesstokenDelegate) { } #endregion #region Public methods /// <summary> /// return the division number of the current user /// </summary> /// <returns>Division number</returns> public int GetDivision() { if (_division > 0) { return _division; } var conn = new ApiConnection(_apiConnector, _exactOnlineApiUrl + "current/Me"); string response = conn.Get("$select=CurrentDivision"); response = ApiResponseCleaner.GetJsonArray(response); var converter = new EntityConverter(); var currentMe = converter.ConvertJsonArrayToObjectList<Me>(response).FirstOrDefault(); ; if (currentMe != null) { _division = currentMe.CurrentDivision; return _division; } throw new Exception("Cannot get division. Please specify division explicitly via the constructor."); } /// <summary> /// Returns instance of ExactOnlineQuery that can be used to manipulate data in Exact Online /// </summary> public ExactOnlineQuery<T> For<T>() where T : class { var controller = _controllers.GetController<T>(); return new ExactOnlineQuery<T>(controller); } #endregion } }
using System; using System.Linq; using ExactOnline.Client.Models; using ExactOnline.Client.Sdk.Delegates; using ExactOnline.Client.Sdk.Helpers; namespace ExactOnline.Client.Sdk.Controllers { /// <summary> /// Front Controller for working with Exact Online Entities /// </summary> public class ExactOnlineClient { private readonly ApiConnector _apiConnector; private readonly string _exactOnlineApiUrl; // https://start.exactonline.nl/api/v1 private readonly ControllerList _controllers; private int _division; #region Constructors /// <summary> /// Create instance of ExactClient /// </summary> /// <param name="exactOnlineUrl">The Exact Online URL for your country</param> /// <param name="division">Division number</param> /// <param name="accesstokenDelegate">Delegate that will be executed the access token is expired</param> public ExactOnlineClient(string exactOnlineUrl, int division, AccessTokenManagerDelegate accesstokenDelegate) { // Set culture for correct deserializing of API Response (comma and points) _apiConnector = new ApiConnector(accesstokenDelegate); //Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); if (!exactOnlineUrl.EndsWith("/")) exactOnlineUrl += "/"; _exactOnlineApiUrl = exactOnlineUrl + "api/v1/"; _division = (division > 0) ? division : GetDivision(); string serviceRoot = _exactOnlineApiUrl + _division + "/"; _controllers = new ControllerList(_apiConnector, serviceRoot); } /// <summary> /// Create instance of ExactClient /// </summary> /// <param name="exactOnlineUrl">{URI}/</param> /// <param name="accesstokenDelegate">Valid oAuth AccessToken</param> public ExactOnlineClient(string exactOnlineUrl, AccessTokenManagerDelegate accesstokenDelegate) : this(exactOnlineUrl, 0, accesstokenDelegate) { } #endregion #region Public methods /// <summary> /// Returns the current user data /// </summary> /// <returns>Me entity</returns> public Me CurrentMe() { var conn = new ApiConnection(_apiConnector, _exactOnlineApiUrl + "current/Me"); string response = conn.Get("$select=*"); response = ApiResponseCleaner.GetJsonArray(response); var converter = new EntityConverter(); var currentMe = converter.ConvertJsonArrayToObjectList<Me>(response); return currentMe.FirstOrDefault(); } /// <summary> /// return the division number of the current user /// </summary> /// <returns>Division number</returns> public int GetDivision() { if (_division > 0) { return _division; } var currentMe = CurrentMe(); if (currentMe != null) { _division = currentMe.CurrentDivision; return _division; } throw new Exception("Cannot get division. Please specify division explicitly via the constructor."); } /// <summary> /// Returns instance of ExactOnlineQuery that can be used to manipulate data in Exact Online /// </summary> public ExactOnlineQuery<T> For<T>() where T : class { var controller = _controllers.GetController<T>(); return new ExactOnlineQuery<T>(controller); } #endregion } }
mit
C#
32ce1a45e25a3e4cc836926bf3c73b1f774bde44
Initialize AliasMatcher with a list of candidate types
appharbor/appharbor-cli
src/AppHarbor/AliasMatcher.cs
src/AppHarbor/AliasMatcher.cs
using System; using System.Collections.Generic; namespace AppHarbor { public class AliasMatcher : IAliasMatcher { private readonly IEnumerable<Type> _candidateTypes; public AliasMatcher(IEnumerable<Type> candidateTypes) { _candidateTypes = candidateTypes; } public Type GetMatchedType(string commandArgument) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor { public class AliasMatcher : IAliasMatcher { public Type GetMatchedType(string commandArgument) { throw new NotImplementedException(); } } }
mit
C#
7aceb3230c49c14427974488d4a27bd884722ab7
change injection replacement to only apply to relevant class in library
ajepst/XlsToEf,ajepst/XlsToEf,ajepst/XlsToEf
src/XlsToEf.Example/DependencyResolution/DefaultRegistry.cs
src/XlsToEf.Example/DependencyResolution/DefaultRegistry.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DefaultRegistry.cs" company="Web Advanced"> // Copyright 2012 Web Advanced (www.webadvanced.com) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Data.Entity; using System.Web; using System.Web.Mvc; using StructureMap; using StructureMap.Graph; using XlsToEf.Example.Infrastructure; using XlsToEf.Import; namespace XlsToEf.Example.DependencyResolution { public class DefaultRegistry : Registry { #region Constructors and Destructors public DefaultRegistry() { Scan( scan => { scan.TheCallingAssembly(); scan.LookForRegistries(); scan.WithDefaultConventions(); scan.AssemblyContainingType<ImportMatchingData>(); scan.AddAllTypesOf(typeof (IModelBinder)); scan.AddAllTypesOf(typeof (IModelBinderProvider)); scan.With(new ControllerConvention()); }); For<HttpSessionStateBase>().Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session)); For<XlsToEfDbContext>().Use(new XlsToEfDbContext("XlsToEf")) .Transient(); ForConcreteType<XlsxToTableImporter>() .Configure.Ctor<DbContext>().Is<XlsToEfDbContext>(); } #endregion } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DefaultRegistry.cs" company="Web Advanced"> // Copyright 2012 Web Advanced (www.webadvanced.com) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Data.Entity; using System.Web; using System.Web.Mvc; using StructureMap; using StructureMap.Graph; using XlsToEf.Example.Infrastructure; using XlsToEf.Import; namespace XlsToEf.Example.DependencyResolution { public class DefaultRegistry : Registry { #region Constructors and Destructors public DefaultRegistry() { Scan( scan => { scan.TheCallingAssembly(); scan.LookForRegistries(); scan.WithDefaultConventions(); scan.AssemblyContainingType<ImportMatchingData>(); scan.AddAllTypesOf(typeof (IModelBinder)); scan.AddAllTypesOf(typeof (IModelBinderProvider)); scan.With(new ControllerConvention()); }); For<HttpSessionStateBase>().Use(() => new HttpSessionStateWrapper(HttpContext.Current.Session)); For<XlsToEfDbContext>().Use(new XlsToEfDbContext("XlsToEf")) .Transient(); Forward<XlsToEfDbContext, DbContext>(); } #endregion } }
mit
C#
9b596755484ed02f0ff6bb0f96741e13ad13cb3d
Hide constructors of Assertion
vain0/EnumerableTest
EnumerableTest.Core/Sdk/Assertion.cs
EnumerableTest.Core/Sdk/Assertion.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EnumerableTest.Sdk { /// <summary> /// Represents a assertion for unit tests. /// <para lang="ja"> /// 単体テストの表明を表す。 /// </para> /// </summary> public sealed class Assertion { /// <summary> /// Gets a value indicating whether the assertion was true. /// <para lang="ja"> /// 表明が成立したかどうかを取得する。 /// </para> /// </summary> public bool IsPassed { get; } /// <summary> /// Gets the message related to the assertion. /// <para lang="ja"> /// 表明に関連するメッセージを取得する。 /// </para> /// </summary> public string MessageOrNull { get; } /// <summary> /// Gets the data related to the assertion. /// <para lang="ja"> /// 表明に関連するデータを取得する。 /// </para> /// </summary> public IEnumerable<KeyValuePair<string, object>> Data { get; } internal Assertion(bool isPassed, string messageOrNull, IEnumerable<KeyValuePair<string, object>> data) { IsPassed = isPassed; MessageOrNull = MessageOrNull; Data = data; } internal Assertion(bool isPassed, IEnumerable<KeyValuePair<string, object>> data) : this(isPassed, null, data) { } internal static Assertion Pass { get; } = new Assertion(true, Enumerable.Empty<KeyValuePair<string, object>>()); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace EnumerableTest.Sdk { /// <summary> /// Represents a assertion for unit tests. /// <para lang="ja"> /// 単体テストの表明を表す。 /// </para> /// </summary> public sealed class Assertion { /// <summary> /// Gets a value indicating whether the assertion was true. /// <para lang="ja"> /// 表明が成立したかどうかを取得する。 /// </para> /// </summary> public bool IsPassed { get; } /// <summary> /// Gets the message related to the assertion. /// <para lang="ja"> /// 表明に関連するメッセージを取得する。 /// </para> /// </summary> public string MessageOrNull { get; } /// <summary> /// Gets the data related to the assertion. /// <para lang="ja"> /// 表明に関連するデータを取得する。 /// </para> /// </summary> public IEnumerable<KeyValuePair<string, object>> Data { get; } public Assertion(bool isPassed, string messageOrNull, IEnumerable<KeyValuePair<string, object>> data) { IsPassed = isPassed; MessageOrNull = MessageOrNull; Data = data; } public Assertion(bool isPassed, IEnumerable<KeyValuePair<string, object>> data) : this(isPassed, null, data) { } public static Assertion Pass { get; } = new Assertion(true, Enumerable.Empty<KeyValuePair<string, object>>()); } }
mit
C#
32c145f03fdd37955df9250582d8dff1629b646e
Remove loosy conversion.
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
src/Narvalo.Finance/Money$.cs
src/Narvalo.Finance/Money$.cs
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Finance { using System; public partial struct Money { public static Money Create(decimal amount) => new Money(amount, Currency.Of("XXX")); public static Money Create(long amount, Currency currency) => new Money(amount, currency); [CLSCompliant(false)] public static Money Create(ulong amount, Currency currency) => new Money(amount, currency); } }
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo.Finance { using System; public partial struct Money { public static Money Create(decimal amount) => new Money(amount, Currency.Of("XXX")); public static Money Create(double amount, Currency currency) => new Money((decimal)amount, currency); public static Money Create(long amount, Currency currency) => new Money(amount, currency); [CLSCompliant(false)] public static Money Create(ulong amount, Currency currency) => new Money(amount, currency); } }
bsd-2-clause
C#
0d971047365c3399ec8cefaa8eab51ae0131964c
Update InputSimulationEnum.cs
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Core/Providers/InputSimulation/InputSimulationEnum.cs
Assets/MRTK/Core/Providers/InputSimulation/InputSimulationEnum.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Defines for how input simulation handles movement /// </summary> public enum InputSimulationControlMode { /// <summary> /// Move in the main camera forward direction /// </summary> Fly, /// <summary> /// Move on a X/Z plane /// </summary> Walk, } /// <summary> /// Defines for how input simulation handles eye gaze /// </summary> public enum EyeGazeSimulationMode { /// <summary> /// Disable eye gaze simulation /// </summary> Disabled, /// <summary> /// Eye gaze follows the camera forward axis /// </summary> CameraForwardAxis, /// <summary> /// Eye gaze follows the mouse /// </summary> Mouse, } /// <summary> /// Defines for how input simulation handles controllers /// </summary> public enum ControllerSimulationMode { /// <summary> /// Disable controller simulation /// </summary> Disabled, /// <summary> /// Raises hand gesture events only /// </summary> HandGestures, /// <summary> /// Provide a fully articulated hand controller /// </summary> ArticulatedHand, /// <summary> /// Provide a 6DoF motion controller /// </summary> MotionController, } #region Obsolete Enum /// <summary> /// Defines for how input simulation handles controllers /// </summary> [Obsolete("Use ControllerSimulationMode instead.")] public enum HandSimulationMode { /// <summary> /// Disable controller simulation /// </summary> Disabled = ControllerSimulationMode.Disabled, /// <summary> /// Raises hand gesture events only /// </summary> Gestures = ControllerSimulationMode.HandGestures, /// <summary> /// Provide a fully articulated hand controller /// </summary> Articulated = ControllerSimulationMode.ArticulatedHand, /// <summary> /// Provide a 6DoF motion controller /// </summary> MotionController = ControllerSimulationMode.MotionController, } #endregion }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit.Input { /// <summary> /// Defines for how input simulation handles movement /// </summary> public enum InputSimulationControlMode { /// <summary> /// Move in the main camera forward direction /// </summary> Fly, /// <summary> /// Move on a X/Z plane /// </summary> Walk, } /// <summary> /// Defines for how input simulation handles eye gaze /// </summary> public enum EyeGazeSimulationMode { /// <summary> /// Disable eye gaze simulation /// </summary> Disabled, /// <summary> /// Eye gaze follows the camera forward axis /// </summary> CameraForwardAxis, /// <summary> /// Eye gaze follows the mouse /// </summary> Mouse, } /// <summary> /// Defines for how input simulation handles controllers /// </summary> public enum ControllerSimulationMode { /// <summary> /// Disable controller simulation /// </summary> Disabled, /// <summary> /// Raises hand gesture events only /// </summary> HandGestures, /// <summary> /// Provide a fully articulated hand controller /// </summary> ArticulatedHand, /// <summary> /// Provide a 6DoF motion controller /// </summary> MotionController, } /// <summary> /// Defines for how input simulation handles controllers /// </summary> [Obsolete("Use ControllerSimulationMode instead.")] public enum HandSimulationMode { /// <summary> /// Disable controller simulation /// </summary> Disabled = ControllerSimulationMode.Disabled, /// <summary> /// Raises hand gesture events only /// </summary> Gestures = ControllerSimulationMode.HandGestures, /// <summary> /// Provide a fully articulated hand controller /// </summary> Articulated = ControllerSimulationMode.ArticulatedHand, /// <summary> /// Provide a 6DoF motion controller /// </summary> MotionController = ControllerSimulationMode.MotionController, } }
mit
C#
53cde896383562d22e6b24ed493ca5110f9cb34f
Update Settings.Designer.cs
sbennett1990/WordOfTheDay
WordOfTheDay.Window/Properties/Settings.Designer.cs
WordOfTheDay.Window/Properties/Settings.Designer.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WordOfTheDay.Window.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("dictionary.dat")] public string DictionaryFileName { get { return ((string)(this["DictionaryFileName"])); } set { this["DictionaryFileName"] = value; } } [global::System.Configuration.UserScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.DefaultSettingValueAttribute("")] public string DictionaryPath { get { return ((string)(this["DictionaryPath"])); } set { this["DictionaryPath"] = value; } } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18444 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WordOfTheDay.Window.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
bsd-2-clause
C#
e5daf18d78723312c4de6d6facb5bdfaa100ca0d
Use const for values of MobilePlatform
rajfidel/appium-dotnet-driver,rajfidel/appium-dotnet-driver,appium/appium-dotnet-driver
appium-dotnet-driver/Appium/Enums/MobilePlatform.cs
appium-dotnet-driver/Appium/Enums/MobilePlatform.cs
//Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //See the NOTICE file distributed with this work for additional //information regarding copyright ownership. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. namespace OpenQA.Selenium.Appium.Enums { public sealed class MobilePlatform { public const string Android = "Android"; public const string IOS = "iOS"; public const string Windows = "Windows"; //FireFoxOS and WinPhone will be added when there will be the supporting of appropriate mobile OS. } }
//Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //See the NOTICE file distributed with this work for additional //information regarding copyright ownership. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. namespace OpenQA.Selenium.Appium.Enums { public sealed class MobilePlatform { public static readonly string Android = "Android"; public static readonly string IOS = "iOS"; public static readonly string Windows = "Windows"; //FireFoxOS and WinPhone will be added when there will be the supporting of appropriate mobile OS. } }
apache-2.0
C#
bc95a4a6c175e5999bcb916048029c933c524532
Add missing @ (#184)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.DotNet.Web.ProjectTemplates/content/StarterWeb-CSharp/Areas/Identity/Views/Account/AccessDenied.cshtml
src/Microsoft.DotNet.Web.ProjectTemplates/content/StarterWeb-CSharp/Areas/Identity/Views/Account/AccessDenied.cshtml
@{ ViewData["Title"] = "Access denied"; } <header> <h2 class="text-danger">@ViewData["Title"]</h2> <p class="text-danger">You do not have access to this resource.</p> </header>
@{ ViewData["Title"] = "Access denied"; } <header> <h2 class="text-danger">ViewData["Title"]</h2> <p class="text-danger">You do not have access to this resource.</p> </header>
apache-2.0
C#
9e7dc6d1b11a62a883745cea92857c6436dae3e6
Make DeadLetterEvent constructor internal
Bee-Htcpcp/protoactor-dotnet,AsynkronIT/protoactor-dotnet,masteryee/protoactor-dotnet,masteryee/protoactor-dotnet,Bee-Htcpcp/protoactor-dotnet,tomliversidge/protoactor-dotnet,raskolnikoov/protoactor-dotnet,raskolnikoov/protoactor-dotnet,tomliversidge/protoactor-dotnet
src/Proto.Actor/DeadLetter.cs
src/Proto.Actor/DeadLetter.cs
// ----------------------------------------------------------------------- // <copyright file="DeadLetter.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- namespace Proto { public class DeadLetterEvent { internal DeadLetterEvent(PID pid, object message, PID sender) { Pid = pid; Message = message; Sender = sender; } public PID Pid { get; } public object Message { get; } public PID Sender { get; } } public class DeadLetterProcess : Process { public static readonly DeadLetterProcess Instance = new DeadLetterProcess(); protected internal override void SendUserMessage(PID pid, object message) { var (msg,sender, _) = MessageEnvelope.Unwrap(message); EventStream.Instance.Publish(new DeadLetterEvent(pid, msg, sender)); } protected internal override void SendSystemMessage(PID pid, object message) { EventStream.Instance.Publish(new DeadLetterEvent(pid, message, null)); } } }
// ----------------------------------------------------------------------- // <copyright file="DeadLetter.cs" company="Asynkron HB"> // Copyright (C) 2015-2017 Asynkron HB All rights reserved // </copyright> // ----------------------------------------------------------------------- namespace Proto { public class DeadLetterEvent { public DeadLetterEvent(PID pid, object message, PID sender) { Pid = pid; Message = message; Sender = sender; } public PID Pid { get; } public object Message { get; } public PID Sender { get; } } public class DeadLetterProcess : Process { public static readonly DeadLetterProcess Instance = new DeadLetterProcess(); protected internal override void SendUserMessage(PID pid, object message) { var (msg,sender, _) = MessageEnvelope.Unwrap(message); EventStream.Instance.Publish(new DeadLetterEvent(pid, msg, sender)); } protected internal override void SendSystemMessage(PID pid, object message) { EventStream.Instance.Publish(new DeadLetterEvent(pid, message, null)); } } }
apache-2.0
C#
c98fc72a9a55a1dcc87c48800d66cecd027ea2d0
Verify ElementExists() executes quickly
rcasady616/Selenium.WeDriver.Equip,rcasady616/Selenium.WeDriver.Equip
SeleniumExtension.Tests/Extensions/SearchContextExtensionTests.cs
SeleniumExtension.Tests/Extensions/SearchContextExtensionTests.cs
using System.Diagnostics; using NUnit.Framework; using OpenQA.Selenium; using TestWebPages.UIFramework.Pages; namespace SeleniumExtension.Tests.Extensions { [TestFixture] [Category("Extension")] public class SearchContextExtentionTests : BaseTest { public AjaxyControlPage Page; [SetUp] public void SetupSearchContextExtentionTests() { Driver.Navigate().GoToUrl(AjaxyControlPage.Url); Page = new AjaxyControlPage(Driver); Assert.AreEqual(true, Page.IsPageLoaded()); } [Category("unit")] [TestCase(true, "red")] [TestCase(false, "NeverGonnaGetItNeverGonnaGetIt")] public void TestElementExists(bool expected, string id) { var sw = new Stopwatch(); sw.Start(); var ret = Driver.ElementExists(By.Id(id)); sw.Stop(); Assert.Less(sw.Elapsed.Seconds, 1); Assert.AreEqual(expected, Driver.ElementExists(By.Id(id))); } } }
using NUnit.Framework; using OpenQA.Selenium; using TestWebPages.UIFramework.Pages; namespace SeleniumExtension.Tests.Extensions { [TestFixture] [Category("Extension")] public class SearchContextExtentionTests : BaseTest { public AjaxyControlPage Page; [SetUp] public void SetupSearchContextExtentionTests() { Driver.Navigate().GoToUrl(AjaxyControlPage.Url); Page = new AjaxyControlPage(Driver); Assert.AreEqual(true, Page.IsPageLoaded()); } [Category("unit")] [TestCase(true, "red")] [TestCase(false, "NeverGonnaGetItNeverGonnaGetIt")] public void TestElementExists(bool expected, string id) { Assert.AreEqual(expected, Driver.ElementExists(By.Id(id))); } } }
mit
C#
57a2f5367c744b74442764e785c02af6bdb433ab
Update Agent String (#3804)
quantumagi/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode
src/Stratis.Bitcoin.Features.SmartContracts/SmartContractVersionProvider.cs
src/Stratis.Bitcoin.Features.SmartContracts/SmartContractVersionProvider.cs
using Stratis.Bitcoin.Interfaces; namespace Stratis.Bitcoin.Features.SmartContracts { public sealed class SmartContractVersionProvider : IVersionProvider { /// <inheritdoc /> public string GetVersion() { return "1.0.1"; } } }
using Stratis.Bitcoin.Interfaces; namespace Stratis.Bitcoin.Features.SmartContracts { public sealed class SmartContractVersionProvider : IVersionProvider { /// <inheritdoc /> public string GetVersion() { return "1.0.0"; } } }
mit
C#
940726ddc7dc2d31620a1348d4fceb898fa60931
Change the layout a little
GNOME/f-spot,dkoeb/f-spot,Yetangitu/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,dkoeb/f-spot,GNOME/f-spot,dkoeb/f-spot,GNOME/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,mans0954/f-spot,mono/f-spot,dkoeb/f-spot,Sanva/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,Sanva/f-spot,NguyenMatthieu/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,mans0954/f-spot,GNOME/f-spot,mono/f-spot,dkoeb/f-spot,mans0954/f-spot,mans0954/f-spot,NguyenMatthieu/f-spot,mono/f-spot,Yetangitu/f-spot,mans0954/f-spot,Yetangitu/f-spot,Sanva/f-spot,mono/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter
src/InfoDisplay.cs
src/InfoDisplay.cs
using System; namespace FSpot { public class InfoDisplay : Gtk.HTML { public InfoDisplay () { } private ExifData exif_info; private Photo photo; public Photo Photo { get { return photo; } set { photo = value; if (exif_info != null) exif_info.Dispose (); if (photo != null) { exif_info = new ExifData (photo.DefaultVersionPath); exif_info.Assemble (); } else { exif_info = null; } this.Update (); } } protected override void OnStyleSet (Gtk.Style previous) { base.OnStyleSet (previous); this.Update (); } private string Color (Gdk.Color color) { Byte r = (byte)(color.Red / 256); Byte b = (byte)(color.Blue / 256); Byte g = (byte)(color.Green / 256); string value = r.ToString ("x2") + g.ToString ("x2") + b.ToString ("x2"); return value; } protected override void OnUrlRequested (string url, Gtk.HTMLStream stream) { if (url == "exif:thumbnail") { byte [] data = exif_info.Data; if (data.Length > 0) { stream.Write (data, data.Length); stream.Close (Gtk.HTMLStreamStatus.Ok); } else stream.Close (Gtk.HTMLStreamStatus.Error); } } private void Update () { Gtk.HTMLStream stream = this.Begin ("text/html; charset=utf-8"); string bg = Color (this.Style.Background (Gtk.StateType.Active)); string fg = Color (this.Style.Foreground (Gtk.StateType.Active)); string ig = Color (this.Style.Base (Gtk.StateType.Active)); if (exif_info != null) { stream.Write ("<table width=100% cellspacing=0 cellpadding=3>"); stream.Write ("<tr><td colspan=2 align=\"center\" bgcolor=\"" + ig + "\"><img center src=\"exif:thumbnail\"></td></tr>"); foreach (ExifTag tag in exif_info.Tags) { stream.Write ("<tr><td valign=top align=right bgcolor=\""+ bg + "\"><font color=\"" + fg + "\">"); stream.Write (ExifUtil.GetTagTitle (tag)); stream.Write ("</font></td><td>"); if (exif_info.LookupString (tag) != "") stream.Write (exif_info.LookupString (tag)); stream.Write ("</td><tr>"); } stream.Write ("</table>"); } End (stream, Gtk.HTMLStreamStatus.Ok); } } }
using System; namespace FSpot { public class InfoDisplay : Gtk.HTML { public InfoDisplay () { } private ExifData exif_info; private Photo photo; public Photo Photo { get { return photo; } set { photo = value; if (exif_info != null) exif_info.Dispose (); if (photo != null) { exif_info = new ExifData (photo.DefaultVersionPath); exif_info.Assemble (); } else { exif_info = null; } this.Update (); } } protected override void OnStyleSet (Gtk.Style previous) { base.OnStyleSet (previous); this.Update (); } private string Color (Gdk.Color color) { Byte r = (byte)(color.Red / 256); Byte b = (byte)(color.Blue / 256); Byte g = (byte)(color.Green / 256); string value = r.ToString ("x2") + g.ToString ("x2") + b.ToString ("x2"); return value; } protected override void OnUrlRequested (string url, Gtk.HTMLStream stream) { if (url == "exif:thumbnail") { byte [] data = exif_info.Data; if (data.Length > 0) { stream.Write (data, data.Length); stream.Close (Gtk.HTMLStreamStatus.Ok); } else stream.Close (Gtk.HTMLStreamStatus.Error); } } private void Update () { Gtk.HTMLStream stream = this.Begin ("text/html; charset=utf-8"); string bg = Color (this.Style.Background (Gtk.StateType.Active)); string fg = Color (this.Style.Foreground (Gtk.StateType.Active)); if (exif_info != null) { stream.Write ("<table width=100% cellspacing=0 cellpadding=3>"); stream.Write ("<tr><td colspan=2 align=\"center\" bgcolor=\"" + bg + "\"><img center src=\"exif:thumbnail\"></td></tr>"); foreach (ExifTag tag in exif_info.Tags) { stream.Write ("<tr><td bgcolor=\""+ bg + "\"><font color=\"" + fg + "\">"); stream.Write (ExifUtil.GetTagTitle (tag)); stream.Write ("</font></td><td>"); if (exif_info.LookupString (tag) != "") stream.Write (exif_info.LookupString (tag)); stream.Write ("</td><tr>"); } stream.Write ("</table>"); } End (stream, Gtk.HTMLStreamStatus.Ok); } } }
mit
C#
1a6d214ffe14989a1d1417addbf7de10a89119f3
Make HebrewMonthConverter internal.
malcolmr/nodatime,jskeet/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,malcolmr/nodatime
src/NodaTime/Calendars/HebrewMonthConverter.cs
src/NodaTime/Calendars/HebrewMonthConverter.cs
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. namespace NodaTime.Calendars { /// <summary> /// Conversions between civil and ecclesiastical month numbers in the Hebrew calendar system. /// </summary> internal static class HebrewMonthConverter { /// <summary> /// Given a civil month number and a year in which it occurs, this method returns /// the equivalent ecclesiastical month number. /// </summary> /// <remarks> /// No validation is performed in this method: an input month number of 13 in a non-leap-year /// will return a result of 7. /// </remarks> /// <param name="year">Year during which the month occurs.</param> /// <param name="month">Civil month number.</param> /// <returns>The ecclesiastical month number.</returns> internal static int CivilToEcclesiastical(int year, int month) { if (month < 7) { return month + 6; } bool leapYear = HebrewEcclesiasticalCalculator.IsLeapYear(year); if (month == 7) // Adar II (13) or Nisan (1) depending on whether it's a leap year. { return leapYear ? 13 : 1; } return leapYear ? month - 7 : month - 6; } /// <summary> /// Given an ecclesiastical month number and a year in which it occurs, this method returns /// the equivalent ecclesiastical month number. /// </summary> /// <remarks> /// No validation is performed in this method: an input month number of 13 in a non-leap-year /// will return a result of 7. /// </remarks> /// <param name="year">Year during which the month occurs.</param> /// <param name="month">Civil month number.</param> /// <returns>The ecclesiastical month number.</returns> internal static int EcclesiasticalToCivil(int year, int month) { if (month >= 7) { return month - 6; } return HebrewEcclesiasticalCalculator.IsLeapYear(year) ? month + 7 : month + 6; } } }
// Copyright 2014 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. namespace NodaTime.Calendars { /// <summary> /// Conversions between civil and ecclesiastical month numbers in the Hebrew calendar system. /// </summary> public static class HebrewMonthConverter { /// <summary> /// Given a civil month number and a year in which it occurs, this method returns /// the equivalent ecclesiastical month number. /// </summary> /// <remarks> /// No validation is performed in this method: an input month number of 13 in a non-leap-year /// will return a result of 7. /// </remarks> /// <param name="year">Year during which the month occurs.</param> /// <param name="month">Civil month number.</param> /// <returns>The ecclesiastical month number.</returns> public static int CivilToEcclesiastical(int year, int month) { if (month < 7) { return month + 6; } bool leapYear = HebrewEcclesiasticalCalculator.IsLeapYear(year); if (month == 7) // Adar II (13) or Nisan (1) depending on whether it's a leap year. { return leapYear ? 13 : 1; } return leapYear ? month - 7 : month - 6; } /// <summary> /// Given an ecclesiastical month number and a year in which it occurs, this method returns /// the equivalent ecclesiastical month number. /// </summary> /// <remarks> /// No validation is performed in this method: an input month number of 13 in a non-leap-year /// will return a result of 7. /// </remarks> /// <param name="year">Year during which the month occurs.</param> /// <param name="month">Civil month number.</param> /// <returns>The ecclesiastical month number.</returns> public static int EcclesiasticalToCivil(int year, int month) { if (month >= 7) { return month - 6; } return HebrewEcclesiasticalCalculator.IsLeapYear(year) ? month + 7 : month + 6; } } }
apache-2.0
C#
c0d20d8ce430a2ee7257c7ac8cf34eeefd54489f
Add some spacing to interface class
peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game.Rulesets.Catch/Objects/Drawables/IHasCatchObjectState.cs
osu.Game.Rulesets.Catch/Objects/Drawables/IHasCatchObjectState.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects.Drawables { /// <summary> /// Provides a visual state of a <see cref="PalpableCatchHitObject"/>. /// </summary> public interface IHasCatchObjectState { PalpableCatchHitObject HitObject { get; } Bindable<Color4> AccentColour { get; } Bindable<bool> HyperDash { get; } Vector2 DisplaySize { get; } float DisplayRotation { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osuTK; using osuTK.Graphics; namespace osu.Game.Rulesets.Catch.Objects.Drawables { /// <summary> /// Provides a visual state of a <see cref="PalpableCatchHitObject"/>. /// </summary> public interface IHasCatchObjectState { PalpableCatchHitObject HitObject { get; } Bindable<Color4> AccentColour { get; } Bindable<bool> HyperDash { get; } Vector2 DisplaySize { get; } float DisplayRotation { get; } } }
mit
C#
541620eb018b76dd7eb20255b087456b8de97341
tidy up to reuse extension method
rzhw/Squirrel.Windows,rzhw/Squirrel.Windows
src/Shimmer.WiXUi/ViewModels/ErrorViewModel.cs
src/Shimmer.WiXUi/ViewModels/ErrorViewModel.cs
using System; using System.Reactive.Linq; using NuGet; using ReactiveUI; using ReactiveUI.Routing; using ReactiveUI.Xaml; using Shimmer.Client.WiXUi; using Shimmer.Core.Extensions; namespace Shimmer.WiXUi.ViewModels { public class ErrorViewModel : ReactiveObject, IErrorViewModel { public string UrlPathSegment { get { return "error"; } } public IScreen HostScreen { get; private set; } IPackage _PackageMetadata; public IPackage PackageMetadata { get { return _PackageMetadata; } set { this.RaiseAndSetIfChanged(x => x.PackageMetadata, value); } } ObservableAsPropertyHelper<string> _Title; public string Title { get { return _Title.Value; } } UserError _Error; public UserError Error { get { return _Error; } set { this.RaiseAndSetIfChanged(x => x.Error, value); } } public ReactiveCommand Shutdown { get; protected set; } public ErrorViewModel(IScreen hostScreen) { HostScreen = hostScreen; Shutdown = new ReactiveCommand(); this.WhenAny(x => x.PackageMetadata, x => x.Value.ExtractTitle()) .ToProperty(this, x => x.Title); } } }
using System; using System.Reactive.Linq; using NuGet; using ReactiveUI; using ReactiveUI.Routing; using ReactiveUI.Xaml; using Shimmer.Client.WiXUi; namespace Shimmer.WiXUi.ViewModels { public class ErrorViewModel : ReactiveObject, IErrorViewModel { public string UrlPathSegment { get { return "error"; } } public IScreen HostScreen { get; private set; } IPackage _PackageMetadata; public IPackage PackageMetadata { get { return _PackageMetadata; } set { this.RaiseAndSetIfChanged(x => x.PackageMetadata, value); } } ObservableAsPropertyHelper<string> _Title; public string Title { get { return _Title.Value; } } UserError _Error; public UserError Error { get { return _Error; } set { this.RaiseAndSetIfChanged(x => x.Error, value); } } public ReactiveCommand Shutdown { get; protected set; } public ErrorViewModel(IScreen hostScreen) { HostScreen = hostScreen; Shutdown = new ReactiveCommand(); this.WhenAny(x => x.PackageMetadata, x => x.Value) .SelectMany(metadata => metadata != null ? Observable.Return(new Tuple<string, string>(metadata.Title, metadata.Id)) : Observable.Return(new Tuple<string, string>("", ""))) .Select(tuple => !String.IsNullOrWhiteSpace(tuple.Item1) ? tuple.Item1 : tuple.Item2) .ToProperty(this, x => x.Title); } } }
mit
C#
f147951d92ff5b4413d7ffdd55dcc91dfcfdfdca
Revert "use WebHost.CreateDefaultBuilder in IdentitySample.Mvc"
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/IdentitySample.Mvc/Program.cs
samples/IdentitySample.Mvc/Program.cs
using System.IO; using Microsoft.AspNetCore.Hosting; namespace IdentitySample { public static class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace IdentitySample { public static class Program { public static void Main(string[] args) => BuildWebHost(args).Run(); public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
apache-2.0
C#
1d939c7f99f735e1a14611a90904f0dca48e1133
Update assembly file version for next release
enckse/StyleCopCmd,enckse/StyleCopCmd
StyleCopCmd.Core/Properties/CommonAssemblyInfo.cs
StyleCopCmd.Core/Properties/CommonAssemblyInfo.cs
//------------------------------------------------------------------------------ // <copyright // file="CommonAssemblyInfo.cs" // company="enckse"> // Copyright (c) All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyFileVersion("1.3.1.0")]
//------------------------------------------------------------------------------ // <copyright // file="CommonAssemblyInfo.cs" // company="enckse"> // Copyright (c) All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyVersion("1.3.0.0")] [assembly: System.CLSCompliant(true)] [assembly: System.Runtime.InteropServices.ComVisible(false)] [assembly: AssemblyFileVersion("1.3.0.0")]
bsd-3-clause
C#
5c5950d17f9a3d6f89cc429e32dd5ef6dcf45bea
add test object creator for valid school model
mzrimsek/resume-site-api
Test.Integration/TestHelpers/TestObjectCreator.cs
Test.Integration/TestHelpers/TestObjectCreator.cs
using System.Net.Http; using Web.Models.JobModels; using Web.Models.JobProjectModels; using Web.Models.SchoolModels; namespace Test.Integration.TestHelpers { public class TestObjectCreator { private HttpClient _client; public TestObjectCreator(HttpClient client) { _client = client; } public int GetIdForNewJob() { var model = TestObjectGetter.GetAddUpdateJobViewModel(); var requestContent = RequestHelper.GetRequestContentFromObject(model); var response = _client.PostAsync($"{ControllerRouteEnum.JOB}", requestContent).Result; return RequestHelper.GetObjectFromResponseContent<JobViewModel>(response).Id; } public int GetIdFromNewJobProject(int jobId) { var model = TestObjectGetter.GetAddUpdateJobProjectViewModel(jobId); var requestContent = RequestHelper.GetRequestContentFromObject(model); var response = _client.PostAsync($"{ControllerRouteEnum.JOB_PROJECT}", requestContent).Result; return RequestHelper.GetObjectFromResponseContent<JobProjectViewModel>(response).Id; } public int GetIdFromNewSchool() { var model = TestObjectGetter.GetAddUpdateSchoolViewModel(); var requestContent = RequestHelper.GetRequestContentFromObject(model); var response = _client.PostAsync($"{ControllerRouteEnum.SCHOOL}", requestContent).Result; return RequestHelper.GetObjectFromResponseContent<SchoolViewModel>(response).Id; } } }
using System.Net.Http; using Web.Models.JobModels; using Web.Models.JobProjectModels; namespace Test.Integration.TestHelpers { public class TestObjectCreator { private HttpClient _client; public TestObjectCreator(HttpClient client) { _client = client; } public int GetIdForNewJob() { var model = TestObjectGetter.GetAddUpdateJobViewModel(); var requestContent = RequestHelper.GetRequestContentFromObject(model); var response = _client.PostAsync($"{ControllerRouteEnum.JOB}", requestContent).Result; return RequestHelper.GetObjectFromResponseContent<JobViewModel>(response).Id; } public int GetIdFromNewJobProject(int jobId) { var model = TestObjectGetter.GetAddUpdateJobProjectViewModel(jobId); var requestContent = RequestHelper.GetRequestContentFromObject(model); var response = _client.PostAsync($"{ControllerRouteEnum.JOB_PROJECT}", requestContent).Result; return RequestHelper.GetObjectFromResponseContent<JobProjectViewModel>(response).Id; } } }
mit
C#
4a16ac53bab407adeceadc992c5ec6c8eb1dd10e
Remove extra newline
peppy/osu,peppy/osu,johnneijzen/osu,smoogipooo/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,ZLima12/osu,2yangk23/osu,EVAST9919/osu,UselessToucan/osu
osu.Game/Database/IModelDownloader.cs
osu.Game/Database/IModelDownloader.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API; using System; namespace osu.Game.Database { /// <summary> /// Represents a <see cref="IModelManager{TModel}"/> that can download new models from an external source. /// </summary> /// <typeparam name="TModel">The model type.</typeparam> public interface IModelDownloader<TModel> : IModelManager<TModel> where TModel : class { /// <summary> /// Fired when a <see cref="TModel"/> download begins. /// </summary> event Action<ArchiveDownloadRequest<TModel>> DownloadBegan; /// <summary> /// Fired when a <see cref="TModel"/> download is interrupted, either due to user cancellation or failure. /// </summary> event Action<ArchiveDownloadRequest<TModel>> DownloadFailed; /// <summary> /// Checks whether a given <see cref="TModel"/> is already available in the local store. /// </summary> /// <param name="model">The <see cref="TModel"/> whose existence needs to be checked.</param> /// <returns>Whether the <see cref="TModel"/> exists.</returns> bool IsAvailableLocally(TModel model); /// <summary> /// Downloads a <see cref="TModel"/>. /// This may post notifications tracking progress. /// </summary> /// <param name="model">The <see cref="TModel"/> to be downloaded.</param> /// <returns>Whether downloading can happen.</returns> bool Download(TModel model); /// <summary> /// Downloads a <see cref="TModel"/> with optional parameters for the download request. /// This may post notifications tracking progress. /// </summary> /// <param name="model">The <see cref="TModel"/> to be downloaded.</param> /// <param name="extra">Optional parameters to be used for creating the download request.</param> /// <returns>Whether downloading can happen.</returns> bool Download(TModel model, params object[] extra); /// <summary> /// Gets an existing <see cref="TModel"/> download request if it exists. /// </summary> /// <param name="model">The <see cref="TModel"/> whose request is wanted.</param> /// <returns>The <see cref="ArchiveDownloadRequest{TModel}"/> object if it exists, otherwise null.</returns> ArchiveDownloadRequest<TModel> GetExistingDownload(TModel model); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Online.API; using System; namespace osu.Game.Database { /// <summary> /// Represents a <see cref="IModelManager{TModel}"/> that can download new models from an external source. /// </summary> /// <typeparam name="TModel">The model type.</typeparam> public interface IModelDownloader<TModel> : IModelManager<TModel> where TModel : class { /// <summary> /// Fired when a <see cref="TModel"/> download begins. /// </summary> event Action<ArchiveDownloadRequest<TModel>> DownloadBegan; /// <summary> /// Fired when a <see cref="TModel"/> download is interrupted, either due to user cancellation or failure. /// </summary> event Action<ArchiveDownloadRequest<TModel>> DownloadFailed; /// <summary> /// Checks whether a given <see cref="TModel"/> is already available in the local store. /// </summary> /// <param name="model">The <see cref="TModel"/> whose existence needs to be checked.</param> /// <returns>Whether the <see cref="TModel"/> exists.</returns> bool IsAvailableLocally(TModel model); /// <summary> /// Downloads a <see cref="TModel"/>. /// This may post notifications tracking progress. /// </summary> /// <param name="model">The <see cref="TModel"/> to be downloaded.</param> /// <returns>Whether downloading can happen.</returns> bool Download(TModel model); /// <summary> /// Downloads a <see cref="TModel"/> with optional parameters for the download request. /// This may post notifications tracking progress. /// </summary> /// <param name="model">The <see cref="TModel"/> to be downloaded.</param> /// <param name="extra">Optional parameters to be used for creating the download request.</param> /// <returns>Whether downloading can happen.</returns> bool Download(TModel model, params object[] extra); /// <summary> /// Gets an existing <see cref="TModel"/> download request if it exists. /// </summary> /// <param name="model">The <see cref="TModel"/> whose request is wanted.</param> /// <returns>The <see cref="ArchiveDownloadRequest{TModel}"/> object if it exists, otherwise null.</returns> ArchiveDownloadRequest<TModel> GetExistingDownload(TModel model); } }
mit
C#
0bf2fa105f5582360c88e4162bc1fd70536ef683
Test jenkins.
sguzunov/CodeIt,sguzunov/CodeIt
CodeIt/CodeIt.UnitTests/DbModels/ChallengeTests/TimeInMs_Should.cs
CodeIt/CodeIt.UnitTests/DbModels/ChallengeTests/TimeInMs_Should.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using CodeIt.Data.Models; using System.ComponentModel.DataAnnotations; namespace CodeIt.UnitTests.DbModels.ChallengeTests { [TestFixture] public class TimeInMs_Should { [Test] public void Be_OfTypeDouble() { // Arrange var challenge = new Challenge(); // Act & Assert Assert.IsTrue(challenge.TimeInMs.GetType() == typeof(double)); } [Test] public void Has_RequiredAttribute() { // Arrange var challenge = new Challenge(); // Act var hasAttr = challenge .GetType() .GetProperty(nameof(Challenge.TimeInMs)) .GetCustomAttributes(false) .Where(x => x.GetType() == typeof(RequiredAttribute)) .Any(); // Assert Assert.IsTrue(hasAttr); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using CodeIt.Data.Models; using System.ComponentModel.DataAnnotations; namespace CodeIt.UnitTests.DbModels.ChallengeTests { [TestFixture] public class TimeInMs_Should { [Test] public void Be_OfTypeInt() { // Arrange var challenge = new Challenge(); // Act & Assert Assert.IsTrue(challenge.TimeInMs.GetType() == typeof(int)); } [Test] public void Has_RequiredAttribute() { // Arrange var challenge = new Challenge(); // Act var hasAttr = challenge .GetType() .GetProperty(nameof(Challenge.TimeInMs)) .GetCustomAttributes(false) .Where(x => x.GetType() == typeof(RequiredAttribute)) .Any(); // Assert Assert.IsTrue(hasAttr); } } }
mit
C#
c7836c384c152dc3ee0c6259198af6c454d48386
Add workaround required after MapODataServiceRoute
luchaoshuai/aspnetboilerplate,fengyeju/aspnetboilerplate,virtualcca/aspnetboilerplate,andmattia/aspnetboilerplate,virtualcca/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,beratcarsi/aspnetboilerplate,AlexGeller/aspnetboilerplate,Nongzhsh/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ryancyq/aspnetboilerplate,zclmoon/aspnetboilerplate,AlexGeller/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,zclmoon/aspnetboilerplate,carldai0106/aspnetboilerplate,beratcarsi/aspnetboilerplate,luchaoshuai/aspnetboilerplate,fengyeju/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,fengyeju/aspnetboilerplate,Nongzhsh/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,andmattia/aspnetboilerplate,andmattia/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,zclmoon/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate
src/Abp.AspNetCore.OData/AspNetCore/OData/Configuration/AbpAspNetCoreODataModuleConfiguration.cs
src/Abp.AspNetCore.OData/AspNetCore/OData/Configuration/AbpAspNetCoreODataModuleConfiguration.cs
using System; using Abp.AspNetCore.Configuration; using Abp.Configuration.Startup; using Microsoft.AspNet.OData; using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Extensions; namespace Abp.AspNetCore.OData.Configuration { internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration { public ODataConventionModelBuilder ODataModelBuilder { get; set; } public Action<IAbpStartupConfiguration> MapAction { get; set; } public AbpAspNetCoreODataModuleConfiguration() { MapAction = configuration => { configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: "odata", model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel() ); // Workaround: https://github.com/OData/WebApi/issues/1175 configuration.Modules.AbpAspNetCore().RouteBuilder.EnableDependencyInjection(); }; } } }
using System; using Abp.AspNetCore.Configuration; using Abp.Configuration.Startup; using Microsoft.AspNet.OData.Builder; using Microsoft.AspNet.OData.Extensions; namespace Abp.AspNetCore.OData.Configuration { internal class AbpAspNetCoreODataModuleConfiguration : IAbpAspNetCoreODataModuleConfiguration { public ODataConventionModelBuilder ODataModelBuilder { get; set; } public Action<IAbpStartupConfiguration> MapAction { get; set; } public AbpAspNetCoreODataModuleConfiguration() { MapAction = configuration => { configuration.Modules.AbpAspNetCore().RouteBuilder.MapODataServiceRoute( routeName: "ODataRoute", routePrefix: "odata", model: configuration.Modules.AbpAspNetCoreOData().ODataModelBuilder.GetEdmModel() ); }; } } }
mit
C#
2a929b3295765132a9b507c947891dc1e0c6da5c
Update MaxAgents test
nunit/nunit-console,nunit/nunit-console,nunit/nunit-console
src/NUnitEngine/nunit.engine.tests/Runners/MultipleTestProcessRunnerTests.cs
src/NUnitEngine/nunit.engine.tests/Runners/MultipleTestProcessRunnerTests.cs
// *********************************************************************** // Copyright (c) 2016 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Framework; namespace NUnit.Engine.Runners.Tests { public class MultipleTestProcessRunnerTests { [TestCase(1, null, 1)] [TestCase(1, 1, 1)] [TestCase(3, null, 3)] [TestCase(3, 1, 1)] [TestCase(3, 2, 2)] [TestCase(3, 3, 3)] [TestCase(20, 8, 8)] [TestCase(8, 20, 8)] public void CheckLevelOfParallelism_ListOfAssemblies(int assemblyCount, int? maxAgents, int expected) { if (maxAgents == null) expected = Math.Min(assemblyCount, Environment.ProcessorCount); var runner = CreateRunner(assemblyCount, maxAgents); Assert.That(runner, Has.Property(nameof(MultipleTestProcessRunner.LevelOfParallelism)).EqualTo(expected)); } [Test] public void CheckLevelOfParallelism_SingleAssembly() { var package = new TestPackage("junk.dll"); Assert.That(new MultipleTestProcessRunner(new ServiceContext(), package).LevelOfParallelism, Is.EqualTo(0)); } // Create a MultipleTestProcessRunner with a fake package consisting of // some number of assemblies and with an optional MaxAgents setting. // Zero means that MaxAgents is not specified. MultipleTestProcessRunner CreateRunner(int assemblyCount, int? maxAgents) { // Currently, we can get away with null entries here var package = new TestPackage(new string[assemblyCount]); if (maxAgents != null) package.Settings[EnginePackageSettings.MaxAgents] = maxAgents; return new MultipleTestProcessRunner(new ServiceContext(), package); } } }
// *********************************************************************** // Copyright (c) 2016 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections.Generic; using NUnit.Framework; namespace NUnit.Engine.Runners.Tests { public class MultipleTestProcessRunnerTests { [TestCase(1, 0, ExpectedResult = 1)] [TestCase(1, 1, ExpectedResult = 1)] [TestCase(3, 0, ExpectedResult = 3)] [TestCase(3, 1, ExpectedResult = 1)] [TestCase(3, 2, ExpectedResult = 2)] [TestCase(3, 3, ExpectedResult = 3)] [TestCase(20, 8, ExpectedResult = 8)] [TestCase(8, 20, ExpectedResult = 8)] public int CheckLevelOfParallelism_ListOfAssemblies(int assemblyCount, int maxAgents) { return CreateRunner(assemblyCount, maxAgents).LevelOfParallelism; } [Test] public void CheckLevelOfParallelism_SingleAssembly() { var package = new TestPackage("junk.dll"); Assert.That(new MultipleTestProcessRunner(new ServiceContext(), package).LevelOfParallelism, Is.EqualTo(0)); } // Create a MultipleTestProcessRunner with a fake package consisting of // some number of assemblies and with an optional MaxAgents setting. // Zero means that MaxAgents is not specified. MultipleTestProcessRunner CreateRunner(int assemblyCount, int maxAgents) { // Currently, we can get away with null entries here var package = new TestPackage(new string[assemblyCount]); if (maxAgents > 0) package.Settings[EnginePackageSettings.MaxAgents] = maxAgents; return new MultipleTestProcessRunner(new ServiceContext(), package); } } }
mit
C#
4a07a7e757ce283e2445abe4522cfb80bdad6bc6
Refactor test
smoogipoo/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu
osu.Game.Rulesets.Osu.Tests/TestSceneSliderApplication.cs
osu.Game.Rulesets.Osu.Tests/TestSceneSliderApplication.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { public class TestSceneSliderApplication : OsuTestScene { [Test] public void TestApplyNewSlider() { DrawableSlider dho = null; AddStep("create slider", () => Child = dho = new DrawableSlider(prepareObject(new Slider { Position = new Vector2(256, 192), IndexInCurrentCombo = 0, StartTime = Time.Current, Path = new SliderPath(PathType.Linear, new[] { Vector2.Zero, new Vector2(150, 100), new Vector2(300, 0), }) }))); AddWaitStep("wait for progression", 1); AddStep("apply new slider", () => dho.Apply(prepareObject(new Slider { Position = new Vector2(256, 192), ComboIndex = 1, StartTime = dho.HitObject.StartTime, Path = new SliderPath(PathType.Bezier, new[] { Vector2.Zero, new Vector2(150, 100), new Vector2(300, 0), }), RepeatCount = 1 }))); } private Slider prepareObject(Slider slider) { slider.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); return slider; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Timing; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Objects; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Osu.Tests { public class TestSceneSliderApplication : OsuTestScene { [Test] public void TestApplyNewSlider() { DrawableSlider dho = null; AddStep("create slider", () => Child = dho = new DrawableSlider(prepareObject(new Slider { Position = new Vector2(256, 192), IndexInCurrentCombo = 0, Path = new SliderPath(PathType.Linear, new[] { Vector2.Zero, new Vector2(150, 100), new Vector2(300, 0), }) })) { Clock = new FramedClock(new StopwatchClock(true)) }); AddWaitStep("wait for progression", 1); AddStep("apply new slider", () => dho.Apply(prepareObject(new Slider { Position = new Vector2(256, 192), ComboIndex = 1, Path = new SliderPath(PathType.Bezier, new[] { Vector2.Zero, new Vector2(150, 100), new Vector2(300, 0), }), RepeatCount = 1 }))); } private Slider prepareObject(Slider slider) { slider.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty()); return slider; } } }
mit
C#
8483f71afead438c4fb63a7ba686e5d877386c6e
Add path for local vs code install
droyad/Assent
src/Assent/Reporters/DiffPrograms/DiffProgramBase.cs
src/Assent/Reporters/DiffPrograms/DiffProgramBase.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Assent.Reporters.DiffPrograms { public abstract class DiffProgramBase : IDiffProgram { protected static IReadOnlyList<string> WindowsProgramFilePaths => new[] { Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramFiles(x86)"), Environment.GetEnvironmentVariable("ProgramW6432"), Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), "Programs") } .Where(p => !string.IsNullOrWhiteSpace(p)) .Distinct() .ToArray(); public IReadOnlyList<string> SearchPaths { get; } protected DiffProgramBase(IReadOnlyList<string> searchPaths) { SearchPaths = searchPaths; } protected virtual string CreateProcessStartArgs( string receivedFile, string approvedFile) { return $"\"{receivedFile}\" \"{approvedFile}\""; } public virtual bool Launch(string receivedFile, string approvedFile) { var path = SearchPaths.FirstOrDefault(File.Exists); if (path == null) return false; var process = Process.Start(new ProcessStartInfo( path, CreateProcessStartArgs(receivedFile, approvedFile))); process.WaitForExit(); return true; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; namespace Assent.Reporters.DiffPrograms { public abstract class DiffProgramBase : IDiffProgram { protected static IReadOnlyList<string> WindowsProgramFilePaths => new[] { Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramFiles(x86)"), Environment.GetEnvironmentVariable("ProgramW6432") } .Where(p => !string.IsNullOrWhiteSpace(p)) .Distinct() .ToArray(); public IReadOnlyList<string> SearchPaths { get; } protected DiffProgramBase(IReadOnlyList<string> searchPaths) { SearchPaths = searchPaths; } protected virtual string CreateProcessStartArgs( string receivedFile, string approvedFile) { return $"\"{receivedFile}\" \"{approvedFile}\""; } public virtual bool Launch(string receivedFile, string approvedFile) { var path = SearchPaths.FirstOrDefault(File.Exists); if (path == null) return false; var process = Process.Start(new ProcessStartInfo( path, CreateProcessStartArgs(receivedFile, approvedFile))); process.WaitForExit(); return true; } } }
mit
C#
72b763a7e1c0d1a59083ebbb9c4c19bb67d5102d
Fix ConsoleHost on Windows CoreCLR build
jsoref/PowerShell,bingbing8/PowerShell,PaulHigin/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,TravisEz13/PowerShell,bmanikm/PowerShell,jsoref/PowerShell,bmanikm/PowerShell,bmanikm/PowerShell,bingbing8/PowerShell,PaulHigin/PowerShell,PaulHigin/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,jsoref/PowerShell,kmosher/PowerShell,KarolKaczmarek/PowerShell,bingbing8/PowerShell,JamesWTruher/PowerShell-1,kmosher/PowerShell,TravisEz13/PowerShell,bingbing8/PowerShell,bingbing8/PowerShell,kmosher/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,TravisEz13/PowerShell,TravisEz13/PowerShell,kmosher/PowerShell,JamesWTruher/PowerShell-1,jsoref/PowerShell,daxian-dbw/PowerShell,PaulHigin/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,jsoref/PowerShell,bmanikm/PowerShell,KarolKaczmarek/PowerShell,daxian-dbw/PowerShell,KarolKaczmarek/PowerShell
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
src/Microsoft.PowerShell.ConsoleHost/AssemblyInfo.cs
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !CORECLR using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif #if CORECLR [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] [assembly:InternalsVisibleTo("powershell-tests")] #else [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] #endif [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; #if !CORECLR using System.Runtime.ConstrainedExecution; using System.Security.Permissions; #endif [assembly:InternalsVisibleTo("powershell-tests")] [assembly:AssemblyCulture("")] [assembly:NeutralResourcesLanguage("en-US")] #if !CORECLR [assembly:AssemblyConfiguration("")] [assembly:AssemblyInformationalVersionAttribute (@"10.0.10011.16384")] [assembly:ReliabilityContractAttribute(Consistency.MayCorruptAppDomain, Cer.MayFail)] [assembly:AssemblyTitle("Microsoft.PowerShell.ConsoleHost")] [assembly:AssemblyDescription("Microsoft Windows PowerShell Console Host")] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5")] [assembly:System.Reflection.AssemblyFileVersion("10.0.10011.16384")] [assembly:AssemblyKeyFileAttribute(@"..\signing\visualstudiopublic.snk")] [assembly:System.Reflection.AssemblyDelaySign(true)] #endif [assembly:System.Runtime.InteropServices.ComVisible(false)] [assembly:System.Reflection.AssemblyVersion("3.0.0.0")] [assembly:System.Reflection.AssemblyProduct("Microsoft (R) Windows (R) Operating System")] [assembly:System.Reflection.AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyCompany("Microsoft Corporation")] internal static class AssemblyStrings { internal const string AssemblyVersion = @"3.0.0.0"; internal const string AssemblyCopyright = "Copyright (C) 2006 Microsoft Corporation. All rights reserved."; }
mit
C#