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
b9242170bc061fe5616178f95eacd0666cbf5fcb
remove comments
421p/grekd
GrekanMonoDaemon/Program.cs
GrekanMonoDaemon/Program.cs
using GrekanMonoDaemon.Job; using GrekanMonoDaemon.Logging; using GrekanMonoDaemon.Server; namespace GrekanMonoDaemon { internal class Program { public static void Main(string[] args) { Logger.InitLogger(); var scheduler = new Scheduler(); scheduler.Engage(); var host = new Host(); host.Start(); } } }
using System; using GrekanMonoDaemon.Job; using GrekanMonoDaemon.Logging; using GrekanMonoDaemon.Server; using GrekanMonoDaemon.Util; using GrekanMonoDaemon.Vk; namespace GrekanMonoDaemon { internal class Program { public static void Main(string[] args) { Logger.InitLogger(false); // var scheduler = new Scheduler(); // scheduler.Engage(); var host = new Host(); host.Start(); } } }
bsd-3-clause
C#
3921e560acd60b9809796d204840f86d5f397194
Add ranged dictionary
caronyan/CSharpRecipe
CSharpRecipe/Recipe.IteratorAndEnumerator/MaxMinValueDictionary.cs
CSharpRecipe/Recipe.IteratorAndEnumerator/MaxMinValueDictionary.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Recipe.IteratorAndEnumerator { [Serializable] public class MaxMinValueDictionary<T, TU> where TU : IComparable<TU> { protected Dictionary<T, TU> InternalDictionary = null; public MaxMinValueDictionary(TU maxValue, TU minValue) { MaxValue = maxValue; MinValue = minValue; InternalDictionary = new Dictionary<T, TU>(); } public TU MaxValue { get; private set; } = default(TU); public TU MinValue { get; private set; } = default(TU); public int Count => InternalDictionary.Count; public Dictionary<T, TU>.KeyCollection Keys => InternalDictionary.Keys; public Dictionary<T, TU>.ValueCollection Values => InternalDictionary.Values; public TU this[T key] { get { return InternalDictionary[key]; } set { if (value.CompareTo(MinValue) >= 0 && value.CompareTo(MaxValue) <= 0) { InternalDictionary[key] = value; } else { throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be within the range {MinValue} to {MaxValue}"); } } } public void Add(T key, TU value) { if (value.CompareTo(MinValue) >= 0 && value.CompareTo(MaxValue) <= 0) { InternalDictionary.Add(key, value); } else { throw new ArgumentOutOfRangeException(nameof(value), value, $"Value must be within the range {MinValue} to {MaxValue}"); } } public bool ContainsKey(T key) => InternalDictionary.ContainsKey(key); public bool ContainsValue(TU value) => InternalDictionary.ContainsValue(value); public override bool Equals(object obj) => InternalDictionary.Equals(obj); public void GetObjectData(SerializationInfo info, StreamingContext context) { InternalDictionary.GetObjectData(info, context); } public IEnumerator GetEnumerator() => InternalDictionary.GetEnumerator(); public override int GetHashCode() => InternalDictionary.GetHashCode(); public void OnDeserialization(object sender) { InternalDictionary.OnDeserialization(sender); } public override string ToString() => InternalDictionary.ToString(); public bool TryGetValue(T key, out TU value) => InternalDictionary.TryGetValue(key, out value); public void Remove(T key) { InternalDictionary.Remove(key); } public void Clear() { InternalDictionary.Clear(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Recipe.IteratorAndEnumerator { class MaxMinValueDictionary { } }
mit
C#
2d66723115a02260925cbd48c4e4ff5c819a82f2
Fix a dialog display glitch on Linux (20190725)
StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop
src/BloomExe/WebLibraryIntegration/OverwriteWarningDialog.cs
src/BloomExe/WebLibraryIntegration/OverwriteWarningDialog.cs
using System.Windows.Forms; namespace Bloom.WebLibraryIntegration { public partial class OverwriteWarningDialog : Form { public OverwriteWarningDialog() { InitializeComponent(); } protected override void OnLoad(System.EventArgs e) { base.OnLoad(e); // Fix a display glitch on Linux with the Mono SWF implementation. The button were half off // the bottom of the dialog on Linux, but fine on Windows. if (SIL.PlatformUtilities.Platform.IsLinux) { if (ClientSize.Height < _replaceExistingButton.Location.Y + _replaceExistingButton.Height) { var delta = ClientSize.Height - (_replaceExistingButton.Location.Y + _replaceExistingButton.Height) - 4; _replaceExistingButton.Location = new System.Drawing.Point(_replaceExistingButton.Location.X, _replaceExistingButton.Location.Y + delta); } if (ClientSize.Height < _cancelButton.Location.Y + _cancelButton.Height) { var delta = ClientSize.Height - (_cancelButton.Location.Y + _cancelButton.Height) - 4; _cancelButton.Location = new System.Drawing.Point(_cancelButton.Location.X, _cancelButton.Location.Y + delta); } } } } }
using System.Windows.Forms; namespace Bloom.WebLibraryIntegration { public partial class OverwriteWarningDialog : Form { public OverwriteWarningDialog() { InitializeComponent(); } } }
mit
C#
1bfc317d12fe7251544135dd747f34d35de74a16
Tidy up BitmapConverter.
wieslawsoltes/Perspex,jkoritzinsky/Avalonia,tshcherban/Perspex,MrDaedra/Avalonia,ncarrillo/Perspex,DavidKarlas/Perspex,wieslawsoltes/Perspex,MrDaedra/Avalonia,OronDF343/Avalonia,kekekeks/Perspex,jkoritzinsky/Avalonia,danwalmsley/Perspex,susloparovdenis/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,susloparovdenis/Perspex,grokys/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,susloparovdenis/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex,punker76/Perspex,SuperJMN/Avalonia,jazzay/Perspex,bbqchickenrobot/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,OronDF343/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,kekekeks/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia
src/Markup/Perspex.Markup.Xaml/Converters/BitmapConverter.cs
src/Markup/Perspex.Markup.Xaml/Converters/BitmapConverter.cs
// ----------------------------------------------------------------------- // <copyright file="BitmapConverter.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Markup.Xaml.Converters { using System; using System.Globalization; using Media.Imaging; using OmniXaml.TypeConversion; public class BitmapConverter : ITypeConverter { public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType) { return sourceType == typeof(string); } public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType) { return false; } public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value) { return new Bitmap((string)value); } public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType) { throw new NotImplementedException(); } } }
// ----------------------------------------------------------------------- // <copyright file="BitmapConverter.cs" company="Steven Kirk"> // Copyright 2015 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Markup.Xaml.Converters { using System; using System.Globalization; using Media.Imaging; using OmniXaml.TypeConversion; public class BitmapConverter : ITypeConverter { public bool CanConvertFrom(IXamlTypeConverterContext context, Type sourceType) { return true; } public bool CanConvertTo(IXamlTypeConverterContext context, Type destinationType) { return true; } public object ConvertFrom(IXamlTypeConverterContext context, CultureInfo culture, object value) { var path = (string)value; return new Bitmap(path); } public object ConvertTo(IXamlTypeConverterContext context, CultureInfo culture, object value, Type destinationType) { return new Bitmap(10, 10); } } }
mit
C#
e639e6171075251d779b1cf30e6b1d0791d95af1
Add realm information for Authenticate API (#3725)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/XPack/Security/Authenticate/AuthenticateResponse.cs
src/Nest/XPack/Security/Authenticate/AuthenticateResponse.cs
using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { public class RealmInfo { [DataMember(Name = "name")] public string Name { get; internal set; } [DataMember(Name = "type")] public string Type { get; internal set; } } public class AuthenticateResponse : ResponseBase { [DataMember(Name = "email")] public string Email { get; internal set; } [DataMember(Name = "full_name")] public string FullName { get; internal set; } [DataMember(Name = "metadata")] public IReadOnlyDictionary<string, object> Metadata { get; internal set; } = EmptyReadOnly<string, object>.Dictionary; [DataMember(Name = "roles")] public IReadOnlyCollection<string> Roles { get; internal set; } = EmptyReadOnly<string>.Collection; [DataMember(Name = "username")] public string Username { get; internal set; } [DataMember(Name = "authentication_realm")] public RealmInfo AuthenticationRealm { get; internal set; } [DataMember(Name = "lookup_realm")] public RealmInfo LookupRealm { get; internal set; } } }
using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { public class AuthenticateResponse : ResponseBase { [DataMember(Name = "email")] public string Email { get; internal set; } [DataMember(Name = "full_name")] public string FullName { get; internal set; } [DataMember(Name = "metadata")] public IReadOnlyDictionary<string, object> Metadata { get; internal set; } = EmptyReadOnly<string, object>.Dictionary; [DataMember(Name = "roles")] public IReadOnlyCollection<string> Roles { get; internal set; } = EmptyReadOnly<string>.Collection; [DataMember(Name = "username")] public string Username { get; internal set; } } }
apache-2.0
C#
87def4a1fe1af32d8263be86e408e5071fa56bb0
Test password for new students.
henkmollema/StudentFollowingSystem,henkmollema/StudentFollowingSystem
src/StudentFollowingSystem/Controllers/StudentsController.cs
src/StudentFollowingSystem/Controllers/StudentsController.cs
using System.Collections.Generic; using System.Web.Helpers; using System.Web.Mvc; using AutoMapper; using StudentFollowingSystem.Data.Repositories; using StudentFollowingSystem.Filters; using StudentFollowingSystem.Models; using StudentFollowingSystem.ViewModels; namespace StudentFollowingSystem.Controllers { [AuthorizeCounseler] public class StudentsController : Controller { private readonly StudentRepository _studentRepository = new StudentRepository(); public ActionResult Dashboard() { var model = new StudentDashboardModel(); return View(model); } public ActionResult List() { var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll()); return View(students); } public ActionResult Add() { return View(new StudentModel()); } [HttpPost] public ActionResult Add(StudentModel model) { if (ModelState.IsValid) { var student = Mapper.Map<Student>(model); student.Password = Crypto.HashPassword("test"); _studentRepository.Add(student); return RedirectToAction("List"); } return View(model); } } }
using System.Collections.Generic; using System.Web.Mvc; using AutoMapper; using StudentFollowingSystem.Data.Repositories; using StudentFollowingSystem.Filters; using StudentFollowingSystem.Models; using StudentFollowingSystem.ViewModels; using Validatr.Filters; namespace StudentFollowingSystem.Controllers { [AuthorizeCounseler] public class StudentsController : Controller { private readonly StudentRepository _studentRepository = new StudentRepository(); public ActionResult Dashboard() { var model = new StudentDashboardModel(); return View(model); } public ActionResult List() { var students = Mapper.Map<List<StudentModel>>(_studentRepository.GetAll()); return View(students); } public ActionResult Add() { return View(new StudentModel()); } [HttpPost] public ActionResult Add(StudentModel model) { if (ModelState.IsValid) { var student = Mapper.Map<Student>(model); _studentRepository.Add(student); return RedirectToAction("List"); } return View(model); } } }
mit
C#
f51a8842f0d99765fb4778bd5efbf99d0e0984a6
Fix hand-written Monitoring snippet to use resource names
benwulfe/google-cloud-dotnet,evildour/google-cloud-dotnet,googleapis/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,jskeet/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,iantalarico/google-cloud-dotnet,chrisdunelm/gcloud-dotnet,jskeet/google-cloud-dotnet,iantalarico/google-cloud-dotnet,chrisdunelm/google-cloud-dotnet,googleapis/google-cloud-dotnet,evildour/google-cloud-dotnet,evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.Snippets/MetricServiceClientSnippets.cs
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.Snippets/MetricServiceClientSnippets.cs
// Copyright 2016 Google Inc. All Rights Reserved. // // 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 Google.Api; using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(*,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); ProjectName projectName = new ProjectName(projectId); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // 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 Google.Api; using Google.Api.Gax; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(*,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); string projectName = new ProjectName(projectId).ToString(); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } }
apache-2.0
C#
dc4f4b00988c4e8bdb283a9565288b797e2f4d21
Add a simple route example for version #
alwynlombaard/MicroService.Nancy.Scaffold,mattgwagner/MicroService.Nancy.Scaffold
Nancy/Modules/HomeModule.cs
Nancy/Modules/HomeModule.cs
using log4net; using MicroService.Nancy.Nancy.Models; using Nancy; using System; namespace MicroService.Nancy.Nancy.Modules { public class HomeModule : NancyModule { public HomeModule(ILog log) : base("/") { Get["/"] = x => { log.Info("Loading home page"); return new HomeModel { Message = "Hello world", Timestamp = DateTime.UtcNow.ToLongTimeString() }; }; Get["/Version"] = _ => { String appName = "Microservice.Nancy"; // Pull from Assembly or Config File? String version = "1.0.0"; // Pull from AssemblyInfo String environment = "Local"; // Local/Test/Staging/Production return Response.AsJson(new { Application = appName, Version = version, Environment = environment, Server = Environment.MachineName }); }; Get["/dynamic"] = x => new DynamicPageModel { Message = "Hello world", Timestamp = DateTime.UtcNow.ToLongTimeString() }; } } }
using System; using log4net; using MicroService.Nancy.Nancy.Models; using Nancy; namespace MicroService.Nancy.Nancy.Modules { public class HomeModule : NancyModule { public HomeModule(ILog log) : base("/") { Get["/"] = x => { log.Info("Loading home page"); return new HomeModel { Message = "Hello world", Timestamp = DateTime.UtcNow.ToLongTimeString() }; }; Get["/dynamic"] = x => new DynamicPageModel { Message = "Hello world", Timestamp = DateTime.UtcNow.ToLongTimeString() }; } } }
mit
C#
3621462f4a9648c89d825d17d9c25ae554704351
Update ShootEvent.cs
Notulp/Pluton,Notulp/Pluton
Pluton/Events/ShootEvent.cs
Pluton/Events/ShootEvent.cs
namespace Pluton.Events { public class ShootEvent : CountedInstance { private BaseEntity.RPCMessage _rpcMessage; private BaseProjectile _projectile; private Player _pl; public ShootEvent(BaseProjectile baseProjectile, BaseEntity.RPCMessage msg) { this._pl = new Player(msg.player); this._rpcMessage = msg; this._projectile = baseProjectile; } public BaseProjectile BaseProjectile { get { return this._projectile; } } public Player Player { get { return this._pl; } } public BaseEntity.RPCMessage RPCMessage { get { return this._rpcMessage; } } } }
namespace Pluton.Events { public class ShootEvent { private BaseEntity.RPCMessage _rpcMessage; private BaseProjectile _projectile; private Player _pl; public ShootEvent(BaseProjectile baseProjectile, BaseEntity.RPCMessage msg) { this._pl = new Player(msg.player); this._rpcMessage = msg; this._projectile = baseProjectile; } public BaseProjectile BaseProjectile { get { return this._projectile; } } public Player Player { get { return this._pl; } } public BaseEntity.RPCMessage RPCMessage { get { return this._rpcMessage; } } } }
mit
C#
eed48eab24ce9d483016e7bf033be76789757963
use simple random string for table name
miltador/AspNetCore.Identity.DynamoDB,miltador/AspNetCore.Identity.DynamoDB
tests/AspNetCore.Identity.DynamoDB.Tests/Common/TestUtils.cs
tests/AspNetCore.Identity.DynamoDB.Tests/Common/TestUtils.cs
using System; using System.Linq; namespace AspNetCore.Identity.DynamoDB.Tests.Common { internal static class TestUtils { private static readonly Random Random = new Random(); /// <remarks> /// See http://stackoverflow.com/a/1344242/463785. /// </remarks> public static string RandomString(int length) => new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length) .Select(s => s[Random.Next(s.Length)]).ToArray()); public static string NewId() => Guid.NewGuid().ToString(); public static string NewTableName() => RandomString(5); } }
using System; using System.Linq; namespace AspNetCore.Identity.DynamoDB.Tests.Common { internal static class TestUtils { private static readonly Random Random = new Random(); /// <remarks> /// See http://stackoverflow.com/a/1344242/463785. /// </remarks> public static string RandomString(int length) => new string(Enumerable.Repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", length) .Select(s => s[Random.Next(s.Length)]).ToArray()); public static string NewId() => Guid.NewGuid().ToString(); public static string NewTableName() => Guid.NewGuid().ToString("N"); } }
mit
C#
0f0b6f3893c553f9c5b1763a87430aafb9077a76
Update HashTests.cs
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
Util/Xamarin.Build.Download/source/Xamarin.Build.Download.Tests/HashTests.cs
Util/Xamarin.Build.Download/source/Xamarin.Build.Download.Tests/HashTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Xamarin.Build.Download; using Xunit; namespace NativeLibraryDownloaderTests { public class HashTests { [Theory] [InlineData("C:\\path\\to\\file.aar")] [InlineData ("/path/to/file.aar")] public void Test_CRC64_Safety(string value) { var crc = DownloadUtils.Crc64(value); Assert.Matches("^[0-9a-zA-Z]+$", crc); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Xamarin.Build.Download; using Xunit; namespace NativeLibraryDownloaderTests { public class HashTests { [Theory] [InlineData("C:\\path\\to\\file.aar")] public void Test_CRC64_Safety(string value) { var crc = DownloadUtils.Crc64(value); Assert.Matches("^[0-9a-zA-Z]+$", crc); } } }
mit
C#
e1a6e3a5477bd54b18bf253c84ac92e8bbdd8124
Add controller changes
akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject,akkirilov/SoftUniProject
02_SoftwareTechnologies/14_AspNetBlog_AdminFunc/Blog/Blog/Controllers/ArticleController.cs
02_SoftwareTechnologies/14_AspNetBlog_AdminFunc/Blog/Blog/Controllers/ArticleController.cs
using Blog.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace Blog.Controllers { public class ArticleController : Controller { //GET: Article/List public ActionResult List() { using (var db = new BlogDbContext()) { var articles = db.Articles.Include(a => a.Author).ToList(); return View(articles); } } //GET: Article/Details public ActionResult Details(int? Id) { if (Id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } using(var db = new BlogDbContext()) { var article = db.Articles.Where(x => x.Id == Id).Include(x => x.Author).First(); if (article == null) { return HttpNotFound(); } return View(article); } } //GET: Article/Create public ActionResult Create() { return View(); } //POST: Article/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Article article) { if (ModelState.IsValid) { using(var db = new BlogDbContext()) { var authorId = db.Users.Where(x => x.UserName == this.User.Identity.Name).First().Id; article.AuthorId = authorId; db.Articles.Add(article); db.SaveChanges(); return RedirectToAction("Index", "Home"); } } return View(article); } } }
using Blog.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; namespace Blog.Controllers { public class ArticleController : Controller { //GET: Article/List public ActionResult List() { using (var db = new BlogDbContext()) { var articles = db.Articles.Include(a => a.Author).ToList(); return View(articles); } } //GET: Article/Details public ActionResult Details(int? Id) { if (Id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } using(var db = new BlogDbContext()) { var article = db.Articles.Where(x => x.Id == Id).Include(x => x.Author).First(); if (article == null) { return HttpNotFound(); } return View(article); } } //POST: Article/Create public ActionResult Create(Article article) { if (ModelState.IsValid) { using(var db = new BlogDbContext()) { var authorId = db.Users.Where(x => x.UserName == this.User.Identity.Name).First().Id; article.AuthorId = authorId; db.Articles.Add(article); db.SaveChanges(); return RedirectToAction("Index", "Home"); } } return View(article); } } }
mit
C#
574d7f8bba83437c49b77f16b1e9d8c9aeef0a3b
Make explicit
CyrusNajmabadi/roslyn,eriawan/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,diryboy/roslyn,AmadeusW/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,physhi/roslyn,bartdesmet/roslyn,tannergooding/roslyn,dotnet/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,mavasani/roslyn,sharwell/roslyn,AmadeusW/roslyn,diryboy/roslyn,AlekseyTs/roslyn,dotnet/roslyn,weltkante/roslyn,tmat/roslyn,weltkante/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,weltkante/roslyn,wvdd007/roslyn,eriawan/roslyn,diryboy/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,tmat/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,sharwell/roslyn,KevinRansom/roslyn
src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionFixAllProvider.cs
src/Analyzers/CSharp/CodeFixes/RemoveConfusingSuppression/CSharpRemoveConfusingSuppressionFixAllProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { internal partial class CSharpRemoveConfusingSuppressionCodeFixProvider { private class CSharpRemoveConfusingSuppressionFixAllProvider : DocumentBasedFixAllProvider { public CSharpRemoveConfusingSuppressionFixAllProvider() { } protected override string CodeActionTitle => CSharpAnalyzersResources.Remove_suppression_operators; protected override async Task<SyntaxNode?> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics) { var cancellationToken = fixAllContext.CancellationToken; var newDoc = await CSharpRemoveConfusingSuppressionCodeFixProvider.FixAllAsync( document, diagnostics, fixAllContext.CodeActionEquivalenceKey == NegateExpression, cancellationToken).ConfigureAwait(false); return await newDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; namespace Microsoft.CodeAnalysis.CSharp.RemoveConfusingSuppression { internal partial class CSharpRemoveConfusingSuppressionCodeFixProvider { private class CSharpRemoveConfusingSuppressionFixAllProvider : DocumentBasedFixAllProvider { public CSharpRemoveConfusingSuppressionFixAllProvider() { } protected override string CodeActionTitle => CSharpAnalyzersResources.Remove_suppression_operators; protected override async Task<SyntaxNode?> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics) { var cancellationToken = fixAllContext.CancellationToken; var newDoc = await FixAllAsync( document, diagnostics, fixAllContext.CodeActionEquivalenceKey == NegateExpression, cancellationToken).ConfigureAwait(false); return await newDoc.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); } } } }
mit
C#
73d62700a0c6811c037e0e98e87965e0060fa688
refactor and use Location class
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Data/Map/Location.cs
TCC.Core/Data/Map/Location.cs
using System.Windows; using TCC.Data.Databases; namespace TCC.Data.Map { public class Location { public uint World { get; } public uint Guard { get; } public uint Section { get; } public string SectionName => SessionManager.MapDatabase.GetName(Guard, Section); public Point Position { get; } public Location() { Position = new Point(0,0); } public Location(uint w, uint g, uint s, double x, double y) { World = w; Guard = g; Section = s; Position = new Point(x, y); } public Location(uint w, uint g, uint s) { World = w; Guard = g; Section = s; Position = new Point(0, 0); } /// <summary> /// /// </summary> /// <param name="value">WorldId_GuardId_SectionId</param> public Location(string value) { var split = value.Split('_'); World = uint.Parse(split[0]); Guard = uint.Parse(split[1]); Section = uint.Parse(split[2]); } } }
using System.Windows; namespace TCC.Data.Map { public class Location { public uint World, Guard, Section; public Point Position; public Location(uint w, uint g, uint s, double x, double y) { World = w; Guard = g; Section = s; Position = new Point(x, y); } } }
mit
C#
3a4dced46edfba9815692b359ec7500f40724952
Add get method for teacher name
victoria92/university-program-generator,victoria92/university-program-generator
UniProgramGen/Data/Teacher.cs
UniProgramGen/Data/Teacher.cs
using System.Collections.Generic; namespace UniProgramGen.Data { public class Teacher { public Requirements requirements { get; internal set; } public string name { get; internal set; } public string Name { get { return name; } } public Teacher(Requirements requirements, string name) { this.requirements = requirements; this.name = name; } } }
using System.Collections.Generic; namespace UniProgramGen.Data { public class Teacher { public Requirements requirements { get; internal set; } public string name { get; internal set; } public Teacher(Requirements requirements, string name) { this.requirements = requirements; this.name = name; } } }
bsd-2-clause
C#
f0528e76b20ca47c37d2bd9a4e4642859851d9f3
Make styling consistent between files
It423/todo-list,wrightg42/todo-list
Todo-List/Todo-List/Note.cs
Todo-List/Todo-List/Note.cs
// Note.cs // <copyright file="Note.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; namespace Todo_List { /// <summary> /// A data representation of a note. /// </summary> public class Note { /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> public Note() { Title = string.Empty; Categories = new string[0]; } /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> /// <param name="title"> The title of the note. </param> /// <param name="categories"> The categories the note is in. </param> public Note(string title, string[] categories) { Title = title; Categories = categories; } /// <summary> /// Gets or sets the title of the note. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets the categories the note is in. /// </summary> public string[] Categories { get; set; } } }
// Note.cs // <copyright file="Note.cs"> This code is protected under the MIT License. </copyright> using System.Collections.Generic; namespace Todo_List { /// <summary> /// A data representation of a note. /// </summary> public class Note { /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> public Note() { this.Title = string.Empty; this.Categories = new string[0]; } /// <summary> /// Initializes a new instance of the <see cref="Note" /> class. /// </summary> /// <param name="title"> The title of the note. </param> /// <param name="categories"> The categories the note is in. </param> public Note(string title, string[] categories) { this.Title = title; this.Categories = categories; } /// <summary> /// Gets or sets the title of the note. /// </summary> public string Title { get; set; } /// <summary> /// Gets or sets the categories the note is in. /// </summary> public string[] Categories { get; set; } } }
mit
C#
44bae2877bc9f18c8ccda6e8ddbb625070a133f6
Make Fact as Theory
tiksn/TIKSN-Framework
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/ExchangeRateService/ExchangeRateServiceBaseTests.cs
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/ExchangeRateService/ExchangeRateServiceBaseTests.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using TIKSN.Globalization; using Xunit; namespace TIKSN.Finance.ForeignExchange.ExchangeRateService.IntegrationTests { [Collection("LiteDbServiceProviderCollection")] public class ExchangeRateServiceBaseTests { private readonly IReadOnlyDictionary<string, IServiceProvider> serviceProviders; public ExchangeRateServiceBaseTests(LiteDbServiceProviderFixture liteDbServiceProviderFixture) => this.serviceProviders = new Dictionary<string, IServiceProvider>() { { "LiteDB", liteDbServiceProviderFixture.Services} }; [Theory] [InlineData("LiteDB")] public async Task Given_10USD_When_ExchangedForEuro_Then_ResultShouldBeEuro(string database) { // Arrange var exchangeRateService = this.serviceProviders[database].GetRequiredService<IExchangeRateService>(); var currencyFactory = this.serviceProviders[database].GetRequiredService<ICurrencyFactory>(); var usd = currencyFactory.Create("USD"); var eur = currencyFactory.Create("EUR"); var usd10 = new Money(usd, 10m); await exchangeRateService.InitializeAsync(default); // Act var result = await exchangeRateService.ConvertCurrencyAsync( usd10, eur, DateTimeOffset.Now, default); // Assert _ = result.Currency.Should().Be(eur); } } }
using System; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using TIKSN.Globalization; using Xunit; namespace TIKSN.Finance.ForeignExchange.ExchangeRateService.IntegrationTests { [Collection("LiteDbServiceProviderCollection")] public class ExchangeRateServiceBaseTests { private readonly LiteDbServiceProviderFixture liteDbServiceProviderFixture; public ExchangeRateServiceBaseTests(LiteDbServiceProviderFixture liteDbServiceProviderFixture) => this.liteDbServiceProviderFixture = liteDbServiceProviderFixture ?? throw new ArgumentNullException(nameof(liteDbServiceProviderFixture)); [Fact] public async Task Given_10USD_When_ExchangedForEuro_Then_ResultShouldBeEuro() { // Arrange var exchangeRateService = this.liteDbServiceProviderFixture.Services.GetRequiredService<IExchangeRateService>(); var currencyFactory = this.liteDbServiceProviderFixture.Services.GetRequiredService<ICurrencyFactory>(); var usd = currencyFactory.Create("USD"); var eur = currencyFactory.Create("EUR"); var usd10 = new Money(usd, 10m); await exchangeRateService.InitializeAsync(default); // Act var result = await exchangeRateService.ConvertCurrencyAsync( usd10, eur, DateTimeOffset.Now, default); // Assert _ = result.Currency.Should().Be(eur); } } }
mit
C#
bf6d45292915ce18755a84fb1bbd831ed3d5db57
Fix bug when deactivating ibus keyboards Setting the Keyboard to null in GlobalInputContext.Clear prevented the IbusKeyboardAdaptor.SetIMEKeyboard method from disabling the keyboard.
tombogle/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,marksvc/libpalaso,darcywong00/libpalaso,hatton/libpalaso,gmartin7/libpalaso,andrew-polk/libpalaso,JohnThomson/libpalaso,mccarthyrb/libpalaso,ddaspit/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,sillsdev/libpalaso,marksvc/libpalaso,gtryus/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,marksvc/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,ddaspit/libpalaso,mccarthyrb/libpalaso,hatton/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,chrisvire/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,hatton/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,chrisvire/libpalaso,darcywong00/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso
PalasoUIWindowsForms/Keyboarding/Linux/GlobalCachedInputContext.cs
PalasoUIWindowsForms/Keyboarding/Linux/GlobalCachedInputContext.cs
#if __MonoCS__ using System; using System.Diagnostics; using System.Runtime.InteropServices; using IBusDotNet; using NDesk.DBus; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary> /// a global cache used only to reduce traffic with ibus via dbus. /// </summary> internal static class GlobalCachedInputContext { /// <summary> /// Caches the current InputContext. /// </summary> public static InputContext InputContext { get; set; } /// <summary> /// Cache the keyboard of the InputContext. /// </summary> public static IBusKeyboardDescription Keyboard { get; set; } /// <summary> /// Clear the cached InputContext details. /// </summary> public static void Clear() { InputContext = null; } } } #endif
#if __MonoCS__ using System; using System.Diagnostics; using System.Runtime.InteropServices; using IBusDotNet; using NDesk.DBus; namespace Palaso.UI.WindowsForms.Keyboarding.Linux { /// <summary> /// a global cache used only to reduce traffic with ibus via dbus. /// </summary> internal static class GlobalCachedInputContext { /// <summary> /// Caches the current InputContext. /// </summary> public static InputContext InputContext { get; set; } /// <summary> /// Cache the keyboard of the InputContext. /// </summary> public static IBusKeyboardDescription Keyboard { get; set; } /// <summary> /// Clear the cached InputContext details. /// </summary> public static void Clear() { Keyboard = null; InputContext = null; } } } #endif
mit
C#
55c28220d900a04bc6aefb9ffc0b0790ee994ba8
Remove old serialization check that is no longer required
hach-que/Dx
Dx.Runtime/DefaultObjectWithTypeSerializer.cs
Dx.Runtime/DefaultObjectWithTypeSerializer.cs
using System; using System.IO; using System.Runtime.Serialization; using ProtoBuf; using ProtoBuf.Meta; namespace Dx.Runtime { public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer { private readonly ILocalNode m_LocalNode; public DefaultObjectWithTypeSerializer(ILocalNode localNode) { this.m_LocalNode = localNode; } public ObjectWithType Serialize(object obj) { if (obj == null) { return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null }; } byte[] serializedObject; using (var memory = new MemoryStream()) { Serializer.Serialize(memory, obj); var length = (int)memory.Position; memory.Seek(0, SeekOrigin.Begin); serializedObject = new byte[length]; memory.Read(serializedObject, 0, length); } return new ObjectWithType { AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName, SerializedObject = serializedObject }; } public object Deserialize(ObjectWithType owt) { if (owt.AssemblyQualifiedTypeName == null) { return null; } var type = Type.GetType(owt.AssemblyQualifiedTypeName); if (type == null) { throw new TypeLoadException(); } using (var memory = new MemoryStream(owt.SerializedObject)) { var value = RuntimeTypeModel.Default.Deserialize(memory, null, type); GraphWalker.Apply(value, this.m_LocalNode); return value; } } } }
using System; using System.IO; using System.Runtime.Serialization; using ProtoBuf; using ProtoBuf.Meta; namespace Dx.Runtime { public class DefaultObjectWithTypeSerializer : IObjectWithTypeSerializer { private readonly ILocalNode m_LocalNode; public DefaultObjectWithTypeSerializer(ILocalNode localNode) { this.m_LocalNode = localNode; } public ObjectWithType Serialize(object obj) { if (obj == null) { return new ObjectWithType { AssemblyQualifiedTypeName = null, SerializedObject = null }; } byte[] serializedObject; using (var memory = new MemoryStream()) { Serializer.Serialize(memory, obj); var length = (int)memory.Position; memory.Seek(0, SeekOrigin.Begin); serializedObject = new byte[length]; memory.Read(serializedObject, 0, length); } return new ObjectWithType { AssemblyQualifiedTypeName = obj.GetType().AssemblyQualifiedName, SerializedObject = serializedObject }; } public object Deserialize(ObjectWithType owt) { if (owt.AssemblyQualifiedTypeName == null) { return null; } var type = Type.GetType(owt.AssemblyQualifiedTypeName); if (type == null) { throw new TypeLoadException(); } using (var memory = new MemoryStream(owt.SerializedObject)) { object instance; if (type == typeof(string)) { instance = string.Empty; } else { instance = FormatterServices.GetUninitializedObject(type); } var value = RuntimeTypeModel.Default.Deserialize(memory, instance, type); GraphWalker.Apply(value, this.m_LocalNode); return value; } } } }
mit
C#
2f2ecfbf6368adc66f51c24220c199b560cb618f
convert endpoint scheme tcp to 'http' internally
ahmetalpbalkan/Docker.DotNet,jterry75/Docker.DotNet,jterry75/Docker.DotNet
Docker.DotNet/DockerClientConfiguration.cs
Docker.DotNet/DockerClientConfiguration.cs
using System; using System.Globalization; namespace Docker.DotNet { public class DockerClientConfiguration { public Uri EndpointBaseUri { get; private set; } public Credentials Credentials { get; private set; } public DockerClientConfiguration(Uri endpoint) : this(endpoint, new AnonymousCredentials()) { } public DockerClientConfiguration(Uri endpoint, Credentials credentials) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.EndpointBaseUri = SanitizeEndpoint(endpoint); this.Credentials = credentials; } public DockerClient CreateClient() { return new DockerClient(this); } private static Uri SanitizeEndpoint(Uri endpoint) { UriBuilder builder = new UriBuilder(endpoint); if (builder.Scheme.Equals("tcp", StringComparison.InvariantCultureIgnoreCase)) { builder.Scheme = "http"; } return builder.Uri; } } }
using System; namespace Docker.DotNet { public class DockerClientConfiguration { public Uri EndpointBaseUri { get; private set; } public Credentials Credentials { get; private set; } public DockerClientConfiguration(Uri endpoint) : this(endpoint, new AnonymousCredentials()) { } public DockerClientConfiguration(Uri endpoint, Credentials credentials) { if (endpoint == null) { throw new ArgumentNullException("endpoint"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.EndpointBaseUri = endpoint; this.Credentials = credentials; } public DockerClient CreateClient() { return new DockerClient(this); } } }
apache-2.0
C#
e2e7e73835634df4ad8229b116742ad1366ae2ff
Clean code with using instead of fixed namespaces
projecteon/thecollection,projecteon/thecollection,projecteon/thecollection,projecteon/thecollection
TheCollection.Domain/Contracts/Repository/ILinqSearchRepository.cs
TheCollection.Domain/Contracts/Repository/ILinqSearchRepository.cs
namespace TheCollection.Domain.Contracts.Repository { using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Threading.Tasks; public interface ILinqSearchRepository<T> where T : class { Task<IEnumerable<T>> SearchItemsAsync(Expression<Func<T, bool>> predicate = null, int pageSize = 0, int page = 0); } }
namespace TheCollection.Domain.Contracts.Repository { using System.Collections.Generic; using System.Threading.Tasks; public interface ILinqSearchRepository<T> where T : class { Task<IEnumerable<T>> SearchItemsAsync(System.Linq.Expressions.Expression<System.Func<T, bool>> predicate = null, int pageSize = 0, int page = 0); } }
apache-2.0
C#
922384267c6d468b98c63047a4104a04c3417ff9
Fix test
agilepartner/SandTigerShark
GameServer.Tests/TicTacToe/TicTacToe_specs.cs
GameServer.Tests/TicTacToe/TicTacToe_specs.cs
using FakeItEasy; using Microsoft.Extensions.Options; using SandTigerShark.GameServer.Services.Commands; using SandTigerShark.GameServer.Services.Configurations; using SandTigerShark.GameServer.Services.Http; using SandTigerShark.GameServer.Services.TicTacToe; using System; using Xunit; namespace SandTigerShark.GameServer.Tests.TicTacToe { public class TicTacToe_specs { private readonly IRestProxy restProxy; private readonly ITicTacToeService ticTacToeService; private readonly AzureConfig configuration; public TicTacToe_specs() { configuration = new AzureConfig { TicTacToe = "" }; restProxy = A.Fake<IRestProxy>(); var options = A.Fake<IOptions<AzureConfig>>(); A.CallTo(() => options.Value).Returns(configuration); ticTacToeService = new TicTacToeService(restProxy, options); } [Fact] public async void it_should_throw_an_ArgumentNullException_for_a_null_command() { var type = typeof(ArgumentNullException); await Assert.ThrowsAsync(type, async() => await ticTacToeService.Play(null)); } [Fact] public async void it_should_send_a_valid_command() { var command = new Play(); await ticTacToeService.Play(command); A.CallTo(() => restProxy.PostAsync<Play>(configuration.TicTacToe, command, null)).MustHaveHappened(); } } }
using FakeItEasy; using Microsoft.Extensions.Options; using SandTigerShark.GameServer.Services.Commands; using SandTigerShark.GameServer.Services.Configurations; using SandTigerShark.GameServer.Services.Http; using SandTigerShark.GameServer.Services.TicTacToe; using System; using Xunit; namespace SandTigerShark.GameServer.Tests.TicTacToe { public class TicTacToe_specs { private readonly IRestProxy restProxy; private readonly ITicTacToeService ticTacToeService; private readonly AzureConfig configuration; public TicTacToe_specs() { configuration = new AzureConfig { TicTacToe = "" }; restProxy = A.Fake<IRestProxy>(); var options = A.Fake<IOptions<AzureConfig>>(); A.CallTo(() => options.Value).Returns(configuration); ticTacToeService = new TicTacToeService(restProxy, options); } [Fact] public async void it_should_throw_an_ArgumentNullException_for_a_null_command() { var type = typeof(ArgumentNullException); await Assert.ThrowsAsync(type, async() => await ticTacToeService.Play(null)); } [Fact] public async void it_should_send_a_valid_command() { var command = new Play(); await ticTacToeService.Play(command); } } }
mit
C#
447b6b8e0f6842032ad1bdcf5b92127edee7358c
Simplify logic in user profile validation
mikesigs/allReady,mikesigs/allReady,mikesigs/allReady,mikesigs/allReady
AllReadyApp/Web-App/AllReady/Models/ApplicationUser.cs
AllReadyApp/Web-App/AllReady/Models/ApplicationUser.cs
using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AllReady.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { [Display(Name = "Associated skills")] public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>(); public string Name { get; set; } [Display(Name = "Time Zone")] [Required] public string TimeZoneId { get; set; } public string PendingNewEmail { get; set; } public IEnumerable<ValidationResult> ValidateProfileCompleteness() { List<ValidationResult> validationResults = new List<ValidationResult>(); if (!EmailConfirmed) { validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) })); } if (string.IsNullOrWhiteSpace(Name)) { validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) })); } if (string.IsNullOrWhiteSpace(PhoneNumber)) { validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) })); } else if (!PhoneNumberConfirmed) { validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) })); } return validationResults; } public bool IsProfileComplete() { return !ValidateProfileCompleteness().Any(); } } }
using Microsoft.AspNet.Identity.EntityFramework; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; namespace AllReady.Models { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { [Display(Name = "Associated skills")] public List<UserSkill> AssociatedSkills { get; set; } = new List<UserSkill>(); public string Name { get; set; } [Display(Name = "Time Zone")] [Required] public string TimeZoneId { get; set; } public string PendingNewEmail { get; set; } public IEnumerable<ValidationResult> ValidateProfileCompleteness() { List<ValidationResult> validationResults = new List<ValidationResult>(); if (!EmailConfirmed) { validationResults.Add(new ValidationResult("Verify your email address", new string[] { nameof(Email) })); } if (string.IsNullOrWhiteSpace(Name)) { validationResults.Add(new ValidationResult("Enter your name", new string[] { nameof(Name) })); } if (string.IsNullOrWhiteSpace(PhoneNumber)) { validationResults.Add(new ValidationResult("Add a phone number", new string[] { nameof(PhoneNumber) })); } if (!string.IsNullOrWhiteSpace(PhoneNumber) && !PhoneNumberConfirmed) { validationResults.Add(new ValidationResult("Confirm your phone number", new string[] { nameof(PhoneNumberConfirmed) })); } return validationResults; } public bool IsProfileComplete() { return !ValidateProfileCompleteness().Any(); } } }
mit
C#
3ca6d4a15b3db19d44f3270b13b9c16d57f5915f
add ToIntUnchecked(), GetLowWord(), GetHighWord()
TakeAsh/cs-WpfUtility
WpfUtility/NativeMethods.cs
WpfUtility/NativeMethods.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace WpfUtility.Native { static class NativeMethods { [DllImport("user32.dll")] public static extern bool SetWindowPlacement( IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl ); [DllImport("user32.dll")] public static extern bool GetWindowPlacement( IntPtr hWnd, out WINDOWPLACEMENT lpwndpl ); /// <summary> /// Convert a value to int. /// </summary> /// <param name="value">Value</param> /// <returns>Int value</returns> /// <remarks> /// [winapi - Win api in C#. Get Hi and low word from IntPtr - Stack Overflow](http://stackoverflow.com/questions/7913325/) /// </remarks> public static int ToIntUnchecked(this IntPtr value) { return IntPtr.Size == 8 ? unchecked((int)value.ToInt64()) : value.ToInt32(); } /// <summary> /// Get low word of a value. /// </summary> /// <param name="value">Value</param> /// <returns>low word of a value</returns> public static int GetLowWord(this IntPtr value) { return unchecked((short)value.ToIntUnchecked()); } /// <summary> /// Get high word of a value. /// </summary> /// <param name="value">Value</param> /// <returns>high word of a value</returns> public static int GetHighWord(this IntPtr value) { return unchecked((short)(((uint)value.ToIntUnchecked()) >> 16)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; namespace WpfUtility.Native { class NativeMethods { [DllImport("user32.dll")] public static extern bool SetWindowPlacement( IntPtr hWnd, [In] ref WINDOWPLACEMENT lpwndpl ); [DllImport("user32.dll")] public static extern bool GetWindowPlacement( IntPtr hWnd, out WINDOWPLACEMENT lpwndpl ); } }
mit
C#
922e84d146e33752b379ba78f24105c79286c1d2
Add collide without manifold generation
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/Physics/Collider/Collider.cs
MadCat/NutEngine/Physics/Collider/Collider.cs
using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<IShape> a, IBody<IShape> b, out Manifold manifold) { return Collide((dynamic)a, (dynamic)b, out manifold); } public static bool Collide(IBody<IShape> a, IBody<IShape> b) { return Collide((dynamic)a, (dynamic)b); } } }
using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<IShape> a, IBody<IShape> b, out Manifold manifold) { return Collide((dynamic)a, (dynamic)b, out manifold); } } }
mit
C#
ce00bca73ed0fb2d4ef928c990683cd96a352a47
replace initonload with menu item
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Providers/Experimental/WindowsSceneUnderstanding/Editor/WindowsSceneUnderstandingConfigChecker.cs
Assets/MRTK/Providers/Experimental/WindowsSceneUnderstanding/Editor/WindowsSceneUnderstandingConfigChecker.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.IO; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.WindowsSceneUnderstanding.Experimental { /// <summary> /// Class to perform checks for configuration checks for the Windows Mixed Reality provider. /// </summary> static class WindowsSceneUnderstandingConfigurationChecker { private const string FileName = "Microsoft.MixedReality.SceneUnderstanding.DotNet.dll"; private static readonly string[] definitions = { "SCENEUNDERSTANDING_PRESENT" }; /// <summary> /// Ensures that the appropriate symbolic constant is defined based on the presence of the SceneUnderstanding binary. /// </summary> [MenuItem("Mixed Reality Toolkit/Utilities/Scene Understanding/Check Configuration")] private static void ReconcileSceneUnderstandingDefine() { FileInfo[] files = FileUtilities.FindFilesInAssets(FileName); if (files.Length > 0) { ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions); } else { ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.IO; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.WindowsSceneUnderstanding.Experimental { /// <summary> /// Class to perform checks for configuration checks for the Windows Mixed Reality provider. /// </summary> [InitializeOnLoad] static class WindowsSceneUnderstandingConfigurationChecker { private const string FileName = "Microsoft.MixedReality.SceneUnderstanding.DotNet.dll"; private static readonly string[] definitions = { "SCENEUNDERSTANDING_PRESENT" }; static WindowsSceneUnderstandingConfigurationChecker() { ReconcileSceneUnderstandingDefine(); } /// <summary> /// Ensures that the appropriate symbolic constant is defined based on the presence of the SceneUnderstanding binary. /// </summary> private static void ReconcileSceneUnderstandingDefine() { FileInfo[] files = FileUtilities.FindFilesInAssets(FileName); if (files.Length > 0) { ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions); } else { ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions); } } } }
mit
C#
aff455eacebbd63330797677a2b01f4057165a60
fix DecodeBlockSZ at CompressionMagicHelper helper class
DarkCaster/DotNetBlocks,DarkCaster/DotNetBlocks
CustomBlocks/DataTransfer/Compression/Private/CompressionMagicHelper.cs
CustomBlocks/DataTransfer/Compression/Private/CompressionMagicHelper.cs
// CompressionMagicHelper.cs // // The MIT License (MIT) // // Copyright (c) 2017 DarkCaster <dark.caster@outlook.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // using System; namespace DarkCaster.DataTransfer.Private { public static class CompressionMagicHelper { public static void EncodeMagic(short magic, byte[] buffer, int offset) { buffer[offset] = (byte)(magic & 0xFF); buffer[offset + 1] = (byte)((magic >> 8) & 0xFF); } public static short DecodeMagic(byte[] buffer, int offset) { return unchecked((short)(buffer[offset + 1] << 8 | buffer[offset])); } public static void EncodeBlockSZ(int size, byte[] buffer, int offset) { if(size > 0xFFFFFF) throw new Exception("Block size too big"); buffer[offset] = (byte)(size & 0xFF); buffer[offset + 1] = (byte)((size >> 8) & 0xFF); buffer[offset + 2] = (byte)((size >> 16) & 0xFF); } public static int DecodeBlockSZ(byte[] buffer, int offset) { return unchecked((int)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16)); } public static void EncodeMagicAndBlockSZ(short magic, int bSize, byte[] buffer, int offset) { EncodeMagic(magic, buffer, offset); EncodeBlockSZ(bSize, buffer, offset + 2); } public static void DecodeMagicAndBlockSZ(byte[] buffer, int offset, out short magic, out int bSize) { magic = DecodeMagic(buffer, offset); bSize = DecodeBlockSZ(buffer, offset + 2); } } }
// CompressionMagicHelper.cs // // The MIT License (MIT) // // Copyright (c) 2017 DarkCaster <dark.caster@outlook.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // using System; namespace DarkCaster.DataTransfer.Private { public static class CompressionMagicHelper { public static void EncodeMagic(short magic, byte[] buffer, int offset) { buffer[offset] = (byte)(magic & 0xFF); buffer[offset + 1] = (byte)((magic >> 8) & 0xFF); } public static short DecodeMagic(byte[] buffer, int offset) { return unchecked((short)(buffer[offset + 1] << 8 | buffer[offset])); } public static void EncodeBlockSZ(int size, byte[] buffer, int offset) { if(size > 0xFFFFFF) throw new Exception("Block size too big"); buffer[offset] = (byte)(size & 0xFF); buffer[offset + 1] = (byte)((size >> 8) & 0xFF); buffer[offset + 2] = (byte)((size >> 16) & 0xFF); } public static int DecodeBlockSZ(byte[] buffer, int offset) { return unchecked((short)(buffer[offset] | buffer[offset + 1] << 8 | buffer[offset + 2] << 16)); } public static void EncodeMagicAndBlockSZ(short magic, int bSize, byte[] buffer, int offset) { EncodeMagic(magic, buffer, offset); EncodeBlockSZ(bSize, buffer, offset + 2); } public static void DecodeMagicAndBlockSZ(byte[] buffer, int offset, out short magic, out int bSize) { magic = DecodeMagic(buffer, offset); bSize = DecodeBlockSZ(buffer, offset + 2); } } }
mit
C#
fa7359d3c9680f56739ae1a4c9cb61a4256746b3
Delete comment.
harujoh/KelpNet,harujoh/KelpNet
KelpNet.Function/Optimizers/WeightDecay.cs
KelpNet.Function/Optimizers/WeightDecay.cs
using System; using System.Collections.Generic; #if DOUBLE using Real = System.Double; #elif NETSTANDARD2_1 using Real = System.Single; using Math = System.MathF; #elif NETSTANDARD2_0 using Real = System.Single; using Math = KelpNet.MathF; #endif namespace KelpNet { #if !DOUBLE public class WeightDecay<T> : Optimizer<T> where T : unmanaged, IComparable<T> { public T Rate; public WeightDecay(T rate) { this.Rate = rate; switch (this) { case WeightDecay<float> weightDecayF: weightDecayF.Update = () => WeightDecayF.Update(weightDecayF.Rate, weightDecayF.FunctionParameters); break; case WeightDecay<double> weightDecayD: weightDecayD.Update = () => WeightDecayD.Update(weightDecayD.Rate, weightDecayD.FunctionParameters); break; } } } #endif #if DOUBLE public static class WeightDecayD #else public static class WeightDecayF #endif { public static void Update(Real rate, List<NdArray<Real>> functionParameters) { foreach (var functionParameter in functionParameters) { for (int i = 0; i < functionParameter.Data.Length; i++) { functionParameter.Grad[i] += functionParameter.Data[i] * rate; } } } } }
using System; using System.Collections.Generic; #if DOUBLE using Real = System.Double; #elif NETSTANDARD2_1 using Real = System.Single; using Math = System.MathF; #elif NETSTANDARD2_0 using Real = System.Single; using Math = KelpNet.MathF; #endif namespace KelpNet { #if !DOUBLE //与えられたthresholdで頭打ちではなく、全パラメータのL2Normからレートを取り補正を行う public class WeightDecay<T> : Optimizer<T> where T : unmanaged, IComparable<T> { public T Rate; public WeightDecay(T rate) { this.Rate = rate; switch (this) { case WeightDecay<float> weightDecayF: weightDecayF.Update = () => WeightDecayF.Update(weightDecayF.Rate, weightDecayF.FunctionParameters); break; case WeightDecay<double> weightDecayD: weightDecayD.Update = () => WeightDecayD.Update(weightDecayD.Rate, weightDecayD.FunctionParameters); break; } } } #endif #if DOUBLE public static class WeightDecayD #else public static class WeightDecayF #endif { public static void Update(Real rate, List<NdArray<Real>> functionParameters) { foreach (var functionParameter in functionParameters) { for (int i = 0; i < functionParameter.Data.Length; i++) { functionParameter.Grad[i] += functionParameter.Data[i] * rate; } } } } }
apache-2.0
C#
837c82c3652f3d55ea64a184f3357328ab65af50
Clean up
Free1man/SeleniumTestsRunner,Free1man/SeleniumTestFramework
SeleniumFramework/SeleniumInfrastructure/Runner/SeleniumDriverRunner.cs
SeleniumFramework/SeleniumInfrastructure/Runner/SeleniumDriverRunner.cs
using SeleniumFramework.SeleniumInfrastructure.AppDirectory; using SeleniumFramework.SeleniumInfrastructure.Browsers; using SeleniumFramework.SeleniumInfrastructure.Config; namespace SeleniumFramework.SeleniumInfrastructure.Runner { public class SeleniumDriverRunner { private static SeleniumDriverRunner _instance; private readonly IBrowserService _browserService; private SeleniumDriverRunner(IBrowserService browserService, IAppWorkingDirectoryService appWorkingDirectoryService) { _browserService = browserService; appWorkingDirectoryService.SetCurrentDirectory(); } public static SeleniumDriverRunner Instance { get { if (_instance == null) { ISettings settings = new Settings(); IBrowserService browserService = new BrowserService(settings); IAppWorkingDirectoryService appWorkingDirectoryService = new AppWorkingDirectoryService(settings.TestFolder); _instance = new SeleniumDriverRunner(browserService, appWorkingDirectoryService); } return _instance; } } public Browser Browser { get; private set; } public Browser SetBrowser(Browser.BrowserType browserType = Browser.BrowserType.ReadFromSettings) { Browser = _browserService.GetBrowser(browserType); return Browser; } } }
using SeleniumFramework.SeleniumInfrastructure.AppDirectory; using SeleniumFramework.SeleniumInfrastructure.Browsers; using SeleniumFramework.SeleniumInfrastructure.Config; namespace SeleniumFramework.SeleniumInfrastructure.Runner { public class SeleniumDriverRunner { private static SeleniumDriverRunner _instance; private readonly IBrowserService _browserService; public Settings Settings; private SeleniumDriverRunner(IBrowserService browserService, IAppWorkingDirectoryService appWorkingDirectoryService) { _browserService = browserService; appWorkingDirectoryService.SetCurrentDirectory(); } public static SeleniumDriverRunner Instance { get { if (_instance == null) { ISettings settings = new Settings(); IBrowserService browserService = new BrowserService(settings); IAppWorkingDirectoryService appWorkingDirectoryService = new AppWorkingDirectoryService(settings.TestFolder); _instance = new SeleniumDriverRunner(browserService, appWorkingDirectoryService); } return _instance; } } public Browser Browser { get; private set; } public Browser SetBrowser(Browser.BrowserType browserType = Browser.BrowserType.ReadFromSettings) { Browser = _browserService.GetBrowser(browserType); return Browser; } } }
mit
C#
3555c08757ba5682670e7c75a11074ff092aa4a3
Update EventStoreSessionInstaller.cs
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
Snittlistan.Web/Infrastructure/Installers/EventStoreSessionInstaller.cs
Snittlistan.Web/Infrastructure/Installers/EventStoreSessionInstaller.cs
using System; using Castle.Core; using Castle.MicroKernel; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using EventStoreLite; using Raven.Client; namespace Snittlistan.Web.Infrastructure.Installers { public class EventStoreSessionInstaller : IWindsorInstaller { private readonly Func<ComponentRegistration<IEventStoreSession>, ComponentRegistration<IEventStoreSession>> func; public EventStoreSessionInstaller() { func = x => x.LifestylePerWebRequest(); } public EventStoreSessionInstaller(LifestyleType lifestyleType) { func = x => x.LifeStyle.Is(lifeStyleType); } public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( func.Invoke( Component.For<IEventStoreSession>() .UsingFactoryMethod(CreateEventStoreSession))); } private static IEventStoreSession CreateEventStoreSession(IKernel kernel) { return kernel.Resolve<EventStore>() .OpenSession(kernel.Resolve<IDocumentStore>(), kernel.Resolve<IDocumentSession>()); } } }
using Castle.Core; using Castle.MicroKernel; using Castle.MicroKernel.Registration; using Castle.MicroKernel.SubSystems.Configuration; using Castle.Windsor; using EventStoreLite; using Raven.Client; namespace Snittlistan.Web.Infrastructure.Installers { public class EventStoreSessionInstaller : IWindsorInstaller { private readonly LifestyleType lifestyleType; public EventStoreSessionInstaller() { lifestyleType = LifestyleType.PerWebRequest; } public EventStoreSessionInstaller(LifestyleType lifestyleType) { this.lifestyleType = lifestyleType; } public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register( Component.For<IEventStoreSession>() .UsingFactoryMethod(CreateEventStoreSession) .LifeStyle.Is(lifestyleType)); } private static IEventStoreSession CreateEventStoreSession(IKernel kernel) { return kernel.Resolve<EventStore>() .OpenSession(kernel.Resolve<IDocumentStore>(), kernel.Resolve<IDocumentSession>()); } } }
mit
C#
567a380351d95a09f637f875d39ef91cc8dd45d6
Update BundleConfig.cs - include "NinjaHive_CategoryPage.js" script
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/App_Start/BundleConfig.cs
NinjaHive.WebApp/App_Start/BundleConfig.cs
using System.Web.Optimization; namespace NinjaHive.WebApp { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new ScriptBundle("~/bundles/extensions").Include( "~/Scripts/BootstrapExtensions/ListGroupExtensions.js")); bundles.Add(new ScriptBundle("~/bundles/ninjahive").Include( "~/Scripts/NinjaHive/NinjaHive_GenericModal.js", "~/Scripts/NinjaHive/NinjaHive_CategoryPage.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/Win8Loader.css", "~/Content/bootstrap.css", "~/Content/site.css")); } } }
using System.Web.Optimization; namespace NinjaHive.WebApp { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new ScriptBundle("~/bundles/extensions").Include( "~/Scripts/BootstrapExtensions/ListGroupExtensions.js")); bundles.Add(new ScriptBundle("~/bundles/ninjahive").Include( "~/Scripts/NinjaHive/NinjaHive_GenericModal.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/Win8Loader.css", "~/Content/bootstrap.css", "~/Content/site.css")); } } }
apache-2.0
C#
ee30ee48a6eae90a45a438dc182b30b1672e79cc
Fix uri concatenation in HttpClientExt
eoin55/HoneyBear.HalClient
Src/HoneyBear.HalClient/Http/HttpClientExt.cs
Src/HoneyBear.HalClient/Http/HttpClientExt.cs
using System; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; namespace HoneyBear.HalClient.Http { static class HttpClientEx { public const string MimeJson = "application/json"; public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content) { HttpRequestMessage request = new HttpRequestMessage { Method = new HttpMethod("PATCH"), RequestUri = new Uri(client.BaseAddress, requestUri), Content = content, }; return client.SendAsync(request); } public static Task<HttpResponseMessage> PatchJsonAsync(this HttpClient client, string requestUri, Type type, object value) { return client.PatchAsync(requestUri, new ObjectContent(type, value, new JsonMediaTypeFormatter(), MimeJson)); } } }
using System; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading.Tasks; namespace HoneyBear.HalClient.Http { static class HttpClientEx { public const string MimeJson = "application/json"; public static Task<HttpResponseMessage> PatchAsync(this HttpClient client, string requestUri, HttpContent content) { HttpRequestMessage request = new HttpRequestMessage { Method = new HttpMethod("PATCH"), RequestUri = new Uri(client.BaseAddress + requestUri), Content = content, }; return client.SendAsync(request); } public static Task<HttpResponseMessage> PatchJsonAsync(this HttpClient client, string requestUri, Type type, object value) { return client.PatchAsync(requestUri, new ObjectContent(type, value, new JsonMediaTypeFormatter(), MimeJson)); } } }
mit
C#
5f471d517a7bca9edb896176228a9fd8e9b35651
add null check
marihachi/MSharp
src/MSharp/Misskey.cs
src/MSharp/Misskey.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using MSharp.Core; using MSharp.Core.Utility; namespace MSharp { /// <summary> /// リクエストメソッドの種類を表します /// </summary> public enum MethodType { GET, POST } public class Misskey { public string AppKey { private set; get; } public string UserKey { private set; get; } public string UserId { private set; get; } private string AuthenticationSessionKey { set; get; } public Misskey(string appKey) { this.AppKey = appKey; } public Misskey( string appKey, string userKey, string userId) { this.AppKey = appKey; this.UserKey = userKey; this.UserId = userId; } public async Task StartAuthorize() { var res = await new MisskeyRequest(this, MethodType.GET, "https://api.misskey.xyz/sauth/get-authentication-session-key").Request(); var json = Json.Parse(res); if (json != null) this.AuthenticationSessionKey = json.AuthenticationSessionKey; else throw new RequestException("AuthenticationSessionKey の取得に失敗しました。"); try { System.Diagnostics.Process.Start("https://api.misskey.xyz/authorize@" + this.AuthenticationSessionKey); } catch (Exception ex) { throw new RequestException("アプリ連携ページの表示に失敗しました。", ex); } } public async Task<Misskey> AuthorizePIN(string pinCode) { var ret = await new MisskeyRequest(this, MethodType.GET, "sauth/get-user-key", new Dictionary<string, string> { { "authentication-session-key", this.AuthenticationSessionKey }, { "pin-code", pinCode} }).Request(); var json = Json.Parse(ret); if(json == null) throw new RequestException("UserKey 取得に失敗しました。"); return new Misskey(this.AppKey, (string)json.userKey, (string)json.userId); } public async Task<string> Request( MethodType method, string endPoint, Dictionary<string, string> parameters = null, string baseUrl = null) { return await new MisskeyRequest(this, method, endPoint, parameters, baseUrl).Request(); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using MSharp.Core; using MSharp.Core.Utility; namespace MSharp { /// <summary> /// リクエストメソッドの種類を表します /// </summary> public enum MethodType { GET, POST } public class Misskey { public string AppKey { private set; get; } public string UserKey { private set; get; } public string UserId { private set; get; } private string AuthenticationSessionKey { set; get; } public Misskey(string appKey) { this.AppKey = appKey; } public Misskey( string appKey, string userKey, string userId) { this.AppKey = appKey; this.UserKey = userKey; this.UserId = userId; } public async Task StartAuthorize() { var res = await new MisskeyRequest(this, MethodType.GET, "https://api.misskey.xyz/sauth/get-authentication-session-key").Request(); var json = Json.Parse(res); if (json != null) this.AuthenticationSessionKey = json.AuthenticationSessionKey; else throw new RequestException("AuthenticationSessionKey の取得に失敗しました。"); try { System.Diagnostics.Process.Start("https://api.misskey.xyz/authorize@" + this.AuthenticationSessionKey); } catch (Exception ex) { throw new RequestException("アプリ連携ページの表示に失敗しました。", ex); } } public async Task<Misskey> AuthorizePIN(string pinCode) { var ret = await new MisskeyRequest(this, MethodType.GET, "sauth/get-user-key", new Dictionary<string, string> { { "authentication-session-key", this.AuthenticationSessionKey }, { "pin-code", pinCode} }).Request(); var json = Json.Parse(ret); return new Misskey(this.AppKey, (string)json.userKey, (string)json.userId); } public async Task<string> Request( MethodType method, string endPoint, Dictionary<string, string> parameters = null, string baseUrl = null) { return await new MisskeyRequest(this, method, endPoint, parameters, baseUrl).Request(); } } }
mit
C#
d4c34e2513dba1fe9195948af78ddc0874039ff2
Fix exception message
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/CrashReport/CrashReporter.cs
WalletWasabi.Gui/CrashReport/CrashReporter.cs
using System; using System.Diagnostics; using WalletWasabi.Logging; using WalletWasabi.Microservices; using WalletWasabi.Models; namespace WalletWasabi.Gui.CrashReport { public class CrashReporter { private const int MaxRecursiveCalls = 5; public int Attempts { get; private set; } public string Base64ExceptionString { get; private set; } = null; public bool IsReport { get; private set; } public bool HadException { get; private set; } public bool IsInvokeRequired => !IsReport && HadException; public SerializableException SerializedException { get; private set; } public void TryInvokeCrashReport() { try { if (Attempts >= MaxRecursiveCalls) { throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors."); } if (string.IsNullOrEmpty(Base64ExceptionString)) { throw new InvalidOperationException($"The crash report exception message is empty."); } var args = $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\""; ProcessBridge processBridge = new ProcessBridge(Process.GetCurrentProcess().MainModule.FileName); processBridge.Start(args, false); } catch (Exception ex) { Logger.LogWarning($"There was a problem while invoking crash report:{ex.ToUserFriendlyString()}."); } } public void SetShowCrashReport(string base64ExceptionString, int attempts) { Attempts = attempts; Base64ExceptionString = base64ExceptionString; SerializedException = SerializableException.FromBase64String(Base64ExceptionString); IsReport = true; } /// <summary> /// Sets the exception when it occurs the first time and should be reported to the user. /// </summary> public void SetException(Exception ex) { SerializedException = ex.ToSerializableException(); Base64ExceptionString = SerializableException.ToBase64String(SerializedException); HadException = true; } } }
using System; using System.Diagnostics; using WalletWasabi.Logging; using WalletWasabi.Microservices; using WalletWasabi.Models; namespace WalletWasabi.Gui.CrashReport { public class CrashReporter { private const int MaxRecursiveCalls = 5; public int Attempts { get; private set; } public string Base64ExceptionString { get; private set; } = null; public bool IsReport { get; private set; } public bool HadException { get; private set; } public bool IsInvokeRequired => !IsReport && HadException; public SerializableException SerializedException { get; private set; } public void TryInvokeCrashReport() { try { if (Attempts >= MaxRecursiveCalls) { throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors."); } if (string.IsNullOrEmpty(Base64ExceptionString)) { throw new InvalidOperationException($"The crash report exception message is empty."); } var args = $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\""; ProcessBridge processBridge = new ProcessBridge(Process.GetCurrentProcess().MainModule.FileName); processBridge.Start(args, false); } catch (Exception ex) { Logger.LogWarning($"There was a problem while invoking crash report:{ex}."); } } public void SetShowCrashReport(string base64ExceptionString, int attempts) { Attempts = attempts; Base64ExceptionString = base64ExceptionString; SerializedException = SerializableException.FromBase64String(Base64ExceptionString); IsReport = true; } /// <summary> /// Sets the exception when it occurs the first time and should be reported to the user. /// </summary> public void SetException(Exception ex) { SerializedException = ex.ToSerializableException(); Base64ExceptionString = SerializableException.ToBase64String(SerializedException); HadException = true; } } }
mit
C#
0075ffc17bc15fefb6814fa5f584942209dbde96
Update cache version
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/src/CacheVersion.cs
resharper/resharper-unity/src/CacheVersion.cs
using JetBrains.Annotations; using JetBrains.Application.PersistentMap; using JetBrains.Serialization; namespace JetBrains.ReSharper.Plugins.Unity { // Cache version [PolymorphicMarshaller(3)] public class CacheVersion { [UsedImplicitly] public static UnsafeReader.ReadDelegate<object> ReadDelegate = r => new CacheVersion(); [UsedImplicitly] public static UnsafeWriter.WriteDelegate<object> WriteDelegate = (w, o) => { }; } }
using JetBrains.Annotations; using JetBrains.Application.PersistentMap; using JetBrains.Serialization; namespace JetBrains.ReSharper.Plugins.Unity { // Cache version [PolymorphicMarshaller(2)] public class CacheVersion { [UsedImplicitly] public static UnsafeReader.ReadDelegate<object> ReadDelegate = r => new CacheVersion(); [UsedImplicitly] public static UnsafeWriter.WriteDelegate<object> WriteDelegate = (w, o) => { }; } }
apache-2.0
C#
72b46f603a15b912cb2ef05637360d10f57daac6
Support for pre-alpha 6
pollend/ParkitectCheats,nozols/ParkitectCheats
Main.cs
Main.cs
using UnityEngine; namespace CheatMod { public class Main : IMod { public GameObject _go; public string Description { get { return "Cheats for Parkitect."; } } public string Name { get { return "Cheat Mod"; } } public void onDisabled() { UnityEngine.Object.Destroy(_go); } public void onEnabled() { _go = new GameObject(); _go.AddComponent<CheatModController>(); } public string Identifier { get; set; } public string Path { get; set; } } }
using UnityEngine; namespace CheatMod { public class Main : IMod { public GameObject _go; public string Description { get { return "Cheats for Parkitect."; } } public string Name { get { return "Cheat Mod"; } } public void onDisabled() { UnityEngine.Object.Destroy(_go); } public void onEnabled() { _go = new GameObject(); _go.AddComponent<CheatModController>(); } } }
apache-2.0
C#
53d3bea8a35696369bb633375f291bb547c68951
Arrange Widgets Using Boxes
HenriqueRocha/gtkcontacts
Main.cs
Main.cs
using System; using Gtk; class MainClass { public static void Main (string[] args) { Application.Init(); SetUpGui (); Application.Run (); } static void SetUpGui () { Window w = new Window ("Gtk# Contacts"); VBox v = new VBox(); v.BorderWidth = 6; v.Spacing = 6; w.Add(v); HBox h = new HBox (); h.BorderWidth = 6; h.Spacing = 6; v.PackStart(h, false, false, 0); Button b = new Button ("Save"); b.Clicked += new EventHandler (Button_Clicked); v.PackStart(b, false, false, 0); v = new VBox (); v.Spacing = 6; h.PackStart (v, false, false, 0); Label l = new Label ("Full name: "); l.Xalign = 0; v.PackStart (l, true, false, 0); l = new Label ("Email address: "); l.Xalign = 0; v.PackStart (l, true, false, 0); v = new VBox (); v.Spacing = 6; h.PackStart (v, true, true, 0); v.PackStart (new Entry(), true, true, 0); v.PackStart (new Entry(), true, true, 0); w.DeleteEvent += new DeleteEventHandler (Window_Delete); w.ShowAll (); } static void Window_Delete (object o, DeleteEventArgs args) { Application.Quit (); args.RetVal = true; } static void Button_Clicked (object o, EventArgs args) { System.Console.WriteLine ("Hello, World!"); } }
using System; using Gtk; class MainClass { public static void Main (string[] args) { Application.Init(); Window w = new Window ("Gtk# Basics"); Button b = new Button ("Hit me"); // set up event handling: verbose to illustrate // the use of delegates. w.DeleteEvent += new DeleteEventHandler (Window_Delete); b.Clicked += new EventHandler (Button_Clicked); // initialize the GUI w.Add (b); w.SetDefaultSize (200, 100); w.ShowAll (); Application.Run(); } static void Window_Delete (object o, DeleteEventArgs args) { Application.Quit (); args.RetVal = true; } static void Button_Clicked (object o, EventArgs args) { System.Console.WriteLine ("Hello, World!"); } }
mit
C#
ccb47c289e4a04fc494b0e9741bbb0639220183c
Remove unused import
MHeasell/Mappy,MHeasell/Mappy
Mappy/Models/IMainFormModel.cs
Mappy/Models/IMainFormModel.cs
namespace Mappy.Models { using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using Mappy.Data; using Mappy.Database; public interface IMainFormModel : INotifyPropertyChanged { IFeatureDatabase FeatureRecords { get; } IList<Section> Sections { get; } bool CanUndo { get; } bool CanRedo { get; } bool CanCut { get; } bool CanCopy { get; } bool CanPaste { get; } bool IsDirty { get; } bool MapOpen { get; } string FilePath { get; } bool IsFileReadOnly { get; } bool GridVisible { get; set; } Size GridSize { get; set; } bool HeightmapVisible { get; } bool FeaturesVisible { get; } bool MinimapVisible { get; } int SeaLevel { get; } void Initialize(); void ChooseColor(); void OpenMapAttributes(); void Undo(); void Redo(); bool New(); bool Save(); bool SaveAs(); bool Open(); bool OpenFromDragDrop(string filename); void Close(); void ShowAbout(); void ToggleHeightmap(); void ToggleMinimap(); void ToggleFeatures(); void RefreshMinimap(); void RefreshMinimapHighQualityWithProgress(); void OpenPreferences(); void CloseMap(); void SetSeaLevel(int value); void FlushSeaLevel(); void CutSelectionToClipboard(); void CopySelectionToClipboard(); void PasteFromClipboard(); void ExportMinimap(); void ExportHeightmap(); void ImportMinimap(); void ImportHeightmap(); void ImportCustomSection(); void ExportMapImage(); } }
namespace Mappy.Models { using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using Geometry; using Mappy.Data; using Mappy.Database; public interface IMainFormModel : INotifyPropertyChanged { IFeatureDatabase FeatureRecords { get; } IList<Section> Sections { get; } bool CanUndo { get; } bool CanRedo { get; } bool CanCut { get; } bool CanCopy { get; } bool CanPaste { get; } bool IsDirty { get; } bool MapOpen { get; } string FilePath { get; } bool IsFileReadOnly { get; } bool GridVisible { get; set; } Size GridSize { get; set; } bool HeightmapVisible { get; } bool FeaturesVisible { get; } bool MinimapVisible { get; } int SeaLevel { get; } void Initialize(); void ChooseColor(); void OpenMapAttributes(); void Undo(); void Redo(); bool New(); bool Save(); bool SaveAs(); bool Open(); bool OpenFromDragDrop(string filename); void Close(); void ShowAbout(); void ToggleHeightmap(); void ToggleMinimap(); void ToggleFeatures(); void RefreshMinimap(); void RefreshMinimapHighQualityWithProgress(); void OpenPreferences(); void CloseMap(); void SetSeaLevel(int value); void FlushSeaLevel(); void CutSelectionToClipboard(); void CopySelectionToClipboard(); void PasteFromClipboard(); void ExportMinimap(); void ExportHeightmap(); void ImportMinimap(); void ImportHeightmap(); void ImportCustomSection(); void ExportMapImage(); } }
mit
C#
ec86700f2903bca40fd9cbc7f5a0d062e0373466
Add the nullable disable annotation back becuse it will cause the api broken if remove the nullable disable annotation in the mania ruleset.
peppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,ppy/osu
osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.cs
osu.Game.Rulesets.Mania/Configuration/ManiaRulesetConfigManager.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. #nullable disable using System; using osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting> { public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); SetDefault(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 5); SetDefault(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down); SetDefault(ManiaRulesetSetting.TimingBasedNoteColouring, false); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, scrollTime => new SettingDescription( rawValue: scrollTime, name: "Scroll Speed", value: $"{scrollTime}ms (speed {(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / scrollTime)})" ) ) }; } public enum ManiaRulesetSetting { ScrollTime, ScrollDirection, TimingBasedNoteColouring } }
// 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 osu.Framework.Configuration.Tracking; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; using osu.Game.Rulesets.Mania.UI; namespace osu.Game.Rulesets.Mania.Configuration { public class ManiaRulesetConfigManager : RulesetConfigManager<ManiaRulesetSetting> { public ManiaRulesetConfigManager(SettingsStore settings, RulesetInfo ruleset, int? variant = null) : base(settings, ruleset, variant) { } protected override void InitialiseDefaults() { base.InitialiseDefaults(); SetDefault(ManiaRulesetSetting.ScrollTime, 1500.0, DrawableManiaRuleset.MIN_TIME_RANGE, DrawableManiaRuleset.MAX_TIME_RANGE, 5); SetDefault(ManiaRulesetSetting.ScrollDirection, ManiaScrollingDirection.Down); SetDefault(ManiaRulesetSetting.TimingBasedNoteColouring, false); } public override TrackedSettings CreateTrackedSettings() => new TrackedSettings { new TrackedSetting<double>(ManiaRulesetSetting.ScrollTime, scrollTime => new SettingDescription( rawValue: scrollTime, name: "Scroll Speed", value: $"{scrollTime}ms (speed {(int)Math.Round(DrawableManiaRuleset.MAX_TIME_RANGE / scrollTime)})" ) ) }; } public enum ManiaRulesetSetting { ScrollTime, ScrollDirection, TimingBasedNoteColouring } }
mit
C#
d8bc7670d78f538c3a6eb5126e8471ed3bbf725b
change scope of response JSON result
shortcutmedia/shortcut-deeplink-sdk-wp
ShortcutDeepLinkingPcl/SCServerResponse.cs
ShortcutDeepLinkingPcl/SCServerResponse.cs
using System; using Newtonsoft.Json.Linq; namespace Shortcut.DeepLinking.Pcl { public class SCServerResponse { private JObject mJson; public SCServerResponse(JObject json) { this.mJson = json; } public JObject Json { get { return this.mJson; } private set { this.mJson = value; } } public string DeepLinkString { get { return mJson[KeyValues.DEEP_LINK_KEY].ToString(); } } public Uri DeepLink { get { return new Uri(this.DeepLinkString); } } } }
using System; using Newtonsoft.Json.Linq; namespace Shortcut.DeepLinking.Pcl { public class SCServerResponse { private JObject mJson; public SCServerResponse(JObject json) { this.mJson = json; } public JObject Json { get { return this.mJson; } set { this.mJson = value; } } public string DeepLinkString { get { return mJson[KeyValues.DEEP_LINK_KEY].ToString(); } } public Uri DeepLink { get { return new Uri(this.DeepLinkString); } } } }
mit
C#
3028259f29fc39cd3f383708a13d27443975b22d
Update SerializerBase.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/SerializerBase.cs
TIKSN.Core/Serialization/SerializerBase.cs
using System; namespace TIKSN.Serialization { public abstract class SerializerBase<TSerial> : ISerializer<TSerial> where TSerial : class { public TSerial Serialize(object obj) { try { return SerializeInternal(obj); } catch (Exception ex) { throw new SerializerException("Serialization failed.", ex); } } protected abstract TSerial SerializeInternal(object obj); } }
using System; namespace TIKSN.Serialization { public abstract class SerializerBase<TSerial> : ISerializer<TSerial> where TSerial : class { public TSerial Serialize(object obj) { if (obj == null) return null; try { return SerializeInternal(obj); } catch (Exception ex) { throw new SerializerException("Serialization failed.", ex); } } protected abstract TSerial SerializeInternal(object obj); } }
mit
C#
b970867929928c50c2e07eaf9dc4e67803f87175
refactor update command
louthy/language-ext,StanJav/language-ext,StefanBertels/language-ext
Samples/Contoso/Contoso.Application/Students/Commands/UpdateStudentHandler.cs
Samples/Contoso/Contoso.Application/Students/Commands/UpdateStudentHandler.cs
using System.Threading; using System.Threading.Tasks; using Contoso.Core; using Contoso.Core.Domain; using Contoso.Core.Interfaces.Repositories; using LanguageExt; using MediatR; using static LanguageExt.Prelude; namespace Contoso.Application.Students.Commands { public class UpdateStudentHandler : IRequestHandler<UpdateStudent, Either<Error, Task>> { private readonly IStudentRepository _studentRepository; public UpdateStudentHandler(IStudentRepository studentRepository) => _studentRepository = studentRepository; public async Task<Either<Error, Task>> Handle(UpdateStudent request, CancellationToken cancellationToken) => (await Validate(request)) .Map(s => ApplyUpdateRequest(s, request)) .ToEither<Task>(); private async Task ApplyUpdateRequest(Student s, UpdateStudent update) { s.FirstName = update.FirstName; s.LastName = update.LastName; await _studentRepository.Update(s); } private async Task<Validation<Error, Student>> Validate(UpdateStudent request) => (ValidateFirstName(request), ValidateLastName(request), await StudentMustExist(request)) .Apply((first, last, studentToUpdate) => studentToUpdate); private async Task<Validation<Error, Student>> StudentMustExist(UpdateStudent updateStudent) => (await _studentRepository.Get(updateStudent.StudentId)) .ToValidation<Error>("Student does not exist."); private Validation<Error, string> ValidateFirstName(UpdateStudent updateStudent) => NotEmpty(updateStudent.FirstName) .Bind(firstName => MaxStringLength(50, firstName)); private Validation<Error, string> ValidateLastName(UpdateStudent updateStudent) => NotEmpty(updateStudent.LastName) .Bind(lastName => MaxStringLength(50, lastName)); private Validation<Error, string> MaxStringLength(int maxLength, string str) => str.Length > maxLength ? Fail<Error, string>($"{str} must not be longer than {maxLength}") : Success<Error, string>(str); private Validation<Error, string> NotEmpty(string str) => string.IsNullOrEmpty(str) ? Fail<Error, string>("Must not be empty") : Success<Error, string>(str); } }
using System.Threading; using System.Threading.Tasks; using Contoso.Core; using Contoso.Core.Domain; using Contoso.Core.Interfaces.Repositories; using LanguageExt; using MediatR; using static LanguageExt.Prelude; namespace Contoso.Application.Students.Commands { public class UpdateStudentHandler : IRequestHandler<UpdateStudent, Either<Error, Task>> { private readonly IStudentRepository _studentRepository; public UpdateStudentHandler(IStudentRepository studentRepository) => _studentRepository = studentRepository; public async Task<Either<Error, Task>> Handle(UpdateStudent request, CancellationToken cancellationToken) => (await Validate(request)) .Map(s => ApplyUpdateRequest(s, request)) .ToEither<Task>(); private async Task ApplyUpdateRequest(Student s, UpdateStudent update) { s.FirstName = update.FirstName; s.LastName = update.LastName; await _studentRepository.Update(s); } private async Task<Validation<Error, Student>> Validate(UpdateStudent request) => (ValidateFirstName(request), ValidateLastName(request), await StudentMustExist(request)) .Apply((first, last, studentToUpdate) => studentToUpdate); private async Task<Validation<Error, Student>> StudentMustExist(UpdateStudent updateStudent) => (await _studentRepository.Get(updateStudent.StudentId)).Match( Some: student => Success<Error, Student>(student), None: () => Fail<Error, Student>($"Student does not exist.")); private Validation<Error, string> ValidateFirstName(UpdateStudent updateStudent) => NotEmpty(updateStudent.FirstName) .Bind(firstName => MaxStringLength(50, firstName)); private Validation<Error, string> ValidateLastName(UpdateStudent updateStudent) => NotEmpty(updateStudent.LastName) .Bind(lastName => MaxStringLength(50, lastName)); private Validation<Error, string> MaxStringLength(int maxLength, string str) => str.Length > maxLength ? Fail<Error, string>($"{str} must not be longer than {maxLength}") : Success<Error, string>(str); private Validation<Error, string> NotEmpty(string str) => string.IsNullOrEmpty(str) ? Fail<Error, string>("Must not be empty") : Success<Error, string>(str); } }
mit
C#
9679491d7c747cafe266a33ec313dcfa23583460
Use Const.tau in Program.cs
lou1306/CIV,lou1306/CIV
CIV/Program.cs
CIV/Program.cs
using System; using Antlr4.Runtime; using Antlr4.Runtime.Tree; using CIV.Ccs; using CIV.Hml; using System.Linq; using CIV.Processes; namespace CIV { class Program { static void Main(string[] args) { // Parse the file var inputStream = CreateInputStream("prisoners.ccs.txt"); var lexer = new CcsLexer(inputStream); var tokens = new CommonTokenStream(lexer); var parser = new CcsParser(tokens); var programCtx = parser.program(); var listener = new CcsListener(); ParseTreeWalker.Default.Walk(listener, programCtx); var factory = listener.GetProcessFactory(); var prison = factory.Create(listener.Processes["Prison"]); RandomTrace(prison, 450); //var formula = new AntlrInputStream("[a]<b>(<c>tt and [b]ff)"); //var lexer = new HmlLexer(formula); //var tokens = new CommonTokenStream(lexer); //var parser = new HmlParser(tokens); //var listener = new HmlListener(); //ParseTreeWalker.Default.Walk(listener, parser.baseHml()); } static AntlrInputStream CreateInputStream(string filename) { var text = System.IO.File.ReadAllText(filename); return new AntlrInputStream(text); } static void RandomTrace(IProcess start, int moves, bool printTau = false) { var rand = new Random(); for (int i = 0; i < moves; i++) { var transitions = start.Transitions(); if (!transitions.Any()) { break; } int index = rand.Next(0, transitions.Count()); var nextTransition = transitions.ElementAt(index); start = nextTransition.Process; if (nextTransition.Label != Const.tau || printTau) { Console.WriteLine("{0:000}: {1}", i, nextTransition.Label); } } } } }
using System; using System.Collections.Generic; using Antlr4.Runtime; using Antlr4.Runtime.Tree; using CIV.Ccs; using System.Linq; using System.Text; using CIV.Processes; namespace CIV { class Program { static void Main(string[] args) { // Parse the file var inputStream = Program.CreateInputStream("prisoners.ccs.txt"); var lexer = new CcsLexer(inputStream); var tokens = new CommonTokenStream(lexer); var parser = new CcsParser(tokens); var programCtx = parser.program(); var listener = new CcsListener(); ParseTreeWalker.Default.Walk(listener, programCtx); var factory = listener.GetProcessFactory(); var prison = factory.Create(listener.Processes["Prison"]); RandomTrace(prison, 450); } static AntlrInputStream CreateInputStream(string filename) { var text = System.IO.File.ReadAllText(filename); return new AntlrInputStream(text); } static void RandomTrace(IProcess start, int moves, bool printTau = false) { var rand = new Random(); for (int i = 0; i < moves; i++) { var transitions = start.Transitions(); if (!transitions.Any()) { break; } int index = rand.Next(0, transitions.Count()); var nextTransition = transitions.ElementAt(index); start = nextTransition.Process; if (nextTransition.Label != "tau" || printTau) { Console.WriteLine( String.Format("{0:000}: {1}", i, nextTransition.Label)); } } } } }
mit
C#
f26ab68fa6a4ead4920582a6e147e39e168a8732
Update IndexRequest
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Api/Requests/Requests.NoNamespace.cs
src/Nest/Api/Requests/Requests.NoNamespace.cs
using System; using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using Elastic.Transport; namespace Nest { public partial interface IIndexRequest<TDocument> : ICustomJsonWriter { TDocument Document { get; set; } // TODO - This should be generated based on the spec Id? Id { get; } } public partial class IndexRequest<TDocument> : ICustomJsonWriter { protected override HttpMethod? DynamicHttpMethod => GetHttpMethod(this); [JsonIgnore] public TDocument Document { get; set; } [JsonIgnore] Id? IIndexRequest<TDocument>.Id => Self.RouteValues.Get<Id>("id"); void ICustomJsonWriter.WriteJson(Utf8JsonWriter writer, ITransportSerializer sourceSerializer) { // TODO: Review perf using var ms = new MemoryStream(); sourceSerializer.Serialize(Document, ms); // TODO - This needs to camelCase ms.Position = 0; using var document = JsonDocument .Parse(ms); // This is not super efficient but a variant on the suggestion at https://github.com/dotnet/runtime/issues/1784#issuecomment-608331125 document.RootElement.WriteTo(writer); // Perhaps can be improved in .NET 6/ updated system.text.json - https://github.com/dotnet/runtime/pull/53212 } internal static HttpMethod GetHttpMethod(IIndexRequest<TDocument> request) => request.Id?.Value is not null || request.RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST; //request.Id?.StringOrLongValue != null || request.RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST; } public partial class IndexDescriptor<TDocument> { public void WriteJson(Utf8JsonWriter writer, ITransportSerializer sourceSerializer) => throw new NotImplementedException(); Id? IIndexRequest<TDocument>.Id => Self.RouteValues.Get<Id>("id"); TDocument IIndexRequest<TDocument>.Document { get; set; } } }
namespace Nest { //public partial interface IIndexRequest<TDocument> : IProxyRequest //{ // TDocument Document { get; set; } // TODO - This should be generated based on the spec // Id? Id { get; } //} //public partial class IndexRequest<TDocument> : IProxyRequest //{ // protected override HttpMethod? DynamicHttpMethod => GetHttpMethod(this); // [JsonIgnore] public TDocument Document { get; set; } // [JsonIgnore] Id IIndexRequest<TDocument>.Id => Self.RouteValues.Get<Id>("id"); // void IProxyRequest.WriteJson(Utf8JsonWriter writer, ITransportSerializer sourceSerializer) // { // // TODO: Review perf // using var ms = new MemoryStream(); // sourceSerializer.Serialize(Document, ms); // TODO - This needs to camelCase // ms.Position = 0; // using var // document = JsonDocument // .Parse(ms); // This is not super efficient but a variant on the suggestion at https://github.com/dotnet/runtime/issues/1784#issuecomment-608331125 // document.RootElement.WriteTo(writer); // // Perhaps can be improved in .NET 6/ updated system.text.json - https://github.com/dotnet/runtime/pull/53212 // } // internal static HttpMethod GetHttpMethod(IIndexRequest<TDocument> request) => // request.Id?.StringOrLongValue != null || request.RouteValues.ContainsId ? HttpMethod.PUT : HttpMethod.POST; //} //public partial class IndexDescriptor<TDocument> //{ // public void WriteJson(Utf8JsonWriter writer, ITransportSerializer sourceSerializer) => // throw new NotImplementedException(); // Id? IIndexRequest<TDocument>.Id => Self.RouteValues.Get<Id>("id"); // TDocument IIndexRequest<TDocument>.Document { get; set; } //} }
apache-2.0
C#
90d6445914b1217a1a7875392837880060c3f8f9
Add unit test for partition change
vishalmane/MVCScrolling,dncuug/X.PagedList,lingsu/PagedList,gary75952/PagedList,troygoode/PagedList,weiwei695/PagedList,kpi-ua/X.PagedList,troygoode/PagedList,lingsu/PagedList,ernado-x/X.PagedList,kpi-ua/X.PagedList,ernado-x/X.PagedList,vishalmane/MVCScrolling,weiwei695/PagedList,lingsu/PagedList,gary75952/PagedList,weiwei695/PagedList,troygoode/PagedList,vishalmane/MVCScrolling,gary75952/PagedList,lingsu/PagedList
src/PagedList.Tests/SplitAndPartitionFacts.cs
src/PagedList.Tests/SplitAndPartitionFacts.cs
using System.Linq; using Xunit; namespace PagedList.Tests { public class SplitAndPartitionFacts { [Fact] public void Partition_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Partition(1000); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } [Fact] public void Paritiion_Returns_Enumerable_With_One_Item_When_Count_Less_Than_Page_Size() { //arrange var list = Enumerable.Range(1,10); //act var partitionList = list.Partition(1000); //assert Assert.Equal(1, splitList.Count()); Assert.Equal(10, splitList.First().Count()); } [Fact] public void Split_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Split(10); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } } }
using System.Linq; using Xunit; namespace PagedList.Tests { public class SplitAndPartitionFacts { [Fact] public void Partition_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Partition(1000); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } [Fact] public void Split_Works() { //arrange var list = Enumerable.Range(1, 9999); //act var splitList = list.Split(10); //assert Assert.Equal(10, splitList.Count()); Assert.Equal(1000, splitList.First().Count()); Assert.Equal(999, splitList.Last().Count()); } } }
mit
C#
c96c56430380e87662e008b7366b206369c4eefb
Fix conversion of zoneEmphasis
OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core
Core/OfficeDevPnP.Core/Utilities/JsonConverters/EmphasisJsonConverter.cs
Core/OfficeDevPnP.Core/Utilities/JsonConverters/EmphasisJsonConverter.cs
using Newtonsoft.Json; using System; namespace OfficeDevPnP.Core.Utilities.JsonConverters { /// <summary> /// Converts Emphasis values into the supported integer format /// </summary> public class EmphasisJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (true); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object initialValue = reader.Value; Int32 result = 0; if (initialValue != null) { var stringValue = initialValue.ToString(); if (!String.IsNullOrEmpty(stringValue) && stringValue.Equals("undefined", StringComparison.InvariantCultureIgnoreCase)) { result = 0; } else if (!Int32.TryParse(stringValue, out result)) { result = 0; } } return (result); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value!=null) { int zoneEmphasis = 0; if (int.TryParse(value.ToString(), out zoneEmphasis)); writer.WriteValue(zoneEmphasis); } } } }
using Newtonsoft.Json; using System; namespace OfficeDevPnP.Core.Utilities.JsonConverters { /// <summary> /// Converts Emphasis values into the supported integer format /// </summary> public class EmphasisJsonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (true); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { object initialValue = reader.Value; Int32 result = 0; if (initialValue != null) { var stringValue = initialValue.ToString(); if (!String.IsNullOrEmpty(stringValue) && stringValue.Equals("undefined", StringComparison.InvariantCultureIgnoreCase)) { result = 0; } else if (!Int32.TryParse(stringValue, out result)) { result = 0; } } return (result); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(value.ToString()); } } }
mit
C#
9aab197d480da2f6db3031e0c92399e3a8321426
fix of framework desc
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
Master/Appleseed/Projects/Appleseed.Framework/Properties/AssemblyInfo.cs
Master/Appleseed/Projects/Appleseed.Framework/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Appleseed.AppCode")] [assembly: AssemblyDescription("Appleseed Portal and Content Management System : Framework.Web ")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal Core Framework")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("03094a42-cc29-4a65-aead-e2f803e90931")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.4.98.383")] [assembly: AssemblyFileVersion("1.4.98.383")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Appleseed.AppCode")] [assembly: AssemblyDescription("This is the core framework dll for the Appleseed portal project")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ANANT Corporation")] [assembly: AssemblyProduct("Appleseed Portal Core Framework")] [assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("03094a42-cc29-4a65-aead-e2f803e90931")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.4.98.383")] [assembly: AssemblyFileVersion("1.4.98.383")]
apache-2.0
C#
e8ad1240cfb285dde60dbf4e91fc7decfea22ef7
Disable debug attached
Fody/Costura,Fody/Costura
src/Costura.Fody/ModuleWeaver.cs
src/Costura.Fody/ModuleWeaver.cs
using System.Collections.Generic; using System.Diagnostics; using Fody; using Mono.Cecil; public partial class ModuleWeaver: BaseModuleWeaver { public IAssemblyResolver AssemblyResolver { get; set; } public override void Execute() { //#if DEBUG // if (!Debugger.IsAttached) // { // Debugger.Launch(); // } //#endif var config = new Configuration(Config); FindMsCoreReferences(); FixResourceCase(); ProcessNativeResources(!config.DisableCompression); EmbedResources(config); CalculateHash(); ImportAssemblyLoader(config.CreateTemporaryAssemblies); CallAttach(config); AddChecksumsToTemplate(); BuildUpNameDictionary(config.CreateTemporaryAssemblies, config.PreloadOrder); } public override IEnumerable<string> GetAssembliesForScanning() { yield return "mscorlib"; yield return "System"; } public override bool ShouldCleanReference => true; }
using System.Collections.Generic; using System.Diagnostics; using Fody; using Mono.Cecil; public partial class ModuleWeaver: BaseModuleWeaver { public IAssemblyResolver AssemblyResolver { get; set; } public override void Execute() { #if DEBUG if (!Debugger.IsAttached) { Debugger.Launch(); } #endif var config = new Configuration(Config); FindMsCoreReferences(); FixResourceCase(); ProcessNativeResources(!config.DisableCompression); EmbedResources(config); CalculateHash(); ImportAssemblyLoader(config.CreateTemporaryAssemblies); CallAttach(config); AddChecksumsToTemplate(); BuildUpNameDictionary(config.CreateTemporaryAssemblies, config.PreloadOrder); } public override IEnumerable<string> GetAssembliesForScanning() { yield return "mscorlib"; yield return "System"; } public override bool ShouldCleanReference => true; }
mit
C#
f2a954e2b28c041a1e0a65587f908cdf7d6f630c
Update ServiceContext.cs
hprose/hprose-dotnet
src/Hprose.RPC/ServiceContext.cs
src/Hprose.RPC/ServiceContext.cs
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ServiceContext.cs | | | | ServiceContext class for C#. | | | | LastModified: Feb 8, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using System.Dynamic; using System.Net; namespace Hprose.RPC { public class ServiceContext : Context { public Service Service { get; private set; } public Method Method { get; set; } = null; public EndPoint RemoteEndPoint { get; set; } = null; public dynamic RequestHeaders { get; } = new ExpandoObject(); public dynamic ResponseHeaders { get; } = new ExpandoObject(); public ServiceContext(Service service) { Service = service; } } }
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | ServiceContext.cs | | | | ServiceContext class for C#. | | | | LastModified: Feb 8, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using System.Dynamic; namespace Hprose.RPC { public class ServiceContext : Context { public Service Service { get; private set; } public Method Method { get; set; } = null; public dynamic RequestHeaders { get; } = new ExpandoObject(); public dynamic ResponseHeaders { get; } = new ExpandoObject(); public ServiceContext(Service service) { Service = service; } } }
mit
C#
63a2182c27f9895986e5493ca65db51ab7d177b6
increment minor version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.14.0")] [assembly: AssemblyInformationalVersion("0.14.0")] /* * Version 0.14.0 * * - [FIX] Makes `ReferenceCollectingVisitor` tread-safe and improves its * performance. * * - [NEW] Introduces the new `RestrictingReferenceAssertion.Verify(Assembly)` * method to be used to verify that all references of a given assembly are * correctly specified, instead of using * `RestrictingReferenceAssertion.Visit(AssemblyElement)`. * * [Fact] * public void Demo() * { * var assertion = new RestrictingReferenceAssertion(); * assertion.Verify(typeof(IEnumerable<object>).Assembly); * } * * - [NEW] Introduces the assertion class `HidingReferenceAssertion` to verify * that specified assemblies are not directly referenced. * * [Fact] * public void Demo() * { * var assertion = new HidingReferenceAssertion(typeof(Enumerable).Assembly); * assertion.Verify(typeof(IEnumerable<object>).Assembly); * } */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.13.1")] [assembly: AssemblyInformationalVersion("0.13.1")] /* * Version 0.14.0 * * - [FIX] Makes `ReferenceCollectingVisitor` tread-safe and improves its * performance. * * - [NEW] Introduces the new `RestrictingReferenceAssertion.Verify(Assembly)` * method to be used to verify that all references of a given assembly are * correctly specified, instead of using * `RestrictingReferenceAssertion.Visit(AssemblyElement)`. * * [Fact] * public void Demo() * { * var assertion = new RestrictingReferenceAssertion(); * assertion.Verify(typeof(IEnumerable<object>).Assembly); * } * * - [NEW] Introduces the assertion class `HidingReferenceAssertion` to verify * that specified assemblies are not directly referenced. * * [Fact] * public void Demo() * { * var assertion = new HidingReferenceAssertion(typeof(Enumerable).Assembly); * assertion.Verify(typeof(IEnumerable<object>).Assembly); * } */
mit
C#
68cb5cd6af8e5d36c761afb9b452de64f21b8367
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.8.7")] [assembly: AssemblyInformationalVersion("0.8.7")] /* * Version 0.8.7 * * Rename TestFixtureAdapter to AutoFixtureAdapter to clarify. * * BREAKING CHNAGE * - before: * TestFixtureAdapter class * after: * AutoFixtureAdapter class */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.8.6")] [assembly: AssemblyInformationalVersion("0.8.6")] /* * Version 0.8.6 * * Change the FirstClassCommand constructor to use MethodInfo directly * instead of Delegate. * * BREAKING CHNAGE * FirstClassCommand * - before: * FirstClassCommand(IMethodInfo, Delegate, object[]) * after: * FirstClassCommand(IMethodInfo, MethodInfo, object[]) * * - before: * Delegate Delegate * after: * MethodInfo TestCase */
mit
C#
830c4e648894ae79358c9e23b8ca563708a3b225
make addressprefix mandatory in subnet
bgold09/azure-powershell,hallihan/azure-powershell,SarahRogers/azure-powershell,rohmano/azure-powershell,stankovski/azure-powershell,pankajsn/azure-powershell,hallihan/azure-powershell,shuagarw/azure-powershell,praveennet/azure-powershell,arcadiahlyy/azure-powershell,zaevans/azure-powershell,stankovski/azure-powershell,enavro/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,juvchan/azure-powershell,arcadiahlyy/azure-powershell,naveedaz/azure-powershell,jasper-schneider/azure-powershell,ankurchoubeymsft/azure-powershell,shuagarw/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,ankurchoubeymsft/azure-powershell,rhencke/azure-powershell,DeepakRajendranMsft/azure-powershell,chef-partners/azure-powershell,jtlibing/azure-powershell,dulems/azure-powershell,haocs/azure-powershell,chef-partners/azure-powershell,oaastest/azure-powershell,ClogenyTechnologies/azure-powershell,Matt-Westphal/azure-powershell,rohmano/azure-powershell,Matt-Westphal/azure-powershell,pelagos/azure-powershell,Matt-Westphal/azure-powershell,shuagarw/azure-powershell,bgold09/azure-powershell,hallihan/azure-powershell,AzureRT/azure-powershell,seanbamsft/azure-powershell,AzureAutomationTeam/azure-powershell,AzureRT/azure-powershell,TaraMeyer/azure-powershell,PashaPash/azure-powershell,devigned/azure-powershell,yoavrubin/azure-powershell,kagamsft/azure-powershell,dominiqa/azure-powershell,jianghaolu/azure-powershell,jtlibing/azure-powershell,jianghaolu/azure-powershell,zaevans/azure-powershell,mayurid/azure-powershell,hovsepm/azure-powershell,AzureRT/azure-powershell,naveedaz/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,AzureAutomationTeam/azure-powershell,PashaPash/azure-powershell,alfantp/azure-powershell,praveennet/azure-powershell,CamSoper/azure-powershell,zaevans/azure-powershell,alfantp/azure-powershell,akurmi/azure-powershell,ankurchoubeymsft/azure-powershell,jtlibing/azure-powershell,yadavbdev/azure-powershell,yadavbdev/azure-powershell,AzureRT/azure-powershell,CamSoper/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,nickheppleston/azure-powershell,TaraMeyer/azure-powershell,jianghaolu/azure-powershell,CamSoper/azure-powershell,enavro/azure-powershell,nickheppleston/azure-powershell,akurmi/azure-powershell,pelagos/azure-powershell,naveedaz/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,hovsepm/azure-powershell,seanbamsft/azure-powershell,yantang-msft/azure-powershell,zaevans/azure-powershell,DeepakRajendranMsft/azure-powershell,kagamsft/azure-powershell,akurmi/azure-powershell,oaastest/azure-powershell,dominiqa/azure-powershell,AzureAutomationTeam/azure-powershell,krkhan/azure-powershell,arcadiahlyy/azure-powershell,hungmai-msft/azure-powershell,SarahRogers/azure-powershell,alfantp/azure-powershell,nemanja88/azure-powershell,hovsepm/azure-powershell,pelagos/azure-powershell,rhencke/azure-powershell,nemanja88/azure-powershell,zhencui/azure-powershell,naveedaz/azure-powershell,pankajsn/azure-powershell,enavro/azure-powershell,pomortaz/azure-powershell,seanbamsft/azure-powershell,SarahRogers/azure-powershell,pelagos/azure-powershell,dulems/azure-powershell,jasper-schneider/azure-powershell,zhencui/azure-powershell,atpham256/azure-powershell,rohmano/azure-powershell,bgold09/azure-powershell,oaastest/azure-powershell,pomortaz/azure-powershell,seanbamsft/azure-powershell,rhencke/azure-powershell,SarahRogers/azure-powershell,akurmi/azure-powershell,yoavrubin/azure-powershell,dominiqa/azure-powershell,haocs/azure-powershell,yadavbdev/azure-powershell,ailn/azure-powershell,yantang-msft/azure-powershell,jianghaolu/azure-powershell,rhencke/azure-powershell,nemanja88/azure-powershell,SarahRogers/azure-powershell,ankurchoubeymsft/azure-powershell,pelagos/azure-powershell,praveennet/azure-powershell,CamSoper/azure-powershell,dulems/azure-powershell,chef-partners/azure-powershell,haocs/azure-powershell,ailn/azure-powershell,ailn/azure-powershell,krkhan/azure-powershell,TaraMeyer/azure-powershell,rohmano/azure-powershell,yoavrubin/azure-powershell,enavro/azure-powershell,bgold09/azure-powershell,zhencui/azure-powershell,ailn/azure-powershell,chef-partners/azure-powershell,krkhan/azure-powershell,tonytang-microsoft-com/azure-powershell,shuagarw/azure-powershell,ClogenyTechnologies/azure-powershell,DeepakRajendranMsft/azure-powershell,CamSoper/azure-powershell,yantang-msft/azure-powershell,tonytang-microsoft-com/azure-powershell,DeepakRajendranMsft/azure-powershell,PashaPash/azure-powershell,alfantp/azure-powershell,atpham256/azure-powershell,tonytang-microsoft-com/azure-powershell,ankurchoubeymsft/azure-powershell,dulems/azure-powershell,rhencke/azure-powershell,juvchan/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,juvchan/azure-powershell,AzureAutomationTeam/azure-powershell,mayurid/azure-powershell,haocs/azure-powershell,ClogenyTechnologies/azure-powershell,rohmano/azure-powershell,yadavbdev/azure-powershell,jasper-schneider/azure-powershell,rohmano/azure-powershell,hungmai-msft/azure-powershell,hungmai-msft/azure-powershell,yoavrubin/azure-powershell,mayurid/azure-powershell,zhencui/azure-powershell,stankovski/azure-powershell,akurmi/azure-powershell,chef-partners/azure-powershell,Matt-Westphal/azure-powershell,arcadiahlyy/azure-powershell,kagamsft/azure-powershell,atpham256/azure-powershell,pomortaz/azure-powershell,hungmai-msft/azure-powershell,AzureAutomationTeam/azure-powershell,nickheppleston/azure-powershell,TaraMeyer/azure-powershell,mayurid/azure-powershell,AzureRT/azure-powershell,Matt-Westphal/azure-powershell,PashaPash/azure-powershell,oaastest/azure-powershell,hovsepm/azure-powershell,yantang-msft/azure-powershell,nemanja88/azure-powershell,stankovski/azure-powershell,jasper-schneider/azure-powershell,pankajsn/azure-powershell,praveennet/azure-powershell,pomortaz/azure-powershell,praveennet/azure-powershell,juvchan/azure-powershell,haocs/azure-powershell,AzureAutomationTeam/azure-powershell,yantang-msft/azure-powershell,atpham256/azure-powershell,pomortaz/azure-powershell,yadavbdev/azure-powershell,bgold09/azure-powershell,mayurid/azure-powershell,seanbamsft/azure-powershell,hallihan/azure-powershell,DeepakRajendranMsft/azure-powershell,zaevans/azure-powershell,oaastest/azure-powershell,nickheppleston/azure-powershell,ClogenyTechnologies/azure-powershell,arcadiahlyy/azure-powershell,hungmai-msft/azure-powershell,kagamsft/azure-powershell,devigned/azure-powershell,juvchan/azure-powershell,naveedaz/azure-powershell,dominiqa/azure-powershell,zhencui/azure-powershell,tonytang-microsoft-com/azure-powershell,pankajsn/azure-powershell,PashaPash/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,ClogenyTechnologies/azure-powershell,stankovski/azure-powershell,hallihan/azure-powershell,nickheppleston/azure-powershell,devigned/azure-powershell,jtlibing/azure-powershell,ailn/azure-powershell,dominiqa/azure-powershell,tonytang-microsoft-com/azure-powershell,krkhan/azure-powershell,yoavrubin/azure-powershell,seanbamsft/azure-powershell,yantang-msft/azure-powershell,kagamsft/azure-powershell,dulems/azure-powershell,AzureRT/azure-powershell,jianghaolu/azure-powershell,enavro/azure-powershell,shuagarw/azure-powershell,jasper-schneider/azure-powershell,TaraMeyer/azure-powershell
src/ResourceManager/Network/Commands.NetworkResourceProvider/VirtualNetwork/Subnet/CommonAzureVirtualNetworkSubnetConfigCmdlet.cs
src/ResourceManager/Network/Commands.NetworkResourceProvider/VirtualNetwork/Subnet/CommonAzureVirtualNetworkSubnetConfigCmdlet.cs
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Commands.NetworkResourceProvider.Models; namespace Microsoft.Azure.Commands.NetworkResourceProvider { public class CommonAzureVirtualNetworkSubnetConfigCmdlet : NetworkBaseClient { [Parameter( Mandatory = false, HelpMessage = "The name of the subnet")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, HelpMessage = "The address prefix of the subnet")] [ValidateNotNullOrEmpty] public string AddressPrefix { get; set; } [Parameter( Mandatory = false, HelpMessage = "The list of Dns Servers")] public List<string> DnsServer { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResourceId", HelpMessage = "NetworkSecurityGroupId")] public string NetworkSecurityGroupId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResource", HelpMessage = "NetworkSecurityGroup")] public PSNetworkSecurityGroup NetworkSecurityGroup { get; set; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; using Microsoft.Azure.Commands.NetworkResourceProvider.Models; namespace Microsoft.Azure.Commands.NetworkResourceProvider { public class CommonAzureVirtualNetworkSubnetConfigCmdlet : NetworkBaseClient { [Parameter( Mandatory = false, HelpMessage = "The name of the subnet")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = false, HelpMessage = "The address prefix of the subnet")] [ValidateNotNullOrEmpty] public string AddressPrefix { get; set; } [Parameter( Mandatory = false, HelpMessage = "The list of Dns Servers")] public List<string> DnsServer { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResourceId", HelpMessage = "NetworkSecurityGroupId")] public string NetworkSecurityGroupId { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = "SetByResource", HelpMessage = "NetworkSecurityGroup")] public PSNetworkSecurityGroup NetworkSecurityGroup { get; set; } } }
apache-2.0
C#
e559a1143e1ffa5f8e67d267f3a227d4446c5b5f
add the framework version so that MSBuild can be found
apache/npanday,apache/npanday,apache/npanday,apache/npanday
dotnet/assemblies/NPanday.ProjectImporter/Engine/src/main/csharp/Converter/Algorithms/ASPNetPomConverter.cs
dotnet/assemblies/NPanday.ProjectImporter/Engine/src/main/csharp/Converter/Algorithms/ASPNetPomConverter.cs
#region Apache License, Version 2.0 // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System.IO; using NPanday.Model.Pom; using NPanday.ProjectImporter.Digest.Model; using NPanday.Utils; using System.Collections.Generic; namespace NPanday.ProjectImporter.Converter.Algorithms { public class ASPNetPomConverter : NormalPomConverter { public ASPNetPomConverter(ProjectDigest projectDigest, string mainPomFile, NPanday.Model.Pom.Model parent, string groupId) : base(projectDigest,mainPomFile,parent, groupId) { } public override void ConvertProjectToPomModel(bool writePom, string scmTag) { // just call the base, but dont write it we still need some minor adjustments for it base.ConvertProjectToPomModel(false,scmTag); List<string> goals = new List<string>(); goals.Add("assemble-package-files"); goals.Add("process-configs"); Plugin aspnetPlugin = AddPlugin("org.apache.npanday.plugins", "aspnet-maven-plugin", null, false); AddPluginExecution(aspnetPlugin, "prepare-package", goals.ToArray(), null); if (!string.IsNullOrEmpty(projectDigest.TargetFramework)) AddPluginConfiguration(aspnetPlugin, "frameworkVersion", projectDigest.TargetFramework); if (!string.IsNullOrEmpty(projectDigest.WebConfig)) { AddPluginConfiguration(aspnetPlugin, "transformationHint", projectDigest.WebConfig); } Plugin msdeployPlugin = AddPlugin("org.apache.npanday.plugins", "msdeploy-maven-plugin", null, false); AddPluginExecution(msdeployPlugin, "create-msdeploy-package", new string[] { "create-package" }, null); if (writePom) { PomHelperUtility.WriteModelToPom(new FileInfo(Path.GetDirectoryName(projectDigest.FullFileName) + @"\pom.xml"), Model); } } } }
#region Apache License, Version 2.0 // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // #endregion using System.IO; using NPanday.Model.Pom; using NPanday.ProjectImporter.Digest.Model; using NPanday.Utils; using System.Collections.Generic; namespace NPanday.ProjectImporter.Converter.Algorithms { public class ASPNetPomConverter : NormalPomConverter { public ASPNetPomConverter(ProjectDigest projectDigest, string mainPomFile, NPanday.Model.Pom.Model parent, string groupId) : base(projectDigest,mainPomFile,parent, groupId) { } public override void ConvertProjectToPomModel(bool writePom, string scmTag) { // just call the base, but dont write it we still need some minor adjustments for it base.ConvertProjectToPomModel(false,scmTag); List<string> goals = new List<string>(); goals.Add("assemble-package-files"); goals.Add("process-configs"); Plugin aspnetPlugin = AddPlugin("org.apache.npanday.plugins", "aspnet-maven-plugin", null, false); AddPluginExecution(aspnetPlugin, "prepare-package", goals.ToArray(), null); if (!string.IsNullOrEmpty(projectDigest.WebConfig)) { AddPluginConfiguration(aspnetPlugin, "transformationHint", projectDigest.WebConfig); } Plugin msdeployPlugin = AddPlugin("org.apache.npanday.plugins", "msdeploy-maven-plugin", null, false); AddPluginExecution(msdeployPlugin, "create-msdeploy-package", new string[] { "create-package" }, null); if (writePom) { PomHelperUtility.WriteModelToPom(new FileInfo(Path.GetDirectoryName(projectDigest.FullFileName) + @"\pom.xml"), Model); } } } }
apache-2.0
C#
fca699e3e7a2dd8d451cc00d32356033fd2152cb
Fix messaging for Stop-AzureEmulator cmdlet
Madhukarc/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,antonba/azure-sdk-tools,johnkors/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,johnkors/azure-sdk-tools,akromm/azure-sdk-tools,antonba/azure-sdk-tools,markcowl/azure-sdk-tools,Madhukarc/azure-sdk-tools,antonba/azure-sdk-tools,akromm/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,antonba/azure-sdk-tools,akromm/azure-sdk-tools,johnkors/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,johnkors/azure-sdk-tools,johnkors/azure-sdk-tools
WindowsAzurePowershell/src/Management.CloudService/Cmdlet/StopAzureEmulator.cs
WindowsAzurePowershell/src/Management.CloudService/Cmdlet/StopAzureEmulator.cs
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Cmdlet { using System; using System.Management.Automation; using System.Security.Permissions; using AzureTools; using Common; using Model; using Properties; using Services; using Microsoft.Samples.WindowsAzure.ServiceManagement; /// <summary> /// Runs the service in the emulator /// </summary> [Cmdlet(VerbsLifecycle.Stop, "AzureEmulator")] public class StopAzureEmulatorCommand : CloudCmdlet<IServiceManagement> { [Parameter(Mandatory = false)] [Alias("ln")] public SwitchParameter Launch { get; set; } public StopAzureEmulatorCommand() { SkipChannelInit = true; } [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public void StopAzureEmulatorProcess() { string standardOutput; string standardError; AzureService service = new AzureService(); SafeWriteVerbose(Resources.StopEmulatorMessage); service.StopEmulator(out standardOutput, out standardError); SafeWriteVerbose(Resources.StoppedEmulatorMessage); } [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] public override void ExecuteCmdlet() { AzureTool.Validate(); base.ExecuteCmdlet(); StopAzureEmulatorProcess(); } } }
// ---------------------------------------------------------------------------------- // // Copyright 2011 Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.CloudService.Cmdlet { using System; using System.Management.Automation; using System.Security.Permissions; using AzureTools; using Common; using Model; using Properties; using Services; using Microsoft.Samples.WindowsAzure.ServiceManagement; /// <summary> /// Runs the service in the emulator /// </summary> [Cmdlet(VerbsLifecycle.Stop, "AzureEmulator")] public class StopAzureEmulatorCommand : CloudCmdlet<IServiceManagement> { [Parameter(Mandatory = false)] [Alias("ln")] public SwitchParameter Launch { get; set; } [PermissionSet(SecurityAction.LinkDemand, Name = "FullTrust")] public string StopAzureEmulatorProcess() { string standardOutput; string standardError; AzureService service = new AzureService(); SafeWriteObject(Resources.StopEmulatorMessage); service.StopEmulator(out standardOutput, out standardError); SafeWriteObject(Resources.StoppedEmulatorMessage); return null; } [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] protected override void ProcessRecord() { try { AzureTool.Validate(); SkipChannelInit = true; base.ProcessRecord(); string result = this.StopAzureEmulatorProcess(); SafeWriteObject(result); } catch (Exception ex) { SafeWriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null)); } } } }
apache-2.0
C#
d2f1c39d12002c0d283d05e07f5f3f91f737de46
Format time
ne1ro/desperation
Assets/Scripts/Timer.cs
Assets/Scripts/Timer.cs
using UnityEngine; using UnityEngine.UI; using System; public class Timer : MonoBehaviour { private float startTime; void Awake() { startTime = Time.time; } void Update() { TimeSpan t = TimeSpan.FromSeconds(Time.time - startTime); GetComponent<Text>().text = string.Format("{0:D2}:{1:D2}", t.Minutes, t.Seconds); } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class Timer : MonoBehaviour { private float startTime; void Awake() { startTime = Time.time; } void Update() { float elapsedTime = Time.time - startTime; GetComponent<Text>().text = elapsedTime.ToString(); } }
mit
C#
6210e9388939d47ee1ef6b8017c2aae5da405d51
Use LineEditor instead of Console.ReadLine.
alldne/school,alldne/school
School/REPL.cs
School/REPL.cs
using System; using Mono.Terminal; namespace School { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); LineEditor editor = new LineEditor("School"); Console.WriteLine("School REPL:"); string line; while ((line = editor.Edit("> ", "")) != null) { try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } } }
using System; namespace School { public class REPL { public REPL() { } public void Run() { Evaluator evaluator = new Evaluator(); string line; Console.WriteLine("School REPL:"); do { Console.Write("> "); line = Console.ReadLine(); if (!String.IsNullOrEmpty(line)) { try { Value value = evaluator.Evaluate(line); Console.WriteLine(value); } catch (Exception e) { Console.WriteLine(e); } } } while (line != null); } } }
apache-2.0
C#
5fb4764742afa4857d43c7332527f77cf2973c19
add update to IoC
mattiasliljenzin/load-testing-simulator
src/simulation/App.cs
src/simulation/App.cs
using System; using System.IO; using System.Net; using System.Threading.Tasks; using Autofac; using Microsoft.Extensions.Configuration; using RequestSimulation.Configuration; using RequestSimulation.Datasources; using RequestSimulation.Executing; using RequestSimulation.Executing.Interceptors; using RequestSimulation.Loadstrategies; namespace RequestSimulation { public class App { public async Task Run() { var from = new DateTime(2017, 09, 20, 13, 00, 00); var to = from.AddHours(1); Console.WriteLine(" "); Console.WriteLine($"Start:\t {from.ToString()} (UTC)"); Console.WriteLine($"To:\t {to.ToString()} (UTC)"); Console.WriteLine(" "); var container = InitializeComponents(); var delegator = container.Resolve<RequestDelegator>(); await delegator.PopulateRequestsAsync(from, to); var simulator = container.Resolve<Simulation>(); simulator.Subscribe(delegator); simulator.SetLoadStrategyEffectRate(1.0); simulator.RunSimulation(from, to); } private IContainer InitializeComponents() { var builder = new ContainerBuilder(); builder.Register(_ => BuildConfiguration()).As<IConfiguration>(); builder.RegisterType<AuthorizationInterceptor>().As<IHttpRequestMessageInterceptor>(); builder.RegisterType<ChangeHostInterceptor>().As<IHttpRequestMessageInterceptor>(); builder.RegisterType<ApplicationInsightsDependencyDataSource>().As<IRequestDataSource>(); builder.RegisterType<RequestExecutor>().As<IRequestExecutor>(); builder.RegisterType<LinearLoadStrategy>().As<ILoadStrategy>().WithParameter("slope", 1.5); builder.RegisterType<TokenStore>().As<ITokenStore>(); builder.RegisterType<FileContentClient>().As<IContentClient>(); builder.RegisterType<ApplicationInsightsConfiguration>(); builder.RegisterType<Simulation>(); builder.RegisterType<RequestDelegator>(); return builder.Build(); } private IConfigurationRoot BuildConfiguration() { return new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json") .AddEnvironmentVariables() .Build(); } } }
using System; using System.IO; using System.Net; using System.Threading.Tasks; using Autofac; using Microsoft.Extensions.Configuration; using RequestSimulation.Configuration; using RequestSimulation.Datasources; using RequestSimulation.Executing; using RequestSimulation.Executing.Interceptors; using RequestSimulation.Loadstrategies; namespace RequestSimulation { public class App { public async Task Run() { var from = DateTime.UtcNow.AddMinutes(-10); var to = DateTime.UtcNow; Console.WriteLine(" "); Console.WriteLine($"Start:\t {from.ToString()} (UTC)"); Console.WriteLine($"To:\t {to.ToString()} (UTC)"); Console.WriteLine(" "); var container = InitializeComponents(); var delegator = container.Resolve<RequestDelegator>(); await delegator.PopulateRequestsAsync(from, to); var simulator = container.Resolve<Simulation>(); simulator.Subscribe(delegator); simulator.SetLoadStrategyEffectRate(1.0); simulator.RunSimulation(from, to); } private IContainer InitializeComponents() { var builder = new ContainerBuilder(); builder.Register(_ => BuildConfiguration()).As<IConfiguration>(); builder.RegisterType<AuthorizationInterceptor>().As<IHttpRequestMessageInterceptor>(); builder.RegisterType<ChangeHostInterceptor>().As<IHttpRequestMessageInterceptor>(); builder.RegisterType<ApplicationInsightsDependencyDataSource>().As<IRequestDataSource>(); builder.RegisterType<RequestExecutor>().As<IRequestExecutor>(); builder.RegisterType<LinearLoadStrategy>().As<ILoadStrategy>().WithParameter("slope", 1.5); builder.RegisterType<ApplicationInsightsConfiguration>(); builder.RegisterType<Simulation>(); builder.RegisterType<RequestDelegator>(); return builder.Build(); } private IConfigurationRoot BuildConfiguration() { return new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json") .AddEnvironmentVariables() .Build(); } } }
mit
C#
f25be9a461756d84508fa0d4f8683506d6b88e07
Add regions to StackTrace class
bartlomiejwolk/FileLogger
StackInfo.cs
StackInfo.cs
using System; using System.Reflection; using System.Diagnostics; namespace ATP.LoggingTools { public class StackInfo { #region FIELDS private StackTrace stackTrace = new StackTrace(); private StackFrame frame; private MethodBase method; private Type classType; #endregion #region PROPERTIES public string MethodName { get { if (frame != null) { return method.Name; } return "[Method info is not available]"; } } public string MethodSignature { get { if (frame != null) { return method.ToString(); } return "[Method info is not available]"; } } public string ClassName { get { // Make sure that there's a frame to get the info from. if (frame != null) { return classType.Name; } return "[Class info is not available]"; } } public string QualifiedClassName { get { // Make sure that there's a frame to get the info from. if (frame != null) { return classType.ToString(); } return "[Class info is not available]"; } } public int FrameCount { get { return stackTrace.FrameCount; } } #endregion #region METHODS public StackInfo(int frameIndex) { frame = stackTrace.GetFrame(frameIndex); // Frame can be null. try { method = frame.GetMethod(); classType = method.DeclaringType; } catch (NullReferenceException e) { UnityEngine.Debug.LogWarning("Frame not found: " + e); } } #endregion } }
using System; using System.Reflection; using System.Diagnostics; namespace ATP.LoggingTools { public class StackInfo { private StackTrace stackTrace = new StackTrace(); private StackFrame frame; private MethodBase method; private Type classType; public string MethodName { get { if (frame != null) { return method.Name; } return "[Method info is not available]"; } } public string MethodSignature { get { if (frame != null) { return method.ToString(); } return "[Method info is not available]"; } } public string ClassName { get { // Make sure that there's a frame to get the info from. if (frame != null) { return classType.Name; } return "[Class info is not available]"; } } public string QualifiedClassName { get { // Make sure that there's a frame to get the info from. if (frame != null) { return classType.ToString(); } return "[Class info is not available]"; } } public int FrameCount { get { return stackTrace.FrameCount; } } public StackInfo (int frameIndex) { frame = stackTrace.GetFrame(frameIndex); // Frame can be null. try { method = frame.GetMethod(); classType = method.DeclaringType; } catch (NullReferenceException e) { UnityEngine.Debug.LogWarning("Frame not found: " + e); } } } }
mit
C#
487b60d45b367760c2c6c1e3a8d38c49314bb9d6
Update assembly description attribute in elbsms_core
eightlittlebits/elbsms
elbsms_core/Properties/AssemblyInfo.cs
elbsms_core/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("elbsms_core")] [assembly: AssemblyDescription("elbsms core")] [assembly: AssemblyProduct("elbsms_core")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("59ef0f57-7a82-4cd8-80a6-0d0536ce1ed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("elbsms_console")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("elbsms_core")] [assembly: AssemblyDescription("")] [assembly: AssemblyProduct("elbsms_core")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("59ef0f57-7a82-4cd8-80a6-0d0536ce1ed3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("elbsms_console")]
mit
C#
6021c83e23c31b028dcba108c961813766ba767c
update variable name
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.Application.UnitTests/Queries/GetProviders/WhenHandlingGetProvidersQuery.cs
src/SFA.DAS.Commitments.Application.UnitTests/Queries/GetProviders/WhenHandlingGetProvidersQuery.cs
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoFixture; using FluentAssertions; using Moq; using NUnit.Framework; using SFA.DAS.Commitments.Application.Queries.GetProviders; using SFA.DAS.Commitments.Domain.Data; using SFA.DAS.Commitments.Domain.Entities; namespace SFA.DAS.Commitments.Application.UnitTests.Queries.GetProviders { public class WhenHandlingGetProvidersQuery { public class WhenHandlingGetProviderQuery { private Mock<IProviderRepository> _repository; private GetProvidersQueryHandler _handler; private List<Provider> _providers; [SetUp] public void Arrange() { var fixture = new Fixture(); _providers = fixture.CreateMany<Provider>().ToList(); _repository = new Mock<IProviderRepository>(); _repository.Setup(x => x.GetProviders()).ReturnsAsync(_providers); _handler = new GetProvidersQueryHandler(_repository.Object); } [Test] public async Task Then_The_Service_Is_Called_And_Providers_Returned() { //Arrange var query = new GetProvidersQuery(); //Act var actual = await _handler.Handle(query); //Assert actual.Providers.ShouldBeEquivalentTo(_providers); } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoFixture; using FluentAssertions; using Moq; using NUnit.Framework; using SFA.DAS.Commitments.Application.Queries.GetProviders; using SFA.DAS.Commitments.Domain.Data; using SFA.DAS.Commitments.Domain.Entities; namespace SFA.DAS.Commitments.Application.UnitTests.Queries.GetProviders { public class WhenHandlingGetProvidersQuery { public class WhenHandlingGetProviderQuery { private Mock<IProviderRepository> _repository; private GetProvidersQueryHandler _handler; private List<Provider> _provider; [SetUp] public void Arrange() { var fixture = new Fixture(); _provider = fixture.CreateMany<Provider>().ToList(); _repository = new Mock<IProviderRepository>(); _repository.Setup(x => x.GetProviders()).ReturnsAsync(_provider); _handler = new GetProvidersQueryHandler(_repository.Object); } [Test] public async Task Then_The_Service_Is_Called_And_Providers_Returned() { //Arrange var query = new GetProvidersQuery(); //Act var actual = await _handler.Handle(query); //Assert actual.Providers.ShouldBeEquivalentTo(_provider); } } } }
mit
C#
0d38ec4a26bc5a888af84ae92a78a2529f163012
increment minor version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.5.0")] [assembly: AssemblyInformationalVersion("0.5.0")] /* * Version 0.5.0 * * - Experiment.AutoFixtureWithExample is release newly, which is to show * examples for how to use Experiment.AutoFixture. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.4.0")] [assembly: AssemblyInformationalVersion("0.4.0")] /* * Version 0.4.0 * * - rename TheoremAttribute to NaiveTheoremAttribute. * * - rename AutoDataTheoremAttribute to TheoremAttribute. * * - The above changes are breaking change but as the current major * version is zero(unstable), the change is acceptable according to * Semantic Versioning. */
mit
C#
e008ceca1d8c5ff1942640b846fcc0798c4c1a26
increment minor version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.23.0")] [assembly: AssemblyInformationalVersion("0.23.0")] /* * Version 0.23.0 * * - [NEW] made Experiment.AutoFixture support creating instances of abstract * types. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.22.4")] [assembly: AssemblyInformationalVersion("0.22.4")] /* * Version 0.23.0 * * - [NEW] made Experiment.AutoFixture support creating instances of abstract * types. */
mit
C#
c543a0a7ecfe27600da43b757d63c2b66402a808
Remove unused Reinterpret reference
FreecraftCore/FreecraftCore.Serializer,FreecraftCore/FreecraftCore.Serializer
src/FreecraftCore.Serializer/Serializers/Primitives/GenericTypePrimitiveSerializerStrategy.cs
src/FreecraftCore.Serializer/Serializers/Primitives/GenericTypePrimitiveSerializerStrategy.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace FreecraftCore.Serializer { //TODO: Cannot support Char due to encoding differences. /// <summary> /// Contract for type serializer that is a primitive and generic. /// </summary> /// <typeparam name="TType"></typeparam> public sealed class GenericTypePrimitiveSerializerStrategy<TType> : StatelessTypeSerializerStrategy<GenericTypePrimitiveSerializerStrategy<TType>, TType> where TType : struct { static GenericTypePrimitiveSerializerStrategy() { if (!typeof(TType).IsPrimitive) throw new InvalidOperationException($"Cannot use {nameof(GenericTypePrimitiveSerializerStrategy<TType>)} for Type: {typeof(TType).Name} as it's not a primitive type."); } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override TType Read(Span<byte> source, ref int offset) { TType value = Unsafe.ReadUnaligned<TType>(ref source[offset]); offset += MarshalSizeOf<TType>.SizeOf; return value; } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void Write(TType value, Span<byte> destination, ref int offset) { Unsafe.As<byte, TType>(ref destination[offset]) = value; offset += MarshalSizeOf<TType>.SizeOf; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using Reinterpret.Net; namespace FreecraftCore.Serializer { //TODO: Cannot support Char due to encoding differences. /// <summary> /// Contract for type serializer that is a primitive and generic. /// </summary> /// <typeparam name="TType"></typeparam> public sealed class GenericTypePrimitiveSerializerStrategy<TType> : StatelessTypeSerializerStrategy<GenericTypePrimitiveSerializerStrategy<TType>, TType> where TType : struct { static GenericTypePrimitiveSerializerStrategy() { if (!typeof(TType).IsPrimitive) throw new InvalidOperationException($"Cannot use {nameof(GenericTypePrimitiveSerializerStrategy<TType>)} for Type: {typeof(TType).Name} as it's not a primitive type."); } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override TType Read(Span<byte> source, ref int offset) { TType value = Unsafe.ReadUnaligned<TType>(ref source[offset]); offset += MarshalSizeOf<TType>.SizeOf; return value; } /// <inheritdoc /> [MethodImpl(MethodImplOptions.AggressiveInlining)] public override void Write(TType value, Span<byte> destination, ref int offset) { Unsafe.As<byte, TType>(ref destination[offset]) = value; offset += MarshalSizeOf<TType>.SizeOf; } } }
agpl-3.0
C#
376834b2eb020b209b228f3387ffb545a3c96672
Improve error message when BlogPost.Content markdown to html fails
croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia.com.au
source/CroquetAustraliaWebsite.Application/app/home/BlogPostViewModel.cs
source/CroquetAustraliaWebsite.Application/app/home/BlogPostViewModel.cs
using System; using System.Web; using Anotar.NLog; using Casper.Domain.Features.BlogPosts; using CroquetAustraliaWebsite.Library.Content; namespace CroquetAustraliaWebsite.Application.App.home { public class BlogPostViewModel { private readonly BlogPost _blogPost; private readonly Lazy<IHtmlString> _contentFactory; public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer) { _blogPost = blogPost; _contentFactory = new Lazy<IHtmlString>(() => MarkdownToHtml(markdownTransformer)); } public string Title => _blogPost.Title; public IHtmlString Content => _contentFactory.Value; public DateTimeOffset Published => _blogPost.Published; private IHtmlString MarkdownToHtml(IMarkdownTransformer markdownTransformer) { try { return markdownTransformer.MarkdownToHtml(_blogPost.Content); } catch (Exception innerException) { var exception = new Exception($"Could not convert content of blog post '{Title}' to HTML.", innerException); exception.Data.Add("BlogPost.Title", _blogPost.Title); exception.Data.Add("BlogPost.Content", _blogPost.Content); exception.Data.Add("BlogPost.Published", _blogPost.Published); exception.Data.Add("BlogPost.RelativeUri", _blogPost.RelativeUri); LogTo.ErrorException(exception.Message, exception); return new HtmlString("<p>Content currently not available.<p>"); } } } }
using System; using System.Web; using Casper.Domain.Features.BlogPosts; using CroquetAustraliaWebsite.Library.Content; namespace CroquetAustraliaWebsite.Application.App.home { public class BlogPostViewModel { private readonly BlogPost _blogPost; private readonly Lazy<IHtmlString> _contentFactory; public BlogPostViewModel(BlogPost blogPost, IMarkdownTransformer markdownTransformer) { _blogPost = blogPost; _contentFactory = new Lazy<IHtmlString>(() => markdownTransformer.MarkdownToHtml(_blogPost.Content)); } public string Title { get { return _blogPost.Title; } } public IHtmlString Content { get { return _contentFactory.Value; } } public DateTimeOffset Published { get { return _blogPost.Published; } } } }
mit
C#
7fa1aba972ad8635296e15311aac9594c8d69a30
Add new constructor to CCPlace that takes a X,Y position.
mono/CocosSharp,mono/CocosSharp,hig-ag/CocosSharp,haithemaraissia/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,netonjm/CocosSharp,netonjm/CocosSharp,MSylvia/CocosSharp,hig-ag/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,MSylvia/CocosSharp,zmaruo/CocosSharp
cocos2d/actions/action_instants/CCPlace.cs
cocos2d/actions/action_instants/CCPlace.cs
namespace CocosSharp { public class CCPlace : CCActionInstant { public CCPoint Position { get; private set; } #region Constructors public CCPlace(CCPoint pos) { Position = pos; } public CCPlace(int posX, int posY) { Position = new CCPoint (posX, posY); } #endregion Constructors protected internal override CCActionState StartAction (CCNode target) { return new CCPlaceState (this, target); } // Take me out later - See comments in CCAction public override bool HasState { get { return true; } } // protected internal override void StartWithTarget(CCNode target) // { // base.StartWithTarget(target); // m_pTarget.Position = Position; // } } public class CCPlaceState : CCFiniteTimeActionState { protected CCPoint Position { get; set; } public CCPlaceState (CCPlace action, CCNode target) : base(action, target) { Position = action.Position; Target.Position = Position; } // This can be taken out once CCActionInstant has it's State separated public override void Step(float dt) { Update(1); } } }
namespace CocosSharp { public class CCPlace : CCActionInstant { public CCPoint Position { get; private set; } #region Constructors public CCPlace(CCPoint pos) { Position = pos; } #endregion Constructors protected internal override CCActionState StartAction (CCNode target) { return new CCPlaceState (this, target); } // Take me out later - See comments in CCAction public override bool HasState { get { return true; } } // protected internal override void StartWithTarget(CCNode target) // { // base.StartWithTarget(target); // m_pTarget.Position = Position; // } } public class CCPlaceState : CCFiniteTimeActionState { protected CCPoint Position { get; set; } public CCPlaceState (CCPlace action, CCNode target) : base(action, target) { Position = action.Position; Target.Position = Position; } // This can be taken out once CCActionInstant has it's State separated public override void Step(float dt) { Update(1); } } }
mit
C#
280cd048f662090d5bdde09191daa9ff978190dc
Fix joystick settings changing enabled state of config level bindables
ppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Overlays/Settings/Sections/Input/JoystickSettings.cs
osu.Game/Overlays/Settings/Sections/Input/JoystickSettings.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.Bindables; using osu.Framework.Graphics; using osu.Framework.Input.Handlers.Joystick; using osu.Framework.Localisation; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Input { public class JoystickSettings : SettingsSubsection { protected override LocalisableString Header => JoystickSettingsStrings.JoystickGamepad; private readonly JoystickHandler joystickHandler; private readonly Bindable<bool> enabled = new BindableBool(true); private SettingsSlider<float> deadzoneSlider; private Bindable<float> handlerDeadzone; private Bindable<float> localDeadzone; public JoystickSettings(JoystickHandler joystickHandler) { this.joystickHandler = joystickHandler; } [BackgroundDependencyLoader] private void load() { // use local bindable to avoid changing enabled state of game host's bindable. handlerDeadzone = joystickHandler.DeadzoneThreshold.GetBoundCopy(); localDeadzone = handlerDeadzone.GetUnboundCopy(); Children = new Drawable[] { new SettingsCheckbox { LabelText = CommonStrings.Enabled, Current = enabled }, deadzoneSlider = new SettingsSlider<float> { LabelText = JoystickSettingsStrings.DeadzoneThreshold, KeyboardStep = 0.01f, DisplayAsPercentage = true, Current = localDeadzone, }, }; } protected override void LoadComplete() { base.LoadComplete(); enabled.BindTo(joystickHandler.Enabled); enabled.BindValueChanged(e => deadzoneSlider.Current.Disabled = !e.NewValue, true); handlerDeadzone.BindValueChanged(val => { bool disabled = localDeadzone.Disabled; localDeadzone.Disabled = false; localDeadzone.Value = val.NewValue; localDeadzone.Disabled = disabled; }, true); localDeadzone.BindValueChanged(val => handlerDeadzone.Value = val.NewValue); } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Framework.Input.Handlers.Joystick; using osu.Framework.Localisation; using osu.Game.Localisation; namespace osu.Game.Overlays.Settings.Sections.Input { public class JoystickSettings : SettingsSubsection { protected override LocalisableString Header => JoystickSettingsStrings.JoystickGamepad; private readonly JoystickHandler joystickHandler; private readonly Bindable<bool> enabled = new BindableBool(true); private SettingsSlider<float> deadzoneSlider; public JoystickSettings(JoystickHandler joystickHandler) { this.joystickHandler = joystickHandler; } [BackgroundDependencyLoader] private void load() { Children = new Drawable[] { new SettingsCheckbox { LabelText = CommonStrings.Enabled, Current = enabled }, deadzoneSlider = new SettingsSlider<float> { LabelText = JoystickSettingsStrings.DeadzoneThreshold, KeyboardStep = 0.01f, DisplayAsPercentage = true, Current = joystickHandler.DeadzoneThreshold, }, }; } protected override void LoadComplete() { base.LoadComplete(); enabled.BindTo(joystickHandler.Enabled); enabled.BindValueChanged(e => deadzoneSlider.Current.Disabled = !e.NewValue, true); } } }
mit
C#
a01896a652ee042cc66149a99ccf5b76dddef535
Fix misordered hit error in score meter types
peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Configuration/ScoreMeterType.cs
osu.Game/Configuration/ScoreMeterType.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.ComponentModel; namespace osu.Game.Configuration { public enum ScoreMeterType { [Description("None")] None, [Description("Hit Error (left)")] HitErrorLeft, [Description("Hit Error (right)")] HitErrorRight, [Description("Hit Error (left+right)")] HitErrorBoth, [Description("Hit Error (bottom)")] HitErrorBottom, [Description("Colour (left)")] ColourLeft, [Description("Colour (right)")] ColourRight, [Description("Colour (left+right)")] ColourBoth, [Description("Colour (bottom)")] ColourBottom, } }
// 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.ComponentModel; namespace osu.Game.Configuration { public enum ScoreMeterType { [Description("None")] None, [Description("Hit Error (left)")] HitErrorLeft, [Description("Hit Error (right)")] HitErrorRight, [Description("Hit Error (bottom)")] HitErrorBottom, [Description("Hit Error (left+right)")] HitErrorBoth, [Description("Colour (left)")] ColourLeft, [Description("Colour (right)")] ColourRight, [Description("Colour (left+right)")] ColourBoth, [Description("Colour (bottom)")] ColourBottom, } }
mit
C#
3ce744674c18f2ebf7545caccac341ef08af26b6
change username property in received notification
Paymentsense/Dapper.SimpleSave
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/Notification/NotificationReceivedDto.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/Notification/NotificationReceivedDto.cs
using PS.Mothership.Core.Common.Template.Event; namespace PS.Mothership.Core.Common.Dto.Event.Notification { public class NotificationReceivedDto { public EventTypeEnum EventType { get; set; } public int EventTypeTotalNotifications { get; set; } public string Username { get; set; } } }
using System.Collections.Generic; using PS.Mothership.Core.Common.Template.Event; namespace PS.Mothership.Core.Common.Dto.Event.Notification { public class NotificationReceivedDto { public EventTypeEnum EventType { get; set; } public int EventTypeTotalNotifications { get; set; } public IList<string> Usernames { get; set; } } }
mit
C#
28ad4ed3bd7cdaa8778d443a829f133426ce421d
Handle returnURL and also grab ticket and query
ucdavis/CasAuthenticationMiddleware,ucdavis/CasAuthenticationMiddleware,ucdavis/CasAuthenticationMiddleware
src/CasAuthenticationMiddleware/CasAuthenticationHandler.cs
src/CasAuthenticationMiddleware/CasAuthenticationHandler.cs
using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; namespace CasAuthenticationMiddleware { public class CasAuthenticationHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : CasAuthenticationOptions { private const string StrTicket = "ticket"; private const string StrReturnUrl = "ReturnURL"; protected override async Task<AuthenticateResult> HandleRemoteAuthenticateAsync() { // build query string but strip out ticket if it is defined var query = Context.Request.Query.Keys.Where( key => string.Compare(key, StrTicket, StringComparison.OrdinalIgnoreCase) != 0) .Aggregate("", (current, key) => current + ("&" + key + "=" + Context.Request.Query[key])); // replace 1st character with ? if query is not empty if (!string.IsNullOrEmpty(query)) { query = "?" + query.Substring(1); } // get ticket & service string ticket = Context.Request.Query[StrTicket]; var returnUrl = Context.Request.Query[StrReturnUrl]; string service = Context.Request.Path.ToUriComponent() + query; if (string.IsNullOrWhiteSpace(ticket)) { return await Task.FromResult(AuthenticateResult.Failed("No authorization ticket found")); } else { //todo: backchannel call var identity = new ClaimsIdentity(Options.ClaimsIssuer); identity.AddClaim(new Claim(ClaimTypes.Name, "postit", ClaimValueTypes.String, Options.ClaimsIssuer)); var principal = new ClaimsPrincipal(identity); var authTicket = new AuthenticationTicket(principal, new AuthenticationProperties {RedirectUri = returnUrl}, "CAS"); return await Task.FromResult(AuthenticateResult.Success(authTicket)); } } protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context) { var authorizationEndpoint = Options.AuthorizationEndpoint + "login?service=" + BuildRedirectUri(Options.CallbackPath) + "?" + StrReturnUrl + "=" + Context.Request.Path; Context.Response.Redirect(authorizationEndpoint); return await Task.FromResult(true); } } }
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authentication; using Microsoft.AspNet.Http.Authentication; using Microsoft.AspNet.Http.Features.Authentication; namespace CasAuthenticationMiddleware { public class CasAuthenticationHandler<TOptions> : RemoteAuthenticationHandler<TOptions> where TOptions : CasAuthenticationOptions { protected override async Task<AuthenticateResult> HandleRemoteAuthenticateAsync() { var query = Context.Request.Query; var identity = new ClaimsIdentity(Options.ClaimsIssuer); identity.AddClaim(new Claim(ClaimTypes.Name, "postit", ClaimValueTypes.String, Options.ClaimsIssuer)); var principal = new ClaimsPrincipal(identity); var authTicket = new AuthenticationTicket(principal, new AuthenticationProperties(), "CAS"); var uri = CurrentUri; return await Task.FromResult(AuthenticateResult.Success(authTicket)); } protected override async Task<bool> HandleUnauthorizedAsync(ChallengeContext context) { var authorizationEndpoint = Options.AuthorizationEndpoint + "login?service=" + BuildRedirectUri(Options.CallbackPath); Context.Response.Redirect(authorizationEndpoint); return await Task.FromResult(true); } } }
mit
C#
4118f44f0199bcd414675ba705c6337ede19cb14
Bump version to 1.4
kevinkuszyk/FluentAssertions.Ioc.Ninject,kevinkuszyk/FluentAssertions.Ioc.Ninject
src/FluentAssertions.Ioc.Ninject/Properties/AssemblyInfo.cs
src/FluentAssertions.Ioc.Ninject/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FluentAssertions.Ioc.Ninject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kevin Kuszyk")] [assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")] [assembly: AssemblyCopyright("Copyright © Kevin Kuszyk 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")] // 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")] [assembly: AssemblyInformationalVersion("1.4.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("FluentAssertions.Ioc.Ninject")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kevin Kuszyk")] [assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")] [assembly: AssemblyCopyright("Copyright © Kevin Kuszyk 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")] // 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.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")] [assembly: AssemblyInformationalVersion("1.3.0")]
apache-2.0
C#
d2af76859987a42a50843d75b87cb2f6b74707e4
Add widget name to automation FileSave dialog for tests
MatterHackers/agg-sharp,jlewin/agg-sharp,larsbrubaker/agg-sharp
Gui/FileDialogs/AutomationFileDialogCreator.cs
Gui/FileDialogs/AutomationFileDialogCreator.cs
using System; using System.Linq; namespace MatterHackers.Agg.UI { internal class AutomationFileDialogCreator : FileDialogCreator { public override bool OpenFileDialog(OpenFileDialogParams openParams, Action<OpenFileDialogParams> callback) { ShowFileDialog((fileText) => { if (fileText.Length > 2) { string[] files = fileText.Split(';', ' ').Select(f => f.Trim('\"')).ToArray(); openParams.FileName = files[0]; openParams.FileNames = files; } UiThread.RunOnIdle(() => callback?.Invoke(openParams)); }); return true; } public override bool SaveFileDialog(SaveFileDialogParams saveParams, Action<SaveFileDialogParams> callback) { ShowFileDialog((fileText) => { if (fileText.Length > 2) { string[] files = fileText.Split(';', ' ').Select(f => f.Trim('\"')).ToArray(); saveParams.FileName = files[0]; saveParams.FileNames = files; } UiThread.RunOnIdle(() => callback?.Invoke(saveParams)); }); return true; } private static void ShowFileDialog(Action<string> dialogClosedHandler) { var systemWindow = new SystemWindow(600, 200) { Title = "TestAutomation File Input", BackgroundColor = RGBA_Bytes.DarkGray }; var warningLabel = new TextWidget("This dialog should not appear outside of automation tests.\nNotify technical support if visible", pointSize: 15, textColor: RGBA_Bytes.Pink) { Margin = new BorderDouble(20), VAnchor = VAnchor.ParentTop, HAnchor = HAnchor.ParentLeftRight }; systemWindow.AddChild(warningLabel); var fileNameInput = new TextEditWidget(pixelWidth: 400) { VAnchor = VAnchor.ParentCenter, HAnchor = HAnchor.ParentLeftRight, Margin = new BorderDouble(30, 15), Name = "Automation Dialog TextEdit" }; fileNameInput.EnterPressed += (s, e) => systemWindow.CloseOnIdle(); systemWindow.AddChild(fileNameInput); systemWindow.Load += (s, e) => fileNameInput.Focus(); systemWindow.Closed += (s, e) => { dialogClosedHandler(fileNameInput.Text); }; systemWindow.ShowAsSystemWindow(); } public override bool SelectFolderDialog(SelectFolderDialogParams folderParams, Action<SelectFolderDialogParams> callback) { throw new NotImplementedException(); } public override string ResolveFilePath(string path) => path; } }
using System; using System.Linq; namespace MatterHackers.Agg.UI { internal class AutomationFileDialogCreator : FileDialogCreator { public override bool OpenFileDialog(OpenFileDialogParams openParams, Action<OpenFileDialogParams> callback) { ShowFileDialog((fileText) => { if (fileText.Length > 2) { string[] files = fileText.Split(';', ' ').Select(f => f.Trim('\"')).ToArray(); openParams.FileName = files[0]; openParams.FileNames = files; } UiThread.RunOnIdle(() => callback?.Invoke(openParams)); }); return true; } public override bool SaveFileDialog(SaveFileDialogParams saveParams, Action<SaveFileDialogParams> callback) { ShowFileDialog((fileText) => { if (fileText.Length > 2) { string[] files = fileText.Split(';', ' ').Select(f => f.Trim('\"')).ToArray(); saveParams.FileName = files[0]; saveParams.FileNames = files; } UiThread.RunOnIdle(() => callback?.Invoke(saveParams)); }); return true; } private static void ShowFileDialog(Action<string> dialogClosedHandler) { var systemWindow = new SystemWindow(600, 200) { Title = "TestAutomation File Input", BackgroundColor = RGBA_Bytes.DarkGray }; var warningLabel = new TextWidget("This dialog should not appear outside of automation tests.\nNotify technical support if visible", pointSize: 15, textColor: RGBA_Bytes.Pink) { Margin = new BorderDouble(20), VAnchor = VAnchor.ParentTop, HAnchor = HAnchor.ParentLeftRight }; systemWindow.AddChild(warningLabel); var fileNameInput = new TextEditWidget(pixelWidth: 400) { VAnchor = VAnchor.ParentCenter, HAnchor = HAnchor.ParentLeftRight, Margin = new BorderDouble(30, 15) }; fileNameInput.EnterPressed += (s, e) => systemWindow.CloseOnIdle(); systemWindow.AddChild(fileNameInput); systemWindow.Load += (s, e) => fileNameInput.Focus(); systemWindow.Closed += (s, e) => { dialogClosedHandler(fileNameInput.Text); }; systemWindow.ShowAsSystemWindow(); } public override bool SelectFolderDialog(SelectFolderDialogParams folderParams, Action<SelectFolderDialogParams> callback) { throw new NotImplementedException(); } public override string ResolveFilePath(string path) => path; } }
bsd-2-clause
C#
e539a4421a3554673d6edb341d16165cac843ff5
Replace hardcoded string with constant
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
samples/ClaimsTransformation/Controllers/AccountController.cs
samples/ClaimsTransformation/Controllers/AccountController.cs
using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Mvc; namespace AuthSamples.ClaimsTransformer.Controllers { public class AccountController : Controller { [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } private bool ValidateLogin(string userName, string password) { // For this sample, all logins are successful. return true; } [HttpPost] public async Task<IActionResult> Login(string userName, string password, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; // Normally Identity handles sign in, but you can do it directly if (ValidateLogin(userName, password)) { var claims = new List<Claim> { new Claim("user", userName), new Claim("role", "Member") }; await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme, "user", "role"))); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); } } return View(); } public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(); return Redirect("/"); } } }
using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace AuthSamples.ClaimsTransformer.Controllers { public class AccountController : Controller { [HttpGet] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } private bool ValidateLogin(string userName, string password) { // For this sample, all logins are successful. return true; } [HttpPost] public async Task<IActionResult> Login(string userName, string password, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; // Normally Identity handles sign in, but you can do it directly if (ValidateLogin(userName, password)) { var claims = new List<Claim> { new Claim("user", userName), new Claim("role", "Member") }; await HttpContext.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies", "user", "role"))); if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); } } return View(); } public async Task<IActionResult> Logout() { await HttpContext.SignOutAsync(); return Redirect("/"); } } }
apache-2.0
C#
a1cc9a970de2679359bfe7ff8f6f29b51f1c4053
Change subcommand60 packet test case name in VS
HelloKitty/Booma.Proxy
tests/Booma.Proxy.Packets.Tests/UnitTests/PacketCaptureTestEntry.cs
tests/Booma.Proxy.Packets.Tests/UnitTests/PacketCaptureTestEntry.cs
namespace Booma.Proxy { public sealed partial class CapturedPacketsTests { public class PacketCaptureTestEntry { public short OpCode { get; } public byte[] BinaryData { get; } public string FileName { get; } /// <inheritdoc /> public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName) { OpCode = opCode; BinaryData = binaryData; FileName = fileName; } /// <inheritdoc /> public override string ToString() { //Special naming for 0x60 to make it easier to search if(OpCode == 0x60) return FileName.Replace("0x60_", $"0x60_0x{(int)(BinaryData[6]):X2}_"); return $"{FileName}"; } /// <inheritdoc /> public override int GetHashCode() { return FileName.GetHashCode(); } } } }
namespace Booma.Proxy { public sealed partial class CapturedPacketsTests { public class PacketCaptureTestEntry { public short OpCode { get; } public byte[] BinaryData { get; } public string FileName { get; } /// <inheritdoc /> public PacketCaptureTestEntry(short opCode, byte[] binaryData, string fileName) { OpCode = opCode; BinaryData = binaryData; FileName = fileName; } /// <inheritdoc /> public override string ToString() { //Special naming for 0x60 to make it easier to search if(OpCode == 0x60) return FileName.Replace("0x60_", $"0x60_0x{BinaryData[6]:X}_"); return $"{FileName}"; } /// <inheritdoc /> public override int GetHashCode() { return FileName.GetHashCode(); } } } }
agpl-3.0
C#
6de92962118b43b70cc409e8833d4eba23e6731c
Add spacing after heart icon
erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner,erooijak/oogstplanner
Oogstplanner.Web/Views/Calendar/NoCrops.cshtml
Oogstplanner.Web/Views/Calendar/NoCrops.cshtml
@{ ViewBag.Title = "Zaaikalender"; } @Scripts.Render("~/Scripts/oogstplanner.likes") <div id="top"></div> <div id="yearCalendar"> <h1>Zaaikalender</h1> <div class="row"> <div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div> <div class="col-lg-4 col-md-6 col-sm-8 col-xs-8"> <div class="panel panel-default dark"> <p> <span class="glyphicon glyphicon-heart-empty"></span>&nbsp;U heeft nog geen gewassen in uw zaaikalender.<br/><br/> @Html.ActionLink("Oogst of zaai eerst een gewas", "SowingAndHarvesting", "Home", null, null)<br/> <!--@Html.ActionLink("Doe inspiratie op bij andere gebruikers", "TODO", "TODO", null, null)<br/> @Html.ActionLink("Zie de veelgestelde vragen lijst (FAQ)", "TODO", "TODO", null, null)<br/>--> ...of ga terug naar de <strong>@Html.ActionLink("OogstPlanner.nl Welkomstpagina", "Index", "Home", null, null)</strong> </p> </div> </div> <div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div> </div> </div> @* End yearcalendar *@
@{ ViewBag.Title = "Zaaikalender"; } @Scripts.Render("~/Scripts/oogstplanner.likes") <div id="top"></div> <div id="yearCalendar"> <h1>Zaaikalender</h1> <div class="row"> <div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div> <div class="col-lg-4 col-md-6 col-sm-8 col-xs-8"> <div class="panel panel-default dark"> <p> <span class="glyphicon glyphicon-heart-empty"></span>U heeft nog geen gewassen in uw zaaikalender.<br/><br/> @Html.ActionLink("Oogst of zaai eerst een gewas", "SowingAndHarvesting", "Home", null, null)<br/> <!--@Html.ActionLink("Doe inspiratie op bij andere gebruikers", "TODO", "TODO", null, null)<br/> @Html.ActionLink("Zie de veelgestelde vragen lijst (FAQ)", "TODO", "TODO", null, null)<br/>--> ...of ga terug naar de <strong>@Html.ActionLink("OogstPlanner.nl Welkomstpagina", "Index", "Home", null, null)</strong> </p> </div> </div> <div class="col-lg-4 col-md-3 col-sm-2 col-xs-2"></div> </div> </div> @* End yearcalendar *@
mit
C#
e7b38087692910e0e9d3aacdf90b6d2ed36ba115
add TODO
dimaaan/pgEdit
PgEdit/Program.cs
PgEdit/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // TODO refresh table data button // TODO table schema, column type. If enumeration - display values in tooltip // TODO what table currently open? // TODO table Fields: more details // TODO navigation: clicking by foreight key cell send user to row with primary key // TODO navigation: clicking by primary key cell opens menu with depend tables. selecting table send user to table with dependent rows filtered // TODO navigation: forward and backward buttons, support mouse additional buttons // TODO SQL editor Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PgEdit { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { // TODO table schema, column type. If enumeration - display values in tooltip // TODO what table currently open? // TODO table Fields: more details // TODO navigation: clicking by foreight key cell send user to row with primary key // TODO navigation: clicking by primary key cell opens menu with depend tables. selecting table send user to table with dependent rows filtered // TODO navigation: forward and backward buttons, support mouse additional buttons // TODO SQL editor Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new frmMain()); } } }
mit
C#
e603038d66463c03d190e8d0c63b4eb9c4795ef6
Work around for bug
mavasani/roslyn,diryboy/roslyn,brettfo/roslyn,davkean/roslyn,sharwell/roslyn,heejaechang/roslyn,bartdesmet/roslyn,weltkante/roslyn,eriawan/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,tmat/roslyn,mgoertz-msft/roslyn,gafter/roslyn,aelij/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,davkean/roslyn,physhi/roslyn,tmat/roslyn,gafter/roslyn,dotnet/roslyn,AmadeusW/roslyn,tmat/roslyn,KirillOsenkov/roslyn,aelij/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,sharwell/roslyn,dotnet/roslyn,AmadeusW/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,wvdd007/roslyn,genlu/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,gafter/roslyn,KevinRansom/roslyn,sharwell/roslyn,reaction1989/roslyn,eriawan/roslyn,dotnet/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,mavasani/roslyn,reaction1989/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,aelij/roslyn,diryboy/roslyn,physhi/roslyn,stephentoub/roslyn,weltkante/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,wvdd007/roslyn,jmarolf/roslyn,genlu/roslyn,diryboy/roslyn,eriawan/roslyn,panopticoncentral/roslyn,stephentoub/roslyn,reaction1989/roslyn
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IExtensionErrorHandler))] [Export(typeof(ITestErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler, ITestErrorHandler { private ImmutableList<Exception> _exceptions = ImmutableList<Exception>.Empty; public ImmutableList<Exception> Exceptions => _exceptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExtensionErrorHandler() { } public void HandleError(object sender, Exception exception) { // Work around bug that is fixed in https://devdiv.visualstudio.com/DevDiv/_git/VS-Platform/pullrequest/209513 if (exception is NullReferenceException && exception.StackTrace.Contains("SpanTrackingWpfToolTipPresenter")) { return; } // Work around for https://github.com/dotnet/roslyn/issues/42982 if (exception is NullReferenceException && exception.StackTrace.Contains("Microsoft.CodeAnalysis.Completion.Providers.AbstractEmbeddedLanguageCompletionProvider.GetLanguageProviders")) { return; } // Work around for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1091056 if (exception is InvalidOperationException && exception.StackTrace.Contains("Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Implementation.CompletionTelemetryHost")) { return; } // This exception is unexpected and as such we want the containing test case to // fail. Unfortuntately throwing an exception here is not going to help because // the editor is going to catch and swallow it. Store it here and wait for the // containing workspace to notice it and throw. _exceptions = _exceptions.Add(exception); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(IExtensionErrorHandler))] [Export(typeof(ITestErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler, ITestErrorHandler { private ImmutableList<Exception> _exceptions = ImmutableList<Exception>.Empty; public ImmutableList<Exception> Exceptions => _exceptions; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TestExtensionErrorHandler() { } public void HandleError(object sender, Exception exception) { // Work around bug that is fixed in https://devdiv.visualstudio.com/DevDiv/_git/VS-Platform/pullrequest/209513 if (exception is NullReferenceException && exception.StackTrace.Contains("SpanTrackingWpfToolTipPresenter")) { return; } // Work around for https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1091056 if (exception is InvalidOperationException && exception.StackTrace.Contains("Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Implementation.CompletionTelemetryHost")) { return; } // This exception is unexpected and as such we want the containing test case to // fail. Unfortuntately throwing an exception here is not going to help because // the editor is going to catch and swallow it. Store it here and wait for the // containing workspace to notice it and throw. _exceptions = _exceptions.Add(exception); } } }
mit
C#
989b21e81356d591bdcea9fb4c7bb042e0c12578
fix documentation spelling
SQLStreamStore/SQLStreamStore,SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore
src/SqlStreamStore/Subscriptions/CreateStreamStoreNotifier.cs
src/SqlStreamStore/Subscriptions/CreateStreamStoreNotifier.cs
namespace SqlStreamStore.Subscriptions { using SqlStreamStore; /// <summary> /// Represents an operation to create a stream store notifier. /// </summary> /// <param name="readonlyStreamStore"></param> /// <returns></returns> public delegate IStreamStoreNotifier CreateStreamStoreNotifier(IReadonlyStreamStore readonlyStreamStore); }
namespace SqlStreamStore.Subscriptions { using SqlStreamStore; /// <summary> /// Represents an operaion to create a stream store notifier. /// </summary> /// <param name="readonlyStreamStore"></param> /// <returns></returns> public delegate IStreamStoreNotifier CreateStreamStoreNotifier(IReadonlyStreamStore readonlyStreamStore); }
mit
C#
7f268529f0feabebb09b982711b624329d9dee5b
add OfflineSldr to SIL.Archiving.Tests
ermshiperete/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso
SIL.Archiving.Tests/Properties/AssemblyInfo.cs
SIL.Archiving.Tests/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using SIL.TestUtilities; // 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("SIL.Archiving.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("49f40cd3-46aa-4d25-b787-868040c9cbc8")] [assembly: OfflineSldr]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SIL.Archiving.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("49f40cd3-46aa-4d25-b787-868040c9cbc8")]
mit
C#
3ef6641583aac5eb63379e265143a8691e7aca2e
Remove unneccessary usings
PearMed/Pear-Interaction-Engine
Assets/PearCore/Examples/KeyboardController/Scripts/SelectWithKeyboard.cs
Assets/PearCore/Examples/KeyboardController/Scripts/SelectWithKeyboard.cs
using Pear.Core.Controllers; using Pear.Core.Controllers.Behaviors; using Pear.Core.Interactables; using UnityEngine; public class SelectWithKeyboard : ControllerBehavior<Controller> { public KeyCode SelectKey = KeyCode.P; HoverOnGaze _hoverOnGaze; InteractableObject _lastSelected; // Use this for initialization void Start () { _hoverOnGaze = GetComponent<HoverOnGaze>(); } // Update is called once per frame void Update () { if(Input.GetKeyUp(SelectKey) && _hoverOnGaze.HoveredObject != null) { InteractableObjectState selectedState = _hoverOnGaze.HoveredObject.Selected; if (selectedState.Contains(Controller)) { selectedState.Remove(Controller); Controller.ActiveObject = null; } else { selectedState.Add(Controller); Controller.ActiveObject = _hoverOnGaze.HoveredObject; if (_lastSelected != _hoverOnGaze.HoveredObject && _lastSelected != null) _lastSelected.Selected.Remove(Controller); _lastSelected = _hoverOnGaze.HoveredObject; } } } }
using Pear.Core.Controllers; using Pear.Core.Controllers.Behaviors; using Pear.Core.Interactables; using System.Collections; using System.Collections.Generic; using UnityEngine; public class SelectWithKeyboard : ControllerBehavior<Controller> { public KeyCode SelectKey = KeyCode.P; HoverOnGaze _hoverOnGaze; InteractableObject _lastSelected; // Use this for initialization void Start () { _hoverOnGaze = GetComponent<HoverOnGaze>(); } // Update is called once per frame void Update () { if(Input.GetKeyUp(SelectKey) && _hoverOnGaze.HoveredObject != null) { InteractableObjectState selectedState = _hoverOnGaze.HoveredObject.Selected; if (selectedState.Contains(Controller)) { selectedState.Remove(Controller); Controller.ActiveObject = null; } else { selectedState.Add(Controller); Controller.ActiveObject = _hoverOnGaze.HoveredObject; if (_lastSelected != _hoverOnGaze.HoveredObject && _lastSelected != null) _lastSelected.Selected.Remove(Controller); _lastSelected = _hoverOnGaze.HoveredObject; } } } }
mit
C#
a6f895b5e524612db82f432d892bdd188fe0ef94
Package info updated
nicopaez/System.IO.Utilities
System.IO.Utilities/Properties/AssemblyInfo.cs
System.IO.Utilities/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("System.IO.Utilities")] [assembly: AssemblyDescription("Wrapper library over System.IO.File class")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NicoPaez")] [assembly: AssemblyProduct("System.IO.Utilities")] [assembly: AssemblyCopyright("Copyright © NicoPaez 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6abb69c2-19ec-4139-9264-b1af74bc9c28")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("System.Extensions.IO")] [assembly: AssemblyDescription("Wrapper library over System.IO.File class")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NicoPaez")] [assembly: AssemblyProduct("System.Utilities")] [assembly: AssemblyCopyright("Copyright © NicoPaez 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6abb69c2-19ec-4139-9264-b1af74bc9c28")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
7c41497e67a416accfe083494d8b0a28d51695db
Fix format for DateTimeOffset input
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Web/Infrastructure/Tags/DefaultAspNetMvcHtmlConventions.cs
SupportManager.Web/Infrastructure/Tags/DefaultAspNetMvcHtmlConventions.cs
using System; using System.ComponentModel.DataAnnotations; using HtmlTags; using HtmlTags.Conventions; namespace SupportManager.Web.Infrastructure.Tags { public class DefaultAspNetMvcHtmlConventions : HtmlConventionRegistry { public DefaultAspNetMvcHtmlConventions() { Editors.Always.AddClass("form-control"); Editors.IfPropertyIs<DateTimeOffset>().ModifyWith(m => m.CurrentTag.Attr("type", "datetime-local").Value(m.Value<DateTimeOffset?>()?.ToLocalTime().DateTime.ToString("s"))); Editors.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag .AddPattern("9{1,2}/9{1,2}/9999") .AddPlaceholder("MM/DD/YYYY") .AddClass("datepicker") .Value(m.Value<DateTime?>() != null ? m.Value<DateTime>().ToShortDateString() : string.Empty)); Editors.If(er => er.Accessor.Name.EndsWith("id", StringComparison.OrdinalIgnoreCase)).BuildBy(a => new HiddenTag().Value(a.StringValue())); Editors.IfPropertyIs<byte[]>().BuildBy(a => new HiddenTag().Value(Convert.ToBase64String(a.Value<byte[]>()))); Editors.BuilderPolicy<UserPhoneNumberSelectElementBuilder>(); Editors.BuilderPolicy<TeamSelectElementBuilder>(); Labels.Always.AddClass("control-label"); Labels.Always.AddClass("col-md-2"); Labels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name)); DisplayLabels.Always.BuildBy<DefaultDisplayLabelBuilder>(); DisplayLabels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name)); Displays.IfPropertyIs<DateTimeOffset>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTimeOffset?>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTime>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTime?>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<decimal>().ModifyWith(m => m.CurrentTag.Text(m.Value<decimal>().ToString("C"))); Displays.IfPropertyIs<bool>().BuildBy<BoolDisplayBuilder>(); this.Defaults(); } public ElementCategoryExpression DisplayLabels { get { return new ElementCategoryExpression(Library.TagLibrary.Category("DisplayLabels").Profile(TagConstants.Default)); } } } }
using System; using System.ComponentModel.DataAnnotations; using HtmlTags; using HtmlTags.Conventions; namespace SupportManager.Web.Infrastructure.Tags { public class DefaultAspNetMvcHtmlConventions : HtmlConventionRegistry { public DefaultAspNetMvcHtmlConventions() { Editors.Always.AddClass("form-control"); Editors.IfPropertyIs<DateTimeOffset>().ModifyWith(m => m.CurrentTag.Attr("type", "datetime-local").Value(m.Value<DateTimeOffset?>()?.ToLocalTime().DateTime.ToString("O"))); Editors.IfPropertyIs<DateTime?>().ModifyWith(m => m.CurrentTag .AddPattern("9{1,2}/9{1,2}/9999") .AddPlaceholder("MM/DD/YYYY") .AddClass("datepicker") .Value(m.Value<DateTime?>() != null ? m.Value<DateTime>().ToShortDateString() : string.Empty)); Editors.If(er => er.Accessor.Name.EndsWith("id", StringComparison.OrdinalIgnoreCase)).BuildBy(a => new HiddenTag().Value(a.StringValue())); Editors.IfPropertyIs<byte[]>().BuildBy(a => new HiddenTag().Value(Convert.ToBase64String(a.Value<byte[]>()))); Editors.BuilderPolicy<UserPhoneNumberSelectElementBuilder>(); Editors.BuilderPolicy<TeamSelectElementBuilder>(); Labels.Always.AddClass("control-label"); Labels.Always.AddClass("col-md-2"); Labels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name)); DisplayLabels.Always.BuildBy<DefaultDisplayLabelBuilder>(); DisplayLabels.ModifyForAttribute<DisplayAttribute>((t, a) => t.Text(a.Name)); Displays.IfPropertyIs<DateTimeOffset>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTimeOffset?>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTime>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<DateTime?>().BuildBy<DateTimeBuilder>(); Displays.IfPropertyIs<decimal>().ModifyWith(m => m.CurrentTag.Text(m.Value<decimal>().ToString("C"))); Displays.IfPropertyIs<bool>().BuildBy<BoolDisplayBuilder>(); this.Defaults(); } public ElementCategoryExpression DisplayLabels { get { return new ElementCategoryExpression(Library.TagLibrary.Category("DisplayLabels").Profile(TagConstants.Default)); } } } }
mit
C#
09d0b9970849f6446afdade1fb1fd136739fcdea
add int to boolean test
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
test/WeihanLi.Common.Test/ExtensionsTest/CoreExtensionTest.cs
test/WeihanLi.Common.Test/ExtensionsTest/CoreExtensionTest.cs
using WeihanLi.Extensions; using Xunit; namespace WeihanLi.Common.Test.ExtensionsTest { /// <summary> /// CoreExtensionTest /// </summary> public class CoreExtensionTest { #region ObjectExtension [Fact] public void ToTest() { var num1 = 1.2; var toNum1 = num1.To<decimal>(); Assert.Equal(typeof(decimal), toNum1.GetType()); Assert.Equal(typeof(double), toNum1.To<double>().GetType()); // int to bool test Assert.False(0.To<bool>()); Assert.True(1.To<bool>()); } #endregion ObjectExtension #region StringExtensionTest [Fact] public void SafeSubstring() { var str = "abcdefg"; Assert.Equal(str.Substring(1, 2), str.SafeSubstring(1, 2)); Assert.Equal("bcdefg", str.SafeSubstring(1, 20)); Assert.Equal("", str.SafeSubstring(10, 20)); Assert.Equal(str.Substring(str.Length), str.SafeSubstring(str.Length)); Assert.Equal("", str.SafeSubstring(10)); } [Fact] public void Sub() { string str = "abcdef"; Assert.Equal("ef", str.Sub(-2)); Assert.Equal("def", str.Sub(3)); } #endregion StringExtensionTest } }
using WeihanLi.Extensions; using Xunit; namespace WeihanLi.Common.Test.ExtensionsTest { /// <summary> /// CoreExtensionTest /// </summary> public class CoreExtensionTest { #region ObjectExtension [Fact] public void ToTest() { var num1 = 1.2; var toNum1 = num1.To<decimal>(); Assert.Equal(typeof(decimal), toNum1.GetType()); Assert.Equal(typeof(double), toNum1.To<double>().GetType()); } #endregion ObjectExtension #region StringExtensionTest [Fact] public void SafeSubstring() { var str = "abcdefg"; Assert.Equal(str.Substring(1, 2), str.SafeSubstring(1, 2)); Assert.Equal("bcdefg", str.SafeSubstring(1, 20)); Assert.Equal("", str.SafeSubstring(10, 20)); Assert.Equal(str.Substring(str.Length), str.SafeSubstring(str.Length)); Assert.Equal("", str.SafeSubstring(10)); } [Fact] public void Sub() { string str = "abcdef"; Assert.Equal("ef", str.Sub(-2)); Assert.Equal("def", str.Sub(3)); } #endregion StringExtensionTest } }
mit
C#
77937c08e5eef547c002b113f55caa374e46aabf
Update IMixedRealityCameraSystem.cs
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit/Interfaces/CameraSystem/IMixedRealityCameraSystem.cs
Assets/MixedRealityToolkit/Interfaces/CameraSystem/IMixedRealityCameraSystem.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace Microsoft.MixedReality.Toolkit.CameraSystem { /// <summary> /// Manager interface for a camera system in the Mixed Reality Toolkit. /// The camera system is expected to manage render settings on the main camera. /// It should update the camera's clear settings, render mask, etc based on platform. /// </summary> public interface IMixedRealityCameraSystem : IMixedRealityEventSystem, IMixedRealityEventSource, IMixedRealityDataProvider { /// <summary> /// Is the current camera displaying on an Opaque (AR) device or a VR / immersive device /// </summary> bool IsOpaque { get; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace Microsoft.MixedReality.Toolkit.CameraSystem { public interface IMixedRealityCameraSystem : IMixedRealityEventSystem, IMixedRealityEventSource, IMixedRealityDataProvider { /// <summary> /// Is the current camera displaying on an Opaque (AR) device or a VR / immersive device /// </summary> bool IsOpaque { get; } } }
mit
C#
fae85ab90b4d5794ab397b4be0b10aed286f60c3
Change Version
smo-key/NXTLib,smo-key/NXTLib
nxtlib/Properties/AssemblyInfo.cs
nxtlib/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NXTLib")] [assembly: AssemblyDescription("LEGO NXT API for Windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NXTLib")] [assembly: AssemblyCopyright("Copyright © 2014 Arthur Pachachura")] [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(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6955B633-F7DF-46EB-9F1B-DEFC017542D7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.4.1.0")] [assembly: AssemblyFileVersion("1.4.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NXTLib")] [assembly: AssemblyDescription("LEGO NXT API for Windows")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NXTLib")] [assembly: AssemblyCopyright("Copyright © 2014 Arthur Pachachura")] [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(true)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6955B633-F7DF-46EB-9F1B-DEFC017542D7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.3.1.0")] [assembly: AssemblyFileVersion("1.3.1.0")]
mit
C#
b42cd1c04889fcade60ee3ebd2abb0c29c652006
Tweak screenshot notification script (minor edit)
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Core/Notification/Screenshot/FormNotificationScreenshotable.cs
Core/Notification/Screenshot/FormNotificationScreenshotable.cs
using System; using System.Windows.Forms; using CefSharp; using TweetDck.Core.Bridge; using TweetDck.Core.Controls; using TweetDck.Resources; namespace TweetDck.Core.Notification.Screenshot{ sealed class FormNotificationScreenshotable : FormNotification{ public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){ browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback)); browser.FrameLoadEnd += (sender, args) => { if (args.Frame.IsMain && browser.Address != "about:blank"){ ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout($TD_NotificationScreenshot.trigger, 25)", "gen:screenshot"); } }; UpdateTitle(); } public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){ browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks); Location = ControlExtensions.InvisibleLocation; FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None; SetNotificationSize(width, height, false); } public void TakeScreenshotAndHide(){ MoveToVisibleLocation(); Activate(); SendKeys.SendWait("%{PRTSC}"); Reset(); } public void Reset(){ Location = ControlExtensions.InvisibleLocation; browser.LoadHtml("", "about:blank"); } } }
using System; using System.Windows.Forms; using CefSharp; using TweetDck.Core.Bridge; using TweetDck.Core.Controls; using TweetDck.Resources; namespace TweetDck.Core.Notification.Screenshot{ sealed class FormNotificationScreenshotable : FormNotification{ public FormNotificationScreenshotable(Action callback, FormBrowser owner, NotificationFlags flags) : base(owner, null, flags){ browser.RegisterAsyncJsObject("$TD_NotificationScreenshot", new CallbackBridge(this, callback)); browser.FrameLoadEnd += (sender, args) => { if (args.Frame.IsMain && browser.Address != "about:blank"){ ScriptLoader.ExecuteScript(args.Frame, "window.setTimeout(() => $TD_NotificationScreenshot.trigger(), 25)", "gen:screenshot"); } }; UpdateTitle(); } public void LoadNotificationForScreenshot(TweetNotification tweet, int width, int height){ browser.LoadHtml(tweet.GenerateHtml(enableCustomCSS: false), "http://tweetdeck.twitter.com/?"+DateTime.Now.Ticks); Location = ControlExtensions.InvisibleLocation; FormBorderStyle = Program.UserConfig.ShowScreenshotBorder ? FormBorderStyle.FixedToolWindow : FormBorderStyle.None; SetNotificationSize(width, height, false); } public void TakeScreenshotAndHide(){ MoveToVisibleLocation(); Activate(); SendKeys.SendWait("%{PRTSC}"); Reset(); } public void Reset(){ Location = ControlExtensions.InvisibleLocation; browser.LoadHtml("", "about:blank"); } } }
mit
C#
fc9e43b0e8e938da2c8c210ea07c0ef28eda07db
Update default package sources
InfinniPlatform/Infinni.Node
Infinni.Node/Packaging/NuGetPackageRepositoryManagerFactory.cs
Infinni.Node/Packaging/NuGetPackageRepositoryManagerFactory.cs
using System.Linq; using Infinni.Node.Settings; using NuGet.Logging; namespace Infinni.Node.Packaging { public class NuGetPackageRepositoryManagerFactory : IPackageRepositoryManagerFactory { private const string DefaultPackagesPath = "packages"; private static readonly string[] DefaultPackageSources = { "https://api.nuget.org/v3/index.json", "https://www.nuget.org/api/v2/", "http://nuget.infinnity.ru/api/v2/", "https://www.myget.org/F/infinniplatform/" }; public NuGetPackageRepositoryManagerFactory(ILogger logger) { _logger = logger; } private readonly ILogger _logger; public IPackageRepositoryManager Create(params string[] packageSources) { var packagesPath = AppSettings.GetValue("PackagesRepository", DefaultPackagesPath); packageSources = GetAllPackageSources(packageSources); return new NuGetPackageRepositoryManager(packagesPath, packageSources, _logger); } private static string[] GetAllPackageSources(string[] packageSources) { return DefaultPackageSources .Union(AppSettings.GetValues("PackageSources", new string[] { })) .Union(packageSources ?? new string[] { }) .Where(i => !string.IsNullOrWhiteSpace(i)) .Select(i => i.Trim()) .ToArray(); } } }
using System.Linq; using Infinni.Node.Settings; using NuGet.Logging; namespace Infinni.Node.Packaging { public class NuGetPackageRepositoryManagerFactory : IPackageRepositoryManagerFactory { private const string DefaultPackagesPath = "packages"; private static readonly string[] DefaultPackageSources = { "https://api.nuget.org/v3/index.json", "https://www.nuget.org/api/v2/", "http://nuget.infinnity.ru/api/v2/" }; public NuGetPackageRepositoryManagerFactory(ILogger logger) { _logger = logger; } private readonly ILogger _logger; public IPackageRepositoryManager Create(params string[] packageSources) { var packagesPath = AppSettings.GetValue("PackagesRepository", DefaultPackagesPath); packageSources = GetAllPackageSources(packageSources); return new NuGetPackageRepositoryManager(packagesPath, packageSources, _logger); } private static string[] GetAllPackageSources(string[] packageSources) { return DefaultPackageSources .Union(AppSettings.GetValues("PackageSources", new string[] { })) .Union(packageSources ?? new string[] { }) .Where(i => !string.IsNullOrWhiteSpace(i)) .Select(i => i.Trim()) .ToArray(); } } }
mit
C#
d28d22be333d86604e7b392dc153686b85b69334
update network factory interface
jobeland/NeuralNetwork
NeuralNetwork/NeuralNetwork/Factories/INeuralNetworkFactory.cs
NeuralNetwork/NeuralNetwork/Factories/INeuralNetworkFactory.cs
using ArtificialNeuralNetwork.Genes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork.Factories { public interface INeuralNetworkFactory { INeuralNetwork Create(int numInputs, int numOutputs, int numHiddenLayers, int numHiddenPerLayer); INeuralNetwork Create(int numInputs, int numOutputs, IList<int> hiddenLayerSpecs); INeuralNetwork Create(NeuralNetworkGene genes); } }
using ArtificialNeuralNetwork.Genes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork.Factories { public interface INeuralNetworkFactory { INeuralNetwork Create(int numInputs, int numOutputs, int numHiddenLayers, int numHiddenPerLayer); INeuralNetwork Create(NeuralNetworkGene genes); } }
mit
C#
18844272fafa25fac6665b9c577e010512db7290
Add temporary warning of upcoming lab closure.
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Home/Index.cshtml
Anlab.Mvc/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">PLEASE NOTE: The Analytical Lab will be closed on July 4th and 5th.</p> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
@{ ViewData["Title"] = "Home Page"; } <div class="col-8"> <p class="lead">The UC Davis Analytical Laboratory is a core support facility of the UC Davis College of Agriculture and Environmental Sciences.</p> <p>Analytical Laboratory clients are University of California academics, other educational institutions, government agencies, and research-based businesses. </p> <p>In addition to analytical services, the Laboratory provides project assistance in the areas of analytical, agricultural and environmental chemistry. The Laboratory has an educational role, providing training to students and researchers in the operation of a number of analytical methods and instruments.</p> </div> <div class="col-4"> <address> <p>UC Davis Analytical Lab<br> University of California Davis, California <br> 95616-5270 <br> Phone: <span style="white-space: nowrap">(530) 752-0147</span> <br> Fax: <span style="white-space: nowrap">(530) 752-9892</span> <br> Email: <a href="mailto:anlab@ucdavis.edu">anlab@ucdavis.edu</a></p> </address> </div>
mit
C#
14975b0ff5bd9a0cb67566a2a895d49949f7423f
Fix IP look up page broken
blrchen/AzureSpeed,blrchen/AzureSpeed,blrchen/AzureSpeed,blrchen/AzureSpeed
AzureSpeed.WebUI/Models/Prefix.cs
AzureSpeed.WebUI/Models/Prefix.cs
using Newtonsoft.Json; namespace AzureSpeed.WebUI.Models { public class Prefix { [JsonProperty("ip_prefix")] public string IpPrefix { get; set; } [JsonProperty("region")] public string Region { get; set; } [JsonProperty("service")] public string Service { get; set; } } }
using Newtonsoft.Json; namespace AzureSpeed.WebUI.Models { public class Prefix { [JsonProperty("ip_prefix")] public string IpPrefix { get; set; } [JsonProperty("region")] public string Region { get; set; } [JsonProperty("region")] public string Service { get; set; } } }
mit
C#
687ccee1005b2f1e40ed2847b33f91c749ed69e5
Fix assembly version
leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,rasmuseeg/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,lars-erik/Umbraco-CMS,NikRimington/Umbraco-CMS,arknu/Umbraco-CMS,WebCentrum/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,tompipe/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,tompipe/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,WebCentrum/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,WebCentrum/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS
src/SolutionInfo.cs
src/SolutionInfo.cs
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("8.0.0")] [assembly: AssemblyFileVersion("8.0.0.20")] [assembly: AssemblyInformationalVersion("8.0.0-alpha0020")]
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("8.0.0")] [assembly: AssemblyInformationalVersion("8.0.0-alpha0020")]
mit
C#
a8a8f991ad9bb78865cf4868b909636f6fbefc33
Add DocumentEncoutner AppointmentType
SnapMD/connectedcare-sdk
SnapMD.VirtualCare.ApiModels/Scheduling/AppointmentTypeCode.cs
SnapMD.VirtualCare.ApiModels/Scheduling/AppointmentTypeCode.cs
namespace SnapMD.VirtualCare.ApiModels.Scheduling { /// <summary> /// Types of appointments. /// </summary> public enum AppointmentTypeCode { /// <summary> /// Not specified. /// </summary> None, /// <summary> /// Clinician scheduled. /// </summary> ClinicianScheduled, /// <summary> /// Appointments on-demand. /// </summary> OnDemand, /// <summary> /// Patient self-scheduled. /// </summary> PatientScheduled, /// <summary> /// Appointment for document encounter /// </summary> DocumentEncounter } }
namespace SnapMD.VirtualCare.ApiModels.Scheduling { /// <summary> /// Types of appointments. /// </summary> public enum AppointmentTypeCode { /// <summary> /// Not specified. /// </summary> None, /// <summary> /// Clinician scheduled. /// </summary> ClinicianScheduled, /// <summary> /// Appointments on-demand. /// </summary> OnDemand, /// <summary> /// Patient self-scheduled. /// </summary> PatientScheduled } }
apache-2.0
C#
c58721e8f8b3921d334979fbf4825f0969248f76
Add xml docs
dreamrain21/Portable.Licensing,dreamrain21/Portable.Licensing,dnauck/Portable.Licensing,dnauck/Portable.Licensing
src/Portable.Licensing/Model/Customer.cs
src/Portable.Licensing/Model/Customer.cs
// // Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de // // Author: // Daniel Nauck <d.nauck(at)nauck-it.de> // // 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.Xml.Linq; namespace Portable.Licensing.Model { /// <summary> /// The customer of a <see cref="License"/>. /// </summary> public class Customer : XElement { private static readonly XNamespace ns = "http://schema.nauck-it.de/portable.licensing#customer"; /// <summary> /// Initializes a new instance of the <see cref="Customer"/> class. /// </summary> public Customer() : base(ns + "Customer") { } /// <summary> /// Gets or sets the Name of this <see cref="Customer"/>. /// </summary> public new string Name { get { return Element(ns + "Name").Value; } set { Add(new XElement(ns + "Name", value)); } } /// <summary> /// Gets or sets the Email of this <see cref="Customer"/>. /// </summary> public string Email { get { return Element(ns + "Email").Value; } set { Add(new XElement(ns + "Email", value)); } } } }
// // Copyright © 2012 - 2013 Nauck IT KG http://www.nauck-it.de // // Author: // Daniel Nauck <d.nauck(at)nauck-it.de> // // 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.Xml.Linq; namespace Portable.Licensing.Model { /// <summary> /// The customer of a <see cref="License"/>. /// </summary> public class Customer : XElement { private static readonly XNamespace ns = "http://schema.nauck-it.de/portable.licensing#customer"; public Customer() : base(ns + "Customer") { } public new string Name { get { return Element(ns + "Name").Value; } set { Add(new XElement(ns + "Name", value)); } } public string Email { get { return Element(ns + "Email").Value; } set { Add(new XElement(ns + "Email", value)); } } } }
mit
C#
8c80f2c685e8657d32595d13cd1f6e5cf11a95de
Remove Idle timeout in IIS
SkillsFundingAgency/das-referencedata,SkillsFundingAgency/das-referencedata
src/SFA.DAS.ReferenceData.Api/WebRole.cs
src/SFA.DAS.ReferenceData.Api/WebRole.cs
using System; using System.Diagnostics; using Microsoft.Web.Administration; using Microsoft.WindowsAzure.ServiceRuntime; using System.Linq; namespace SFA.DAS.ReferenceData.Api { public class WebRole : RoleEntryPoint { public override void Run() { using (var serverManager = new ServerManager()) { foreach (var application in serverManager.Sites.SelectMany(x => x.Applications)) { application["preloadEnabled"] = true; } foreach (var applicationPool in serverManager.ApplicationPools) { applicationPool["startMode"] = "AlwaysRunning"; applicationPool.ProcessModel.IdleTimeout = new System.TimeSpan(0); } serverManager.CommitChanges(); } base.Run(); } } }
using System; using System.Diagnostics; using Microsoft.Web.Administration; using Microsoft.WindowsAzure.ServiceRuntime; using System.Linq; namespace SFA.DAS.ReferenceData.Api { public class WebRole : RoleEntryPoint { public override void Run() { using (var serverManager = new ServerManager()) { foreach (var application in serverManager.Sites.SelectMany(x => x.Applications)) { application["preloadEnabled"] = true; } foreach (var applicationPool in serverManager.ApplicationPools) { applicationPool["startMode"] = "AlwaysRunning"; } serverManager.CommitChanges(); } base.Run(); } } }
mit
C#
ce5533180664b81b450be711ed69207499ba6175
Use switch-case instead of else-if in TraktErrorObjectJsonReader
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/JsonReader/Basic/TraktErrorObjectJsonReader.cs
Source/Lib/TraktApiSharp/Objects/JsonReader/Basic/TraktErrorObjectJsonReader.cs
namespace TraktApiSharp.Objects.JsonReader.Basic { using Newtonsoft.Json; using Objects.Basic; using System.IO; internal class TraktErrorObjectJsonReader : ITraktObjectJsonReader<TraktError> { private const string PROPERTY_NAME_ERROR = "error"; private const string PROPERTY_NAME_ERROR_DESCRIPTION = "error_description"; public TraktError ReadObject(string json) { if (string.IsNullOrEmpty(json)) return null; using (var reader = new StringReader(json)) using (var jsonReader = new JsonTextReader(reader)) { return ReadObject(jsonReader); } } public TraktError ReadObject(JsonTextReader jsonReader) { if (jsonReader == null) return null; if (jsonReader.Read() && jsonReader.TokenType == JsonToken.StartObject) { var traktError = new TraktError(); while (jsonReader.Read() && jsonReader.TokenType == JsonToken.PropertyName) { var propertyName = jsonReader.Value.ToString(); switch (propertyName) { case PROPERTY_NAME_ERROR: traktError.Error = jsonReader.ReadAsString(); break; case PROPERTY_NAME_ERROR_DESCRIPTION: traktError.Description = jsonReader.ReadAsString(); break; default: jsonReader.Read(); // read unmatched property value break; } } return traktError; } return null; } } }
namespace TraktApiSharp.Objects.JsonReader.Basic { using Newtonsoft.Json; using Objects.Basic; using System.IO; internal class TraktErrorObjectJsonReader : ITraktObjectJsonReader<TraktError> { private const string PROPERTY_NAME_ERROR = "error"; private const string PROPERTY_NAME_ERROR_DESCRIPTION = "error_description"; public TraktError ReadObject(string json) { if (string.IsNullOrEmpty(json)) return null; using (var reader = new StringReader(json)) using (var jsonReader = new JsonTextReader(reader)) { return ReadObject(jsonReader); } } public TraktError ReadObject(JsonTextReader jsonReader) { if (jsonReader == null) return null; if (jsonReader.Read() && jsonReader.TokenType == JsonToken.StartObject) { var traktError = new TraktError(); while (jsonReader.Read() && jsonReader.TokenType == JsonToken.PropertyName) { var propertyName = jsonReader.Value.ToString(); if (propertyName == PROPERTY_NAME_ERROR) traktError.Error = jsonReader.ReadAsString(); else if (propertyName == PROPERTY_NAME_ERROR_DESCRIPTION) traktError.Description = jsonReader.ReadAsString(); else jsonReader.Read(); // read unmatched property value } return traktError; } return null; } } }
mit
C#
72155a7c525818431fef2c76565eb3995a1f769a
Replace if pattern-matching check with switch cases instead
smoogipooo/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacySpinnerApproachCircle.cs
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacySpinnerApproachCircle.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 JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.Osu.Skinning.Legacy { public class LegacySpinnerApproachCircle : CompositeDrawable { private DrawableSpinner drawableSpinner; [CanBeNull] private Sprite approachCircle; [BackgroundDependencyLoader] private void load(DrawableHitObject drawableHitObject, ISkinSource source) { drawableSpinner = (DrawableSpinner)drawableHitObject; AutoSizeAxes = Axes.Both; var spinnerProvider = source.FindProvider(s => s.GetTexture("spinner-circle") != null || s.GetTexture("spinner-top") != null); if (spinnerProvider is DefaultLegacySkin) return; InternalChild = approachCircle = new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, Texture = source.GetTexture("spinner-approachcircle"), Scale = new Vector2(1.86f), }; } protected override void LoadComplete() { base.LoadComplete(); drawableSpinner.ApplyCustomUpdateState += updateStateTransforms; updateStateTransforms(drawableSpinner, drawableSpinner.State.Value); } private void updateStateTransforms(DrawableHitObject drawableHitObject, ArmedState state) { switch (drawableHitObject) { case DrawableSpinner spinner: using (BeginAbsoluteSequence(spinner.HitObject.StartTime)) approachCircle?.ScaleTo(0.1f, spinner.HitObject.Duration); break; } } } }
// 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 JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Skinning; using osuTK; namespace osu.Game.Rulesets.Osu.Skinning.Legacy { public class LegacySpinnerApproachCircle : CompositeDrawable { private DrawableSpinner drawableSpinner; [CanBeNull] private Sprite approachCircle; [BackgroundDependencyLoader] private void load(DrawableHitObject drawableHitObject, ISkinSource source) { drawableSpinner = (DrawableSpinner)drawableHitObject; AutoSizeAxes = Axes.Both; var spinnerProvider = source.FindProvider(s => s.GetTexture("spinner-circle") != null || s.GetTexture("spinner-top") != null); if (spinnerProvider is DefaultLegacySkin) return; InternalChild = approachCircle = new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, Texture = source.GetTexture("spinner-approachcircle"), Scale = new Vector2(1.86f), }; } protected override void LoadComplete() { base.LoadComplete(); drawableSpinner.ApplyCustomUpdateState += updateStateTransforms; updateStateTransforms(drawableSpinner, drawableSpinner.State.Value); } private void updateStateTransforms(DrawableHitObject drawableHitObject, ArmedState state) { if (!(drawableHitObject is DrawableSpinner spinner)) return; using (BeginAbsoluteSequence(spinner.HitObject.StartTime)) approachCircle?.ScaleTo(0.1f, spinner.HitObject.Duration); } } }
mit
C#
b85a7ce3ef5e28e02c41e3963f7cd8e8ae3887b9
Remove docker compose rm
syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service
build.cake
build.cake
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); DockerComposeRm(new DockerComposeRmSettings { Force = true }); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
mit
C#
fb716ccc38f4cdc9ecad35cbb8755b027334131c
fix bug.
tangxuehua/ecommon,Aaron-Liu/ecommon
src/ECommon/Properties/AssemblyInfo.cs
src/ECommon/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ECommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ECommon")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.3")] [assembly: AssemblyFileVersion("2.0.3")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ECommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ECommon")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.2")] [assembly: AssemblyFileVersion("2.0.2")]
mit
C#
cdc73e93380a46f6951dcd44edc577e70375a673
Add WebException handling to WrapHttpWebRequest
patchkit-net/patchkit-library-dotnet,patchkit-net/patchkit-library-dotnet
src/PatchKit.Api/WrapHttpWebRequest.cs
src/PatchKit.Api/WrapHttpWebRequest.cs
using System; using System.Net; namespace PatchKit.Api { public class WrapHttpWebRequest : IHttpWebRequest { private readonly HttpWebRequest _httpWebRequest; public int Timeout { get { return _httpWebRequest.Timeout; } set { _httpWebRequest.Timeout = value; } } public Uri Address { get { return _httpWebRequest.Address; } } public WrapHttpWebRequest(HttpWebRequest httpWebRequest) { _httpWebRequest = httpWebRequest; } public IHttpWebResponse GetResponse() { return new WrapHttpWebResponse(GetHttpResponse()); } private HttpWebResponse GetHttpResponse() { try { return (HttpWebResponse) _httpWebRequest.GetResponse(); } catch (WebException webException) { if (webException.Status == WebExceptionStatus.ProtocolError) { return (HttpWebResponse) webException.Response; } throw; } } } }
using System; using System.Net; namespace PatchKit.Api { public class WrapHttpWebRequest : IHttpWebRequest { private readonly HttpWebRequest _httpWebRequest; public int Timeout { get { return _httpWebRequest.Timeout; } set { _httpWebRequest.Timeout = value; } } public Uri Address { get { return _httpWebRequest.Address; } } public WrapHttpWebRequest(HttpWebRequest httpWebRequest) { _httpWebRequest = httpWebRequest; } public IHttpWebResponse GetResponse() { return new WrapHttpWebResponse((HttpWebResponse) _httpWebRequest.GetResponse()); } } }
mit
C#
ec0dc74116e141c0190fd86ac0a13812a46d8ef8
Update src/Abp.Zero.Common/Notifications/NotificationSubscriptionSynchronizer.cs
ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate
src/Abp.Zero.Common/Notifications/NotificationSubscriptionSynchronizer.cs
src/Abp.Zero.Common/Notifications/NotificationSubscriptionSynchronizer.cs
using System; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; namespace Abp.Notifications { public class NotificationSubscriptionSynchronizer : IEventHandler<EntityDeletedEventData<AbpUserBase>>, ITransientDependency { private readonly IRepository<NotificationSubscriptionInfo, Guid> _notificationSubscriptionRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public NotificationSubscriptionSynchronizer( IRepository<NotificationSubscriptionInfo, Guid> notificationSubscriptionRepository, IUnitOfWorkManager unitOfWorkManager ) { _notificationSubscriptionRepository = notificationSubscriptionRepository; _unitOfWorkManager = unitOfWorkManager; } public virtual void HandleEvent(EntityDeletedEventData<AbpUserBase> eventData) { using (var uow = _unitOfWorkManager.Begin()) { using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { _notificationSubscriptionRepository.Delete(x => x.UserId == eventData.Entity.Id && x.TenantId == eventData.Entity.TenantId); uow.Complete(); } } } } }
using System; using Abp.Authorization.Users; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; namespace Abp.Notifications { public class NotificationSubscriptionSynchronizer : IEventHandler<EntityDeletedEventData<AbpUserBase>>, ITransientDependency { private readonly IRepository<NotificationSubscriptionInfo, Guid> _notificationSubscriptionRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public NotificationSubscriptionSynchronizer( IRepository<NotificationSubscriptionInfo, Guid> notificationSubscriptionRepository, IUnitOfWorkManager unitOfWorkManager ) { _notificationSubscriptionRepository = notificationSubscriptionRepository; _unitOfWorkManager = unitOfWorkManager; } public virtual void HandleEvent(EntityDeletedEventData<AbpUserBase> eventData) { using (var uow = _unitOfWorkManager.Begin()) { using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant)) { _notificationSubscriptionRepository.Delete(x => x.UserId == eventData.Entity.Id && x.TenantId == eventData.Entity.TenantId); uow.CompleteAsync(); } } } } }
mit
C#
4b88d69cd1e92fe12b130a2e839b29a03154a693
add comment.
reaction1989/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,diryboy/roslyn,reaction1989/roslyn,aelij/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,weltkante/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,jmarolf/roslyn,mavasani/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,brettfo/roslyn,gafter/roslyn,wvdd007/roslyn,reaction1989/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,davkean/roslyn,wvdd007/roslyn,stephentoub/roslyn,heejaechang/roslyn,KevinRansom/roslyn,agocke/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,dotnet/roslyn,heejaechang/roslyn,davkean/roslyn,gafter/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,tannergooding/roslyn,AmadeusW/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,jmarolf/roslyn,stephentoub/roslyn,physhi/roslyn,VSadov/roslyn,KevinRansom/roslyn,jmarolf/roslyn,aelij/roslyn,jasonmalinowski/roslyn,VSadov/roslyn,brettfo/roslyn,physhi/roslyn,AlekseyTs/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,gafter/roslyn,diryboy/roslyn,heejaechang/roslyn,diryboy/roslyn,abock/roslyn,eriawan/roslyn,AmadeusW/roslyn,dotnet/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,agocke/roslyn,davkean/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,tannergooding/roslyn,brettfo/roslyn,genlu/roslyn,VSadov/roslyn,tmat/roslyn,aelij/roslyn,abock/roslyn,ErikSchierboom/roslyn,abock/roslyn,tmat/roslyn,tmat/roslyn,nguerrera/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,sharwell/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,ErikSchierboom/roslyn
src/Features/Core/Portable/EmbeddedLanguages/IEmbeddedLanguageFeatures.cs
src/Features/Core/Portable/EmbeddedLanguages/IEmbeddedLanguageFeatures.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages { /// <summary> /// Services related to a specific embedded language. /// </summary> internal interface IEmbeddedLanguageFeatures : IEmbeddedLanguage { /// <summary> /// A optional highlighter that can highlight spans for an embedded language string. /// </summary> IDocumentHighlightsService DocumentHighlightsService { get; } /// <summary> /// An optional analyzer that produces diagnostics for an embedded language string. /// </summary> AbstractBuiltInCodeStyleDiagnosticAnalyzer DiagnosticAnalyzer { get; } /// <summary> /// An optional completion provider that can provide completion items for this /// specific embedded language. /// /// <see cref="EmbeddedLanguageCompletionProvider"/> will aggregate all these /// individual providers and expose them as one single completion provider to /// the rest of Roslyn. /// </summary> CompletionProvider CompletionProvider { get; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices; namespace Microsoft.CodeAnalysis.Features.EmbeddedLanguages { /// <summary> /// Services related to a specific embedded language. /// </summary> internal interface IEmbeddedLanguageFeatures : IEmbeddedLanguage { /// <summary> /// A optional highlighter that can highlight spans for an embedded language string. /// </summary> IDocumentHighlightsService DocumentHighlightsService { get; } /// <summary> /// An optional analyzer that produces diagnostics for an embedded language string. /// </summary> AbstractBuiltInCodeStyleDiagnosticAnalyzer DiagnosticAnalyzer { get; } /// <summary> /// An optional completion provider that can provide completion items. /// </summary> CompletionProvider CompletionProvider { get; } } }
mit
C#