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 |
|---|---|---|---|---|---|---|---|---|
b1b8afcdec8b610457b565d84d0c25c17f533a7a | stop application when initialize failed in asp.net core | zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,303248153/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb | ZKWeb/ZKWeb.Hosting.AspNetCore/StartupBase.cs | ZKWeb/ZKWeb.Hosting.AspNetCore/StartupBase.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using System;
using System.IO;
using System.Threading.Tasks;
using ZKWebStandard.Ioc;
namespace ZKWeb.Hosting.AspNetCore {
/// <summary>
/// Base startup class for Asp.Net Core
/// </summary>
public abstract class StartupBase {
/// <summary>
/// Get website root directory
/// </summary>
/// <returns></returns>
public virtual string GetWebsiteRootDirectory() {
var path = PlatformServices.Default.Application.ApplicationBasePath;
while (!File.Exists(Path.Combine(path, "Web.config"))) {
path = Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(path)) {
throw new DirectoryNotFoundException("Website root directory not found");
}
}
return path;
}
/// <summary>
/// Allow child class to configure middlewares
/// </summary>
protected virtual void ConfigureMiddlewares(IApplicationBuilder app) { }
/// <summary>
/// Configure application
/// </summary>
public virtual void Configure(IApplicationBuilder app, IApplicationLifetime lifetime) {
// Initialize application
try {
Application.Ioc.RegisterMany<CoreWebsiteStopper>(ReuseType.Singleton);
Application.Initialize(GetWebsiteRootDirectory());
Application.Ioc.RegisterInstance(lifetime);
} catch {
lifetime.StopApplication();
throw;
}
// Configure middlewares
ConfigureMiddlewares(app);
// Set request handler, it will running in thread pool
// It can't throw any exception otherwise application will get killed
app.Run(coreContext => Task.Run(() => {
var context = new CoreHttpContextWrapper(coreContext);
try {
// Handle request
Application.OnRequest(context);
} catch (CoreHttpResponseEndException) {
// Success
} catch (Exception ex) {
// Error
try {
Application.OnError(context, ex);
} catch (CoreHttpResponseEndException) {
// Handle error success
} catch (Exception) {
// Handle error failed
}
}
}));
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.PlatformAbstractions;
using System;
using System.IO;
using System.Threading.Tasks;
using ZKWebStandard.Ioc;
namespace ZKWeb.Hosting.AspNetCore {
/// <summary>
/// Base startup class for Asp.Net Core
/// </summary>
public abstract class StartupBase {
/// <summary>
/// Get website root directory
/// </summary>
/// <returns></returns>
public virtual string GetWebsiteRootDirectory() {
var path = PlatformServices.Default.Application.ApplicationBasePath;
while (!File.Exists(Path.Combine(path, "Web.config"))) {
path = Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(path)) {
throw new DirectoryNotFoundException("Website root directory not found");
}
}
return path;
}
/// <summary>
/// Allow child class to configure middlewares
/// </summary>
protected virtual void ConfigureMiddlewares(IApplicationBuilder app) { }
/// <summary>
/// Configure application
/// </summary>
public virtual void Configure(IApplicationBuilder app, IApplicationLifetime lifetime) {
// Initialize application
Application.Ioc.RegisterMany<CoreWebsiteStopper>(ReuseType.Singleton);
Application.Initialize(GetWebsiteRootDirectory());
Application.Ioc.RegisterInstance(lifetime);
// Configure middlewares
ConfigureMiddlewares(app);
// Set request handler, it will running in thread pool
// It can't throw any exception otherwise application will get killed
app.Run(coreContext => Task.Run(() => {
var context = new CoreHttpContextWrapper(coreContext);
try {
// Handle request
Application.OnRequest(context);
} catch (CoreHttpResponseEndException) {
// Success
} catch (Exception ex) {
// Error
try {
Application.OnError(context, ex);
} catch (CoreHttpResponseEndException) {
// Handle error success
} catch (Exception) {
// Handle error failed
}
}
}));
}
}
}
| mit | C# |
1a1c480943f837d0b57f487690c1f62f84baa941 | Simplify syntax | martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode | tests/AdventOfCode.Tests/Benchmarks/BenchmarkTests.cs | tests/AdventOfCode.Tests/Benchmarks/BenchmarkTests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using static MartinCostello.AdventOfCode.Benchmarks.PuzzleBenchmarks;
namespace MartinCostello.AdventOfCode.Benchmarks;
public static class BenchmarkTests
{
public static IEnumerable<object[]> Benchmarks()
{
foreach (object puzzle in PuzzleBenchmarks.Puzzles())
{
yield return new[] { puzzle };
}
}
[Theory]
[MemberData(nameof(Benchmarks))]
public static async Task Can_Run_Benchmarks(PuzzleInput input)
{
// Arrange
IPuzzle puzzle = input.Puzzle;
string[] args = input.Args;
// Act (no Assert)
await puzzle.SolveAsync(args, CancellationToken.None);
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using static MartinCostello.AdventOfCode.Benchmarks.PuzzleBenchmarks;
namespace MartinCostello.AdventOfCode.Benchmarks;
public static class BenchmarkTests
{
public static IEnumerable<object[]> Benchmarks()
{
foreach (object puzzle in PuzzleBenchmarks.Puzzles())
{
yield return new object[] { puzzle };
}
}
[Theory]
[MemberData(nameof(Benchmarks))]
public static async Task Can_Run_Benchmarks(PuzzleInput input)
{
// Arrange
IPuzzle puzzle = input.Puzzle;
string[] args = input.Args;
// Act (no Assert)
await puzzle.SolveAsync(args, CancellationToken.None);
}
}
| apache-2.0 | C# |
2cba9103737ae5f85fccb1328966fb986cc5ed60 | Update Path.cs | primo-ppcg/BF-Crunch | src/Path.cs | src/Path.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ppcg {
[Serializable]
public class Path : LinkedList<Node> {
public int Cost {
get {
return this.Sum(node => node.Cost);
}
}
public Path() { }
public Path(IEnumerable<Node> nodes) : base(nodes) { }
protected Path(SerializationInfo info, StreamingContext context) : base(info, context) { }
public override string ToString() {
return string.Join(", ", this);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
namespace ppcg {
[Serializable]
public class Path : LinkedList<Node> {
public int Cost {
get {
return this.Sum(node => node.Cost);
}
}
public Path() { }
protected Path(SerializationInfo info, StreamingContext context) : base(info, context) { }
public override string ToString() {
return string.Join(", ", this);
}
}
}
| mit | C# |
72187ffbdc4d08f5c65a34aa765db2517acd8f05 | Update annotations_multiple.cs | pardeike/Harmony | Harmony/Documentation/examples/annotations_multiple.cs | Harmony/Documentation/examples/annotations_multiple.cs | namespace Annotations_Multiple
{
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Example
{
// <example>
[HarmonyPatch] // make sure Harmony inspects the class
class MyPatches
{
static IEnumerable<MethodBase> TargetMethods()
{
return AccessTools.GetTypesFromAssembly(someAssembly)
.SelectMany(type => type.GetMethods())
.Where(method => method.ReturnType != typeof(void) && method.Name.StartsWith("Player"))
.Cast<MethodBase>();
}
// prefix all methods in someAssembly with a non-void return type and beginning with "Player"
static void Prefix(MethodBase __originalMethod)
{
// use __originalMethod to decide what to do
}
}
// </example>
class MyCode { }
public static Assembly someAssembly;
}
}
| namespace Annotations_Multiple
{
using HarmonyLib;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Example
{
// <example>
[HarmonyPatch] // make sure Harmony inspects the class
class MyPatches
{
IEnumerable<MethodBase> TargetMethods()
{
return AccessTools.GetTypesFromAssembly(someAssembly)
.SelectMany(type => type.GetMethods())
.Where(method => method.ReturnType != typeof(void) && method.Name.StartsWith("Player"))
.Cast<MethodBase>();
}
// prefix all methods in someAssembly with a non-void return type and beginning with "Player"
static void Prefix(MethodBase __originalMethod)
{
// use __originalMethod to decide what to do
}
}
// </example>
class MyCode { }
public static Assembly someAssembly;
}
}
| mit | C# |
021fd65fa2edbc946759141cad23a3fe15984d5f | update to latest from GOTG | hungweng/MarkerMetro.Unity.WinShared,hungweng/MarkerMetro.Unity.WinShared,MarkerMetro/MarkerMetro.Unity.WinShared,cedw032/MarkerMetro.Unity.WinShared,Kezeali/MarkerMetro.Unity.WinShared | Assets/Editor/MarkerMetro/DTX5TexturePostprocessor.cs | Assets/Editor/MarkerMetro/DTX5TexturePostprocessor.cs | using UnityEngine;
using UnityEditor;
class DTX5TexturePostprocessor : AssetPostprocessor {
const bool Enabled = false;
#pragma warning disable
/**
* Change the import settings of the texture to import as DXT5.
* This is preferable over the post process method since it changes the meta file so
* you can commit the changes.
*
* Attention! Reimport all doesn't work (it changes the import settings but somehow doesn't change the
* meta file). Also, filtering textures via search box in Unity (4.5f6) doesn't always list all textures.
*/
public void OnPreprocessTexture()
{
if (!Enabled)
return;
TextureImporter textureImporter = assetImporter as TextureImporter;
textureImporter.npotScale = TextureImporterNPOTScale.ToNearest;
textureImporter.textureFormat = TextureImporterFormat.DXT5;
}
/**
* Tries to apply a DXT5 compression when importing a texture.
* This doesn't actually change anything (meta file, the texture), only
* Unity's internal representation of the texture.
*/
public void OnPostprocessTexture(Texture2D t)
{
//if(Enabled)
// EditorUtility.CompressTexture(t, TextureFormat.DXT5, 2);
}
#pragma warning restore
}
| using UnityEngine;
using UnityEditor;
/**
* Tries to apply a DXT5 compression when importing a texture.
* This will change the texture meta file.
*/
class DTX5TexturePostprocessor : AssetPostprocessor {
// ENABLE HERE TO MAKE THE SCRIPT WORK
const bool Enabled = false;
#pragma warning disable
public void OnPostprocessTexture (Texture2D t) {
if(Enabled)
EditorUtility.CompressTexture(t, TextureFormat.DXT5, 2);
}
#pragma warning restore
} | mit | C# |
25650f59ff5fa354d9154e724ea1f164cfc165d8 | Handle bad values | campersau/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer | PackageExplorer/Converters/TargetFrameworkConverter.cs | PackageExplorer/Converters/TargetFrameworkConverter.cs | using System;
using System.Windows;
using System.Windows.Data;
using NuGet.Frameworks;
namespace PackageExplorer
{
public class TargetFrameworkConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var framework = (NuGetFramework)value;
if (framework == null)
{
return null;
}
return framework.GetShortFolderName();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var stringValue = (string)value;
if (string.IsNullOrEmpty(stringValue))
{
return null;
}
try
{
var framework = NuGetFramework.Parse(stringValue);
if (framework.IsUnsupported)
{
return DependencyProperty.UnsetValue;
}
return framework;
}
catch (Exception) // could be an invalid value
{
return DependencyProperty.UnsetValue;
}
}
}
}
| using System;
using System.Windows;
using System.Windows.Data;
using NuGet.Frameworks;
namespace PackageExplorer
{
public class TargetFrameworkConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var framework = (NuGetFramework)value;
if (framework == null)
{
return null;
}
return framework.GetShortFolderName();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var stringValue = (string)value;
if (string.IsNullOrEmpty(stringValue))
{
return null;
}
var framework = NuGetFramework.Parse(stringValue);
if (framework.IsUnsupported)
{
return DependencyProperty.UnsetValue;
}
return framework;
}
}
} | mit | C# |
8c090e8a3eef420fc88cf338db56814154b1f7b7 | Update Book Index View to show the correct information needed. I.E. Title, Author, ISBN, and Genre, and a column name for Availability for future use. | Programazing/Open-School-Library,Programazing/Open-School-Library | src/Open-School-Library/Views/Books/Index.cshtml | src/Open-School-Library/Views/Books/Index.cshtml | @model IEnumerable<Open_School_Library.Models.DatabaseModels.Book>
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
@Html.DisplayNameFor(model => model.ISBN)
</th>
<th>
Genre
</th>
<th>
Availability
</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.ISBN)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.BookID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.BookID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.BookID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
| @model IEnumerable<Open_School_Library.Models.DatabaseModels.Book>
@{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>
<a asp-action="Create">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
@Html.DisplayNameFor(model => model.ISBN)
</th>
<th>
@Html.DisplayNameFor(model => model.SubTitle)
</th>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.ISBN)
</td>
<td>
@Html.DisplayFor(modelItem => item.SubTitle)
</td>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
<a asp-action="Edit" asp-route-id="@item.BookID">Edit</a> |
<a asp-action="Details" asp-route-id="@item.BookID">Details</a> |
<a asp-action="Delete" asp-route-id="@item.BookID">Delete</a>
</td>
</tr>
}
</tbody>
</table>
| mit | C# |
f33a552be3d7bacdb4148c04adeea4ae33fd5fb1 | Revert fix | leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net | JoinRpg.Domain/SubscribeExtensions.cs | JoinRpg.Domain/SubscribeExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using JoinRpg.DataModel;
using JoinRpg.Helpers;
namespace JoinRpg.Domain
{
public static class SubscribeExtensions
{
public static IEnumerable<User> GetSubscriptions(this ForumThread claim, [CanBeNull] IEnumerable<User> extraRecepients, bool isVisibleToPlayer)
{
return
claim.Subscriptions //get subscriptions on forum
.Select(u => u.User) //Select users
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || !claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
}
public static IEnumerable<User> GetSubscriptions(
this Claim claim,
Func<UserSubscription, bool> predicate,
[CanBeNull] IEnumerable<User> extraRecepients,
bool isVisibleToPlayer)
{
return claim.GetTarget().GetGroupsPartOf() //Get all groups for claim
.SelectMany(g => g.Subscriptions) //get subscriptions on groups
.Union(claim.Subscriptions) //subscribtions on claim
.Union(claim.Character?.Subscriptions ?? new UserSubscription[] {}) //and on characters
.Where(predicate) //type of subscribe (on new comments, on new claims etc.)
.Select(u => u.User) //Select users
.Union(claim.ResponsibleMasterUser) //Responsible master is always subscribed on everything
.Union(claim.Player) //...and player himself also
.Union(extraRecepients ?? Enumerable.Empty<User>()) //add extra recepients
.Where(u => isVisibleToPlayer || claim.HasMasterAccess(u.UserId)); //remove player if we doing something not player visible
;
}
}
}
| mit | C# |
20aba8b158a2fdf5212464ed0a1d0d37fdc99e54 | Improve sorting | leotsarev/joinrpg-net,kirillkos/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | Joinrpg/Controllers/HomeController.cs | Joinrpg/Controllers/HomeController.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using JoinRpg.Data.Interfaces;
using JoinRpg.Domain;
using JoinRpg.Web.Models;
using JoinRpg.Web.Models.CommonTypes;
namespace JoinRpg.Web.Controllers
{
public class HomeController : Common.ControllerBase
{
private const int projectsOnHomePage = 9;
private readonly IProjectRepository _projectRepository;
private readonly IClaimsRepository _claimsRepository;
public HomeController(IProjectRepository projectRepository, ApplicationUserManager userManager, IClaimsRepository claimsRepository) : base (userManager)
{
_projectRepository = projectRepository;
_claimsRepository = claimsRepository;
}
public async Task<ActionResult> Index()
{
return View(await LoadModel(projectsOnHomePage));
}
private async Task<HomeViewModel> LoadModel(int maxProjects = int.MaxValue)
{
var projects =
(await _projectRepository.GetActiveProjectsWithClaimCount()).Select(p => new ProjectListItemViewModel()
{
ProjectId = p.ProjectId,
IsMaster = p.HasMasterAccess(CurrentUserIdOrDefault),
ProjectAnnounce = new MarkdownViewModel(p.Details?.ProjectAnnounce),
ProjectName = p.ProjectName,
MyClaims = p.Claims.Where(c => c.PlayerUserId == CurrentUserIdOrDefault),
ClaimCount = p.Claims.Count(c => c.IsActive),
}).ToList();
var alwaysShowProjects =
projects.Where(p => p.IsMaster || p.MyClaims.Any()).OrderByDescending(p => p.IsMaster).ThenByDescending(p => p.ClaimCount);
var otherProjects =
projects.Except(alwaysShowProjects)
.OrderByDescending(p => p.ClaimCount)
.Take(Math.Max(0, maxProjects - alwaysShowProjects.Count())); // Add more projects until we have 9 total
var finalProjects = alwaysShowProjects.Union(otherProjects).ToList();
return new HomeViewModel
{
ActiveProjects = finalProjects,
HasMoreProjects = projects.Count > finalProjects.Count
};
}
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult AboutTest()
{
return View();
}
public async Task<ViewResult> BrowseGames()
{
return View(await LoadModel());
}
}
} | using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using JoinRpg.Data.Interfaces;
using JoinRpg.Domain;
using JoinRpg.Web.Models;
using JoinRpg.Web.Models.CommonTypes;
namespace JoinRpg.Web.Controllers
{
public class HomeController : Common.ControllerBase
{
private const int projectsOnHomePage = 9;
private readonly IProjectRepository _projectRepository;
private readonly IClaimsRepository _claimsRepository;
public HomeController(IProjectRepository projectRepository, ApplicationUserManager userManager, IClaimsRepository claimsRepository) : base (userManager)
{
_projectRepository = projectRepository;
_claimsRepository = claimsRepository;
}
public async Task<ActionResult> Index()
{
return View(await LoadModel(projectsOnHomePage));
}
private async Task<HomeViewModel> LoadModel(int maxProjects = int.MaxValue)
{
var homeViewModel = new HomeViewModel();
var projects = (await _projectRepository.GetActiveProjectsWithClaimCount()).Select(p => new ProjectListItemViewModel()
{
ProjectId = p.ProjectId,
IsMaster = p.HasMasterAccess(CurrentUserIdOrDefault),
ProjectAnnounce = new MarkdownViewModel(p.Details?.ProjectAnnounce),
ProjectName = p.ProjectName,
MyClaims = p.Claims.Where(c => c.PlayerUserId == CurrentUserIdOrDefault),
ClaimCount = p.Claims.Count(c => c.IsActive),
}).ToList();
var alwaysShowProjects = projects.Where(p => p.IsMaster || p.MyClaims.Any()).OrderByDescending(p => p.IsMaster);
var otherProjects =
projects.Except(alwaysShowProjects)
.OrderByDescending(p => p.ClaimCount)
.Take(Math.Max(0, maxProjects - alwaysShowProjects.Count())); // Add more projects until we have 9 total
homeViewModel.ActiveProjects =
alwaysShowProjects.Union(otherProjects).ToList();
homeViewModel.HasMoreProjects = projects.Count > homeViewModel.ActiveProjects.Count();
return homeViewModel;
}
public ActionResult About()
{
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
public ActionResult AboutTest()
{
return View();
}
public async Task<ViewResult> BrowseGames()
{
return View(await LoadModel());
}
}
} | mit | C# |
f388cfadef6a8a4922165c785cfbead9c96fc5c8 | Fix TextCaster | Seddryck/NBi,Seddryck/NBi | NBi.Core/Scalar/Casting/TextCaster.cs | NBi.Core/Scalar/Casting/TextCaster.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Scalar.Casting
{
class TextCaster : ICaster<string>
{
public string Execute(object value)
{
if (value is string)
return (string)value;
if (value is DateTime)
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
if (value is bool)
return (bool)value ? "True" : "False";
var numericCaster = new NumericCaster();
if (numericCaster.IsStrictlyValid(value))
return Convert.ToDecimal(value).ToString(new CultureFactory().Invariant.NumberFormat);
return value.ToString();
}
object ICaster.Execute(object value) => Execute(value);
public bool IsValid(object value)
{
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Scalar.Casting
{
class TextCaster : ICaster<string>
{
public string Execute(object value)
{
if (value is string)
return (string)value;
if (value is DateTime)
return ((DateTime)value).ToString("yyyy-MM-dd hh:mm:ss");
if (value is bool)
return (bool)value ? "True" : "False";
var numericCaster = new NumericCaster();
if (numericCaster.IsStrictlyValid(value))
return Convert.ToDouble(value).ToString(new CultureFactory().Invariant.NumberFormat);
return value.ToString();
}
object ICaster.Execute(object value) => Execute(value);
public bool IsValid(object value)
{
return true;
}
}
}
| apache-2.0 | C# |
d367c8b5cd3ceb2bc1196324fdc2edb896602d2c | fix SecurityHeaderTest due to text formatting issue | projectkudu/SiteExtensionGallery,projectkudu/SiteExtensionGallery,skbkontur/NuGetGallery,skbkontur/NuGetGallery,ScottShingler/NuGetGallery,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,ScottShingler/NuGetGallery,mtian/SiteExtensionGallery,projectkudu/SiteExtensionGallery,mtian/SiteExtensionGallery,grenade/NuGetGallery_download-count-patch,grenade/NuGetGallery_download-count-patch,skbkontur/NuGetGallery | tests/NuGetGallery.FunctionalTests/WebUITests/BasicPages/SecurityHeaderTest.cs | tests/NuGetGallery.FunctionalTests/WebUITests/BasicPages/SecurityHeaderTest.cs | using Microsoft.VisualStudio.TestTools.WebTesting;
using NuGetGallery.FunctionalTests.Helpers;
using NuGetGallery.FunctionTests.Helpers;
using System;
using System.Collections.Generic;
namespace NuGetGallery.FunctionalTests
{
/// <summary>
/// Verify that an expected series of security headers is returned as part of the response.
/// Priority :P2
/// </summary>
public class SecurityHeaderTest : WebTest
{
public SecurityHeaderTest()
{
this.PreAuthenticate = true;
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
//send a request to home page and check for security headers.
WebTestRequest homePageRequest = new WebTestRequest(UrlHelper.BaseUrl);
homePageRequest.ParseDependentRequests = false;
ValidationRuleFindHeaderText homePageTextValidationRule = new ValidationRuleFindHeaderText(
@"X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: maxage=31536000; includeSubDomains");
homePageRequest.ValidateResponse += new EventHandler<ValidationEventArgs>(homePageTextValidationRule.Validate);
yield return homePageRequest;
homePageRequest = null;
//send a request to Packages page and check for security headers.
WebTestRequest packagesPageRequest = new WebTestRequest(UrlHelper.PackagesPageUrl);
packagesPageRequest.ParseDependentRequests = false;
ValidationRuleFindHeaderText packagesPageTextValidationRule = new ValidationRuleFindHeaderText(
@"X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: maxage=31536000; includeSubDomains");
packagesPageRequest.ValidateResponse += new EventHandler<ValidationEventArgs>(packagesPageTextValidationRule.Validate);
yield return packagesPageRequest;
packagesPageRequest = null;
}
}
}
| using Microsoft.VisualStudio.TestTools.WebTesting;
using NuGetGallery.FunctionalTests.Helpers;
using NuGetGallery.FunctionTests.Helpers;
using System;
using System.Collections.Generic;
namespace NuGetGallery.FunctionalTests
{
/// <summary>
/// Verify that an expected series of security headers is returned as part of the response.
/// Priority :P2
/// </summary>
public class SecurityHeaderTest : WebTest
{
public SecurityHeaderTest()
{
this.PreAuthenticate = true;
}
public override IEnumerator<WebTestRequest> GetRequestEnumerator()
{
//send a request to home page and check for security headers.
WebTestRequest homePageRequest = new WebTestRequest(UrlHelper.BaseUrl);
homePageRequest.ParseDependentRequests = false;
ValidationRuleFindHeaderText homePageTextValidationRule = new ValidationRuleFindHeaderText(
@"X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: maxage=31536000; includeSubDomains");
homePageRequest.ValidateResponse += new EventHandler<ValidationEventArgs>(homePageTextValidationRule.Validate);
yield return homePageRequest;
homePageRequest = null;
//send a request to Packages page and check for security headers.
WebTestRequest packagesPageRequest = new WebTestRequest(UrlHelper.PackagesPageUrl);
packagesPageRequest.ParseDependentRequests = false;
ValidationRuleFindHeaderText packagesPageTextValidationRule = new ValidationRuleFindHeaderText(
@"X-Frame-Options: deny
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Strict-Transport-Security: maxage=31536000; includeSubDomains");
packagesPageRequest.ValidateResponse += new EventHandler<ValidationEventArgs>(packagesPageTextValidationRule.Validate);
yield return packagesPageRequest;
packagesPageRequest = null;
}
}
}
| apache-2.0 | C# |
b815f10d4dbc8b4889a16c2a70239a8d91f00d52 | Update RadialLookupCollection.cs | ADAPT/ADAPT | source/ADAPT/Prescriptions/RadialLookupCollection.cs | source/ADAPT/Prescriptions/RadialLookupCollection.cs | /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
*
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Representations;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Prescriptions
{
public class RadialLookupCollection
{
public RadialLookupCollection()
{
RadialLookups = new List<RxRadialLookup>();
ShapeLookups = new List<RxShapeLookup>();
}
public List<RxRadialLookup> RadialLookups { get; set; }
public NumericRepresentationValue StartAngle { get; set; }
public NumericRepresentationValue EndAngle { get; set; }
public Point RotCtr { get; set; }
public List<RxShapeLookup> ShapeLookups { get; set; }
}
}
| /*******************************************************************************
* Copyright (C) 2015 AgGateway and ADAPT Contributors
* Copyright (C) 2015 Deere and Company
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
*
*
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Representations;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Prescriptions
{
public class RadialLookupCollection
{
public RadialPrescription()
{
RadialLookups = new List<RxRadialLookup>();
ShapeLookups = new List<RxShapeLookup>();
}
public List<RxRadialLookup> RadialLookups { get; set; }
public NumericRepresentationValue StartAngle { get; set; }
public NumericRepresentationValue EndAngle { get; set; }
public Point RotCtr { get; set; }
public List<RxShapeLookup> ShapeLookups { get; set; }
}
}
| epl-1.0 | C# |
05f667b0bcc38cd7a1cadead7c09e328f26dd7de | Extend integration test migration timeout | Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server | tests/Tgstation.Server.Tests/IntegrationTest.cs | tests/Tgstation.Server.Tests/IntegrationTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Client;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
[TestClass]
public sealed class IntegrationTest
{
readonly IServerClientFactory clientFactory = new ServerClientFactory(new ProductHeaderValue(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString()));
[TestMethod]
public async Task FullMonty()
{
using (var server = new TestingServer())
using (var serverCts = new CancellationTokenSource())
{
var cancellationToken = serverCts.Token;
var serverTask = server.RunAsync(cancellationToken);
try
{
IServerClient adminClient;
var giveUpAt = DateTimeOffset.Now.AddSeconds(60);
do
{
try
{
adminClient = await clientFactory.CreateServerClient(server.Url, User.AdminName, User.DefaultAdminPassword).ConfigureAwait(false);
break;
}
catch (ServiceUnavailableException)
{
//migrating, to be expected
if (DateTimeOffset.Now > giveUpAt)
throw;
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
} while (true);
using (adminClient)
{
var serverInfo = await adminClient.Version(default).ConfigureAwait(false);
Assert.AreEqual(ApiHeaders.Version, serverInfo.ApiVersion);
Assert.AreEqual(typeof(IServer).Assembly.GetName().Version, serverInfo.Version);
await new AdministrationTest(adminClient.Administration).Run(cancellationToken).ConfigureAwait(false);
await new InstanceManagerTest(adminClient.Instances, server.Directory).Run(cancellationToken).ConfigureAwait(false);
}
}
finally
{
serverCts.Cancel();
try
{
await serverTask.ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Net.Http.Headers;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Tgstation.Server.Api;
using Tgstation.Server.Api.Models;
using Tgstation.Server.Client;
using Tgstation.Server.Host;
namespace Tgstation.Server.Tests
{
[TestClass]
public sealed class IntegrationTest
{
readonly IServerClientFactory clientFactory = new ServerClientFactory(new ProductHeaderValue(Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Version.ToString()));
[TestMethod]
public async Task FullMonty()
{
using (var server = new TestingServer())
using (var serverCts = new CancellationTokenSource())
{
var cancellationToken = serverCts.Token;
var serverTask = server.RunAsync(cancellationToken);
try
{
IServerClient adminClient;
var giveUpAt = DateTimeOffset.Now.AddSeconds(30);
do
{
try
{
adminClient = await clientFactory.CreateServerClient(server.Url, User.AdminName, User.DefaultAdminPassword).ConfigureAwait(false);
break;
}
catch (ServiceUnavailableException)
{
//migrating, to be expected
if (DateTimeOffset.Now > giveUpAt)
throw;
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
} while (true);
using (adminClient)
{
var serverInfo = await adminClient.Version(default).ConfigureAwait(false);
Assert.AreEqual(ApiHeaders.Version, serverInfo.ApiVersion);
Assert.AreEqual(typeof(IServer).Assembly.GetName().Version, serverInfo.Version);
await new AdministrationTest(adminClient.Administration).Run(cancellationToken).ConfigureAwait(false);
await new InstanceManagerTest(adminClient.Instances, server.Directory).Run(cancellationToken).ConfigureAwait(false);
}
}
finally
{
serverCts.Cancel();
try
{
await serverTask.ConfigureAwait(false);
}
catch (OperationCanceledException) { }
}
}
}
}
}
| agpl-3.0 | C# |
899a4237aa6bcfb03e177a0b8e681c5b6a54a3e2 | Mark GlobalSSPI fields as readonly | cydhaselton/corefx,the-dwyer/corefx,Ermiar/corefx,parjong/corefx,ericstj/corefx,ravimeda/corefx,nchikanov/corefx,rubo/corefx,the-dwyer/corefx,cydhaselton/corefx,YoupHulsebos/corefx,axelheer/corefx,mazong1123/corefx,krytarowski/corefx,marksmeltzer/corefx,Petermarcu/corefx,ptoonen/corefx,rjxby/corefx,jlin177/corefx,nchikanov/corefx,ViktorHofer/corefx,dhoehna/corefx,elijah6/corefx,ptoonen/corefx,weltkante/corefx,ravimeda/corefx,DnlHarvey/corefx,cydhaselton/corefx,dhoehna/corefx,gkhanna79/corefx,DnlHarvey/corefx,nbarbettini/corefx,rjxby/corefx,weltkante/corefx,yizhang82/corefx,gkhanna79/corefx,richlander/corefx,the-dwyer/corefx,zhenlan/corefx,Ermiar/corefx,rahku/corefx,DnlHarvey/corefx,alexperovich/corefx,dotnet-bot/corefx,weltkante/corefx,the-dwyer/corefx,gkhanna79/corefx,mazong1123/corefx,ravimeda/corefx,seanshpark/corefx,ptoonen/corefx,krytarowski/corefx,YoupHulsebos/corefx,Petermarcu/corefx,Ermiar/corefx,Jiayili1/corefx,dotnet-bot/corefx,richlander/corefx,yizhang82/corefx,ericstj/corefx,billwert/corefx,fgreinacher/corefx,marksmeltzer/corefx,nchikanov/corefx,nchikanov/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,cydhaselton/corefx,fgreinacher/corefx,dhoehna/corefx,yizhang82/corefx,cydhaselton/corefx,rjxby/corefx,stone-li/corefx,ViktorHofer/corefx,stephenmichaelf/corefx,yizhang82/corefx,ericstj/corefx,nbarbettini/corefx,ericstj/corefx,krytarowski/corefx,dotnet-bot/corefx,nbarbettini/corefx,stephenmichaelf/corefx,rahku/corefx,rjxby/corefx,Jiayili1/corefx,JosephTremoulet/corefx,zhenlan/corefx,gkhanna79/corefx,mmitche/corefx,parjong/corefx,shimingsg/corefx,axelheer/corefx,nbarbettini/corefx,krk/corefx,Petermarcu/corefx,billwert/corefx,krytarowski/corefx,axelheer/corefx,DnlHarvey/corefx,Petermarcu/corefx,shimingsg/corefx,krk/corefx,mmitche/corefx,Jiayili1/corefx,stone-li/corefx,dotnet-bot/corefx,lggomez/corefx,lggomez/corefx,lggomez/corefx,BrennanConroy/corefx,rahku/corefx,weltkante/corefx,mmitche/corefx,Ermiar/corefx,Ermiar/corefx,MaggieTsang/corefx,alexperovich/corefx,parjong/corefx,stone-li/corefx,lggomez/corefx,elijah6/corefx,Petermarcu/corefx,alexperovich/corefx,nchikanov/corefx,tijoytom/corefx,dotnet-bot/corefx,ViktorHofer/corefx,nbarbettini/corefx,richlander/corefx,shimingsg/corefx,richlander/corefx,jlin177/corefx,YoupHulsebos/corefx,seanshpark/corefx,rjxby/corefx,alexperovich/corefx,tijoytom/corefx,dhoehna/corefx,richlander/corefx,tijoytom/corefx,MaggieTsang/corefx,rubo/corefx,ptoonen/corefx,lggomez/corefx,jlin177/corefx,JosephTremoulet/corefx,twsouthwick/corefx,rahku/corefx,krk/corefx,stephenmichaelf/corefx,billwert/corefx,ptoonen/corefx,yizhang82/corefx,twsouthwick/corefx,ravimeda/corefx,twsouthwick/corefx,MaggieTsang/corefx,ericstj/corefx,nchikanov/corefx,mazong1123/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,parjong/corefx,rjxby/corefx,cydhaselton/corefx,krk/corefx,marksmeltzer/corefx,yizhang82/corefx,seanshpark/corefx,MaggieTsang/corefx,twsouthwick/corefx,fgreinacher/corefx,ViktorHofer/corefx,parjong/corefx,axelheer/corefx,stephenmichaelf/corefx,stone-li/corefx,shimingsg/corefx,ptoonen/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,richlander/corefx,mmitche/corefx,stone-li/corefx,lggomez/corefx,axelheer/corefx,marksmeltzer/corefx,the-dwyer/corefx,ravimeda/corefx,wtgodbe/corefx,marksmeltzer/corefx,wtgodbe/corefx,rjxby/corefx,ericstj/corefx,rubo/corefx,stone-li/corefx,tijoytom/corefx,axelheer/corefx,Petermarcu/corefx,MaggieTsang/corefx,parjong/corefx,wtgodbe/corefx,jlin177/corefx,twsouthwick/corefx,ravimeda/corefx,ptoonen/corefx,dhoehna/corefx,billwert/corefx,stephenmichaelf/corefx,richlander/corefx,weltkante/corefx,dhoehna/corefx,nbarbettini/corefx,elijah6/corefx,elijah6/corefx,tijoytom/corefx,weltkante/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,ericstj/corefx,zhenlan/corefx,krytarowski/corefx,rahku/corefx,ViktorHofer/corefx,krk/corefx,mazong1123/corefx,jlin177/corefx,yizhang82/corefx,ViktorHofer/corefx,Ermiar/corefx,DnlHarvey/corefx,YoupHulsebos/corefx,wtgodbe/corefx,shimingsg/corefx,weltkante/corefx,dhoehna/corefx,Ermiar/corefx,marksmeltzer/corefx,zhenlan/corefx,seanshpark/corefx,wtgodbe/corefx,seanshpark/corefx,ravimeda/corefx,JosephTremoulet/corefx,Jiayili1/corefx,mazong1123/corefx,Petermarcu/corefx,krytarowski/corefx,stephenmichaelf/corefx,krk/corefx,dotnet-bot/corefx,zhenlan/corefx,rahku/corefx,seanshpark/corefx,rubo/corefx,shimingsg/corefx,billwert/corefx,wtgodbe/corefx,alexperovich/corefx,marksmeltzer/corefx,alexperovich/corefx,Jiayili1/corefx,stone-li/corefx,elijah6/corefx,rubo/corefx,mmitche/corefx,billwert/corefx,seanshpark/corefx,nchikanov/corefx,billwert/corefx,jlin177/corefx,Jiayili1/corefx,the-dwyer/corefx,lggomez/corefx,JosephTremoulet/corefx,nbarbettini/corefx,DnlHarvey/corefx,ViktorHofer/corefx,tijoytom/corefx,alexperovich/corefx,krk/corefx,MaggieTsang/corefx,wtgodbe/corefx,jlin177/corefx,gkhanna79/corefx,mazong1123/corefx,BrennanConroy/corefx,Jiayili1/corefx,krytarowski/corefx,dotnet-bot/corefx,elijah6/corefx,gkhanna79/corefx,mazong1123/corefx,twsouthwick/corefx,rahku/corefx,the-dwyer/corefx,parjong/corefx,mmitche/corefx,elijah6/corefx,zhenlan/corefx,gkhanna79/corefx,shimingsg/corefx,fgreinacher/corefx,DnlHarvey/corefx,tijoytom/corefx,BrennanConroy/corefx,mmitche/corefx,zhenlan/corefx,twsouthwick/corefx,cydhaselton/corefx | src/Common/src/Interop/Windows/sspicli/GlobalSSPI.cs | src/Common/src/Interop/Windows/sspicli/GlobalSSPI.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Net
{
internal static class GlobalSSPI
{
internal static readonly SSPIInterface SSPIAuth = new SSPIAuthType();
internal static readonly SSPIInterface SSPISecureChannel = new SSPISecureChannelType();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Net
{
internal static class GlobalSSPI
{
internal static SSPIInterface SSPIAuth = new SSPIAuthType();
internal static SSPIInterface SSPISecureChannel = new SSPISecureChannelType();
}
}
| mit | C# |
738580ec617a23789236575f2525606a6a4d227e | Add IsTopLevel property | UselessToucan/osu,peppy/osu,smoogipooo/osu,peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,ppy/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,ppy/osu,2yangk23/osu,2yangk23/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu | osu.Game/Online/API/Requests/Responses/Comment.cs | osu.Game/Online/API/Requests/Responses/Comment.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 Newtonsoft.Json;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class Comment
{
[JsonProperty(@"id")]
public long Id { get; set; }
private long? parentId;
[JsonProperty(@"parent_id")]
public long? ParentId
{
get => parentId;
set
{
parentId = value;
IsTopLevel = value != null;
}
}
[JsonProperty(@"user_id")]
public long UserId { get; set; }
[JsonProperty(@"message")]
public string Message { get; set; }
[JsonProperty(@"message_html")]
public string MessageHTML { get; set; }
[JsonProperty(@"replies_count")]
public int RepliesCount { get; set; }
[JsonProperty(@"votes_count")]
public int VotesCount { get; set; }
[JsonProperty(@"commenatble_type")]
public string CommentableType { get; set; }
[JsonProperty(@"commentable_id")]
public int CommentableId { get; set; }
[JsonProperty(@"legacy_name")]
public string LegacyName { get; set; }
[JsonProperty(@"created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty(@"updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty(@"deleted_at")]
public DateTimeOffset DeletedAt { get; set; }
[JsonProperty(@"edited_at")]
public DateTimeOffset EditedAt { get; set; }
[JsonProperty(@"edited_by_id")]
public long EditedById { get; set; }
public bool IsTopLevel { get; set; }
}
}
| // 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 Newtonsoft.Json;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class Comment
{
[JsonProperty(@"id")]
public long Id { get; set; }
[JsonProperty(@"parent_id")]
public long ParentId { get; set; }
[JsonProperty(@"user_id")]
public long UserId { get; set; }
[JsonProperty(@"message")]
public string Message { get; set; }
[JsonProperty(@"message_html")]
public string MessageHTML { get; set; }
[JsonProperty(@"replies_count")]
public int RepliesCount { get; set; }
[JsonProperty(@"votes_count")]
public int VotesCount { get; set; }
[JsonProperty(@"commenatble_type")]
public string CommentableType { get; set; }
[JsonProperty(@"commentable_id")]
public int CommentableId { get; set; }
[JsonProperty(@"legacy_name")]
public string LegacyName { get; set; }
[JsonProperty(@"created_at")]
public DateTimeOffset CreatedAt { get; set; }
[JsonProperty(@"updated_at")]
public DateTimeOffset UpdatedAt { get; set; }
[JsonProperty(@"deleted_at")]
public DateTimeOffset DeletedAt { get; set; }
[JsonProperty(@"edited_at")]
public DateTimeOffset EditedAt { get; set; }
[JsonProperty(@"edited_by_id")]
public long EditedById { get; set; }
}
}
| mit | C# |
2bfc7d482e813c31989a20f230e06f53b6902c4d | fix focus next item behavior. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/Behaviors/FocusNextItemBehavior.cs | WalletWasabi.Fluent/Behaviors/FocusNextItemBehavior.cs | using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
using ReactiveUI;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace WalletWasabi.Fluent.Behaviors
{
internal class FocusNextItemBehavior : DisposingBehavior<Control>
{
public static readonly StyledProperty<bool> IsFocusedProperty =
AvaloniaProperty.Register<FocusNextItemBehavior, bool>(nameof(IsFocused), true);
public bool IsFocused
{
get => GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
protected override void OnAttached(CompositeDisposable disposables)
{
this.WhenAnyValue(x => x.IsFocused)
.Where(x => x == false)
.Subscribe(
_ =>
{
var parentControl = AssociatedObject.FindAncestorOfType<ItemsControl>();
if (parentControl is { })
{
foreach (var item in parentControl.GetLogicalChildren())
{
var nextToFocus = item.FindLogicalDescendantOfType<TextBox>();
if (nextToFocus.IsEnabled)
{
nextToFocus.Focus();
return;
}
}
AssociatedObject?.Focus();
}
})
.DisposeWith(disposables);
}
}
} | using Avalonia;
using Avalonia.Controls;
using Avalonia.LogicalTree;
using Avalonia.VisualTree;
using ReactiveUI;
using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
namespace WalletWasabi.Fluent.Behaviors
{
internal class FocusNextItemBehavior : DisposingBehavior<Control>
{
public static readonly StyledProperty<bool> IsFocusedProperty =
AvaloniaProperty.Register<FocusNextItemBehavior, bool>(nameof(IsFocused), true);
public bool IsFocused
{
get => GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
protected override void OnAttached(CompositeDisposable disposables)
{
this.WhenAnyValue(x => x.IsFocused)
.Where(x => x == false)
.Subscribe(
_ =>
{
var parentControl = AssociatedObject.FindAncestorOfType<ItemsControl>();
foreach (var item in parentControl.GetLogicalChildren())
{
var nextToFocus = item.FindLogicalDescendantOfType<TextBox>();
if (nextToFocus.IsEnabled)
{
nextToFocus.Focus();
return;
}
}
})
.DisposeWith(disposables);
}
}
} | mit | C# |
7453fd9b6c3a58074288ee400fe9b80636e8214d | Remove illegal await in catch block. | jagrem/msg | Msg.Infrastructure/Server/ClientRequestProcessor.cs | Msg.Infrastructure/Server/ClientRequestProcessor.cs | using System.Net.Sockets;
using System.Threading.Tasks;
using Version = Msg.Core.Versioning.Version;
using System.Linq;
namespace Msg.Infrastructure.Server
{
class ClientRequestProcessor
{
readonly AmqpSettings settings;
public ClientRequestProcessor (AmqpSettings settings)
{
this.settings = settings;
}
public async Task ProcessClient (TcpClient client)
{
var stream = client.GetStream ();
try {
var version = await stream.ReadVersionAsync ();
if (IsVersionSupported (version)) {
await stream.WriteVersionAsync (version);
} else {
await stream.WriteVersionAsync (this.settings.PreferredVersion);
}
} finally {
if (client.Connected) {
client.Close ();
}
}
}
bool IsVersionSupported (Version version)
{
return this.settings.SupportedVersions.Any (range => range.Contains (version));
}
}
}
| using System.Net.Sockets;
using System.Threading.Tasks;
using Version = Msg.Core.Versioning.Version;
using System.Linq;
namespace Msg.Infrastructure.Server
{
class ClientRequestProcessor
{
readonly AmqpSettings settings;
public ClientRequestProcessor (AmqpSettings settings)
{
this.settings = settings;
}
public async Task ProcessClient (TcpClient client)
{
var stream = client.GetStream ();
try {
var version = await stream.ReadVersionAsync ();
if (IsVersionSupported (version)) {
await stream.WriteVersionAsync (version);
} else {
await stream.WriteVersionAsync (this.settings.PreferredVersion);
}
} catch {
await stream.WriteVersionAsync (this.settings.PreferredVersion);
} finally {
if (client.Connected) {
client.Close ();
}
}
}
bool IsVersionSupported (Version version)
{
return this.settings.SupportedVersions.Any (range => range.Contains (version));
}
}
}
| apache-2.0 | C# |
4e6b35e108c55b93fb09cf403748ed344007528b | Update PiaHeader.cs | Allockse/PiaNO,phusband/PiaNO | PiaHeader.cs | PiaHeader.cs | //
// Copyright © 2014 Parrish Husband (parrish.husband@gmail.com)
// The MIT License (MIT) - See LICENSE.txt for further details.
//
using System;
using System.Globalization;
namespace PiaNO
{
public class PiaHeader
{
private string _headerData;
public double PiaFileVersion { get; private set; }
public short TypeVersion { get; private set; }
public PiaType PiaType { get; private set; }
public PiaHeader(string headerString)
{
_headerData = headerString;
var firstLine = headerString.Split()[0];
var headerArray = headerString.Split(new char[] { ',', '_'});
if (headerArray.Length < 4)
throw new ArgumentOutOfRangeException();
NumberFormatInfo wNFI = new NumberFormatInfo();
wNFI.CurrencyDecimalSeparator=".";
PiaFileVersion = Double.Parse(headerArray[1], wNFI);
var typeString = headerArray[2].Substring(0, 3);
PiaType = (PiaType)Enum.Parse(typeof(PiaType), typeString);
var versionString = headerArray[2].Substring(3).ToUpper().Replace("VER", string.Empty);
TypeVersion = Int16.Parse(versionString);
}
public override string ToString()
{
return _headerData;
//var fileversionString = string.Format("{0:0.0}", Math.Truncate(PiaFileVersion * 10) / 10);
//return string.Format(PIA_HEADER_FORMAT, fileversionString, PiaType, TypeVersion);
}
}
}
| //
// Copyright © 2014 Parrish Husband (parrish.husband@gmail.com)
// The MIT License (MIT) - See LICENSE.txt for further details.
//
using System;
namespace PiaNO
{
public class PiaHeader
{
private string _headerData;
public double PiaFileVersion { get; private set; }
public short TypeVersion { get; private set; }
public PiaType PiaType { get; private set; }
public PiaHeader(string headerString)
{
_headerData = headerString;
var firstLine = headerString.Split()[0];
var headerArray = headerString.Split(new char[] { ',', '_'});
if (headerArray.Length < 4)
throw new ArgumentOutOfRangeException();
PiaFileVersion = Double.Parse(headerArray[1]);
var typeString = headerArray[2].Substring(0, 3);
PiaType = (PiaType)Enum.Parse(typeof(PiaType), typeString);
var versionString = headerArray[2].Substring(3).ToUpper().Replace("VER", string.Empty);
TypeVersion = Int16.Parse(versionString);
}
public override string ToString()
{
return _headerData;
//var fileversionString = string.Format("{0:0.0}", Math.Truncate(PiaFileVersion * 10) / 10);
//return string.Format(PIA_HEADER_FORMAT, fileversionString, PiaType, TypeVersion);
}
}
}
| mit | C# |
5856671a21f0cdfbae5492a109c830c85095d535 | Update version to 1.0.3 | tdiehl/raygun4net,nelsonsar/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,articulate/raygun4net,ddunkin/raygun4net,nelsonsar/raygun4net,ddunkin/raygun4net,tdiehl/raygun4net,MindscapeHQ/raygun4net,articulate/raygun4net | Mindscape.Raygun4Net.WinRT/Properties/AssemblyInfo.cs | Mindscape.Raygun4Net.WinRT/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("Mindscape.Raygun4Net.WinRT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mindscape.Raygun4Net.WinRT")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
[assembly: ComVisible(false)] | 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("Mindscape.Raygun4Net.WinRT")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Mindscape.Raygun4Net.WinRT")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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: ComVisible(false)] | mit | C# |
033e923a7908b52b2b9f517494a0d7b70d63434c | Store the already serialised RaygunMessage object. | MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net | Mindscape.Raygun4Net/Storage/IRaygunOfflineStorage.cs | Mindscape.Raygun4Net/Storage/IRaygunOfflineStorage.cs | using System.Collections.Generic;
using Mindscape.Raygun4Net.Messages;
namespace Mindscape.Raygun4Net.Storage
{
public interface IRaygunOfflineStorage
{
/// <summary>
/// Persist the <paramref name="message"/>> to local storage.
/// </summary>
/// <param name="message">The serialized error report to store locally.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>
bool Store(string message, string apiKey);
/// <summary>
/// Retrieve all files from local storage.
/// </summary>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns>A container of files that are currently stored locally.</returns>
IList<IRaygunFile> FetchAll(string apiKey);
/// <summary>
/// Delete a file from local storage that has the following <paramref name="name"/>.
/// </summary>
/// <param name="name">The filename of the local file.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>
bool Remove(string name, string apiKey);
}
} | using System.Collections.Generic;
using Mindscape.Raygun4Net.Messages;
namespace Mindscape.Raygun4Net.Storage
{
public interface IRaygunOfflineStorage
{
/// <summary>
/// Persist the <paramref name="message"/>> to local storage.
/// </summary>
/// <param name="message">The error report to store locally.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>
bool Store(RaygunMessage message, string apiKey);
/// <summary>
/// Retrieve all files from local storage.
/// </summary>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns>A container of files that are currently stored locally.</returns>
IList<IRaygunFile> FetchAll(string apiKey);
/// <summary>
/// Delete a file from local storage that has the following <paramref name="name"/>.
/// </summary>
/// <param name="name">The filename of the local file.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>
bool Remove(string name, string apiKey);
}
} | mit | C# |
7c62d5246964b244172146171688131f88635916 | remove commented out code | jonnii/chinchilla | src/Chinchilla.Sample.SharedSubscriptions/FastMessageSubscriber.cs | src/Chinchilla.Sample.SharedSubscriptions/FastMessageSubscriber.cs | using System;
using System.Threading;
using Chinchilla.Topologies;
namespace Chinchilla.Sample.SharedSubscriptions
{
public class FastMessageSubscriber
{
private readonly IBus bus;
public FastMessageSubscriber()
{
bus = Depot.Connect("localhost/shared-subscriptions");
}
public void Start()
{
var builder = new DefaultSubscribeTopologyBuilder();
bus.Subscribe<SharedMessage>(
ProcessMessage, a => a.SetTopology(builder).SubscribeOn("fast-messages").DeliverUsing<WorkerPoolDeliveryStrategy>(s => s.NumWorkers = 1));
}
public void ProcessMessage(SharedMessage message)
{
Console.WriteLine("Processing (fast) {0}", message);
Thread.Sleep(3000);
}
public void Stop()
{
bus.Dispose();
}
}
} | using System;
using System.Threading;
using Chinchilla.Topologies;
namespace Chinchilla.Sample.SharedSubscriptions
{
public class FastMessageSubscriber
{
private readonly IBus bus;
public FastMessageSubscriber()
{
bus = Depot.Connect("localhost/shared-subscriptions");
}
public void Start()
{
var builder = new DefaultSubscribeTopologyBuilder();
bus.Subscribe<SharedMessage>(
ProcessMessage, a => a.SetTopology(builder).SubscribeOn("fast-messages").DeliverUsing<WorkerPoolDeliveryStrategy>(s => s.NumWorkers = 1));
}
public void ProcessMessage(SharedMessage message)
{
//if (message.MessageType == MessageType.Slow)
//{
// throw new Exception("Fast message consumer cannot process slow messages");
//}
Console.WriteLine("Processing (fast) {0}", message);
Thread.Sleep(3000);
}
public void Stop()
{
bus.Dispose();
}
}
} | apache-2.0 | C# |
85b18aea48e95de5ca56e6197b33516b2c72b4df | 更新 .net 4.5 项目版本号 | JeffreySu/Senparc.WebSocket | src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs | src/Senparc.WebSocket/Senparc.WebSocket/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
//[assembly: AssemblyTitle("Senparc.WebSocket")]
//[assembly: AssemblyDescription("")]
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("Senparc.WebSocket")]
//[assembly: AssemblyCopyright("Copyright © 2018")]
//[assembly: AssemblyTrademark("")]
//[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.9.0.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
//[assembly: AssemblyTitle("Senparc.WebSocket")]
//[assembly: AssemblyDescription("")]
//[assembly: AssemblyConfiguration("")]
//[assembly: AssemblyCompany("")]
//[assembly: AssemblyProduct("Senparc.WebSocket")]
//[assembly: AssemblyCopyright("Copyright © 2018")]
//[assembly: AssemblyTrademark("")]
//[assembly: AssemblyCulture("")]
//将 ComVisible 设置为 false 将使此程序集中的类型
//对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("b745f5f5-9120-4d56-a86d-ed34eadb703c")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.8.3.*")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
fe28b48035fe846ed6d681e153cf93d205567436 | Make the include file adder well known in the interface. We may have to add IncludeFiles too in a bit. | gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT | LINQToTTree/LinqToTTreeInterfacesLib/IGeneratedCode.cs | LINQToTTree/LinqToTTreeInterfacesLib/IGeneratedCode.cs |
namespace LinqToTTreeInterfacesLib
{
/// <summary>
/// Interface for implementing an object that will contain a complete single query
/// </summary>
public interface IGeneratedCode
{
/// <summary>
/// Add a new statement to the current spot where the "writing" currsor is pointed.
/// </summary>
/// <param name="s"></param>
void Add(IStatement s);
/// <summary>
/// Book a variable at the inner most scope
/// </summary>
/// <param name="v"></param>
void Add(IVariable v);
/// <summary>
/// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code
/// (for example, a ROOT object that needs to be written to a TFile).
/// </summary>
/// <param name="v"></param>
void QueueForTransfer(string key, object value);
/// <summary>
/// Returns the outter most coding block
/// </summary>
IBookingStatementBlock CodeBody { get; }
/// <summary>
/// Adds an include file to be included for this query's C++ file.
/// </summary>
/// <param name="filename"></param>
void AddIncludeFile(string filename);
}
}
|
namespace LinqToTTreeInterfacesLib
{
/// <summary>
/// Interface for implementing an object that will contain a complete single query
/// </summary>
public interface IGeneratedCode
{
/// <summary>
/// Add a new statement to the current spot where the "writing" currsor is pointed.
/// </summary>
/// <param name="s"></param>
void Add(IStatement s);
/// <summary>
/// Book a variable at the inner most scope
/// </summary>
/// <param name="v"></param>
void Add(IVariable v);
/// <summary>
/// This variable's inital value is "complex" and must be transfered over the wire in some way other than staight into the code
/// (for example, a ROOT object that needs to be written to a TFile).
/// </summary>
/// <param name="v"></param>
void QueueForTransfer(string key, object value);
/// <summary>
/// Returns the outter most coding block
/// </summary>
IBookingStatementBlock CodeBody { get; }
}
}
| lgpl-2.1 | C# |
5d9353ea75e0ddf6b57e35afc50234208d79f01c | Fix null reference exception when spawning Fungus objects in Unity 5.1 | RonanPearce/Fungus,Nilihum/fungus,lealeelu/Fungus,tapiralec/Fungus,snozbot/fungus,FungusGames/Fungus,inarizushi/Fungus,kdoore/Fungus | Assets/Fungus/Flowchart/Editor/FlowchartMenuItems.cs | Assets/Fungus/Flowchart/Editor/FlowchartMenuItems.cs | using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
namespace Fungus
{
public class FlowchartMenuItems
{
[MenuItem("Tools/Fungus/Create/Flowchart", false, 0)]
static void CreateFlowchart()
{
GameObject go = SpawnPrefab("Flowchart");
go.transform.position = Vector3.zero;
}
public static GameObject SpawnPrefab(string prefabName)
{
GameObject prefab = Resources.Load<GameObject>(prefabName);
if (prefab == null)
{
return null;
}
GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
PrefabUtility.DisconnectPrefabInstance(go);
SceneView view = SceneView.currentDrawingSceneView;
if (view != null)
{
Camera sceneCam = view.camera;
Vector3 pos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f));
pos.z = 0f;
go.transform.position = pos;
}
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Object");
return go;
}
}
} | using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections;
namespace Fungus
{
public class FlowchartMenuItems
{
[MenuItem("Tools/Fungus/Create/Flowchart", false, 0)]
static void CreateFlowchart()
{
GameObject go = SpawnPrefab("Flowchart");
go.transform.position = Vector3.zero;
}
public static GameObject SpawnPrefab(string prefabName)
{
GameObject prefab = Resources.Load<GameObject>(prefabName);
if (prefab == null)
{
return null;
}
GameObject go = PrefabUtility.InstantiatePrefab(prefab) as GameObject;
PrefabUtility.DisconnectPrefabInstance(go);
Camera sceneCam = SceneView.currentDrawingSceneView.camera;
Vector3 pos = sceneCam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 10f));
pos.z = 0f;
go.transform.position = pos;
Selection.activeGameObject = go;
Undo.RegisterCreatedObjectUndo(go, "Create Object");
return go;
}
}
} | mit | C# |
9ceba84de1c1b32fdcf41e378a1487fb90e9c615 | Remove hardcoded service alert | RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server | CorvallisBus.Core/WebClients/ServiceAlertsClient.cs | CorvallisBus.Core/WebClients/ServiceAlertsClient.cs | using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
return alerts;
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
| using System;
using System.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using CorvallisBus.Core.Models;
using HtmlAgilityPack;
namespace CorvallisBus.Core.WebClients
{
public static class ServiceAlertsClient
{
static readonly Uri FEED_URL = new Uri("https://www.corvallisoregon.gov/news?field_microsite_tid=581");
static readonly HttpClient httpClient = new HttpClient();
public static async Task<List<ServiceAlert>> GetServiceAlerts()
{
var responseStream = await httpClient.GetStreamAsync(FEED_URL);
var htmlDocument = new HtmlDocument();
htmlDocument.Load(responseStream);
var alerts = htmlDocument.DocumentNode.SelectNodes("//tbody/tr")
.Select(row => ParseRow(row))
.ToList();
alerts.Insert(0, new ServiceAlert(
title: "App Update for Upcoming CTS Schedule",
publishDate: "2019-09-15T00:00:00-07:00",
link: "https://rikkigibson.github.io/corvallisbus"));
return alerts;
}
private static ServiceAlert ParseRow(HtmlNode row)
{
var anchor = row.Descendants("a").First();
var relativeLink = anchor.Attributes["href"].Value;
var link = new Uri(FEED_URL, relativeLink).ToString();
var title = anchor.InnerText;
var publishDate = row.Descendants("span")
.First(node => node.HasClass("date-display-single"))
.Attributes["content"]
.Value;
return new ServiceAlert(title, publishDate, link);
}
}
}
| mit | C# |
fab5ae8cd30c691506cb614594b133ca7f67cc60 | Increase diagnostic log limit | File-New-Project/EarTrumpet | EarTrumpet/Diagnosis/CircularBufferTraceListener.cs | EarTrumpet/Diagnosis/CircularBufferTraceListener.cs | using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace EarTrumpet.Diagnosis
{
class CircularBufferTraceListener : TraceListener
{
private const int MAX_LOG_LINES = 800;
private readonly ConcurrentQueue<string> _log = new ConcurrentQueue<string>();
private readonly DefaultTraceListener _defaultListener = new DefaultTraceListener();
public override void Write(string message) => Debug.Assert(false);
public override void WriteLine(string message)
{
var threadId = Thread.CurrentThread.ManagedThreadId;
var idText = threadId == 1 ? "UI" : threadId.ToString().PadLeft(2, ' ') + " ";
message = $"{DateTime.Now.ToString("HH:mm:ss.fff")} {idText} {message}";
_log.Enqueue(message + Environment.NewLine);
while (_log.Count > MAX_LOG_LINES)
{
_log.TryDequeue(out var unused);
}
_defaultListener.WriteLine(message);
}
public string GetLogText()
{
var ret = new StringBuilder();
foreach(var line in _log.ToArray())
{
ret.Append(line);
}
return ret.ToString();
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace EarTrumpet.Diagnosis
{
class CircularBufferTraceListener : TraceListener
{
private const int MAX_LOG_LINES = 400;
private readonly ConcurrentQueue<string> _log = new ConcurrentQueue<string>();
private readonly DefaultTraceListener _defaultListener = new DefaultTraceListener();
public override void Write(string message) => Debug.Assert(false);
public override void WriteLine(string message)
{
var threadId = Thread.CurrentThread.ManagedThreadId;
var idText = threadId == 1 ? "UI" : threadId.ToString().PadLeft(2, ' ') + " ";
message = $"{DateTime.Now.ToString("HH:mm:ss.fff")} {idText} {message}";
_log.Enqueue(message + Environment.NewLine);
while (_log.Count > MAX_LOG_LINES)
{
_log.TryDequeue(out var unused);
}
_defaultListener.WriteLine(message);
}
public string GetLogText()
{
var ret = new StringBuilder();
foreach(var line in _log.ToArray())
{
ret.Append(line);
}
return ret.ToString();
}
}
}
| mit | C# |
d8562e3b5da99ce45aeab3f7047dc8a1cc7201a5 | Move variable declaration to the top of method | deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground,deniscostadsc/playground | solutions/beecrowd/1010/1010.cs | solutions/beecrowd/1010/1010.cs | using System;
class Solution {
static void Main() {
int b;
double c, s = 0.0;
string line;
string[] numbers;
while ((line = Console.ReadLine()) != null) {
numbers = line.Split(' ');
b = Convert.ToInt16(numbers[1]);
c = Convert.ToDouble(numbers[2]);
s += c * b;
}
Console.WriteLine("VALOR A PAGAR: R$ {0:F2}", s);
}
}
| using System;
class Solution {
static void Main() {
int b;
double c, s = 0.0;
string line;
while ((line = Console.ReadLine()) != null) {
string[] numbers = line.Split(' ');
b = Convert.ToInt16(numbers[1]);
c = Convert.ToDouble(numbers[2]);
s += c * b;
}
Console.WriteLine("VALOR A PAGAR: R$ {0:F2}", s);
}
}
| mit | C# |
2d73f62f14f04a59e3beac3febb3e9fd312505af | Update Place.cs | ADAPT/ADAPT | source/ADAPT/Logistics/Place.cs | source/ADAPT/Logistics/Place.cs | /*******************************************************************************
* Copyright (C) 2019 AgGateway, ADAPT Contributors, and Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* 20190319: R. Andres Ferreyra - Created class from Traceability WG and PAIL work
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Logistics
{
// Place enables specifying where something is/was/will be, with varying degrees of detail.
// Initially planned for use when specifying actions performed with containers, and With PAIL OM.
public class Place
{
public Place()
{
Id = CompoundIdentifierFactory.Instance.Create();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Description { get; set; }
/// <summary>
/// PlaceType property. </summary>
/// <value>
/// This declares what class the Place is standing in for (e.g., Position, Container, etc. This value is required. Note that "Mixed" is an option.</value>
public PlaceTypeEnum PlaceType { get; set; }
public int? DeviceElementId { get; set; } // Allows associating an observation or ProductContainerOperation to a DeviceElement
public int? ContainerId { get; set; } // Allows associating an observation or ProductContainerOperation to a Container
public int? FarmId { get; set; }
public int? FieldId { get; set; }
public int? CropZoneId { get; set; }
public int? FacilityId { get; set; }
public Location Location { get; set; } // Enables using Locations by reference, like in PAIL and ISO 19112.
/// <summary>
/// ContextItems property. </summary>
/// <value>
/// Optional list of ContextItem objects.</value>
public List<ContextItem> ContextItems { get; set; }
}
}
| /*******************************************************************************
* Copyright (C) 2019 AgGateway, ADAPT Contributors, and Syngenta
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contributors:
* 20190319: R. Andres Ferreyra - Created class from Traceability WG and PAIL work
*******************************************************************************/
using System.Collections.Generic;
using AgGateway.ADAPT.ApplicationDataModel.Common;
using AgGateway.ADAPT.ApplicationDataModel.Shapes;
namespace AgGateway.ADAPT.ApplicationDataModel.Logistics
{
// Place enables specifying where something is/was/will be, with varying degrees of detail.
// Initially planned for use when specifying actions performed with containers, and With PAIL OM.
public class Place
{
public Place()
{
Id = CompoundIdentifierFactory.Instance.Create();
ContextItems = new List<ContextItem>();
}
public CompoundIdentifier Id { get; private set; }
public string Description { get; set; }
/// <summary>
/// PlaceType property. </summary>
/// <value>
/// This declares what class the Place is standing in for (e.g., Position, Container, etc. This value is required. Note that "Mixed" is an option.</value>
public PlaceTypeEnum PlaceType { get; set; }
public int? DeviceElementId { get; set; }
public int? ContainerId { get; set; }
public int? FarmId { get; set; }
public int? FieldId { get; set; }
public int? CropZoneId { get; set; }
public int? FacilityId { get; set; }
public MultiPolygon MultiPolygon { get; set; }
public LineString LineString { get; set; }
public Location Location { get; set; }
public Point Position { get; set; }
/// <summary>
/// ContextItems property. </summary>
/// <value>
/// Optional list of ContextItem objects.</value>
public List<ContextItem> ContextItems { get; set; }
}
} | epl-1.0 | C# |
5c48b0b10e667a52c50d0c346e277c1baf8a5a7c | Update Note | markaschell/SoftwareThresher | code/SoftwareThresher/SoftwareThresher/Tasks/Filter.cs | code/SoftwareThresher/SoftwareThresher/Tasks/Filter.cs | using System.Collections.Generic;
using System.Text.RegularExpressions;
using SoftwareThresher.Observations;
namespace SoftwareThresher.Tasks {
public class Filter : Task {
// TODO - make nullable when the next parameter is added - make sure the nullable is represented in the usage - Either use ? or if get has an implementation
// NOTE - RegEx format
public string LocationSearchPattern { get; set; }
public string ReportTitle { get { return "Items Filtered"; } }
public List<Observation> Execute(List<Observation> observations) {
var regex = new Regex(LocationSearchPattern, RegexOptions.RightToLeft | RegexOptions.Singleline);
return observations.FindAll(o => !regex.IsMatch(o.Location));
}
}
}
| using System.Collections.Generic;
using System.Text.RegularExpressions;
using SoftwareThresher.Observations;
namespace SoftwareThresher.Tasks {
public class Filter : Task {
// TODO - make nullable when the next parameter is added
// NOTE - RegEx format
public string LocationSearchPattern { get; set; }
public string ReportTitle { get { return "Items Filtered"; } }
public List<Observation> Execute(List<Observation> observations) {
var regex = new Regex(LocationSearchPattern, RegexOptions.RightToLeft | RegexOptions.Singleline);
return observations.FindAll(o => !regex.IsMatch(o.Location));
}
}
}
| mit | C# |
0d3842438aae97db9637d099cb54a8fa15ad0ee9 | Format RequireHttpsAttribute | appharbor/ConsolR,appharbor/ConsolR | CodeConsole.Web/Infrastructure/RequireHttpsAttribute.cs | CodeConsole.Web/Infrastructure/RequireHttpsAttribute.cs | using System;
using System.Web.Mvc;
namespace ConsolR.Web.Infrastructure
{
/// <summary>
/// Redirects HTTP requests to HTTPS.</summary>
/// <remarks>
/// Overriding the default behavior is necessary to avoid a redirect loop. See this article for details:
/// http://support.appharbor.com/kb/tips-and-tricks/ssl-and-certificates </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
var header = filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"];
if (string.Equals(header, "https", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
}
| using System;
using System.Web.Mvc;
namespace ConsolR.Web.Infrastructure
{
/// <summary>
/// Redirects HTTP requests to HTTPS.</summary>
/// <remarks>
/// Overriding the default behavior is necessary to avoid a redirect loop. See this article for details:
/// http://support.appharbor.com/kb/tips-and-tricks/ssl-and-certificates </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class RequireHttpsAttribute : System.Web.Mvc.RequireHttpsAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (filterContext.HttpContext.Request.IsSecureConnection)
{
return;
}
var header = filterContext.HttpContext.Request.Headers["X-Forwarded-Proto"];
if (string.Equals(header, "https", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
if (filterContext.HttpContext.Request.IsLocal)
{
return;
}
HandleNonHttpsRequest(filterContext);
}
}
}
| mit | C# |
648e290e55133a2cf3d7452917a7f71570fd7099 | Fix delete tests | visualeyes/cabinet,visualeyes/cabinet,visualeyes/cabinet | src/Cabinet.Tests/S3/Results/DeleteResultFacts.cs | src/Cabinet.Tests/S3/Results/DeleteResultFacts.cs | using Cabinet.S3.Results;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Cabinet.Tests.S3.Results {
public class DeleteResultFacts {
[Theory]
[InlineData(HttpStatusCode.NoContent, true)]
[InlineData(HttpStatusCode.NotFound, false)]
[InlineData(HttpStatusCode.Forbidden, false)]
[InlineData(HttpStatusCode.InternalServerError, false)]
public void Sets_Success(HttpStatusCode code, bool success) {
var result = new DeleteResult(code);
Assert.Equal(success, result.Success);
}
[Fact]
public void Null_Exception_Throws() {
Assert.Throws<ArgumentNullException>(() => new DeleteResult(null));
}
[Fact]
public void Sets_Exception() {
var exception = new Exception("Test");
var result = new DeleteResult(exception);
Assert.False(result.Success);
Assert.Equal(exception, result.Exception);
}
[Theory]
[MemberData("GetExceptionMessages")]
public void Get_Exception_Message(Exception e, string msg) {
var result = new DeleteResult(e);
Assert.Equal(msg, result.GetErrorMessage());
}
public static object[] GetExceptionMessages() {
return new object[] {
new object[] { new Exception(), "System.Exception: Exception of type 'System.Exception' was thrown." },
};
}
}
}
| using Cabinet.S3.Results;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace Cabinet.Tests.S3.Results {
public class DeleteResultFacts {
[Theory]
[InlineData(HttpStatusCode.OK, true)]
[InlineData(HttpStatusCode.NotFound, false)]
[InlineData(HttpStatusCode.Forbidden, false)]
[InlineData(HttpStatusCode.InternalServerError, false)]
public void Sets_Success(HttpStatusCode code, bool success) {
var result = new DeleteResult(code);
Assert.Equal(success, result.Success);
}
[Fact]
public void Null_Exception_Throws() {
Assert.Throws<ArgumentNullException>(() => new DeleteResult(null));
}
[Fact]
public void Sets_Exception() {
var exception = new Exception("Test");
var result = new DeleteResult(exception);
Assert.False(result.Success);
Assert.Equal(exception, result.Exception);
}
[Theory]
[MemberData("GetExceptionMessages")]
public void Get_Exception_Message(Exception e, string msg) {
var result = new DeleteResult(e);
Assert.Equal(msg, result.GetErrorMessage());
}
public static object[] GetExceptionMessages() {
return new object[] {
new object[] { new Exception(), null },
};
}
}
}
| mit | C# |
bf5547d8563b1cf23c625f00a7cdcc1b6a1368e6 | Update StephanosConstantinou.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/StephanosConstantinou.cs | src/Firehose.Web/Authors/StephanosConstantinou.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class StephanosConstantinou : IAmACommunityMember
{
public string FirstName => "Stephanos";
public string LastName => "Constantinou";
public string ShortBioOrTagLine => "Senior System Administrator. I am using PowerShell a lot to perform day to day tasks and automate procedures.";
public string StateOrRegion => "Limassol,Cyprus";
public string EmailAddress => "stephanos@sconstantinou.com";
public string TwitterHandle => "SCPowerShell";
public string GravatarHash => "04de5e0523cf48e9493c11905fd5999f";
public string GitHubHandle => "SConstantinou";
public GeoPosition Position => new GeoPosition(34.706249, 33.022578);
public Uri WebSite => new Uri("https://www.sconstantinou.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.sconstantinou.com/feed/"); } }
public bool Filter(SyndicationItem item)
{
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell scripts"));
return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell tutorials"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class StephanosConstantinou : IAmACommunityMember
{
public string FirstName => "Stephanos";
public string LastName => "Constantinou";
public string ShortBioOrTagLine => "Senior System Administrator. I am using PowerShell a lot to perform day to day tasks and automate procedures.";
public string StateOrRegion => "Limassol,Cyprus";
public string EmailAddress => "stephanos@sconstantinou.com";
public string TwitterHandle => "SCPowerShell";
public string GravatarHash => "04de5e0523cf48e9493c11905fd5999f";
public string GitHubHandle => "SConstantinou";
public GeoPosition Position => new GeoPosition(34.706249, 33.022578);
public Uri WebSite => new Uri("https://www.sconstantinou.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.sconstantinou.com/feed/"); } }
}
}
| mit | C# |
7a4c3c9fb068379587aafbee47ec133444187ad6 | Fix a typo in the GitHub.UI.Reactive assembly title | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.UI.Reactive/Properties/AssemblyInfo.cs | src/GitHub.UI.Reactive/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("GitHub.UI.Reactive")]
[assembly: AssemblyDescription("GitHub flavored WPF styles and controls that require Rx and RxUI")]
[assembly: Guid("885a491c-1d13-49e7-baa6-d61f424befcb")]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: XmlnsDefinition("https://github.com/github/VisualStudio", "GitHub.UI")]
| using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Markup;
[assembly: AssemblyTitle("GitHub.UI.Recative")]
[assembly: AssemblyDescription("GitHub flavored WPF styles and controls that require Rx and RxUI")]
[assembly: Guid("885a491c-1d13-49e7-baa6-d61f424befcb")]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
[assembly: XmlnsDefinition("https://github.com/github/VisualStudio", "GitHub.UI")]
| mit | C# |
3cb3d004d0173a61771d4f0b714414c2d264fb2a | Fix typo. | eealeivan/mixpanel-csharp | src/Mixpanel/Mixpanel/MixpanelBatchMessageTest.cs | src/Mixpanel/Mixpanel/MixpanelBatchMessageTest.cs | using System;
using System.Collections.Generic;
namespace Mixpanel
{
/// <summary>
/// Can be used to check all steps of creating a batch mixpanel messages for
/// MixpanelClient 'Send' and 'SendAsync' methods.
/// </summary>
public sealed class MixpanelBatchMessageTest
{
/// <summary>
/// Message data that was constructed from user input.
/// </summary>
public IList<IDictionary<string, object>> Data { get; internal set; }
/// <summary>
/// <see cref="Data"/> serialized to JSON.
/// </summary>
public string Json { get; internal set; }
/// <summary>
/// <see cref="Json"/> converted to Base64 string.
/// </summary>
public string Base64 { get; internal set; }
/// <summary>
/// Contains the exception if some error occurs during the process of creating a message.
/// </summary>
public Exception Exception { get; internal set; }
}
} | using System;
using System.Collections.Generic;
namespace Mixpanel
{
/// <summary>
/// Can be used to check all steps of creating a batch mixapnel messages for
/// MixpanelClient 'Send' and 'SendAsync' methods.
/// </summary>
public sealed class MixpanelBatchMessageTest
{
/// <summary>
/// Message data that was constructed from user input.
/// </summary>
public IList<IDictionary<string, object>> Data { get; internal set; }
/// <summary>
/// <see cref="Data"/> serialized to JSON.
/// </summary>
public string Json { get; internal set; }
/// <summary>
/// <see cref="Json"/> converted to Base64 string.
/// </summary>
public string Base64 { get; internal set; }
/// <summary>
/// Contains the exception if some error occurs during the process of creating a message.
/// </summary>
public Exception Exception { get; internal set; }
}
} | mit | C# |
1999729687850a5a12549860357d0e10f25cee3d | Use friendly url while sending transfer | leonaascimento/Neblina | src/Neblina.Api/Controllers/TransferController.cs | src/Neblina.Api/Controllers/TransferController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Neblina.Api.Core;
using Neblina.Api.Models.TransferViewModels;
using Neblina.Api.Core.Models;
namespace Neblina.Api.Controllers
{
[Route("transfers")]
public class TransferController : Controller
{
private IUnitOfWork _repos;
private int _accountId;
public TransferController(IUnitOfWork repos)
{
_repos = repos;
_accountId = 1;
}
// POST transfers/send
[HttpPost("send")]
public IActionResult Send(string bank, bool scheduled, [FromBody]SendTransferViewModel transfer)
{
TransactionType type;
switch (bank)
{
case "same":
type = scheduled ? TransactionType.SameBankScheduled : TransactionType.SameBankRealTime;
break;
case "another":
type = scheduled ? TransactionType.AnotherBankScheduled : TransactionType.AnotherBankRealTime;
break;
default:
return NotFound();
}
var transaction = new Transaction()
{
Date = DateTime.Now,
Description = "Transfer sent",
AccountId = _accountId,
DestinationBankId = transfer.DestinationBankId,
DestinationAccountId = transfer.DestinationAccountId,
Amount = transfer.Amount * -1,
Type = type,
Status = TransactionStatus.Pending
};
_repos.Transactions.Add(transaction);
_repos.SaveAndApply();
var receipt = new SendTransferReceiptViewModel()
{
TransactionId = transaction.TransactionId,
DestinationBankId = transfer.DestinationBankId,
DestinationAccountId = transfer.DestinationAccountId,
Amount = transaction.Amount
};
return Ok(receipt);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Neblina.Api.Core;
using Neblina.Api.Models.TransferViewModels;
using Neblina.Api.Core.Models;
namespace Neblina.Api.Controllers
{
[Route("transfers")]
public class TransferController : Controller
{
private IUnitOfWork _repos;
private int _accountId;
public TransferController(IUnitOfWork repos)
{
_repos = repos;
_accountId = 1;
}
// POST transfers/send
[HttpPost("send")]
public IActionResult Send(TransactionType type, [FromBody]SendTransferViewModel transfer)
{
var transaction = new Transaction()
{
Date = DateTime.Now,
Description = "Transfer sent",
AccountId = _accountId,
DestinationBankId = transfer.DestinationBankId,
DestinationAccountId = transfer.DestinationAccountId,
Amount = transfer.Amount * -1,
Type = type,
Status = TransactionStatus.Pending
};
_repos.Transactions.Add(transaction);
_repos.SaveAndApply();
var receipt = new SendTransferReceiptViewModel()
{
TransactionId = transaction.TransactionId,
DestinationBankId = transfer.DestinationBankId,
DestinationAccountId = transfer.DestinationAccountId,
Amount = transaction.Amount
};
return Ok(receipt);
}
}
}
| mit | C# |
526ceef60d6b764643b53f2efb71b487322beabd | Fix a bug that admiral information is not updated. | bllue78/KanColleViewer,GIGAFortress/KanColleViewer,kookxiang/KanColleViewer,lcxit/KanColleViewer,Yuubari/KanColleViewer,BossaGroove/KanColleViewer,gakada/KanColleViewer,kyoryo/test,Astrologers/KanColleViewer,ShunKun/KanColleViewer,balderm/KanColleViewer,stu43005/KanColleViewer,maron8676/KanColleViewer,twinkfrag/KanColleViewer,Yuubari/LegacyKCV,yuyuvn/KanColleViewer,Grabacr07/KanColleViewer,Cosmius/KanColleViewer,gakada/KanColleViewer,ss840429/KanColleViewer,KatoriKai/KanColleViewer,GreenDamTan/KanColleViewer,risingkav/KanColleViewer,the-best-flash/KanColleViewer,fin-alice/KanColleViewer,kbinani/KanColleViewer,nagatoyk/KanColleViewer,soap-DEIM/KanColleViewer,SquallATF/KanColleViewer,about518/KanColleViewer,KCV-Localisation/KanColleViewer,Zharay/KanColleViewer,gakada/KanColleViewer,AnnaKutou/KanColleViewer,heartfelt-fancy/KanColleViewer,hazytint/KanColleViewer | Grabacr07.KanColleViewer/ViewModels/AdmiralViewModel.cs | Grabacr07.KanColleViewer/ViewModels/AdmiralViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper;
using Grabacr07.KanColleWrapper.Models;
using Livet;
using Livet.EventListeners;
namespace Grabacr07.KanColleViewer.ViewModels
{
public class AdmiralViewModel : ViewModel
{
#region Model 変更通知プロパティ
public Admiral Model
{
get { return KanColleClient.Current.Homeport.Admiral; }
}
#endregion
public AdmiralViewModel()
{
this.CompositeDisposable.Add(new PropertyChangedEventListener(KanColleClient.Current.Homeport)
{
{ "Admiral", (sender, args) => this.Update() },
});
}
private void Update()
{
this.RaisePropertyChanged("Model");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Grabacr07.KanColleWrapper;
using Grabacr07.KanColleWrapper.Models;
using Livet;
using Livet.EventListeners;
namespace Grabacr07.KanColleViewer.ViewModels
{
public class AdmiralViewModel : ViewModel
{
#region Model 変更通知プロパティ
public Admiral Model
{
get { return KanColleClient.Current.Homeport.Admiral; }
}
#endregion
public AdmiralViewModel()
{
this.CompositeDisposable.Add(new PropertyChangedEventListener(KanColleClient.Current.Homeport)
{
{"Admiral", (sender, args) => this.Update() },
});
}
private void Update()
{
this.RaisePropertyChanged("Admiral");
}
}
}
| mit | C# |
72b7cc26d8b5fbace8665f995ea61f753b112b03 | Update MicrosoftBannerAdUnitBundle.cs | tiksn/TIKSN-Framework | TIKSN.Core/Advertising/MicrosoftBannerAdUnitBundle.cs | TIKSN.Core/Advertising/MicrosoftBannerAdUnitBundle.cs | namespace TIKSN.Advertising
{
public class MicrosoftBannerAdUnitBundle : MicrosoftAdUnitBundle
{
public static readonly AdUnit MicrosoftTestModeBannerAdUnit = new(AdProviders.Microsoft,
"3f83fe91-d6be-434d-a0ae-7351c5a997f1",
"10865270", true);
public MicrosoftBannerAdUnitBundle(string applicationId, string adUnitId)
: base(MicrosoftTestModeBannerAdUnit, applicationId, adUnitId)
{
}
}
}
| namespace TIKSN.Advertising
{
public class MicrosoftBannerAdUnitBundle : MicrosoftAdUnitBundle
{
public static readonly AdUnit MicrosoftTestModeBannerAdUnit = new AdUnit(AdProviders.Microsoft,
"3f83fe91-d6be-434d-a0ae-7351c5a997f1",
"10865270", true);
public MicrosoftBannerAdUnitBundle(string applicationId, string adUnitId)
: base(MicrosoftTestModeBannerAdUnit, applicationId, adUnitId)
{
}
}
} | mit | C# |
eb85ef69ab5dcc26e1440e4bb205c88cf15dd4c3 | Add DeliveryPointId to RouteLocation | MiXTelematics/MiX.Integrate.Api.Client | MiX.Integrate.Shared/Entities/Journeys/RouteLocation.cs | MiX.Integrate.Shared/Entities/Journeys/RouteLocation.cs | using System;
namespace MiX.Integrate.Shared.Entities.Journeys
{
public class RouteLocation
{
public string RouteId { get; set; }
public int RouteOrder { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool RestStop { get; set; }
public bool FuelStop { get; set; }
public bool LoadingStop { get; set; }
public bool OffLoadingStop { get; set; }
public int StopDuration { get; set; }
public string ReverseGeo { get; set; }
public string LocationId { get; set; }
public long? DeliveryPointId { get; set; }
public string StopActivityInstructions { get; set; }
public DateTimeOffset? DepartureDateTime { get; set; }
public DateTimeOffset? ArrivalDateTime { get; set; }
/// <summary>
/// Copies the entity.
/// </summary>
/// <returns></returns>
public RouteLocation CopyEntity()
{
return (RouteLocation) this.MemberwiseClone();
}
}
}
| using System;
namespace MiX.Integrate.Shared.Entities.Journeys
{
public class RouteLocation
{
public string RouteId { get; set; }
public int RouteOrder { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public bool RestStop { get; set; }
public bool FuelStop { get; set; }
public bool LoadingStop { get; set; }
public bool OffLoadingStop { get; set; }
public int StopDuration { get; set; }
public string ReverseGeo { get; set; }
public string LocationId { get; set; }
public string StopActivityInstructions { get; set; }
public DateTimeOffset? DepartureDateTime { get; set; }
public DateTimeOffset? ArrivalDateTime { get; set; }
/// <summary>
/// Copies the entity.
/// </summary>
/// <returns></returns>
public RouteLocation CopyEntity()
{
return (RouteLocation) this.MemberwiseClone();
}
}
}
| mit | C# |
3cfa4248fee7f00f3936f1f560a86aaba8dc6677 | fix unit test | NiallHow/Software-Eng,M-Zuber/MyHome | MyHome.Infrastructure.Tests/Validation/ContractTests.cs | MyHome.Infrastructure.Tests/Validation/ContractTests.cs | using System;
using MyHome.Infrastructure.Validation;
using NUnit.Framework;
namespace MyHome.Infrastructure.Tests.Validation
{
[TestFixture]
public class ContractTests
{
[Test]
public void Contract_Requires_WithNoMessage_ShouldLeaveNoMessage()
{
// Act
Action failingRequire = () => Contract.Requires<Exception>(false);
// Assert
var message = Assert.Throws<Exception>(() => failingRequire()).Message;
Assert.That(message, Is.Empty);
}
[Test]
public void Contract_Requires_WithMessage_ShouldUseGivenMessage()
{
// Arrange
const string exceptionMessage = "TheExceptionMessage";
// Act
Action failingRequire = () => Contract.Requires<Exception>(false, exceptionMessage);
// Assert
var actualMessage = Assert.Throws<Exception>(() => failingRequire()).Message;
Assert.That(actualMessage, Is.EqualTo(exceptionMessage));
}
}
}
| using System;
using MyHome.Infrastructure.Validation;
using NUnit.Framework;
namespace MyHome.Infrastructure.Tests.Validation
{
[TestFixture]
public class ContractTests
{
[Test]
public void Contract_Requires_WithNoMessage_ShouldLeaveNoMessage()
{
// Act
Action failingRequire = () => Contract.Requires<Exception>(false);
// Assert
var message = Assert.Throws<Exception>(() => failingRequire()).Message;
Assert.That(message, Is.Null);
}
[Test]
public void Contract_Requires_WithMessage_ShouldUseGivenMessage()
{
// Arrange
const string exceptionMessage = "TheExceptionMessage";
// Act
Action failingRequire = () => Contract.Requires<Exception>(false, exceptionMessage);
// Assert
var actualMessage = Assert.Throws<Exception>(() => failingRequire()).Message;
Assert.That(actualMessage, Is.EqualTo(exceptionMessage));
}
}
}
| mit | C# |
15c8341e4a9c8f3d6aca5807c844b2cb1ecf6f43 | Add alias for CreateAppCommand | appharbor/appharbor-cli | src/AppHarbor/Commands/CreateAppCommand.cs | src/AppHarbor/Commands/CreateAppCommand.cs | using System;
using System.Linq;
namespace AppHarbor.Commands
{
[CommandHelp("Create an application", "[NAME]", "create")]
public class CreateAppCommand : ICommand
{
private readonly IAppHarborClient _appHarborClient;
private readonly IApplicationConfiguration _applicationConfiguration;
public CreateAppCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration)
{
_appHarborClient = appHarborClient;
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("An application name must be provided to create an application");
}
var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault());
Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID);
Console.WriteLine("");
try
{
Console.WriteLine("This directory is already configured to track application \"{0}\".",
_applicationConfiguration.GetApplicationId());
}
catch (ApplicationConfigurationException)
{
_applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser());
}
}
}
}
| using System;
using System.Linq;
namespace AppHarbor.Commands
{
[CommandHelp("Create an application", "[NAME]")]
public class CreateAppCommand : ICommand
{
private readonly IAppHarborClient _appHarborClient;
private readonly IApplicationConfiguration _applicationConfiguration;
public CreateAppCommand(IAppHarborClient appHarborClient, IApplicationConfiguration applicationConfiguration)
{
_appHarborClient = appHarborClient;
_applicationConfiguration = applicationConfiguration;
}
public void Execute(string[] arguments)
{
if (arguments.Length == 0)
{
throw new CommandException("An application name must be provided to create an application");
}
var result = _appHarborClient.CreateApplication(arguments.First(), arguments.Skip(1).FirstOrDefault());
Console.WriteLine("Created application \"{0}\" | URL: https://{0}.apphb.com", result.ID);
Console.WriteLine("");
try
{
Console.WriteLine("This directory is already configured to track application \"{0}\".",
_applicationConfiguration.GetApplicationId());
}
catch (ApplicationConfigurationException)
{
_applicationConfiguration.SetupApplication(result.ID, _appHarborClient.GetUser());
}
}
}
}
| mit | C# |
43bfff83a048ff78fe6989f3b874bf048605faba | Update IAnimationSetter.cs | Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,Perspex/Perspex | src/Avalonia.Animation/IAnimationSetter.cs | src/Avalonia.Animation/IAnimationSetter.cs | namespace Avalonia.Animation
{
public interface IAnimationSetter
{
AvaloniaProperty Property { get; set; }
object Value { get; set; }
}
}
| using System;
namespace Avalonia.Animation
{
public interface IAnimationSetter
{
AvaloniaProperty Property { get; set; }
object Value { get; set; }
}
}
| mit | C# |
36667f0afedf9ac596c258375392b66b1a95e57d | fix StringLengthValidator.Min for Body | MehdyKarimpour/extensions,signumsoftware/extensions,AlejandroCano/extensions,MehdyKarimpour/extensions,signumsoftware/extensions,signumsoftware/framework,signumsoftware/framework,AlejandroCano/extensions | Signum.Entities.Extensions/Dynamic/DynamicExpression.cs | Signum.Entities.Extensions/Dynamic/DynamicExpression.cs | using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Entities.Dynamic
{
[Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)]
public class DynamicExpressionEntity : Entity
{
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string Name { get; set; }
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string FromType { get; set; }
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string ReturnType { get; set; }
[NotNullable, SqlDbType(Size = int.MaxValue)]
[StringLengthValidator(AllowNulls = false, Min = 1, MultiLine = true)]
public string Body { get; set; }
public DynamicExpressionTranslation Translation { get; set; }
static Expression<Func<DynamicExpressionEntity, string>> ToStringExpression = @this => @this.ReturnType + " " + @this.Name + "(" + @this.FromType + " e)";
[ExpressionField]
public override string ToString()
{
return ToStringExpression.Evaluate(this);
}
}
public enum DynamicExpressionTranslation
{
TranslateExpressionName,
ReuseTranslationOfReturnType,
NoTranslation,
}
[AutoInit]
public static class DynamicExpressionOperation
{
public static readonly ConstructSymbol<DynamicExpressionEntity>.From<DynamicExpressionEntity> Clone;
public static readonly ExecuteSymbol<DynamicExpressionEntity> Save;
public static readonly DeleteSymbol<DynamicExpressionEntity> Delete;
}
public interface IDynamicExpressionEvaluator
{
object EvaluateUntyped(Entity entity);
}
}
| using Signum.Entities;
using Signum.Entities.Basics;
using Signum.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Signum.Entities.Dynamic
{
[Serializable, EntityKind(EntityKind.Main, EntityData.Transactional)]
public class DynamicExpressionEntity : Entity
{
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string Name { get; set; }
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string FromType { get; set; }
[NotNullable, SqlDbType(Size = 100)]
[StringLengthValidator(AllowNulls = false, Min = 3, Max = 100)]
public string ReturnType { get; set; }
[NotNullable, SqlDbType(Size = int.MaxValue)]
[StringLengthValidator(AllowNulls = false, Min = 3, MultiLine = true)]
public string Body { get; set; }
public DynamicExpressionTranslation Translation { get; set; }
static Expression<Func<DynamicExpressionEntity, string>> ToStringExpression = @this => @this.ReturnType + " " + @this.Name + "(" + @this.FromType + " e)";
[ExpressionField]
public override string ToString()
{
return ToStringExpression.Evaluate(this);
}
}
public enum DynamicExpressionTranslation
{
TranslateExpressionName,
ReuseTranslationOfReturnType,
NoTranslation,
}
[AutoInit]
public static class DynamicExpressionOperation
{
public static readonly ConstructSymbol<DynamicExpressionEntity>.From<DynamicExpressionEntity> Clone;
public static readonly ExecuteSymbol<DynamicExpressionEntity> Save;
public static readonly DeleteSymbol<DynamicExpressionEntity> Delete;
}
public interface IDynamicExpressionEvaluator
{
object EvaluateUntyped(Entity entity);
}
}
| mit | C# |
3fe149a689782de8f1d789627f1b8a38e7086109 | Add category service tests. | markshark05/GForum,markshark05/GForum | GForum/GForum.Services.Tests/CategoryServiceTests.cs | GForum/GForum.Services.Tests/CategoryServiceTests.cs | using System;
using System.Linq;
using GForum.Data.Contracts;
using GForum.Data.Models;
using Moq;
using NUnit.Framework;
namespace GForum.Services.Tests
{
[TestFixture]
public class CategoryServiceTests
{
[Test]
public void Create_ShouldCallRepositoryAddAndUnitOFWorkComplete()
{
// Arrange
var repositoryMock = new Mock<IRepository<Category>>();
var postRepositoryMock = new Mock<IRepository<Post>>();
var unitOfWorkMock = new Mock<IUnitOfWork>();
var postService = new CategoryService(unitOfWorkMock.Object, repositoryMock.Object, postRepositoryMock.Object);
// Act
var result = postService.Create("userid", "title");
// Assert
repositoryMock.Verify(x => x.Add(It.Is<Category>(c =>
c.AuthorId == "userid" &&
c.Title == "title" &&
c.Id != default(Guid))), Times.Once);
}
[Test]
public void Delete_ShouldCallRepositoryDeleteForAllPostsAndUnitOFWorkComplete()
{
// Arrange
var posts = new[] { new Post(), new Post(), new Post() };
var category = new Category { Id = Guid.NewGuid(), Posts = posts };
var categories = new[] { category }.AsQueryable();
var repositoryMock = new Mock<IRepository<Category>>();
repositoryMock.Setup(x => x.QueryAll).Returns(categories);
var postRepositoryMock = new Mock<IRepository<Post>>();
var unitOfWorkMock = new Mock<IUnitOfWork>();
var postService = new CategoryService(unitOfWorkMock.Object, repositoryMock.Object, postRepositoryMock.Object);
// Act
postService.Delete(category.Id);
// Assert
postRepositoryMock.Verify(x => x.Remove(It.IsAny<Post>()), Times.Exactly(posts.Length));
unitOfWorkMock.Verify(x => x.Complete(), Times.Once);
}
[Test]
public void Delete_ShouldNotComplete_IfNoCategoriesAreFound()
{
// Arrange
var repositoryMock = new Mock<IRepository<Category>>();
var postRepositoryMock = new Mock<IRepository<Post>>();
var unitOfWorkMock = new Mock<IUnitOfWork>();
var postService = new CategoryService(unitOfWorkMock.Object, repositoryMock.Object, postRepositoryMock.Object);
// Act
postService.Delete(Guid.Empty);
// Assert
unitOfWorkMock.Verify(x => x.Complete(), Times.Never);
}
}
}
| using System;
using GForum.Data.Contracts;
using GForum.Data.Models;
using Moq;
using NUnit.Framework;
namespace GForum.Services.Tests
{
[TestFixture]
public class CategoryServiceTests
{
[Test]
public void Create_ShouldCallRepositoryAddAndUnitOFWorkComplete()
{
// Arrange
var repositoryMock = new Mock<IRepository<Category>>();
var postRepositoryMock = new Mock<IRepository<Post>>();
var unitOfWorkMock = new Mock<IUnitOfWork>();
var postService = new CategoryService(unitOfWorkMock.Object, repositoryMock.Object, postRepositoryMock.Object);
// Act
var result = postService.Create("userid", "title");
// Assert
repositoryMock.Verify(x => x.Add(It.Is<Category>(c =>
c.AuthorId == "userid" &&
c.Title == "title" &&
c.Id != default(Guid))), Times.Once);
}
}
}
| mit | C# |
b802f11ba32b10630836578c8c199f0ca3824011 | Fix checked, | NuGetPackageExplorer/NuGetPackageExplorer,NuGetPackageExplorer/NuGetPackageExplorer,campersau/NuGetPackageExplorer | PackageViewModel/PackageAnalyzer/PrereleasePackageDependencyRule.cs | PackageViewModel/PackageAnalyzer/PrereleasePackageDependencyRule.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Globalization;
using NuGetPe;
using NuGetPackageExplorer.Types;
using NuGet.Packaging.Core;
namespace PackageExplorerViewModel.Rules
{
[Export(typeof(IPackageRule))]
internal class PrereleasePackageDependencyRule : IPackageRule
{
#region IPackageRule Members
public IEnumerable<PackageIssue> Validate(IPackage package, string packagePath)
{
if (package.Version.IsPrerelease)
{
return new PackageIssue[0];
}
return package.DependencyGroups.SelectMany(p => p.Packages)
.Where(IsPrereleaseDependency)
.Select(CreatePackageIssue);
}
#endregion
private static bool IsPrereleaseDependency(PackageDependency pd)
{
if (pd.VersionRange == null)
{
return false;
}
return pd.VersionRange.MinVersion?.IsPrerelease == true || pd.VersionRange.MaxVersion?.IsPrerelease == true;
}
private static PackageIssue CreatePackageIssue(PackageDependency target)
{
return new PackageIssue(
PackageIssueLevel.Error,
"Invalid prerelease dependency",
String.Format(CultureInfo.CurrentCulture,
"A stable release of a package must not have a dependency on a prerelease package, '{0}'.",
target),
String.Format(CultureInfo.CurrentCulture,
"Either modify the version spec of dependency '{0}' or update the version field.", target)
);
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Globalization;
using NuGetPe;
using NuGetPackageExplorer.Types;
using NuGet.Packaging.Core;
namespace PackageExplorerViewModel.Rules
{
[Export(typeof(IPackageRule))]
internal class PrereleasePackageDependencyRule : IPackageRule
{
#region IPackageRule Members
public IEnumerable<PackageIssue> Validate(IPackage package, string packagePath)
{
if (package.Version.IsPrerelease)
{
return new PackageIssue[0];
}
return package.DependencyGroups.SelectMany(p => p.Packages)
.Where(IsPrereleaseDependency)
.Select(CreatePackageIssue);
}
#endregion
private static bool IsPrereleaseDependency(PackageDependency pd)
{
if (pd.VersionRange == null)
{
return false;
}
return pd.VersionRange.MinVersion.IsPrerelease || pd.VersionRange.MaxVersion.IsPrerelease;
}
private static PackageIssue CreatePackageIssue(PackageDependency target)
{
return new PackageIssue(
PackageIssueLevel.Error,
"Invalid prerelease dependency",
String.Format(CultureInfo.CurrentCulture,
"A stable release of a package must not have a dependency on a prerelease package, '{0}'.",
target),
String.Format(CultureInfo.CurrentCulture,
"Either modify the version spec of dependency '{0}' or update the version field.", target)
);
}
}
} | mit | C# |
ff22aad68d529b79b22d189329d37253f88978cc | Make pagination list result enumerable. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Basic/TraktPaginationListResult.cs | Source/Lib/TraktApiSharp/Objects/Basic/TraktPaginationListResult.cs | namespace TraktApiSharp.Objects.Basic
{
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Represents results of requests supporting pagination.<para />
/// Contains the current page, the item limitation per page, the total page count, the total item count
/// and can also contain the total user count (e.g. in trending shows and movies requests).
/// </summary>
/// <typeparam name="ListItem">The underlying item type of the list results.</typeparam>
public class TraktPaginationListResult<ListItem> : IEnumerable<ListItem>
{
/// <summary>Gets or sets the actual list results.</summary>
public IEnumerable<ListItem> Items { get; set; }
/// <summary>Gets or sets the current page number.</summary>
public int? Page { get; set; }
/// <summary>Gets or sets the item limitation per page.</summary>
public int? Limit { get; set; }
/// <summary>Gets or sets the total page count.</summary>
public int? PageCount { get; set; }
/// <summary>Gets or sets the total item results count.</summary>
public int? ItemCount { get; set; }
/// <summary>
/// Gets or sets the total user count.
/// <para>
/// May be only supported for trending shows and movies requests.
/// </para>
/// </summary>
public int? UserCount { get; set; }
public IEnumerator<ListItem> GetEnumerator()
{
return Items.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| namespace TraktApiSharp.Objects.Basic
{
using System.Collections.Generic;
/// <summary>
/// Represents results of requests supporting pagination.<para />
/// Contains the current page, the item limitation per page, the total page count, the total item count
/// and can also contain the total user count (e.g. in trending shows and movies requests).
/// </summary>
/// <typeparam name="ListItem">The underlying item type of the list results.</typeparam>
public class TraktPaginationListResult<ListItem>
{
/// <summary>Gets or sets the actual list results.</summary>
public IEnumerable<ListItem> Items { get; set; }
/// <summary>Gets or sets the current page number.</summary>
public int? Page { get; set; }
/// <summary>Gets or sets the item limitation per page.</summary>
public int? Limit { get; set; }
/// <summary>Gets or sets the total page count.</summary>
public int? PageCount { get; set; }
/// <summary>Gets or sets the total item results count.</summary>
public int? ItemCount { get; set; }
/// <summary>
/// Gets or sets the total user count.
/// <para>
/// May be only supported for trending shows and movies requests.
/// </para>
/// </summary>
public int? UserCount { get; set; }
}
}
| mit | C# |
0767182ed81969b76a48225ddf036b1c76a140bb | Fix Base Class Property Resolving | Domysee/Pather.CSharp | src/Pather.CSharp/PathElements/Property.cs | src/Pather.CSharp/PathElements/Property.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : PathElementBase
{
private string property;
public Property(string property)
{
this.property = property;
}
public override object Apply(object target)
{
PropertyInfo p = target.GetType().GetRuntimeProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Pather.CSharp.PathElements
{
public class Property : PathElementBase
{
private string property;
public Property(string property)
{
this.property = property;
}
public override object Apply(object target)
{
PropertyInfo p = target.GetType().GetTypeInfo().GetDeclaredProperty(property);
if (p == null)
throw new ArgumentException($"The property {property} could not be found.");
var result = p.GetValue(target);
return result;
}
}
}
| mit | C# |
96e79bfa202e09c1695a6569eaea5fd6b19a7322 | 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.10.2")]
[assembly: AssemblyInformationalVersion("0.10.2")]
/*
* Version 0.10.2
*
* Renames CompositeEnumerables to CompositeEnumerable, which fixes the typo.
*/ | 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.10.1")]
[assembly: AssemblyInformationalVersion("0.10.1")]
/*
* Version 0.10.1
*
* Renames CompositeTestCases to CompositeEnumerables and makes it generic type.
*
* BREAKING-CHANGE
* - Rename: CompositeTestCases -> CompositeEnumerables
* - Make generic type: CompositeEnumerables<T>
*/ | mit | C# |
9f814b1c91c0e2f179ab7aec733213509549f168 | Remove unused property | crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin | SignInCheckIn/SignInCheckIn/Models/DTO/EventRoomDto.cs | SignInCheckIn/SignInCheckIn/Models/DTO/EventRoomDto.cs | using System.Collections.Generic;
namespace SignInCheckIn.Models.DTO
{
public class EventRoomDto
{
public int? EventRoomId { get; set; }
public int RoomId { get; set; }
public int EventId { get; set; }
public string RoomName { get; set; }
public string RoomNumber { get; set; }
public bool AllowSignIn { get; set; }
public int Volunteers { get; set; }
public int Capacity { get; set; }
public int SignedIn { get; set; }
public int CheckedIn { get; set; }
public string Label { get; set; }
public List<AgeGradeDto> AssignedGroups { get; set; }
}
} | using System.Collections.Generic;
using System.Linq;
namespace SignInCheckIn.Models.DTO
{
public class EventRoomDto
{
public int? EventRoomId { get; set; }
public int RoomId { get; set; }
public int EventId { get; set; }
public string RoomName { get; set; }
public string RoomNumber { get; set; }
public bool AllowSignIn { get; set; }
public int Volunteers { get; set; }
public int Capacity { get; set; }
public int SignedIn { get; set; }
public int CheckedIn { get; set; }
public string Label { get; set; }
public List<AgeGradeDto> AssignedGroups { get; set; }
public bool HasSelections()
{
return AssignedGroups != null && AssignedGroups.Any() && AssignedGroups.Exists(g => g.Selected);
}
}
} | bsd-2-clause | C# |
92bf6a8b152e5ac23f8f3a1d551657e4e1548d54 | Modify ShoppingCart to add CreatedUserId property. | v1nc3ntl1/VS-Project,v1nc3ntl1/VS-Project,v1nc3ntl1/VS-Project | WebApplication1/MvcApplication1/Models/ShoppingCart.cs | WebApplication1/MvcApplication1/Models/ShoppingCart.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public class ShoppingCart
{
private string _id = "";
private string _customerId;
private decimal _grossTotal;
private decimal _nettTotal;
private decimal _taxTotal;
public string Id
{
get { return _id;}
set { _id = value; }
}
public string CustomerId
{
get { return _customerId; }
set { _customerId = value; }
}
public decimal GrossTotal
{
get { return _grossTotal; }
set { _grossTotal = value; }
}
public decimal NettTotal
{
get { return _nettTotal; }
set { _nettTotal = value; }
}
public decimal TaxTotal
{
get { return _taxTotal; }
set { _taxTotal = value; }
}
private int _createdUserId;
public int CreatedUserId
{
get { return _createdUserId; }
set { _createdUserId = value; }
}
private Collection<ShoppingCartLineItem> _lineItems;
public Collection<ShoppingCartLineItem> LineItems
{
get { return _lineItems; }
set { _lineItems = value; }
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Linq;
using System.Web;
namespace MvcApplication1.Models
{
public class ShoppingCart
{
private string _id = "";
private string _customerId;
private decimal _grossTotal;
private decimal _nettTotal;
private decimal _taxTotal;
public string Id
{
get { return _id;}
set { _id = value; }
}
public string CustomerId
{
get { return _customerId; }
set { _customerId = value; }
}
public decimal GrossTotal
{
get { return _grossTotal; }
set { _grossTotal = value; }
}
public decimal NettTotal
{
get { return _nettTotal; }
set { _nettTotal = value; }
}
public decimal TaxTotal
{
get { return _taxTotal; }
set { _taxTotal = value; }
}
private Collection<ShoppingCartLineItem> _lineItems;
public Collection<ShoppingCartLineItem> LineItems
{
get { return _lineItems; }
set { _lineItems = value; }
}
}
} | mit | C# |
0ec71e397e1ce1621d73aa2c0a3b824fd65b7199 | Handle string ids when downloading artifacts | ermshiperete/BuildDependency | BuildDependencyLib/Artifacts/ArtifactTemplate.cs | BuildDependencyLib/Artifacts/ArtifactTemplate.cs | // Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using BuildDependency.Artifacts;
using BuildDependency.TeamCity;
using BuildDependency.TeamCity.RestClasses;
using System.IO;
using System.Threading.Tasks;
namespace BuildDependency.Artifacts
{
public class ArtifactTemplate: ArtifactProperties
{
public ArtifactTemplate(Server server, Project project, string buildTypeId)
{
Server = server;
Project = project;
SourceBuildTypeId = buildTypeId;
Condition = Conditions.All;
}
public ArtifactTemplate(Server server, ArtifactProperties artifact)
{
Server = server;
PathRules = artifact.PathRules;
RevisionName = artifact.RevisionName;
RevisionValue = artifact.RevisionValue;
SourceBuildTypeId = artifact.SourceBuildTypeId;
CleanDestinationDirectory = artifact.CleanDestinationDirectory;
Project = ((TeamCityApi)server).Projects[Config.ProjectId];
Condition = Conditions.All;
}
public string ConfigName
{
get
{
return Config.Name;
}
}
public BuildType Config
{
get { return ((TeamCityApi)Server).BuildTypes[SourceBuildTypeId]; }
}
public Conditions Condition { get; set; }
public Project Project { get; set; }
public Server Server { get; set; }
public string RepoUrl
{
get
{
return string.Format("{0}/download/{1}/{2}", ((TeamCityApi)Server).BaseRepoUrl,
Config.IdForArtifacts, RevisionValue);
}
}
public string Source
{
get
{
var source = string.Format("{0}::{1}\n({2})", Server.Name, ConfigName, TagLabel);
if ((Condition & Conditions.All) != Conditions.All && Condition != Conditions.None)
source = string.Format("{0}\nCondition: {1}", source, Condition);
return source;
}
}
public async Task<List<IJob>> GetJobs()
{
var rules = new List<ArtifactRule>();
foreach (var ruleString in PathRules.Split('\n'))
{
if (string.IsNullOrEmpty(ruleString.Trim()))
continue;
rules.Add(new ArtifactRule(Condition, RepoUrl, ruleString));
}
var jobs = new List<IJob>();
var artifacts = await ((TeamCityApi)Server).GetArtifactsAsync(this);
foreach (var file in artifacts)
{
foreach (var rule in rules)
{
var jobsForThisRule = rule.GetJobs(file.ToString());
if (jobsForThisRule != null)
jobs.AddRange(jobsForThisRule);
}
}
return jobs;
}
}
}
| // Copyright (c) 2014 Eberhard Beilharz
// This software is licensed under the MIT license (http://opensource.org/licenses/MIT)
using System;
using System.Collections.Generic;
using BuildDependency.Artifacts;
using BuildDependency.TeamCity;
using BuildDependency.TeamCity.RestClasses;
using System.IO;
using System.Threading.Tasks;
namespace BuildDependency.Artifacts
{
public class ArtifactTemplate: ArtifactProperties
{
public ArtifactTemplate(Server server, Project project, string buildTypeId)
{
Server = server;
Project = project;
SourceBuildTypeId = buildTypeId;
Condition = Conditions.All;
}
public ArtifactTemplate(Server server, ArtifactProperties artifact)
{
Server = server;
PathRules = artifact.PathRules;
RevisionName = artifact.RevisionName;
RevisionValue = artifact.RevisionValue;
SourceBuildTypeId = artifact.SourceBuildTypeId;
CleanDestinationDirectory = artifact.CleanDestinationDirectory;
Project = ((TeamCityApi)server).Projects[Config.ProjectId];
Condition = Conditions.All;
}
public string ConfigName
{
get
{
return Config.Name;
}
}
public BuildType Config
{
get { return ((TeamCityApi)Server).BuildTypes[SourceBuildTypeId]; }
}
public Conditions Condition { get; set; }
public Project Project { get; set; }
public Server Server { get; set; }
public string RepoUrl
{
get
{
return string.Format("{0}/download/{1}/{2}", ((TeamCityApi)Server).BaseRepoUrl, Config.Id, RevisionValue);
}
}
public string Source
{
get
{
var source = string.Format("{0}::{1}\n({2})", Server.Name, ConfigName, TagLabel);
if ((Condition & Conditions.All) != Conditions.All && Condition != Conditions.None)
source = string.Format("{0}\nCondition: {1}", source, Condition);
return source;
}
}
public async Task<List<IJob>> GetJobs()
{
var rules = new List<ArtifactRule>();
foreach (var ruleString in PathRules.Split('\n'))
{
if (string.IsNullOrEmpty(ruleString.Trim()))
continue;
rules.Add(new ArtifactRule(Condition, RepoUrl, ruleString));
}
var jobs = new List<IJob>();
var artifacts = await ((TeamCityApi)Server).GetArtifactsAsync(this);
foreach (var file in artifacts)
{
foreach (var rule in rules)
{
var jobsForThisRule = rule.GetJobs(file.ToString());
if (jobsForThisRule != null)
jobs.AddRange(jobsForThisRule);
}
}
return jobs;
}
}
}
| mit | C# |
d328bd5fe715abb7d2e1e265d28f2dce1ed19ec6 | make backing store read-only | solomobro/Instagram,solomobro/Instagram,solomobro/Instagram | src/Solomobro.Instagram/Ioc.cs | src/Solomobro.Instagram/Ioc.cs | using System;
using System.Collections.Generic;
namespace Solomobro.Instagram
{
/// <summary>
/// Internal-only homegrown IOC container.
/// It's not really meant to make our code more flexible
/// Just makes it possible to substitute some types for unit testing
/// </summary>
internal static class Ioc
{
private static readonly Dictionary<string, object> Substitutes = new Dictionary<string, object>();
/// <summary>
/// Meant to be called within a unit test only
/// DO NOT CALL THIS INSIDE THE LIBRARY
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mockInstance">the mock instance</param>
public static void Substitute<T>(T mockInstance) where T: class
{
if (mockInstance == null)
{
throw new InvalidOperationException("Not allowed to substitute with a null instance");
}
Substitutes[Key<T>()] = mockInstance;
}
public static T Resolve<T>() where T: class
{
object instance;
if (Substitutes.TryGetValue(Key<T>(), out instance))
{
return (T) instance;
}
return null;
}
private static string Key<T>()
{
return (typeof(T)).FullName;
}
}
}
| using System;
using System.Collections.Generic;
namespace Solomobro.Instagram
{
/// <summary>
/// Internal-only homegrown IOC container.
/// It's not really meant to make our code more flexible
/// Just makes it possible to substitute some types for unit testing
/// </summary>
internal static class Ioc
{
private static Dictionary<string, object> _substitutes = new Dictionary<string, object>();
/// <summary>
/// Meant to be called within a unit test only
/// DO NOT CALL THIS INSIDE THE LIBRARY
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="mockInstance">the mock instance</param>
public static void Substitute<T>(T mockInstance) where T: class
{
if (mockInstance == null)
{
throw new InvalidOperationException("Not allowed to substitute with a null instance");
}
_substitutes[Key<T>()] = mockInstance;
}
public static T Resolve<T>() where T: class
{
object instance;
if (_substitutes.TryGetValue(Key<T>(), out instance))
{
return (T) instance;
}
return null;
}
private static string Key<T>()
{
return (typeof(T)).FullName;
}
}
}
| apache-2.0 | C# |
8dce11cf0315cd33fe4712485335c1f72e6b526a | Fix build | ChocoPacker/ChocoPacker.Clr | ChocoPacker.Burn.Tests/ManifestExtensionsTests.cs | ChocoPacker.Burn.Tests/ManifestExtensionsTests.cs | using Xunit;
namespace ChocoPacker.Burn.Tests
{
public class ManifestExtensionsTests
{
[Fact]
public void ParseInstallerInfo_Parse_Proper_Manifest()
{
const string expectedUninstall = "%ALLUSERSPROFILE%\\Package Cache\\{aa4ffaa7-f2a1-40c4-a7b9-e2424e3620f8}\\dotnet-dev-win-x64.1.0.0-rc2-002543.exe";
var resource = TestUtils.ReadXmlResource("ChocoPacker.Burn.Tests.TestData.PrettyManifest.xml");
var installerInfo = resource.ParseInstallerInfo();
Assert.Equal("Microsoft Corporation", installerInfo.Author);
Assert.Equal("Microsoft .NET Core CLI for Windows (1.0.0-rc2-002543)", installerInfo.ProductName);
Assert.Equal("1.0.0.2543", installerInfo.ProductVersion);
Assert.Equal(expectedUninstall, installerInfo.UninstallExecutable);
Assert.Equal("/uninstall /quiet /norestart", installerInfo.UninstallArguments);
}
}
} | using Xunit;
namespace ChocoPacker.Burn.Tests
{
public class ManifestExtensionsTests
{
[Fact]
public void ParseInstallerInfo_Parse_Proper_Manifest()
{
const string expectedUninstall = "%ALLUSERSPROFILE%\\Package Cache\\{aa4ffaa7-f2a1-40c4-a7b9-e2424e3620f8}\\dotnet-dev-win-x64.1.0.0-rc2-002543.exe";
var resource = TestUtils.ReadXmlResource("ChocoPacker.Burn.Tests.TestData.PrettyManifest.xml");
var installerInfo = resource.ParseInstallerInfo();
Assert.Equal("Microsoft Corporation", installerInfo.Author);
Assert.Equal("Microsoft .NET Core CLI for Windows (1.0.0-rc2-002543)", installerInfo.ProductName);
Assert.Equal("1.0.0.2543", installerInfo.ProductVersion);
Assert.Equal(expectedUninstall, installerInfo.UninstallExecutable);
Assert.Equal("/uninstall /quiet /norestart", installerInfo.UninstallArguments)
}
}
} | mit | C# |
93267c81b3523ae4dcd606a2fecd952476b1dc6e | Update FormatPivotTableCells.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET | Examples/CSharp/Articles/FormatPivotTableCells.cs | Examples/CSharp/Articles/FormatPivotTableCells.cs | using System.IO;
using Aspose.Cells;
using Aspose.Cells.Pivot;
using System.Drawing;
namespace Aspose.Cells.Examples.Articles
{
public class FormatPivotTableCells
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir + "pivotTable_test.xlsx";
//Create workbook object from source file containing pivot table
Workbook workbook = new Workbook(filePath);
//Access the worksheet by its name
Worksheet worksheet = workbook.Worksheets["PivotTable"];
//Access the pivot table
PivotTable pivotTable = worksheet.PivotTables[0];
//Create a style object with background color light blue
Style style = workbook.CreateStyle();
style.Pattern = BackgroundType.Solid;
style.BackgroundColor = Color.LightBlue;
//Format entire pivot table with light blue color
pivotTable.FormatAll(style);
//Create another style object with yellow color
style = workbook.CreateStyle();
style.Pattern = BackgroundType.Solid;
style.BackgroundColor = Color.Yellow;
//Format the cells of the first row of the pivot table with yellow color
for (int col = 0; col < 5; col++)
{
pivotTable.Format(1, col, style);
}
//Save the workbook object
workbook.Save(dataDir+ "output.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using Aspose.Cells.Pivot;
using System.Drawing;
namespace Aspose.Cells.Examples.Articles
{
public class FormatPivotTableCells
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
string filePath = dataDir + "pivotTable_test.xlsx";
//Create workbook object from source file containing pivot table
Workbook workbook = new Workbook(filePath);
//Access the worksheet by its name
Worksheet worksheet = workbook.Worksheets["PivotTable"];
//Access the pivot table
PivotTable pivotTable = worksheet.PivotTables[0];
//Create a style object with background color light blue
Style style = workbook.CreateStyle();
style.Pattern = BackgroundType.Solid;
style.BackgroundColor = Color.LightBlue;
//Format entire pivot table with light blue color
pivotTable.FormatAll(style);
//Create another style object with yellow color
style = workbook.CreateStyle();
style.Pattern = BackgroundType.Solid;
style.BackgroundColor = Color.Yellow;
//Format the cells of the first row of the pivot table with yellow color
for (int col = 0; col < 5; col++)
{
pivotTable.Format(1, col, style);
}
//Save the workbook object
workbook.Save(dataDir+ "output.out.xlsx");
}
}
} | mit | C# |
a9e0b4a5431f6b50a57dd55f8b2eb852773f4584 | Fix #669: Отключение оптимизаций StandaloneRunner. | Faithfinder/OneScript,artbear/OneScript,artbear/OneScript,EvilBeaver/OneScript,Faithfinder/OneScript,EvilBeaver/OneScript,artbear/OneScript,dmpas/OneScript,EvilBeaver/OneScript,dmpas/OneScript,dmpas/OneScript,artbear/OneScript,EvilBeaver/OneScript,dmpas/OneScript,artbear/OneScript,Faithfinder/OneScript,EvilBeaver/OneScript,Faithfinder/OneScript | src/StandaloneRunner/Program.cs | src/StandaloneRunner/Program.cs | /*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace StandaloneRunner
{
internal static class Program
{
private static int Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
return Run(args);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static int Run(string[] args)
{
var sp = new StandaloneProcess
{
CommandLineArguments = args
};
return sp.Run();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var resourceName = "StandaloneRunner." + new AssemblyName(args.Name).Name + ".dll";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
var asmData = new byte[stream.Length];
stream.Read(asmData, 0, asmData.Length);
return Assembly.Load(asmData);
}
}
}
} | /*----------------------------------------------------------
This Source Code Form is subject to the terms of the
Mozilla Public License, v.2.0. If a copy of the MPL
was not distributed with this file, You can obtain one
at http://mozilla.org/MPL/2.0/.
----------------------------------------------------------*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace StandaloneRunner
{
internal static class Program
{
private static int Main(string[] args)
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
return Run(args);
}
private static int Run(string[] args)
{
var sp = new StandaloneProcess
{
CommandLineArguments = args
};
return sp.Run();
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var resourceName = "StandaloneRunner." + new AssemblyName(args.Name).Name + ".dll";
using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
{
var asmData = new byte[stream.Length];
stream.Read(asmData, 0, asmData.Length);
return Assembly.Load(asmData);
}
}
}
} | mpl-2.0 | C# |
b3e1e58206faa231c1da202e1ee4343f3d1eedb5 | Send the kerbal when evaing | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | Client/Systems/VesselCrewSys/VesselCrewEvents.cs | Client/Systems/VesselCrewSys/VesselCrewEvents.cs | using LunaClient.Base;
using LunaClient.Systems.Lock;
using LunaClient.Systems.VesselProtoSys;
using LunaClient.Systems.VesselRemoveSys;
using LunaClient.VesselUtilities;
namespace LunaClient.Systems.VesselCrewSys
{
public class VesselCrewEvents : SubSystem<VesselCrewSystem>
{
/// <summary>
/// Event triggered when a kerbal boards a vessel
/// </summary>
public void OnCrewBoard(GameEvents.FromToAction<Part, Part> partAction)
{
LunaLog.Log("Crew boarding detected!");
if (!VesselCommon.IsSpectating)
{
var kerbalVessel = partAction.from.vessel;
var vessel = partAction.to.vessel;
LunaLog.Log($"EVA Boarding. Kerbal: {kerbalVessel.id} ({kerbalVessel.vesselName}) boarding: {vessel.id} ({vessel.vesselName})");
VesselRemoveSystem.Singleton.MessageSender.SendVesselRemove(kerbalVessel.id);
VesselRemoveSystem.Singleton.AddToKillList(kerbalVessel.id, "Killing kerbal as it boarded a vessel");
LockSystem.Singleton.ReleaseAllVesselLocks(new[] { kerbalVessel.vesselName }, kerbalVessel.id);
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(vessel, false);
}
}
/// <summary>
/// The vessel has changed as it has less crew now so send the definition
/// </summary>
public void OnCrewTransfered(GameEvents.HostedFromToAction<ProtoCrewMember, Part> data)
{
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(data.from.vessel, false);
}
/// <summary>
/// The vessel has changed as it has less crew now so send the definition.
/// Also send the definition of the EVA
/// </summary>
public void OnCrewEva(GameEvents.FromToAction<Part, Part> data)
{
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(data.from.vessel, false);
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(data.to.vessel, false);
}
}
}
| using LunaClient.Base;
using LunaClient.Systems.Lock;
using LunaClient.Systems.VesselProtoSys;
using LunaClient.Systems.VesselRemoveSys;
using LunaClient.VesselUtilities;
namespace LunaClient.Systems.VesselCrewSys
{
public class VesselCrewEvents : SubSystem<VesselCrewSystem>
{
/// <summary>
/// Event triggered when a kerbal boards a vessel
/// </summary>
public void OnCrewBoard(GameEvents.FromToAction<Part, Part> partAction)
{
LunaLog.Log("Crew boarding detected!");
if (!VesselCommon.IsSpectating)
{
var kerbalVessel = partAction.from.vessel;
var vessel = partAction.to.vessel;
LunaLog.Log($"EVA Boarding. Kerbal: {kerbalVessel.id} ({kerbalVessel.vesselName}) boarding: {vessel.id} ({vessel.vesselName})");
VesselRemoveSystem.Singleton.MessageSender.SendVesselRemove(kerbalVessel.id);
VesselRemoveSystem.Singleton.AddToKillList(kerbalVessel.id, "Killing kerbal as it boarded a vessel");
LockSystem.Singleton.ReleaseAllVesselLocks(new[] { kerbalVessel.vesselName }, kerbalVessel.id);
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(vessel, false);
}
}
/// <summary>
/// The vessel has changed as it has less crew now so send the definition
/// </summary>
public void OnCrewTransfered(GameEvents.HostedFromToAction<ProtoCrewMember, Part> data)
{
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(data.from.vessel, false);
}
/// <summary>
/// The vessel has changed as it has less crew now so send the definition
/// </summary>
public void OnCrewEva(GameEvents.FromToAction<Part, Part> data)
{
VesselProtoSystem.Singleton.MessageSender.SendVesselMessage(data.from.vessel, false);
}
}
}
| mit | C# |
444aa2a44fbb5ed730c9b2f6fc6d01e418496d27 | Comment Response Added | augustjared1/EntityLINQPractice,augustjared1/EntityLINQPractice | EntityLINQPractice/Controllers/HomeController.cs | EntityLINQPractice/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EntityLINQPractice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//Hey there Jared
//Sup Homeslice
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace EntityLINQPractice.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
//Hey there Jared
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
} | mit | C# |
3bed1c2b57665eff190b42b4e9949aa2ab9c0f17 | Change ISession | jpdante/HTCSharp | Modules/HtcSharp.HttpModule/Http.Features/ISession.cs | Modules/HtcSharp.HttpModule/Http.Features/ISession.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace HtcSharp.HttpModule.Http.Features {
// SourceTools-Start
// Remote-File C:\ASP\src\Http\Http.Features\src\ISession.cs
// Start-At-Remote-Line 9
// Ignore-Local-Line-Range 27-72
// SourceTools-End
public interface ISession {
/// <summary>
/// Indicate whether the current session has loaded.
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// A unique identifier for the current session. This is not the same as the session cookie
/// since the cookie lifetime may not be the same as the session entry lifetime in the data store.
/// </summary>
string Id { get; }
/// <summary>
/// Load the session from the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Store the session in the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the value of the given key, if present.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
bool TryGetValue<T>(string key, out T value);
/// <summary>
/// Set the given key and value in the current session. This will throw if the session
/// was not established prior to sending the response.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void Set<T>(string key, T value);
/// <summary>
/// Set the given key and value in the current session. This will throw if the session
/// was not established prior to sending the response.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="expireSpan"></param>
void Set<T>(string key, T value, TimeSpan expireSpan);
/// <summary>
/// Remove the given key from the session if present.
/// </summary>
/// <param name="key"></param>
void Remove(string key);
/// <summary>
/// Remove all entries from the current session, if any.
/// The session cookie is not removed.
/// </summary>
void Clear();
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace HtcSharp.HttpModule.Http.Features {
// SourceTools-Start
// Remote-File C:\ASP\src\Http\Http.Features\src\ISession.cs
// Start-At-Remote-Line 9
// SourceTools-End
public interface ISession {
/// <summary>
/// Indicate whether the current session has loaded.
/// </summary>
bool IsAvailable { get; }
/// <summary>
/// A unique identifier for the current session. This is not the same as the session cookie
/// since the cookie lifetime may not be the same as the session entry lifetime in the data store.
/// </summary>
string Id { get; }
/// <summary>
/// Enumerates all the keys, if any.
/// </summary>
IEnumerable<string> Keys { get; }
/// <summary>
/// Load the session from the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task LoadAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Store the session in the data store. This may throw if the data store is unavailable.
/// </summary>
/// <returns></returns>
Task CommitAsync(CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the value of the given key, if present.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
bool TryGetValue(string key, out byte[] value);
/// <summary>
/// Set the given key and value in the current session. This will throw if the session
/// was not established prior to sending the response.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
void Set(string key, byte[] value);
/// <summary>
/// Remove the given key from the session if present.
/// </summary>
/// <param name="key"></param>
void Remove(string key);
/// <summary>
/// Remove all entries from the current session, if any.
/// The session cookie is not removed.
/// </summary>
void Clear();
}
} | mit | C# |
aca880d573816388240640401f1d6b5e31b86575 | increase version no | gigya/microdot | Gigya.ServiceContract/Properties/AssemblyInfo.cs | Gigya.ServiceContract/Properties/AssemblyInfo.cs | #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.7.0")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.7.0")]
[assembly: AssemblyFileVersion("2.7.0")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Gigya.Microdot.SharedLogic")] | #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
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("Gigya.ServiceContract")]
[assembly: AssemblyProduct("Gigya.ServiceContract")]
[assembly: InternalsVisibleTo("Gigya.Microdot.ServiceProxy")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("db6d3561-835e-40d5-b9d4-83951cf426df")]
[assembly: AssemblyCompany("Gigya")]
[assembly: AssemblyCopyright("© 2017 Gigya Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyInformationalVersion("2.6.2")]// if pre-release should be in the format of "2.4.11-pre01".
[assembly: AssemblyVersion("2.6.2")]
[assembly: AssemblyFileVersion("2.6.2")]
[assembly: AssemblyDescription("")]
// 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)]
[assembly: CLSCompliant(false)]
[assembly: InternalsVisibleTo("Gigya.Microdot.SharedLogic")] | apache-2.0 | C# |
94f37b3c3f3c9f0d4f2e682bdb86aede7f74947b | Add view for news details route | Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife | PhotoLife/PhotoLife.Web/Views/News/NewsDetails.cshtml | PhotoLife/PhotoLife.Web/Views/News/NewsDetails.cshtml | @model PhotoLife.ViewModels.News.NewsDetailsViewModel
@{
ViewBag.Title = "NewsDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>NewsDetails</h2>
<div>
<h4>NewsDetailsViewModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ImageUrl)
</dt>
<dd>
@Html.DisplayFor(model => model.ImageUrl)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DatePublished)
</dt>
<dd>
@Html.DisplayFor(model => model.DatePublished)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Views)
</dt>
<dd>
@Html.DisplayFor(model => model.Views)
</dd>
</dl>
</div>
@Html.Raw(HttpUtility.HtmlDecode(Model.Text))
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
| @model PhotoLife.ViewModels.News.NewsDetailsViewModel
@{
ViewBag.Title = "NewsDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>NewsDetails</h2>
<div>
<h4>NewsDetailsViewModel</h4>
<hr />
<dl class="dl-horizontal">
<dt>
@Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
@Html.DisplayFor(model => model.Title)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Text)
</dt>
<dd>
@Html.DisplayFor(model => model.Text)
</dd>
<dt>
@Html.DisplayNameFor(model => model.ImageUrl)
</dt>
<dd>
@Html.DisplayFor(model => model.ImageUrl)
</dd>
<dt>
@Html.DisplayNameFor(model => model.DatePublished)
</dt>
<dd>
@Html.DisplayFor(model => model.DatePublished)
</dd>
<dt>
@Html.DisplayNameFor(model => model.Views)
</dt>
<dd>
@Html.DisplayFor(model => model.Views)
</dd>
</dl>
</div>
<p>
@Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
@Html.ActionLink("Back to List", "Index")
</p>
| mit | C# |
7d8a07e703cc87c1fc14b912bbbef0df790c6a0f | Fix KeepAlive Config so that value from appsettings.json is used (#12224) | arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS | src/Umbraco.Core/Configuration/Models/KeepAliveSettings.cs | src/Umbraco.Core/Configuration/Models/KeepAliveSettings.cs | // Copyright (c) Umbraco.
// See LICENSE for more details.
using System.ComponentModel;
namespace Umbraco.Cms.Core.Configuration.Models
{
/// <summary>
/// Typed configuration options for keep alive settings.
/// </summary>
[UmbracoOptions(Constants.Configuration.ConfigKeepAlive)]
public class KeepAliveSettings
{
internal const bool StaticDisableKeepAliveTask = false;
internal const string StaticKeepAlivePingUrl = "~/api/keepalive/ping";
/// <summary>
/// Gets or sets a value indicating whether the keep alive task is disabled.
/// </summary>
[DefaultValue(StaticDisableKeepAliveTask)]
public bool DisableKeepAliveTask { get; set; } = StaticDisableKeepAliveTask;
/// <summary>
/// Gets or sets a value for the keep alive ping URL.
/// </summary>
[DefaultValue(StaticKeepAlivePingUrl)]
public string KeepAlivePingUrl { get; set; } = StaticKeepAlivePingUrl;
}
}
| // Copyright (c) Umbraco.
// See LICENSE for more details.
using System.ComponentModel;
namespace Umbraco.Cms.Core.Configuration.Models
{
/// <summary>
/// Typed configuration options for keep alive settings.
/// </summary>
[UmbracoOptions(Constants.Configuration.ConfigKeepAlive)]
public class KeepAliveSettings
{
internal const bool StaticDisableKeepAliveTask = false;
/// <summary>
/// Gets or sets a value indicating whether the keep alive task is disabled.
/// </summary>
[DefaultValue(StaticDisableKeepAliveTask)]
public bool DisableKeepAliveTask { get; set; } = StaticDisableKeepAliveTask;
/// <summary>
/// Gets a value for the keep alive ping URL.
/// </summary>
public string KeepAlivePingUrl => "~/api/keepalive/ping";
}
}
| mit | C# |
1aa0b5c062f71424b5c0085bbaefa2d0bd851e33 | Remove unnecessary override in AudioResourceDecorator | antonio-bakula/simpleDLNA,itamar82/simpleDLNA,nmaier/simpleDLNA,bra1nb3am3r/simpleDLNA | server/Types/AudioResourceDecorator.cs | server/Types/AudioResourceDecorator.cs | using System;
namespace NMaier.SimpleDlna.Server
{
internal class AudioResourceDecorator : MediaResourceDecorator<IMediaAudioResource>
{
public AudioResourceDecorator(IMediaAudioResource resource)
: base(resource)
{
}
public virtual string MetaAlbum
{
get
{
return resource.MetaAlbum;
}
}
public virtual string MetaArtist
{
get
{
return resource.MetaArtist;
}
}
public virtual string MetaDescription
{
get
{
return resource.MetaDescription;
}
}
public virtual TimeSpan? MetaDuration
{
get
{
return resource.MetaDuration;
}
}
public virtual string MetaGenre
{
get
{
return resource.MetaGenre;
}
}
public virtual string MetaPerformer
{
get
{
return resource.MetaPerformer;
}
}
public virtual int? MetaTrack
{
get
{
return resource.MetaTrack;
}
}
}
}
| using System;
namespace NMaier.SimpleDlna.Server
{
internal class AudioResourceDecorator : MediaResourceDecorator<IMediaAudioResource>
{
public AudioResourceDecorator(IMediaAudioResource resource)
: base(resource)
{
}
virtual public IMediaCoverResource Cover
{
get
{
return resource.Cover;
}
}
public virtual string MetaAlbum
{
get
{
return resource.MetaAlbum;
}
}
public virtual string MetaArtist
{
get
{
return resource.MetaArtist;
}
}
public virtual string MetaDescription
{
get
{
return resource.MetaDescription;
}
}
public virtual TimeSpan? MetaDuration
{
get
{
return resource.MetaDuration;
}
}
public virtual string MetaGenre
{
get
{
return resource.MetaGenre;
}
}
public virtual string MetaPerformer
{
get
{
return resource.MetaPerformer;
}
}
public virtual int? MetaTrack
{
get
{
return resource.MetaTrack;
}
}
}
}
| bsd-2-clause | C# |
71bba88e70f5a88087ac6d45a263273a09424a40 | Increase timeout from 20s to 2 minutes. | nycdotnet/RedGate.AppHost,red-gate/RedGate.AppHost | RedGate.AppHost.Server/StartProcessWithTimeout.cs | RedGate.AppHost.Server/StartProcessWithTimeout.cs | using System;
using System.Diagnostics;
using System.Threading;
namespace RedGate.AppHost.Server
{
internal class StartProcessWithTimeout : IProcessStartOperation
{
private readonly IProcessStartOperation m_WrappedProcessStarter;
private static readonly TimeSpan s_TimeOut = TimeSpan.FromMinutes(2);
public StartProcessWithTimeout(IProcessStartOperation wrappedProcessStarter)
{
if (wrappedProcessStarter == null)
throw new ArgumentNullException("wrappedProcessStarter");
m_WrappedProcessStarter = wrappedProcessStarter;
}
public Process StartProcess(string assemblyName, string remotingId, bool openDebugConsole = false)
{
using (var signal = new EventWaitHandle(false, EventResetMode.ManualReset, remotingId))
{
var process = m_WrappedProcessStarter.StartProcess(assemblyName, remotingId, openDebugConsole);
WaitForReadySignal(signal);
return process;
}
}
private static void WaitForReadySignal(EventWaitHandle signal)
{
if (!signal.WaitOne(s_TimeOut))
throw new ApplicationException("WPF child process didn't respond quickly enough");
}
}
} | using System;
using System.Diagnostics;
using System.Threading;
namespace RedGate.AppHost.Server
{
internal class StartProcessWithTimeout : IProcessStartOperation
{
private readonly IProcessStartOperation m_WrappedProcessStarter;
private static readonly TimeSpan s_TimeOut = TimeSpan.FromSeconds(20);
public StartProcessWithTimeout(IProcessStartOperation wrappedProcessStarter)
{
if (wrappedProcessStarter == null)
throw new ArgumentNullException("wrappedProcessStarter");
m_WrappedProcessStarter = wrappedProcessStarter;
}
public Process StartProcess(string assemblyName, string remotingId, bool openDebugConsole = false)
{
using (var signal = new EventWaitHandle(false, EventResetMode.ManualReset, remotingId))
{
var process = m_WrappedProcessStarter.StartProcess(assemblyName, remotingId, openDebugConsole);
WaitForReadySignal(signal);
return process;
}
}
private static void WaitForReadySignal(EventWaitHandle signal)
{
if (!signal.WaitOne(s_TimeOut))
throw new ApplicationException("WPF child process didn't respond quickly enough");
}
}
} | apache-2.0 | C# |
548d24e0aa692bdb44d13cd5ca1e512ed8c73a16 | Remove incorrect HostingChannel property from TwitchHostedChannel | fedoaa/SimpleTwitchBot | SimpleTwitchBot.Lib/Models/TwitchHostedChannel.cs | SimpleTwitchBot.Lib/Models/TwitchHostedChannel.cs | namespace SimpleTwitchBot.Lib.Models
{
public class TwitchHostedChannel : TwitchMessage
{
public string HosterDisplayName { get; set; }
public bool IsAutohost { get; set; }
public int NumberOfViewers { get; set; }
public string TargetChannel { get; set; }
public TwitchHostedChannel(IrcMessage message)
{
TargetChannel = $"#{message.Channel}";
string jtvMessage = message.Params[1];
IsAutohost = jtvMessage.Contains("auto hosting");
string[] parameters = jtvMessage.Split(' ');
if (int.TryParse(parameters[parameters.Length - 1], out int numberOfViewers))
{
NumberOfViewers = numberOfViewers;
}
HosterDisplayName = parameters[0];
}
}
} | namespace SimpleTwitchBot.Lib.Models
{
public class TwitchHostedChannel : TwitchMessage
{
public string HostingChannel { get; set; }
public string HosterDisplayName { get; set; }
public bool IsAutohost { get; set; }
public int NumberOfViewers { get; set; }
public string TargetChannel { get; set; }
public TwitchHostedChannel(IrcMessage message)
{
TargetChannel = $"#{message.Params[0]}";
string jtvMessage = message.Params[1];
IsAutohost = jtvMessage.Contains("auto hosting");
string[] parameters = jtvMessage.Split(' ');
if (int.TryParse(parameters[parameters.Length - 1], out int numberOfViewers))
{
NumberOfViewers = numberOfViewers;
}
HosterDisplayName = parameters[0];
HostingChannel = $"#{HosterDisplayName.ToLower()}";
}
}
} | mit | C# |
1fc888a32059c7259f83e8924f12edb18a48015e | Add documentation | vdaron/ovhapicil,vdaron/ovhapicil | OVHApi/Commands/Dedicated/Server/Intervention.cs | OVHApi/Commands/Dedicated/Server/Intervention.cs | //
// Intervention.cs
//
// Author:
// Vincent DARON <vda@depfac.com>
//
// Copyright (c) 2013 Vincent DARON
//
// 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 OVHApi.Commands.Dedicated.Server
{
public class Intervention
{
/// <summary>
/// the intervention identifier.
/// </summary>
/// <value>The intervention identifier.</value>
public long InterventionId{ get; internal set;}
/// <summary>
/// the intervention start date.
/// </summary>
/// <value>The date.</value>
public DateTime Date{ get; internal set;}
/// <summary>
/// the intervention type.
/// </summary>
/// <value>The type.</value>
public string Type{ get; internal set;}
}
}
| //
// Intervention.cs
//
// Author:
// Vincent DARON <vda@depfac.com>
//
// Copyright (c) 2013 Vincent DARON
//
// 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 OVHApi.Commands.Dedicated.Server
{
public class Intervention
{
public long InterventionId{ get; set;}
public DateTime Date{ get; set;}
public string Type{ get; set;}
}
}
| mit | C# |
5092f01cfcfa431cac6400bac7463403399d8c0d | Add RegisterTypeForNavigation to IKernel and NinjectModule | ali-hk/Prism,ederbond/Prism,dersia/Prism,allanrsmith/Prism,frogger3d/Prism,hardcodet/Prism,ethedy/Prism | Source/Wpf/Prism.Ninject.Wpf/NinjectExtensions.cs | Source/Wpf/Prism.Ninject.Wpf/NinjectExtensions.cs | using System;
using Ninject;
using Ninject.Modules;
using Ninject.Parameters;
namespace Prism.Ninject
{
public static class NinjectExtensions
{
public static bool IsRegistered<TService>(this IKernel kernel)
{
return kernel.IsRegistered(typeof(TService));
}
public static bool IsRegistered(this IKernel kernel, Type type)
{
return kernel.CanResolve(kernel.CreateRequest(type, _ => true, new IParameter[] { }, false, false));
}
public static void RegisterTypeIfMissing<TFrom, TTo>(this IKernel kernel, bool asSingleton)
{
kernel.RegisterTypeIfMissing(typeof(TFrom), typeof(TTo), asSingleton);
}
public static void RegisterTypeIfMissing(this IKernel kernel, Type from, Type to, bool asSingleton)
{
// Don't do anything if there are already bindings registered
if (kernel.IsRegistered(from))
{
return;
}
// Register the types
var binding = kernel.Bind(from).To(to);
if (asSingleton)
{
binding.InSingletonScope();
}
else
{
binding.InTransientScope();
}
}
public static void RegisterTypeForNavigation<T>(this NinjectModule ninjectModule)
{
ninjectModule.Bind<object>().To<T>().Named(typeof(T).Name);
}
public static void RegisterTypeForNavigation<T>(this IKernel kernel)
{
kernel.Bind<object>().To<T>().Named(typeof(T).Name);
}
}
} | using System;
using Ninject;
using Ninject.Parameters;
namespace Prism.Ninject
{
public static class NinjectExtensions
{
public static bool IsRegistered<TService>(this IKernel kernel)
{
return kernel.IsRegistered(typeof(TService));
}
public static bool IsRegistered(this IKernel kernel, Type type)
{
return kernel.CanResolve(kernel.CreateRequest(type, _ => true, new IParameter[] { }, false, false));
}
public static void RegisterTypeIfMissing<TFrom, TTo>(this IKernel kernel, bool asSingleton)
{
kernel.RegisterTypeIfMissing(typeof(TFrom), typeof(TTo), asSingleton);
}
public static void RegisterTypeIfMissing(this IKernel kernel, Type from, Type to, bool asSingleton)
{
// Don't do anything if there are already bindings registered
if (kernel.IsRegistered(from))
{
return;
}
// Register the types
var binding = kernel.Bind(from).To(to);
if (asSingleton)
{
binding.InSingletonScope();
}
else
{
binding.InTransientScope();
}
}
}
} | apache-2.0 | C# |
48ead7708cbf76a113067bf3423eaa9340248168 | bump version | Fody/Fielder | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fielder")]
[assembly: AssemblyProduct("Fielder")]
[assembly: AssemblyVersion("1.1.5")] | using System.Reflection;
[assembly: AssemblyTitle("Fielder")]
[assembly: AssemblyProduct("Fielder")]
[assembly: AssemblyVersion("1.1.4")] | mit | C# |
48eb07c90ce1128a55689e7ea5c8612a12cb57ae | bump version | dpurge/GitVersion,pascalberger/GitVersion,anobleperson/GitVersion,onovotny/GitVersion,asbjornu/GitVersion,JakeGinnivan/GitVersion,orjan/GitVersion,JakeGinnivan/GitVersion,pascalberger/GitVersion,Philo/GitVersion,TomGillen/GitVersion,TomGillen/GitVersion,alexhardwicke/GitVersion,RaphHaddad/GitVersion,openkas/GitVersion,Kantis/GitVersion,DanielRose/GitVersion,distantcam/GitVersion,ParticularLabs/GitVersion,GitTools/GitVersion,anobleperson/GitVersion,Philo/GitVersion,GeertvanHorrik/GitVersion,onovotny/GitVersion,distantcam/GitVersion,gep13/GitVersion,JakeGinnivan/GitVersion,onovotny/GitVersion,Kantis/GitVersion,DanielRose/GitVersion,pascalberger/GitVersion,ermshiperete/GitVersion,Kantis/GitVersion,asbjornu/GitVersion,anobleperson/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,RaphHaddad/GitVersion,dpurge/GitVersion,MarkZuber/GitVersion,alexhardwicke/GitVersion,openkas/GitVersion,FireHost/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,dazinator/GitVersion,orjan/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,ParticularLabs/GitVersion,dazinator/GitVersion,JakeGinnivan/GitVersion,ermshiperete/GitVersion,GeertvanHorrik/GitVersion,MarkZuber/GitVersion,dpurge/GitVersion,FireHost/GitVersion | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("GitFlowVersion")]
[assembly: AssemblyProduct("GitFlowVersion")]
[assembly: AssemblyVersion("0.3.0")]
[assembly: AssemblyFileVersion("0.3.0")]
[assembly: InternalsVisibleTo("Tests")]
| using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("GitFlowVersion")]
[assembly: AssemblyProduct("GitFlowVersion")]
[assembly: AssemblyVersion("0.2.0")]
[assembly: AssemblyFileVersion("0.2.0")]
[assembly: InternalsVisibleTo("Tests")]
| mit | C# |
c6405bec35e2d1f0ae3915cfdc5bdc8400e1890c | bump version | Fody/Obsolete | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Obsolete")]
[assembly: AssemblyProduct("Obsolete")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
[assembly: AssemblyTitle("Obsolete")]
[assembly: AssemblyProduct("Obsolete")]
[assembly: AssemblyVersion("0.10.0.0")]
[assembly: AssemblyFileVersion("0.10.0.0")]
| mit | C# |
83705f7256ed9000fb5df77dbd985742f81deadb | Fix manual plugin unattended mode (#573) | Lone-Coder/letsencrypt-win-simple | letsencrypt-win-simple/Plugins/TargetPlugins/Manual.cs | letsencrypt-win-simple/Plugins/TargetPlugins/Manual.cs | using LetsEncrypt.ACME.Simple.Services;
using System.Collections.Generic;
using System.Linq;
namespace LetsEncrypt.ACME.Simple.Plugins.TargetPlugins
{
class Manual : ManualPlugin, ITargetPlugin
{
string IHasName.Name
{
get
{
return nameof(Manual);
}
}
string ITargetPlugin.Description
{
get
{
return "Manually input host names";
}
}
Target ITargetPlugin.Default(Options options)
{
if (!string.IsNullOrEmpty(options.ManualHost))
{
var fqdns = ParseSanList(options.ManualHost);
if (fqdns != null)
{
return new Target()
{
PluginName = nameof(Manual),
Host = fqdns.First(),
WebRootPath = options.WebRoot,
AlternativeNames = fqdns
};
}
}
return null;
}
Target ITargetPlugin.Aquire(Options options)
{
return InputTarget(nameof(Manual), new[] { "Enter a site path (the web root of the host for http authentication)" });
}
Target ITargetPlugin.Refresh(Options options, Target scheduled)
{
return scheduled;
}
}
} | using LetsEncrypt.ACME.Simple.Services;
using System.Collections.Generic;
using System.Linq;
namespace LetsEncrypt.ACME.Simple.Plugins.TargetPlugins
{
class Manual : ManualPlugin, ITargetPlugin
{
string IHasName.Name
{
get
{
return nameof(Manual);
}
}
string ITargetPlugin.Description
{
get
{
return "Manually input host names";
}
}
Target ITargetPlugin.Default(Options options)
{
if (!string.IsNullOrEmpty(options.ManualHost))
{
var fqdns = ParseSanList(options.ManualHost);
if (fqdns != null)
{
return new Target()
{
Host = fqdns.First(),
WebRootPath = options.WebRoot,
AlternativeNames = fqdns
};
}
}
return null;
}
Target ITargetPlugin.Aquire(Options options)
{
return InputTarget(nameof(Manual), new[] { "Enter a site path (the web root of the host for http authentication)" });
}
Target ITargetPlugin.Refresh(Options options, Target scheduled)
{
return scheduled;
}
}
} | apache-2.0 | C# |
46b3eddfe8df1656eea73192b458ffe1c90e4331 | Update VTexFormat | SteamDatabase/ValveResourceFormat | ValveResourceFormat/Resource/Enums/VTexFormat.cs | ValveResourceFormat/Resource/Enums/VTexFormat.cs | using System;
namespace ValveResourceFormat
{
public enum VTexFormat
{
#pragma warning disable 1591
UNKNOWN = 0,
DXT1 = 1,
DXT5 = 2,
I8 = 3,
RGBA8888 = 4,
R16 = 5,
RG1616 = 6,
RGBA16161616 = 7,
R16F = 8,
RG1616F = 9,
RGBA16161616F = 10,
R32F = 11,
RG3232F = 12,
RGB323232F = 13,
RGBA32323232F = 14,
JPEG_RGBA8888 = 15,
PNG_RGBA8888 = 16,
JPEG_DXT5 = 17,
PNG_DXT5 = 18,
BC6H = 19,
BC7 = 20,
ATI2N = 21,
IA88 = 22,
ETC2 = 23,
ETC2_EAC = 24,
R11_EAC = 25,
RG11_EAC = 26,
ATI1N = 27,
#pragma warning restore 1591
}
}
| using System;
namespace ValveResourceFormat
{
public enum VTexFormat
{
#pragma warning disable 1591
UNKNOWN = 0,
DXT1 = 1,
DXT5 = 2,
I8 = 3,
RGBA8888 = 4,
R16 = 5,
RG1616 = 6,
RGBA16161616 = 7,
R16F = 8,
RG1616F = 9,
RGBA16161616F = 10,
R32F = 11,
RG3232F = 12,
RGB323232F = 13,
RGBA32323232F = 14,
PNG = 16, // TODO: resourceinfo doesn't know about this
JPG = 17,
PNG2 = 18, // TODO: Why is there PNG twice?
IA88 = 22,
#pragma warning restore 1591
}
}
| mit | C# |
1008a539e1ac52a0ce12ef80c701acff842880b1 | Remove debug statement | eggapauli/MyDocs,eggapauli/MyDocs | Common.Test/ViewModel/RenameCategoryCommandTest.cs | Common.Test/ViewModel/RenameCategoryCommandTest.cs | using FakeItEasy;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyDocs.Common.Contract.Service;
using System.Threading.Tasks;
namespace MyDocs.Common.Test.ViewModel
{
public partial class DocumentViewModelTest
{
[TestMethod]
public void RenamingCategoryShouldBeDisabledWhenCategoryNameIsEmpty()
{
var sut = CreateSut();
sut.NewCategoryName = "";
sut.RenameCategoryCommand.CanExecute(null).Should().BeFalse();
}
[TestMethod]
public void RenamingCategoryCommandShouldBeEnabledWhenCategoryNameIsSet()
{
var sut = CreateSut();
sut.NewCategoryName = "New category";
sut.RenameCategoryCommand.CanExecute(null).Should().BeTrue();
}
[TestMethod]
public void ViewModelShouldCallServiceMethodWhenRenamingCategory()
{
const string oldCategoryName = "Old category";
const string newCategoryName = "New category";
var documentService = A.Fake<IDocumentService>();
var sut = CreateSut(documentService: documentService);
sut.NewCategoryName = newCategoryName;
using (Fake.CreateScope())
{
sut.RenameCategoryCommand.Execute(new Model.View.Category(oldCategoryName));
A.CallTo(() => documentService.RenameCategoryAsync(oldCategoryName, newCategoryName)).MustHaveHappened();
}
}
[TestMethod]
public void ViewModelShouldBeBusyWhileRenamingCategories()
{
var tcs = new TaskCompletionSource<object>();
var documentService = A.Fake<IDocumentService>();
A.CallTo(() => documentService.RenameCategoryAsync(A<string>._, A<string>._)).Returns(tcs.Task);
var sut = CreateSut(documentService: documentService);
sut.NewCategoryName = "New category";
sut.IsBusy.Should().BeFalse();
sut.RenameCategoryCommand.Execute(new Model.View.Category("Old category"));
sut.IsBusy.Should().BeTrue();
tcs.SetResult(null);
sut.IsBusy.Should().BeFalse();
}
}
}
| using FakeItEasy;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MyDocs.Common.Contract.Service;
using System.Threading.Tasks;
namespace MyDocs.Common.Test.ViewModel
{
public partial class DocumentViewModelTest
{
[TestMethod]
public void RenamingCategoryShouldBeDisabledWhenCategoryNameIsEmpty()
{
var sut = CreateSut();
sut.NewCategoryName = "";
sut.RenameCategoryCommand.CanExecute(null).Should().BeFalse();
}
[TestMethod]
public void RenamingCategoryCommandShouldBeEnabledWhenCategoryNameIsSet()
{
var sut = CreateSut();
sut.NewCategoryName = "New category";
sut.RenameCategoryCommand.CanExecute(null).Should().BeTrue();
}
[TestMethod]
public void ViewModelShouldCallServiceMethodWhenRenamingCategory()
{
const string oldCategoryName = "Old category";
const string newCategoryName = "New category";
var documentService = A.Fake<IDocumentService>();
var sut = CreateSut(documentService: documentService);
sut.NewCategoryName = newCategoryName;
using (Fake.CreateScope())
{
sut.RenameCategoryCommand.Execute(new Model.View.Category(oldCategoryName));
A.CallTo(() => documentService.RenameCategoryAsync(oldCategoryName, newCategoryName)).MustHaveHappened();
}
}
[TestMethod]
public void ViewModelShouldBeBusyWhileRenamingCategories()
{
System.Diagnostics.Debugger.Break();
var tcs = new TaskCompletionSource<object>();
var documentService = A.Fake<IDocumentService>();
A.CallTo(() => documentService.RenameCategoryAsync(A<string>._, A<string>._)).Returns(tcs.Task);
var sut = CreateSut(documentService: documentService);
sut.NewCategoryName = "New category";
sut.IsBusy.Should().BeFalse();
sut.RenameCategoryCommand.Execute(new Model.View.Category("Old category"));
sut.IsBusy.Should().BeTrue();
tcs.SetResult(null);
sut.IsBusy.Should().BeFalse();
}
}
}
| mit | C# |
0938c9882a9bffa089f72fb04091c4207e8578cb | Change calling convention of ImGuiInputTextCallback | mellinoe/ImGui.NET,mellinoe/ImGui.NET | src/ImGui.NET/ImGuiTextEditCallback.cs | src/ImGui.NET/ImGuiTextEditCallback.cs | using System.Runtime.InteropServices;
namespace ImGuiNET
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public unsafe delegate int ImGuiInputTextCallback(ImGuiInputTextCallbackData* data);
}
| namespace ImGuiNET
{
public unsafe delegate int ImGuiInputTextCallback(ImGuiInputTextCallbackData* data);
}
| mit | C# |
d461ce149f6216326c510a1efc99c005e390af98 | Add try/catch on subscriber | northspb/RawRabbit,pardahlman/RawRabbit | src/RawRabbit/Operations/Subscriber.cs | src/RawRabbit/Operations/Subscriber.cs | using System;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using RabbitMQ.Client.Events;
using RawRabbit.Common;
using RawRabbit.Configuration.Subscribe;
using RawRabbit.Context;
using RawRabbit.Context.Provider;
using RawRabbit.Serialization;
namespace RawRabbit.Operations
{
public interface ISubscriber<out TMessageContext> where TMessageContext : IMessageContext
{
Task SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config);
}
public class Subscriber<TMessageContext> : OperatorBase, ISubscriber<TMessageContext> where TMessageContext : IMessageContext
{
private readonly IMessageContextProvider<TMessageContext> _contextProvider;
public Subscriber(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider)
: base(channelFactory, serializer)
{
_contextProvider = contextProvider;
}
public Task SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config)
{
var queueTask = DeclareQueueAsync(config.Queue);
var exchangeTask = DeclareExchangeAsync(config.Exchange);
return Task
.WhenAll(queueTask, exchangeTask)
.ContinueWith(t => BindQueue(config.Queue, config.Exchange, config.RoutingKey))
.ContinueWith(t => SubscribeAsync<T>(config, subscribeMethod));
}
private Task SubscribeAsync<T>(SubscriptionConfiguration config, Func<T, TMessageContext, Task> subscribeMethod)
{
return Task.Run(() =>
{
var channel = ChannelFactory.GetChannel();
ConfigureQosAsync(channel, config.PrefetchCount);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var bodyTask = Task.Run(() => Serializer.Deserialize<T>(ea.Body));
var contextTask = _contextProvider.ExtractContextAsync(ea.BasicProperties.Headers[_contextProvider.ContextHeaderName]);
Task
.WhenAll(bodyTask, contextTask)
.ContinueWith(task =>
{
Task subscribeTask;
try
{
subscribeTask = subscribeMethod(bodyTask.Result, contextTask.Result);
}
catch (Exception)
{
return;
// TODO: error handling here.
}
subscribeTask
.ContinueWith(t=> BasicAck(channel, ea.DeliveryTag));
});
};
channel.BasicConsume(
queue: config.Queue.QueueName,
noAck: config.NoAck,
consumer: consumer
);
});
}
}
}
| using System;
using System.Threading.Tasks;
using RabbitMQ.Client.Events;
using RawRabbit.Common;
using RawRabbit.Configuration.Subscribe;
using RawRabbit.Context;
using RawRabbit.Context.Provider;
using RawRabbit.Serialization;
namespace RawRabbit.Operations
{
public interface ISubscriber<out TMessageContext> where TMessageContext : IMessageContext
{
Task SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config);
}
public class Subscriber<TMessageContext> : OperatorBase, ISubscriber<TMessageContext> where TMessageContext : IMessageContext
{
private readonly IMessageContextProvider<TMessageContext> _contextProvider;
public Subscriber(IChannelFactory channelFactory, IMessageSerializer serializer, IMessageContextProvider<TMessageContext> contextProvider)
: base(channelFactory, serializer)
{
_contextProvider = contextProvider;
}
public Task SubscribeAsync<T>(Func<T, TMessageContext, Task> subscribeMethod, SubscriptionConfiguration config)
{
var queueTask = DeclareQueueAsync(config.Queue);
var exchangeTask = DeclareExchangeAsync(config.Exchange);
return Task
.WhenAll(queueTask, exchangeTask)
.ContinueWith(t => BindQueue(config.Queue, config.Exchange, config.RoutingKey))
.ContinueWith(t => SubscribeAsync<T>(config, subscribeMethod));
}
private Task SubscribeAsync<T>(SubscriptionConfiguration config, Func<T, TMessageContext, Task> subscribeMethod)
{
return Task.Run(() =>
{
var channel = ChannelFactory.GetChannel();
ConfigureQosAsync(channel, config.PrefetchCount);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var bodyTask = Task.Run(() => Serializer.Deserialize<T>(ea.Body));
var contextTask = _contextProvider.ExtractContextAsync(ea.BasicProperties.Headers[_contextProvider.ContextHeaderName]);
Task
.WhenAll(bodyTask, contextTask)
.ContinueWith(task =>
{
subscribeMethod(bodyTask.Result, contextTask.Result)
.ContinueWith(subscribeTask => BasicAck(channel, ea.DeliveryTag));
});
};
channel.BasicConsume(
queue: config.Queue.QueueName,
noAck: config.NoAck,
consumer: consumer
);
});
}
}
}
| mit | C# |
c135fe60fc2b3cda522978bf680441cdf60e06a4 | bump version | ParticularLabs/SetStartupProjects | src/SetStartupProjects/AssemblyInfo.cs | src/SetStartupProjects/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("SetStartupProjects")]
[assembly: AssemblyProduct("SetStartupProjects")]
[assembly: AssemblyCopyright("Copyright © NServiceBus Ltd")]
[assembly: AssemblyVersion("1.3.0")]
[assembly: AssemblyFileVersion("1.3.0")]
[assembly: InternalsVisibleTo("Tests")] | using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("SetStartupProjects")]
[assembly: AssemblyProduct("SetStartupProjects")]
[assembly: AssemblyCopyright("Copyright © NServiceBus Ltd")]
[assembly: AssemblyVersion("1.2.4")]
[assembly: AssemblyFileVersion("1.2.4")]
[assembly: InternalsVisibleTo("Tests")] | mit | C# |
5f0f9634441da53fbcb5179a4ecfa03f0f35c048 | Update test RP to include client id in change email / password links | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/TestRP/Views/Shared/_Layout.cshtml | src/TestRP/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test relying party</title>
</head>
<body>
<div>
@if (User.Identity.IsAuthenticated)
{
<span><a href="https://localhost:44334/account/changeemail?clientid=testrp&returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Email</a></span>
<span><a href="https://localhost:44334/account/changepassword?clientid=testrp&returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Password</a></span>
<span><a href="@Url.Action("Logout", "Home")">Logout</a></span>
}
else
{
<span><a href="@Url.Action("Login", "Home")">Login</a></span>
}
</div>
<div>
@RenderBody()
</div>
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test relying party</title>
</head>
<body>
<div>
@if (User.Identity.IsAuthenticated)
{
<span><a href="https://localhost:44334/account/changeemail?returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Email</a></span>
<span><a href="https://localhost:44334/account/changepassword?returnUrl=@Url.Action("Index", "Home", null, Request.Url.Scheme)">Change Password</a></span>
<span><a href="@Url.Action("Logout", "Home")">Logout</a></span>
}
else
{
<span><a href="@Url.Action("Login", "Home")">Login</a></span>
}
</div>
<div>
@RenderBody()
</div>
</body>
</html>
| mit | C# |
1d109c6ca436c64dd1b067b0fe4f3a785a2ac18f | Update FitAllWorksheetColumns.cs | aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/FitAllWorksheetColumns.cs | Examples/CSharp/Articles/FitAllWorksheetColumns.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class FitAllWorksheetColumns
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create and initialize an instance of Workbook
Workbook book = new Workbook(dataDir + "TestBook.xlsx");
//Create and initialize an instance of PdfSaveOptions
PdfSaveOptions saveOptions = new PdfSaveOptions(SaveFormat.Pdf);
//Set AllColumnsInOnePagePerSheet to true
saveOptions.AllColumnsInOnePagePerSheet = true;
//Save Workbook to PDF fromart by passing the object of PdfSaveOptions
book.Save(dataDir+ "output.out.pdf", saveOptions);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class FitAllWorksheetColumns
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Create and initialize an instance of Workbook
Workbook book = new Workbook(dataDir + "TestBook.xlsx");
//Create and initialize an instance of PdfSaveOptions
PdfSaveOptions saveOptions = new PdfSaveOptions(SaveFormat.Pdf);
//Set AllColumnsInOnePagePerSheet to true
saveOptions.AllColumnsInOnePagePerSheet = true;
//Save Workbook to PDF fromart by passing the object of PdfSaveOptions
book.Save(dataDir+ "output.out.pdf", saveOptions);
//ExEnd:1
}
}
}
| mit | C# |
e7e431b8ccaed667bf5186599781e9ee52380106 | make Summa.Net.Feed.Parse() work correctly | wfarr/newskit,wfarr/newskit | src/Summa/Summa.Net/Feed.cs | src/Summa/Summa.Net/Feed.cs | using System;
using System.Xml;
namespace Summa {
namespace Net {
public static class Feed {
public static Summa.Data.Parser.FeedParser Sniff(Summa.Net.Request request) {
Summa.Data.Parser.FeedParser parser = null;
try {
parser = new Summa.Data.Parser.AtomParser(request.Uri, request.Xml);
} catch ( Exception e ) {}
if ( parser != null ) {
if ( parser.Name == null ) {
try {
parser = new Summa.Data.Parser.RssParser(request.Uri, request.Xml);
} catch ( Exception e ) {}
}
} else {
try {
parser = new Summa.Data.Parser.RssParser(request.Uri, request.Xml);
} catch ( Exception e ) {}
}
if ( parser != null ) {
if ( parser.Name == null ) {
return null;
} else {
return parser;
}
} else {
return null;
}
}
}
}
}
| using System;
using System.Xml;
namespace Summa {
namespace Net {
public static class Feed {
public static Summa.Data.Parser.FeedParser Sniff(Summa.Net.Request request) {
Summa.Data.Parser.FeedParser parser = null;
//try {
parser = new Summa.Data.Parser.AtomParser(request.Uri, request.Xml);
return parser;
//} catch ( Exception e ) {}
if ( parser != null ) {
if ( parser.Name == null ) {
try {
parser = new Summa.Data.Parser.RssParser(request.Uri, request.Xml);
} catch ( Exception e ) {}
}
} else {
try {
parser = new Summa.Data.Parser.RssParser(request.Uri, request.Xml);
} catch ( Exception e ) {}
}
if ( parser != null ) {
if ( parser.Name == null ) {
return null;
} else {
return parser;
}
} else {
return null;
}
}
}
}
}
| mit | C# |
efc343283f022f9d35851627852a6c377a96d880 | Mark methods as virtual | scottbrady91/ScottBrady91.AspNetCore.Identity.BCryptPasswordHasher | src/ScottBrady91.AspNetCore.Identity.BCryptPasswordHasher/BCryptPasswordHasher.cs | src/ScottBrady91.AspNetCore.Identity.BCryptPasswordHasher/BCryptPasswordHasher.cs | using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace ScottBrady91.AspNetCore.Identity
{
public class BCryptPasswordHasher<TUser> : IPasswordHasher<TUser> where TUser : class
{
private readonly BCryptPasswordHasherOptions options;
public BCryptPasswordHasher(IOptions<BCryptPasswordHasherOptions> optionsAccessor = null)
{
options = optionsAccessor?.Value ?? new BCryptPasswordHasherOptions();
}
public virtual string HashPassword(TUser user, string password)
{
if (password == null) throw new ArgumentNullException(nameof(password));
return BCrypt.Net.BCrypt.HashPassword(password, options.WorkFactor, options.EnhancedEntropy);
}
public virtual PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
{
if (hashedPassword == null) throw new ArgumentNullException(nameof(hashedPassword));
if (providedPassword == null) throw new ArgumentNullException(nameof(providedPassword));
var isValid = BCrypt.Net.BCrypt.Verify(providedPassword, hashedPassword, options.EnhancedEntropy);
return isValid ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed;
}
}
}
| using System;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace ScottBrady91.AspNetCore.Identity
{
public class BCryptPasswordHasher<TUser> : IPasswordHasher<TUser> where TUser : class
{
private readonly BCryptPasswordHasherOptions options;
public BCryptPasswordHasher(IOptions<BCryptPasswordHasherOptions> optionsAccessor = null)
{
options = optionsAccessor?.Value ?? new BCryptPasswordHasherOptions();
}
public string HashPassword(TUser user, string password)
{
if (password == null) throw new ArgumentNullException(nameof(password));
return BCrypt.Net.BCrypt.HashPassword(password, options.WorkFactor, options.EnhancedEntropy);
}
public PasswordVerificationResult VerifyHashedPassword(TUser user, string hashedPassword, string providedPassword)
{
if (hashedPassword == null) throw new ArgumentNullException(nameof(hashedPassword));
if (providedPassword == null) throw new ArgumentNullException(nameof(providedPassword));
var isValid = BCrypt.Net.BCrypt.Verify(providedPassword, hashedPassword, options.EnhancedEntropy);
return isValid ? PasswordVerificationResult.Success : PasswordVerificationResult.Failed;
}
}
} | mit | C# |
d2e9c167317fa7bc6c66f3fb7c5b0dca8c7da813 | Fix compilation warning. | Microsoft/ApplicationInsights-SDK-Labs | WCF/Shared.Tests/ClientExceptionExtensionsTests.cs | WCF/Shared.Tests/ClientExceptionExtensionsTests.cs | using Microsoft.ApplicationInsights.Wcf.Implementation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf.Tests
{
[TestClass]
public class ClientExceptionExtensionsTests
{
[TestMethod]
public void When_ExceptionIsNull_ExceptionIsThrown()
{
bool failed = false;
try
{
ClientExceptionExtensions.ToResultCode(null);
} catch ( ArgumentNullException )
{
failed = true;
}
Assert.IsTrue(failed, "ToResultCode() did not throw ArgumentNullException");
}
[TestMethod]
public void When_TimeoutException()
{
TestException<TimeoutException>("Timeout");
}
[TestMethod]
public void When_EndpointNotFoundException()
{
TestException<EndpointNotFoundException>("EndpointNotFound");
}
[TestMethod]
public void When_ServerTooBusyException()
{
TestException<ServerTooBusyException>("ServerTooBusy");
}
[TestMethod]
public void When_FaultException()
{
TestException<FaultException>("SoapFault");
}
[TestMethod]
public void When_OtherException()
{
TestException<ChannelTerminatedException>("ChannelTerminatedException");
}
private void TestException<TException>(string expected) where TException : Exception, new()
{
var ex = new TException();
Assert.AreEqual(expected, ex.ToResultCode());
}
}
}
| using Microsoft.ApplicationInsights.Wcf.Implementation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ServiceModel;
namespace Microsoft.ApplicationInsights.Wcf.Tests
{
[TestClass]
public class ClientExceptionExtensionsTests
{
[TestMethod]
public void When_ExceptionIsNull_ExceptionIsThrown()
{
bool failed = false;
try
{
ClientExceptionExtensions.ToResultCode(null);
} catch (ArgumentNullException ex)
{
failed = true;
}
Assert.IsTrue(failed, "ToResultCode() did not throw ArgumentNullException");
}
[TestMethod]
public void When_TimeoutException()
{
TestException<TimeoutException>("Timeout");
}
[TestMethod]
public void When_EndpointNotFoundException()
{
TestException<EndpointNotFoundException>("EndpointNotFound");
}
[TestMethod]
public void When_ServerTooBusyException()
{
TestException<ServerTooBusyException>("ServerTooBusy");
}
[TestMethod]
public void When_FaultException()
{
TestException<FaultException>("SoapFault");
}
[TestMethod]
public void When_OtherException()
{
TestException<ChannelTerminatedException>("ChannelTerminatedException");
}
private void TestException<TException>(string expected) where TException : Exception, new()
{
var ex = new TException();
Assert.AreEqual(expected, ex.ToResultCode());
}
}
}
| mit | C# |
08c96757782995bc45e3b557fa019bcf7da6be79 | Make XNAControls internals visible to XNAControls.Test | ethanmoffat/XNAControls | Properties/AssemblyInfo.cs | 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("XNAControls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XNAControls")]
[assembly: AssemblyCopyright("Copyright © Ethan Moffat 2014-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("8314a04c-752e-49fb-828d-40ef66d2ce39")]
// 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("XNAControls.Test")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XNAControls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XNAControls")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("8314a04c-752e-49fb-828d-40ef66d2ce39")]
// 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# |
b1f09d2f169d56fb9ba9c90a2c283fec5d50d1ee | comment out ToString for StringBuilder, there is no need for plug anymore | sgetaz/Cosmos,trivalik/Cosmos,Cyber4/Cosmos,sgetaz/Cosmos,fanoI/Cosmos,zdimension/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,tgiphil/Cosmos,zhangwenquan/Cosmos,zarlo/Cosmos,kant2002/Cosmos-1,fanoI/Cosmos,kant2002/Cosmos-1,zhangwenquan/Cosmos,zdimension/Cosmos,kant2002/Cosmos-1,MetSystem/Cosmos,Cyber4/Cosmos,Cyber4/Cosmos,MyvarHD/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,zhangwenquan/Cosmos,Cyber4/Cosmos,zarlo/Cosmos,sgetaz/Cosmos,fanoI/Cosmos,zdimension/Cosmos,MetSystem/Cosmos,MetSystem/Cosmos,sgetaz/Cosmos,zarlo/Cosmos,MyvarHD/Cosmos,MetSystem/Cosmos,trivalik/Cosmos,trivalik/Cosmos,sgetaz/Cosmos,zhangwenquan/Cosmos,CosmosOS/Cosmos,zhangwenquan/Cosmos,MyvarHD/Cosmos,zdimension/Cosmos,Cyber4/Cosmos,kant2002/Cosmos-1,MyvarHD/Cosmos,zdimension/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,MyvarHD/Cosmos,MetSystem/Cosmos,jp2masa/Cosmos,jp2masa/Cosmos | source2/IL2CPU/Cosmos.IL2CPU/CustomImplementation/System/Text/StringBuilderImpl.cs | source2/IL2CPU/Cosmos.IL2CPU/CustomImplementation/System/Text/StringBuilderImpl.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.IL2CPU.CustomImplementation.System.Text
{
// no need for plug, after 64 bit support
//[Plug(Target = typeof(StringBuilder))]
//public static class StringBuilderImpl
//{
// public static string ToString(StringBuilder aThis)
// {
// var xResult = new char[aThis.Length];
// int xLength = aThis.Length;
// for (int i = 0; i < xLength; i++)
// {
// xResult[i] = aThis[i];
// }
// var xResultStr = new String(xResult);
// return xResultStr;
// }
//}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cosmos.IL2CPU.Plugs;
namespace Cosmos.IL2CPU.CustomImplementation.System.Text
{
[Plug(Target = typeof(StringBuilder))]
public static class StringBuilderImpl
{
public static string ToString(StringBuilder aThis)
{
var xResult = new char[aThis.Length];
int xLength = aThis.Length;
for (int i = 0; i < xLength; i++)
{
xResult[i] = aThis[i];
}
var xResultStr = new String(xResult);
return xResultStr;
}
}
}
| bsd-3-clause | C# |
0f760b9ff725115c8b12cfa62d78936277aadfc5 | fix else statements, and add line num and pos for error | ilovepi/Compiler,ilovepi/Compiler | compiler/frontend/Parser.cs | compiler/frontend/Parser.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
int lineno;
int pos;
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {
error();
}
}
public void error(string str)
{
//TODO: determine location in file for error messages
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file for error messages
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else {
error();
}
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {error();
}
}
public void error(string str)
{
//TODO: determine location in file for error messages
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else error();
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
| mit | C# |
e1251c7d65c65f60013229b5abd95cc2f8e477b8 | Fix double Ergo auth request header problem | coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore,coinfoundry/miningcore | src/Miningcore/Blockchain/Ergo/ErgoClientExtensions.cs | src/Miningcore/Blockchain/Ergo/ErgoClientExtensions.cs | using System.Text;
namespace Miningcore.Blockchain.Ergo;
public partial class ErgoClient
{
public Dictionary<string, string> RequestHeaders { get; } = new();
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, StringBuilder url, CancellationToken ct)
{
foreach(var pair in RequestHeaders)
request.Headers.Add(pair.Key, pair.Value);
return Task.CompletedTask;
}
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, String url, CancellationToken ct)
{
return Task.CompletedTask;
}
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, string url)
{
return Task.CompletedTask;
}
private static Task ProcessResponseAsync(HttpClient client, HttpResponseMessage response, CancellationToken ct)
{
return Task.CompletedTask;
}
}
| using System.Text;
namespace Miningcore.Blockchain.Ergo;
public partial class ErgoClient
{
public Dictionary<string, string> RequestHeaders { get; } = new();
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, StringBuilder url, CancellationToken ct)
{
foreach(var pair in RequestHeaders)
request.Headers.Add(pair.Key, pair.Value);
return Task.CompletedTask;
}
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, String url, CancellationToken ct)
{
foreach(var pair in RequestHeaders)
request.Headers.Add(pair.Key, pair.Value);
return Task.CompletedTask;
}
private Task PrepareRequestAsync(HttpClient client, HttpRequestMessage request, string url)
{
return Task.CompletedTask;
}
private static Task ProcessResponseAsync(HttpClient client, HttpResponseMessage response, CancellationToken ct)
{
return Task.CompletedTask;
}
}
| mit | C# |
ab8223f0059e272a5a7aafa8b327d7f09a271c91 | Update SceneManager. | cmilr/Unity2D-Components,jguarShark/Unity2D-Components | Scene/SceneManager.cs | Scene/SceneManager.cs | using UnityEngine;
using System.Collections;
using DG.Tweening;
using Matcha.Game.Tweens;
public class SceneManager : CacheBehaviour {
// private SceneData sData;
private float timeToFade = 2f;
private float fadeInAfter = 0f;
private float fadeOutAfter = 2f;
private float timeBeforeLevelReload = 3f;
void Start()
{
// sData = GameObject.Find("_SceneData").GetComponent<SceneData>();
spriteRenderer.DOKill();
MTween.FadeInSprite(spriteRenderer, fadeInAfter, timeToFade);
Messenger.Broadcast<int>("set groundline", -50);
}
void OnLoadLevel(int newLevel)
{
MTween.FadeOutSprite(spriteRenderer, fadeOutAfter, timeToFade);
StartCoroutine(Timer.Start(timeBeforeLevelReload, true, () =>
{
Application.LoadLevel("Scene" + newLevel);
System.GC.Collect();
}));
}
void OnEnable()
{
Messenger.AddListener<int>( "load level", OnLoadLevel);
}
void OnDestroy()
{
Messenger.RemoveListener<int>( "load level", OnLoadLevel);
}
}
| using UnityEngine;
using System.Collections;
using DG.Tweening;
using Matcha.Game.Tweens;
public class SceneManager : CacheBehaviour {
// private SceneData data;
private float timeToFade = 2f;
private float fadeInAfter = 0f;
private float fadeOutAfter = 2f;
private float timeBeforeLevelReload = 3f;
void Start()
{
// data = GameObject.Find("_SceneData").GetComponent<SceneData>();
spriteRenderer.DOKill();
MTween.FadeInSprite(spriteRenderer, fadeInAfter, timeToFade);
Messenger.Broadcast<int>("set groundline", -50);
}
void OnLoadLevel(int newLevel)
{
MTween.FadeOutSprite(spriteRenderer, fadeOutAfter, timeToFade);
StartCoroutine(Timer.Start(timeBeforeLevelReload, true, () =>
{
Application.LoadLevel("Scene" + newLevel);
System.GC.Collect();
}));
}
void OnEnable()
{
Messenger.AddListener<int>( "load level", OnLoadLevel);
}
void OnDestroy()
{
Messenger.RemoveListener<int>( "load level", OnLoadLevel);
}
}
| mit | C# |
9df4674ee529d28ce6bfa67f1bb666b44dfc18ed | Make property attributes public in IR | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Razor.Evolution/Intermediate/SetTagHelperPropertyIRNode.cs | src/Microsoft.AspNetCore.Razor.Evolution/Intermediate/SetTagHelperPropertyIRNode.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.Evolution.Legacy;
namespace Microsoft.AspNetCore.Razor.Evolution.Intermediate
{
public class SetTagHelperPropertyIRNode : RazorIRNode
{
public override IList<RazorIRNode> Children { get; } = new List<RazorIRNode>();
public override RazorIRNode Parent { get; set; }
public override SourceSpan? Source { get; set; }
public string TagHelperTypeName { get; set; }
public string PropertyName { get; set; }
public string AttributeName { get; set; }
internal HtmlAttributeValueStyle ValueStyle { get; set; }
public TagHelperAttributeDescriptor Descriptor { get; set; }
public override void Accept(RazorIRNodeVisitor visitor)
{
if (visitor == null)
{
throw new ArgumentNullException(nameof(visitor));
}
visitor.VisitSetTagHelperProperty(this);
}
public override TResult Accept<TResult>(RazorIRNodeVisitor<TResult> visitor)
{
if (visitor == null)
{
throw new ArgumentNullException(nameof(visitor));
}
return visitor.VisitSetTagHelperProperty(this);
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Razor.Evolution.Legacy;
namespace Microsoft.AspNetCore.Razor.Evolution.Intermediate
{
public class SetTagHelperPropertyIRNode : RazorIRNode
{
public override IList<RazorIRNode> Children { get; } = new List<RazorIRNode>();
public override RazorIRNode Parent { get; set; }
public override SourceSpan? Source { get; set; }
public string TagHelperTypeName { get; set; }
public string PropertyName { get; set; }
public string AttributeName { get; set; }
internal HtmlAttributeValueStyle ValueStyle { get; set; }
internal TagHelperAttributeDescriptor Descriptor { get; set; }
public override void Accept(RazorIRNodeVisitor visitor)
{
if (visitor == null)
{
throw new ArgumentNullException(nameof(visitor));
}
visitor.VisitSetTagHelperProperty(this);
}
public override TResult Accept<TResult>(RazorIRNodeVisitor<TResult> visitor)
{
if (visitor == null)
{
throw new ArgumentNullException(nameof(visitor));
}
return visitor.VisitSetTagHelperProperty(this);
}
}
}
| apache-2.0 | C# |
46828843c560b42d7c18616c25da63a180807b39 | Update dotnet tests for 3.1.302. | OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | tests/OmniSharp.Tests/DotNetCliServiceFacts.cs | tests/OmniSharp.Tests/DotNetCliServiceFacts.cs | using OmniSharp.Services;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Tests
{
public class DotNetCliServiceFacts : AbstractTestFixture
{
public DotNetCliServiceFacts(ITestOutputHelper output)
: base(output)
{
}
[Fact]
public void GetVersion()
{
using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current))
{
var dotNetCli = host.GetExport<IDotNetCliService>();
var version = dotNetCli.GetVersion();
Assert.Equal(3, version.Major);
Assert.Equal(1, version.Minor);
Assert.Equal(302, version.Patch);
Assert.Equal("", version.Release);
}
}
[Fact]
public void GetInfo()
{
using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current))
{
var dotNetCli = host.GetExport<IDotNetCliService>();
var info = dotNetCli.GetInfo();
Assert.Equal(3, info.Version.Major);
Assert.Equal(1, info.Version.Minor);
Assert.Equal(302, info.Version.Patch);
Assert.Equal("", info.Version.Release);
}
}
}
}
| using OmniSharp.Services;
using TestUtility;
using Xunit;
using Xunit.Abstractions;
namespace OmniSharp.Tests
{
public class DotNetCliServiceFacts : AbstractTestFixture
{
public DotNetCliServiceFacts(ITestOutputHelper output)
: base(output)
{
}
[Fact]
public void GetVersion()
{
using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current))
{
var dotNetCli = host.GetExport<IDotNetCliService>();
var version = dotNetCli.GetVersion();
Assert.Equal(3, version.Major);
Assert.Equal(1, version.Minor);
Assert.Equal(201, version.Patch);
Assert.Equal("", version.Release);
}
}
[Fact]
public void GetInfo()
{
using (var host = CreateOmniSharpHost(dotNetCliVersion: DotNetCliVersion.Current))
{
var dotNetCli = host.GetExport<IDotNetCliService>();
var info = dotNetCli.GetInfo();
Assert.Equal(3, info.Version.Major);
Assert.Equal(1, info.Version.Minor);
Assert.Equal(201, info.Version.Patch);
Assert.Equal("", info.Version.Release);
}
}
}
}
| mit | C# |
3f2b0d63c92b0ccbb124c4af73db8fa88381bbd7 | Change the order of properties and methods. | CountrySideEngineer/Ev3Controller | dev/src/Ev3Controller/Model/PeriodicCommandRoutine.cs | dev/src/Ev3Controller/Model/PeriodicCommandRoutine.cs | using Ev3Controller.Ev3Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Ev3Controller.Model
{
public class PeriodicCommandRoutine : CommandRoutine
{
#region Constructors and the Finalizer
/// <summary>
/// Constructor.
/// Setup command to send in the routine.
/// </summary>
public PeriodicCommandRoutine()
{
this.CommandQueue = new Queue<ACommand>();
this.CommandQueue.Enqueue(new Command_06_00());
this.CommandQueue.Enqueue(new Command_0C_00());
this.CommandQueue.Enqueue(new Command_12_00());
this.CommandQueue.Enqueue(new Command_16_00());
this.CommandQueue.Enqueue(new Command_10_01());
this.CommandQueue.Enqueue(new Command_F0_00());
}
#endregion
#region Public Properties
public Queue<ACommand> CommandQueue { get; protected set; }
#endregion
#region Other methods and private properties in calling order
/// <summary>
/// Method to run periodic command routine.
/// </summary>
/// <param name="ComPortAcc">ComPortAccess class contains COM port abstract object.</param>
/// <param name="Sequence">Sequence class to run routine.</param>
/// <param name="TimerCount">Passed time.</param>
/// <returns></returns>
public override bool Routine(
ComPortAccess ComPortAcc,
ComPortSendRecvSequence Sequence,
int TimerCount = 0)
{
foreach (ACommand Command in this.CommandQueue)
{
Thread.Sleep(1);
Command.UpdateCmdData();
try
{
Sequence.SendAndRecvRoutine(ComPortAcc, Command);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return false;
}
#endregion
}
}
| using Ev3Controller.Ev3Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Ev3Controller.Model
{
public class PeriodicCommandRoutine : CommandRoutine
{
/// <summary>
/// Constructor.
/// Setup command to send in the routine.
/// </summary>
public PeriodicCommandRoutine()
{
this.CommandQueue = new Queue<ACommand>();
this.CommandQueue.Enqueue(new Command_06_00());
this.CommandQueue.Enqueue(new Command_0C_00());
this.CommandQueue.Enqueue(new Command_12_00());
this.CommandQueue.Enqueue(new Command_16_00());
this.CommandQueue.Enqueue(new Command_10_01());
this.CommandQueue.Enqueue(new Command_F0_00());
}
/// <summary>
/// Method to run periodic command routine.
/// </summary>
/// <param name="ComPortAcc">ComPortAccess class contains COM port abstract object.</param>
/// <param name="Sequence">Sequence class to run routine.</param>
/// <param name="TimerCount">Passed time.</param>
/// <returns></returns>
public override bool Routine(
ComPortAccess ComPortAcc,
ComPortSendRecvSequence Sequence,
int TimerCount = 0)
{
foreach (ACommand Command in this.CommandQueue)
{
Thread.Sleep(1);
Command.UpdateCmdData();
try
{
Sequence.SendAndRecvRoutine(ComPortAcc, Command);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
return false;
}
public Queue<ACommand> CommandQueue { get; protected set; }
}
}
| mit | C# |
ff903b1efdb4cb7610c597db74bb8237f0c0ae99 | Add FindFocusedControl method | fredatgithub/UsefulFunctions | FonctionsUtiles.Fred.Csharp/FunctionsApplicationFeatures.cs | FonctionsUtiles.Fred.Csharp/FunctionsApplicationFeatures.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsApplicationFeatures
{
public static string GetStartupPath()
{
try
{
if (string.IsNullOrEmpty(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)))
{
return string.Empty;
}
return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
catch (Exception)
{
return string.Empty;
}
}
private static Control FindFocusedControl(IEnumerable<Control> container)
{
return container.FirstOrDefault(control => control.Focused);
}
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System;
using System.IO;
using System.Reflection;
namespace FonctionsUtiles.Fred.Csharp
{
public class FunctionsApplicationFeatures
{
public static string GetStartupPath()
{
try
{
if (string.IsNullOrEmpty(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)))
{
return string.Empty;
}
else
{
return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
}
catch (Exception)
{
return string.Empty;
}
}
}
} | mit | C# |
b6ce997b454019e1f57b76d712943cce1554e7ab | Disable check on MacOS. | dlemstra/Magick.NET,dlemstra/Magick.NET | tests/Magick.NET.Tests/Shared/Settings/MagickSettingsTests/TheFontFamilyProperty.cs | tests/Magick.NET.Tests/Shared/Settings/MagickSettingsTests/TheFontFamilyProperty.cs | // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontFamilyProperty
{
[Fact]
public void ShouldChangeTheFont()
{
using (var image = new MagickImage())
{
Assert.Null(image.Settings.FontFamily);
Assert.Equal(0, image.Settings.FontPointsize);
Assert.Equal(FontStyleType.Undefined, image.Settings.FontStyle);
Assert.Equal(FontWeight.Undefined, image.Settings.FontWeight);
image.Settings.FontFamily = "Courier New";
image.Settings.FontPointsize = 40;
image.Settings.FontStyle = FontStyleType.Oblique;
image.Settings.FontWeight = FontWeight.ExtraBold;
image.Read("label:Test");
Assert.Contains(image.Width, new[] { 97, 98 });
Assert.Equal(48, image.Height);
// Different result on MacOS
if (image.Width != 97)
ColorAssert.Equal(MagickColors.Black, image, 13, 13);
}
}
}
}
}
| // Copyright 2013-2020 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/>
//
// Licensed under the ImageMagick License (the "License"); you may not use this file except in
// compliance with the License. You may obtain a copy of the License at
//
// https://www.imagemagick.org/script/license.php
//
// 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 ImageMagick;
using Xunit;
namespace Magick.NET.Tests
{
public partial class MagickSettingsTests
{
public class TheFontFamilyProperty
{
[Fact]
public void ShouldChangeTheFont()
{
using (var image = new MagickImage())
{
Assert.Null(image.Settings.FontFamily);
Assert.Equal(0, image.Settings.FontPointsize);
Assert.Equal(FontStyleType.Undefined, image.Settings.FontStyle);
Assert.Equal(FontWeight.Undefined, image.Settings.FontWeight);
image.Settings.FontFamily = "Courier New";
image.Settings.FontPointsize = 40;
image.Settings.FontStyle = FontStyleType.Oblique;
image.Settings.FontWeight = FontWeight.ExtraBold;
image.Read("label:Test");
Assert.Contains(image.Width, new[] { 97, 98 });
Assert.Equal(48, image.Height);
ColorAssert.Equal(MagickColors.Black, image, 13, 13);
}
}
}
}
}
| apache-2.0 | C# |
a358c0459ff59f7d054a2bd514e079221afa3d3f | add using | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey.ExpenseServices.Azure.Shared/AzureFileStorageService.cs | client/BlueMonkey/BlueMonkey.ExpenseServices.Azure.Shared/AzureFileStorageService.cs | using BlueMonkey.MediaServices;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;
namespace BlueMonkey.ExpenseServices.Azure
{
public class AzureFileStorageService : IFileStorageService
{
private static readonly string ContainerName = "pictures";
private readonly CloudBlobContainer _container;
public AzureFileStorageService()
{
var account = CloudStorageAccount.Parse(Secrets.FileUploadStorageConnectionString);
var client = account.CreateCloudBlobClient();
_container = client.GetContainerReference(ContainerName);
}
public async Task<IMediaFile> DownloadMediaFileAsync(Uri uri)
{
await _container.CreateIfNotExistsAsync();
await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var fileName = Path.GetFileName(uri.AbsolutePath);
var blockBlob = _container.GetBlockBlobReference(fileName);
using (var ms = new MemoryStream())
{
await blockBlob.DownloadToStreamAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
return new MediaFile(Path.GetExtension(fileName), ms.ToArray());
}
}
public async Task<Uri> UploadMediaFileAsync(IMediaFile mediaFile)
{
await _container.CreateIfNotExistsAsync();
await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var fileName = $"{Guid.NewGuid()}{mediaFile.Extension}";
var blockBlob = _container.GetBlockBlobReference(fileName);
using (var stream = mediaFile.GetStream())
{
await blockBlob.UploadFromStreamAsync(stream);
}
return blockBlob.Uri;
}
}
}
| using BlueMonkey.MediaServices;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.IO;
using System.Threading.Tasks;
namespace BlueMonkey.ExpenseServices.Azure
{
public class AzureFileStorageService : IFileStorageService
{
private static readonly string ContainerName = "pictures";
private readonly CloudBlobContainer _container;
public AzureFileStorageService()
{
var account = CloudStorageAccount.Parse(Secrets.FileUploadStorageConnectionString);
var client = account.CreateCloudBlobClient();
_container = client.GetContainerReference(ContainerName);
}
public async Task<IMediaFile> DownloadMediaFileAsync(Uri uri)
{
await _container.CreateIfNotExistsAsync();
await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var fileName = Path.GetFileName(uri.AbsolutePath);
var blockBlob = _container.GetBlockBlobReference(fileName);
var ms = new MemoryStream();
await blockBlob.DownloadToStreamAsync(ms);
ms.Seek(0, SeekOrigin.Begin);
return new MediaFile(Path.GetExtension(fileName), ms.ToArray());
}
public async Task<Uri> UploadMediaFileAsync(IMediaFile mediaFile)
{
await _container.CreateIfNotExistsAsync();
await _container.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
var fileName = $"{Guid.NewGuid()}{mediaFile.Extension}";
var blockBlob = _container.GetBlockBlobReference(fileName);
using (var stream = mediaFile.GetStream())
{
await blockBlob.UploadFromStreamAsync(stream);
}
return blockBlob.Uri;
}
}
}
| mit | C# |
2bacb6003f3bc2c3b58107c1118346dca3f5fa13 | Fix typo in XML doc | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNetCore.Mvc.Core/ApplicationParts/IApplicationFeatureProviderOfT.cs | src/Microsoft.AspNetCore.Mvc.Core/ApplicationParts/IApplicationFeatureProviderOfT.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.AspNetCore.Mvc.ApplicationParts
{
/// <summary>
/// A provider for a given <typeparamref name="TFeature"/> feature.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
public interface IApplicationFeatureProvider<TFeature> : IApplicationFeatureProvider
{
/// <summary>
/// Updates the <paramref name="feature"/> instance.
/// </summary>
/// <param name="parts">The list of <see cref="ApplicationPart"/>s of the
/// application.
/// </param>
/// <param name="feature">The feature instance to populate.</param>
void PopulateFeature(IEnumerable<ApplicationPart> parts, TFeature feature);
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
namespace Microsoft.AspNetCore.Mvc.ApplicationParts
{
/// <summary>
/// A provider for a given <typeparamref name="TFeature"/> feature.
/// </summary>
/// <typeparam name="TFeature">The type of the feature.</typeparam>
public interface IApplicationFeatureProvider<TFeature> : IApplicationFeatureProvider
{
/// <summary>
/// Updates the <paramref name="feature"/> intance.
/// </summary>
/// <param name="parts">The list of <see cref="ApplicationPart"/>s of the
/// application.
/// </param>
/// <param name="feature">The feature instance to populate.</param>
void PopulateFeature(IEnumerable<ApplicationPart> parts, TFeature feature);
}
}
| apache-2.0 | C# |
333c0cd4f9c717187cc8a15f6ba93207a02ffbbf | Add open folder button to open currently selected tournament | ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu | osu.Game.Tournament/Screens/Setup/TournamentSwitcher.cs | osu.Game.Tournament/Screens/Setup/TournamentSwitcher.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
private OsuButton folderButton;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
string startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
folderButton.Action = storage.PresentExternally;
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
{
Width = 510
});
FlowContainer.Insert(-2, folderButton = new TriangleButton
{
Text = "Open folder",
Width = 100
});
return drawable;
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Graphics.UserInterface;
using osu.Game.Tournament.IO;
namespace osu.Game.Tournament.Screens.Setup
{
internal class TournamentSwitcher : ActionableInfo
{
private OsuDropdown<string> dropdown;
[Resolved]
private TournamentGameBase game { get; set; }
[BackgroundDependencyLoader]
private void load(TournamentStorage storage)
{
string startupTournament = storage.CurrentTournament.Value;
dropdown.Current = storage.CurrentTournament;
dropdown.Items = storage.ListTournaments();
dropdown.Current.BindValueChanged(v => Button.Enabled.Value = v.NewValue != startupTournament, true);
Action = () => game.GracefullyExit();
ButtonText = "Close osu!";
}
protected override Drawable CreateComponent()
{
var drawable = base.CreateComponent();
FlowContainer.Insert(-1, dropdown = new OsuDropdown<string>
{
Width = 510
});
return drawable;
}
}
}
| mit | C# |
0d051ae60fdac75bd5418598f41a0073a7a4d5ad | Add missing * and / operators to ExpressionParser | dpek/unity-raconteur,exodrifter/unity-raconteur | Assets/Raconteur/RenPy/Script/Expressions/ExpressionParserFactory.cs | Assets/Raconteur/RenPy/Script/Expressions/ExpressionParserFactory.cs | using UnityEngine;
namespace DPek.Raconteur.RenPy.Script
{
/// <summary>
/// A convenience class for getting Expression Parsers of a specific
/// setup.
/// </summary>
public class ExpressionParserFactory
{
private static ExpressionParser m_renPyExpressionParser;
private ExpressionParserFactory()
{
// Defeats instantiation
}
/// <summary>
/// Returns a new ExpressionParser for Ren'Py expressions.
/// </summary>
/// <returns>
/// An ExpressionParser for parsing Ren'Py expressions.ß
/// </returns>
public static ExpressionParser GetRenPyParser()
{
if(m_renPyExpressionParser != null) {
return m_renPyExpressionParser;
}
var parser = m_renPyExpressionParser = new ExpressionParser();
parser.SetupOperator(Get<OperatorAssignPlus>("+="));
parser.SetupOperator(Get<OperatorAssignMinus>("-="));
parser.SetupOperator(Get<OperatorAssignMultiply>("*="));
parser.SetupOperator(Get<OperatorAssignDivide>("/="));
parser.SetupOperator(Get<OperatorEquals>("=="));
parser.SetupOperator(Get<OperatorNotEquals>("!="));
parser.SetupOperator(Get<OperatorLessThanOrEqual>("<="));
parser.SetupOperator(Get<OperatorGreaterThanOrEqual>(">="));
parser.SetupOperator(Get<OperatorAssign>("="));
parser.SetupOperator(Get<OperatorPlus>("+"));
parser.SetupOperator(Get<OperatorMinus>("-"));
parser.SetupOperator(Get<OperatorMultiply>("*"));
parser.SetupOperator(Get<OperatorDivide>("/"));
parser.SetupOperator(Get<OperatorLessThan>("<"));
parser.SetupOperator(Get<OperatorGreaterThan>(">"));
return m_renPyExpressionParser;
}
/// <summary>
/// Returns a new Operator with the specified symbol.
/// </summary>
/// <param name="symbol">
/// The symbol to use for the new Operator.
/// </param>
/// <typeparam name="T">
/// The type of the Operator to get.
/// </typeparam>
private static Operator Get<T>(string symbol) where T : Operator
{
T op = ScriptableObject.CreateInstance<T>();
op.Symbol = symbol;
return op;
}
}
}
| using UnityEngine;
namespace DPek.Raconteur.RenPy.Script
{
/// <summary>
/// A convenience class for getting Expression Parsers of a specific
/// setup.
/// </summary>
public class ExpressionParserFactory
{
private static ExpressionParser m_renPyExpressionParser;
private ExpressionParserFactory()
{
// Defeats instantiation
}
/// <summary>
/// Returns a new ExpressionParser for Ren'Py expressions.
/// </summary>
/// <returns>
/// An ExpressionParser for parsing Ren'Py expressions.ß
/// </returns>
public static ExpressionParser GetRenPyParser()
{
if(m_renPyExpressionParser != null) {
return m_renPyExpressionParser;
}
var parser = m_renPyExpressionParser = new ExpressionParser();
parser.SetupOperator(Get<OperatorAssignPlus>("+="));
parser.SetupOperator(Get<OperatorAssignMinus>("-="));
parser.SetupOperator(Get<OperatorAssignMultiply>("*="));
parser.SetupOperator(Get<OperatorAssignDivide>("/="));
parser.SetupOperator(Get<OperatorEquals>("=="));
parser.SetupOperator(Get<OperatorNotEquals>("!="));
parser.SetupOperator(Get<OperatorLessThanOrEqual>("<="));
parser.SetupOperator(Get<OperatorGreaterThanOrEqual>(">="));
parser.SetupOperator(Get<OperatorAssign>("="));
parser.SetupOperator(Get<OperatorPlus>("+"));
parser.SetupOperator(Get<OperatorMinus>("-"));
parser.SetupOperator(Get<OperatorLessThan>("<"));
parser.SetupOperator(Get<OperatorGreaterThan>(">"));
return m_renPyExpressionParser;
}
/// <summary>
/// Returns a new Operator with the specified symbol.
/// </summary>
/// <param name="symbol">
/// The symbol to use for the new Operator.
/// </param>
/// <typeparam name="T">
/// The type of the Operator to get.
/// </typeparam>
private static Operator Get<T>(string symbol) where T : Operator
{
T op = ScriptableObject.CreateInstance<T>();
op.Symbol = symbol;
return op;
}
}
}
| bsd-3-clause | C# |
8ebb787831aaadc5fd1697fc828d2bddd6e0d41d | 支持在.Net Core上编译common.base | 303248153/ZKWeb.Plugins,303248153/ZKWeb.Plugins,zkweb-framework/ZKWeb.Plugins,303248153/ZKWeb.Plugins,zkweb-framework/ZKWeb.Plugins,zkweb-framework/ZKWeb.Plugins | Common.Base/src/Extensions/_DataTable/DataTableExtensions.cs | Common.Base/src/Extensions/_DataTable/DataTableExtensions.cs | #if !NETCORE
using System.Data;
using System.Text;
using ZKWeb.Localize;
using ZKWebStandard.Collection;
using ZKWebStandard.Extensions;
using ZKWebStandard.Utils;
namespace ZKWeb.Plugins.Common.Base.src.Extensions {
/// <summary>
/// 数据表格的扩展函数
/// </summary>
public static class DataTableExtensions {
/// <summary>
/// 转换数据表格到Html
/// 表格头可以使用DataColumn.ExtendedProperties指定参数allowHtml和width
/// 表格行中的数据如果类型是HtmlString将会直接描画,否则进行html编码后描画
/// </summary>
/// <param name="table">表格数据</param>
/// <param name="tableClass">表格的css类,默认是table table-bordered table-hover</param>
/// <param name="tableHeadRowClass">表格头部行的css类,默认是heading</param>
/// <returns></returns>
public static HtmlString ToHtml(this DataTable table,
string tableClass = null, string tableHeadRowClass = null) {
var htmlBuilder = new StringBuilder();
tableClass = HttpUtils.HtmlEncode(tableClass ?? "table table-bordered table-hover");
tableHeadRowClass = HttpUtils.HtmlEncode(tableHeadRowClass ?? "heading");
htmlBuilder.AppendFormat("<table class='{0}'>", tableClass);
htmlBuilder.AppendFormat("<thead><tr role='row' class='{0}'>", tableHeadRowClass);
foreach (DataColumn column in table.Columns) {
var width = HttpUtils.HtmlEncode(
(column.ExtendedProperties["width"] ?? "").ToString());
var allowHtml = column.ExtendedProperties["allowHtml"].ConvertOrDefault<bool>();
var caption = allowHtml ? column.Caption : HttpUtils.HtmlEncode(column.Caption);
htmlBuilder.AppendFormat("<th width='{0}'>{1}</th>", width, new T(caption));
}
htmlBuilder.Append("</tr></thead><tbody>");
foreach (DataRow row in table.Rows) {
htmlBuilder.Append("<tr role='row'>");
foreach (DataColumn column in table.Columns) {
var data = row[column];
var html = (data is HtmlString) ? data : HttpUtils.HtmlEncode((data ?? "").ToString());
htmlBuilder.AppendFormat("<td>{0}</td>", html);
}
htmlBuilder.Append("</tr>");
}
htmlBuilder.Append("</tbody></table>");
return new HtmlString(htmlBuilder.ToString());
}
}
}
#endif
| using System.Data;
using System.Text;
using ZKWeb.Localize;
using ZKWebStandard.Collection;
using ZKWebStandard.Extensions;
using ZKWebStandard.Utils;
namespace ZKWeb.Plugins.Common.Base.src.Extensions {
/// <summary>
/// 数据表格的扩展函数
/// </summary>
public static class DataTableExtensions {
/// <summary>
/// 转换数据表格到Html
/// 表格头可以使用DataColumn.ExtendedProperties指定参数allowHtml和width
/// 表格行中的数据如果类型是HtmlString将会直接描画,否则进行html编码后描画
/// </summary>
/// <param name="table">表格数据</param>
/// <param name="tableClass">表格的css类,默认是table table-bordered table-hover</param>
/// <param name="tableHeadRowClass">表格头部行的css类,默认是heading</param>
/// <returns></returns>
public static HtmlString ToHtml(this DataTable table,
string tableClass = null, string tableHeadRowClass = null) {
var htmlBuilder = new StringBuilder();
tableClass = HttpUtils.HtmlEncode(tableClass ?? "table table-bordered table-hover");
tableHeadRowClass = HttpUtils.HtmlEncode(tableHeadRowClass ?? "heading");
htmlBuilder.AppendFormat("<table class='{0}'>", tableClass);
htmlBuilder.AppendFormat("<thead><tr role='row' class='{0}'>", tableHeadRowClass);
foreach (DataColumn column in table.Columns) {
var width = HttpUtils.HtmlEncode(
(column.ExtendedProperties["width"] ?? "").ToString());
var allowHtml = column.ExtendedProperties["allowHtml"].ConvertOrDefault<bool>();
var caption = allowHtml ? column.Caption : HttpUtils.HtmlEncode(column.Caption);
htmlBuilder.AppendFormat("<th width='{0}'>{1}</th>", width, new T(caption));
}
htmlBuilder.Append("</tr></thead><tbody>");
foreach (DataRow row in table.Rows) {
htmlBuilder.Append("<tr role='row'>");
foreach (DataColumn column in table.Columns) {
var data = row[column];
var html = (data is HtmlString) ? data : HttpUtils.HtmlEncode((data ?? "").ToString());
htmlBuilder.AppendFormat("<td>{0}</td>", html);
}
htmlBuilder.Append("</tr>");
}
htmlBuilder.Append("</tbody></table>");
return new HtmlString(htmlBuilder.ToString());
}
}
}
| mit | C# |
04b003d4cca2a4069e9be9363251850b54718c67 | Remove unused constructor | ilovepi/Compiler,ilovepi/Compiler | compiler/middleend/optimization/CopyPropagation.cs | compiler/middleend/optimization/CopyPropagation.cs | using System.Collections.Generic;
using compiler.middleend.ir;
namespace compiler.middleend.optimization
{
public class CopyPropagation
{
private static HashSet<Node> _visited = null;
public static void Propagate(Node root)
{
_visited = new HashSet<Node>();
PropagateValues(root);
}
private static void PropagateValues(Node root )
{
if ( (root == null) || _visited.Contains(root) )
{
return;
}
_visited.Add(root);
foreach (var instruction in root.Bb.Instructions)
{
if (instruction.Arg1?.Kind == Operand.OpType.Variable)
{
instruction.Arg1 = instruction.Arg1.Variable.Value.OpenOperand();
}
if ((instruction.Arg2?.Kind == Operand.OpType.Variable) && (instruction.Op != IrOps.Store))
{
instruction.Arg2 = instruction.Arg2.Variable.Value.OpenOperand();
}
}
var children = root.GetAllChildren();
foreach (var child in children)
{
PropagateValues(child);
}
}
}
}
| using System.Collections.Generic;
using compiler.middleend.ir;
namespace compiler.middleend.optimization
{
public class CopyPropagation
{
public CopyPropagation()
{
}
private static HashSet<Node> _visited = null;
public static void Propagate(Node root)
{
_visited = new HashSet<Node>();
PropagateValues(root);
}
private static void PropagateValues(Node root )
{
if ( (root == null) || _visited.Contains(root) )
{
return;
}
_visited.Add(root);
foreach (var instruction in root.Bb.Instructions)
{
if (instruction.Arg1?.Kind == Operand.OpType.Variable)
{
instruction.Arg1 = instruction.Arg1.Variable.Value.OpenOperand();
}
if ((instruction.Arg2?.Kind == Operand.OpType.Variable) && (instruction.Op != IrOps.Store))
{
instruction.Arg2 = instruction.Arg2.Variable.Value.OpenOperand();
}
}
var children = root.GetAllChildren();
foreach (var child in children)
{
PropagateValues(child);
}
}
}
}
| mit | C# |
086e696b71091a59cde0e601bdc89f97ede89d00 | Throw an exception if a popover is attempted to be shown without a parent `PopoverContainer` | peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework | osu.Framework/Extensions/PopoverExtensions.cs | osu.Framework/Extensions/PopoverExtensions.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;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
{
var popoverContainer = origin.FindClosestParent<PopoverContainer>()
?? throw new InvalidOperationException($"Cannot show or hide a popover without a parent {nameof(PopoverContainer)} in the hierarchy");
popoverContainer.SetTarget(target);
}
}
}
| // 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.Graphics;
using osu.Framework.Graphics.Cursor;
#nullable enable
namespace osu.Framework.Extensions
{
public static class PopoverExtensions
{
/// <summary>
/// Shows the popover for <paramref name="hasPopover"/> on its nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void ShowPopover(this IHasPopover hasPopover) => setTargetOnNearestPopover((Drawable)hasPopover, hasPopover);
/// <summary>
/// Hides the popover shown on <paramref name="drawable"/>'s nearest <see cref="PopoverContainer"/> ancestor.
/// </summary>
public static void HidePopover(this Drawable drawable) => setTargetOnNearestPopover(drawable, null);
private static void setTargetOnNearestPopover(Drawable origin, IHasPopover? target)
=> origin.FindClosestParent<PopoverContainer>()?.SetTarget(target);
}
}
| mit | C# |
0841719d0899141fa15e1b5c175020270708d1eb | Change 3M performance test to 5M | billboga/silverpop-dotnet-api,kendaleiv/silverpop-dotnet-api,ritterim/silverpop-dotnet-api,kendaleiv/silverpop-dotnet-api | test/Silverpop.Core.Performance/Program.cs | test/Silverpop.Core.Performance/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Silverpop.Core.Performance
{
internal class Program
{
private static void Main(string[] args)
{
var tagValue = new string(
Enumerable.Repeat("ABC", 1000)
.SelectMany(x => x)
.ToArray());
var personalizationTags = new TestPersonalizationTags()
{
TagA = tagValue,
TagB = tagValue,
TagC = tagValue,
TagD = tagValue,
TagE = tagValue,
TagF = tagValue,
TagG = tagValue,
TagH = tagValue,
TagI = tagValue,
TagJ = tagValue,
TagK = tagValue,
TagL = tagValue,
TagM = tagValue,
TagN = tagValue,
TagO = tagValue
};
var numberOfTags = personalizationTags.GetType().GetProperties().Count();
Console.WriteLine("Testing 1 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(1000000, 5000, personalizationTags);
Console.WriteLine("Testing 5 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(5000000, 5000, personalizationTags);
Console.ReadLine();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
namespace Silverpop.Core.Performance
{
internal class Program
{
private static void Main(string[] args)
{
var tagValue = new string(
Enumerable.Repeat("ABC", 1000)
.SelectMany(x => x)
.ToArray());
var personalizationTags = new TestPersonalizationTags()
{
TagA = tagValue,
TagB = tagValue,
TagC = tagValue,
TagD = tagValue,
TagE = tagValue,
TagF = tagValue,
TagG = tagValue,
TagH = tagValue,
TagI = tagValue,
TagJ = tagValue,
TagK = tagValue,
TagL = tagValue,
TagM = tagValue,
TagN = tagValue,
TagO = tagValue
};
var numberOfTags = personalizationTags.GetType().GetProperties().Count();
Console.WriteLine("Testing 1 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(1000000, 5000, personalizationTags);
Console.WriteLine("Testing 3 million recipients with {0} tags using batches of 5000:", numberOfTags);
new TransactMessagePerformance()
.InvokeGetRecipientBatchedMessages(3000000, 5000, personalizationTags);
Console.ReadLine();
}
}
} | mit | C# |
7c79543ac1cb3ca1d4130fdef76a305573ab0ed0 | support incremental progress events (#1381) | lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows | ReactWindows/ReactNative.Shared/Modules/Network/DefaultHttpClient.cs | ReactWindows/ReactNative.Shared/Modules/Network/DefaultHttpClient.cs | using System;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Web.Http;
#else
using System.Net.Http;
#endif
namespace ReactNative.Modules.Network
{
class DefaultHttpClient : IHttpClient
{
private readonly HttpClient _client;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "HttpClient disposed by container.")]
public DefaultHttpClient()
: this(new HttpClient())
{
}
public DefaultHttpClient(HttpClient client)
{
_client = client;
}
public async Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request, CancellationToken token)
{
#if WINDOWS_UWP
var asyncInfo = _client.SendRequestAsync(request, HttpCompletionOption.ResponseHeadersRead);
using (token.Register(asyncInfo.Cancel))
{
try
{
return await asyncInfo.AsTask().ConfigureAwait(false);
}
catch (OperationCanceledException)
{
token.ThrowIfCancellationRequested();
throw;
}
}
#else
return await _client.SendAsync(request, token).ConfigureAwait(false);
#endif
}
public void Dispose()
{
_client.Dispose();
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
#if WINDOWS_UWP
using Windows.Web.Http;
#else
using System.Net.Http;
#endif
namespace ReactNative.Modules.Network
{
class DefaultHttpClient : IHttpClient
{
private readonly HttpClient _client;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "HttpClient disposed by container.")]
public DefaultHttpClient()
: this(new HttpClient())
{
}
public DefaultHttpClient(HttpClient client)
{
_client = client;
}
public async Task<HttpResponseMessage> SendRequestAsync(HttpRequestMessage request, CancellationToken token)
{
#if WINDOWS_UWP
var asyncInfo = _client.SendRequestAsync(request);
using (token.Register(asyncInfo.Cancel))
{
try
{
return await asyncInfo.AsTask().ConfigureAwait(false);
}
catch (OperationCanceledException)
{
token.ThrowIfCancellationRequested();
throw;
}
}
#else
return await _client.SendAsync(request, token).ConfigureAwait(false);
#endif
}
public void Dispose()
{
_client.Dispose();
}
}
}
| mit | C# |
3e3b8e19ff5b7e86f013a3b99d2e60d26a6afd21 | Use thread context parameter for find implementations. | panopticoncentral/roslyn,nguerrera/roslyn,KevinRansom/roslyn,brettfo/roslyn,mavasani/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,aelij/roslyn,stephentoub/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,gafter/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,heejaechang/roslyn,weltkante/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,davkean/roslyn,tmat/roslyn,wvdd007/roslyn,sharwell/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,mgoertz-msft/roslyn,agocke/roslyn,brettfo/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,genlu/roslyn,abock/roslyn,physhi/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,abock/roslyn,tannergooding/roslyn,diryboy/roslyn,diryboy/roslyn,sharwell/roslyn,jmarolf/roslyn,davkean/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,tmat/roslyn,dotnet/roslyn,eriawan/roslyn,nguerrera/roslyn,agocke/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,physhi/roslyn,aelij/roslyn,bartdesmet/roslyn,abock/roslyn,nguerrera/roslyn,tmat/roslyn,reaction1989/roslyn,tannergooding/roslyn,gafter/roslyn,KevinRansom/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,reaction1989/roslyn,jmarolf/roslyn,sharwell/roslyn,bartdesmet/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,genlu/roslyn,genlu/roslyn,diryboy/roslyn,weltkante/roslyn,tannergooding/roslyn,gafter/roslyn | src/Features/LanguageServer/Protocol/Handler/References/FindImplementationsHandler.cs | src/Features/LanguageServer/Protocol/Handler/References/FindImplementationsHandler.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 System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.PooledObjects;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[Shared]
[ExportLspMethod(LSP.Methods.TextDocumentImplementationName)]
internal class FindImplementationsHandler : IRequestHandler<LSP.TextDocumentPositionParams, object>
{
public async Task<object> HandleRequestAsync(Solution solution, LSP.TextDocumentPositionParams request,
LSP.ClientCapabilities clientCapabilities, CancellationToken cancellationToken, bool keepThreadContext = false)
{
var locations = ArrayBuilder<LSP.Location>.GetInstance();
var document = solution.GetDocumentFromURI(request.TextDocument.Uri);
if (document == null)
{
return locations.ToArrayAndFree();
}
var findUsagesService = document.Project.LanguageServices.GetService<IFindUsagesService>();
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(keepThreadContext);
var context = new SimpleFindUsagesContext(cancellationToken);
await findUsagesService.FindImplementationsAsync(document, position, context).ConfigureAwait(keepThreadContext);
foreach (var definition in context.GetDefinitions())
{
var text = definition.GetClassifiedText();
foreach (var sourceSpan in context.GetDefinitions().SelectMany(definition => definition.SourceSpans))
{
if (clientCapabilities?.HasVisualStudioLspCapability() == true)
{
locations.Add(await ProtocolConversions.DocumentSpanToLocationWithTextAsync(sourceSpan, text, cancellationToken).ConfigureAwait(keepThreadContext));
}
else
{
locations.Add(await ProtocolConversions.DocumentSpanToLocationAsync(sourceSpan, cancellationToken).ConfigureAwait(keepThreadContext));
}
}
}
return locations.ToArrayAndFree();
}
}
}
| // 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 System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.FindUsages;
using Microsoft.CodeAnalysis.PooledObjects;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
[Shared]
[ExportLspMethod(LSP.Methods.TextDocumentImplementationName)]
internal class FindImplementationsHandler : IRequestHandler<LSP.TextDocumentPositionParams, object>
{
public async Task<object> HandleRequestAsync(Solution solution, LSP.TextDocumentPositionParams request,
LSP.ClientCapabilities clientCapabilities, CancellationToken cancellationToken)
{
var locations = ArrayBuilder<LSP.Location>.GetInstance();
var document = solution.GetDocumentFromURI(request.TextDocument.Uri);
if (document == null)
{
return locations.ToArrayAndFree();
}
var findUsagesService = document.Project.LanguageServices.GetService<IFindUsagesService>();
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var context = new SimpleFindUsagesContext(cancellationToken);
await findUsagesService.FindImplementationsAsync(document, position, context).ConfigureAwait(false);
foreach (var definition in context.GetDefinitions())
{
var text = definition.GetClassifiedText();
foreach (var sourceSpan in context.GetDefinitions().SelectMany(definition => definition.SourceSpans))
{
if (clientCapabilities?.HasVisualStudioLspCapability() == true)
{
locations.Add(await ProtocolConversions.DocumentSpanToLocationWithTextAsync(sourceSpan, text, cancellationToken).ConfigureAwait(false));
}
else
{
locations.Add(await ProtocolConversions.DocumentSpanToLocationAsync(sourceSpan, cancellationToken).ConfigureAwait(false));
}
}
}
return locations.ToArrayAndFree();
}
}
}
| mit | C# |
e232dd7d7e1618eadac67dffcfa7ac9e30692c6f | Add a space between "Test" and "Email" in the UI. | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Models/ServerViewModels/EmailsViewModel.cs | BTCPayServer/Models/ServerViewModels/EmailsViewModel.cs | using BTCPayServer.Services.Mails;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BTCPayServer.Models.ServerViewModels
{
public class EmailsViewModel
{
public string StatusMessage
{
get; set;
}
public EmailSettings Settings
{
get; set;
}
[EmailAddress]
[Display(Name = "Test Email")]
public string TestEmail
{
get; set;
}
}
}
| using BTCPayServer.Services.Mails;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace BTCPayServer.Models.ServerViewModels
{
public class EmailsViewModel
{
public string StatusMessage
{
get; set;
}
public EmailSettings Settings
{
get; set;
}
[EmailAddress]
public string TestEmail
{
get; set;
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.