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
f85ac240a73845cb1da90061473ae8fabfa4bda8
Update MarcBruins.cs (#378)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/MarcBruins.cs
src/Firehose.Web/Authors/MarcBruins.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MarcBruins : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Marc"; public string LastName => "Bruins"; public string ShortBioOrTagLine => "is a native iOS/Android developer who fell in love with Xamarin"; public string EmailAddress => "marc@marcbruins.nl"; public string TwitterHandle => "MarcBruins"; public string GravatarHash => "3795d2031be87499f76f6336ec5a3a45"; public string StateOrRegion => "Utrecht, Netherlands"; public Uri WebSite => new Uri("https://www.marcbruins.nl"); public string GitHubHandle => "MarcBruins"; public GeoPosition Position => new GeoPosition(53.2193840, 6.5665020); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.marcbruins.nl/feed.xml"); } } public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MarcBruins : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Marc"; public string LastName => "Bruins"; public string ShortBioOrTagLine => "is a native iOS/Android developer who fell in love with Xamarin"; public string EmailAddress => "marc@marcbruins.nl"; public string TwitterHandle => "MarcBruins"; public string GravatarHash => "3795d2031be87499f76f6336ec5a3a45"; public string StateOrRegion => "Groningen, Netherlands"; public Uri WebSite => new Uri("http://www.marcbruins.nl"); public string GitHubHandle => "MarcBruins"; public GeoPosition Position => new GeoPosition(53.2193840, 6.5665020); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://www.marcbruins.nl/feed/"); } } public bool Filter(SyndicationItem item) => item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Any(category => category.Name.ToLowerInvariant().Contains("xamarin")); } }
mit
C#
00400f55e19032d45dd1e6a2130ca5e4452bb124
update description to better match the behavior
jamesmanning/RunProcessAsTask
src/RunProcessAsTask/ProcessResults.cs
src/RunProcessAsTask/ProcessResults.cs
using System; using System.Diagnostics; namespace RunProcessAsTask { public sealed class ProcessResults : IDisposable { /// <summary> /// Contains information about process after it has exited. /// </summary> public ProcessResults(Process process, DateTime processStartTime, string[] standardOutput, string[] standardError) { Process = process; ExitCode = process.ExitCode; RunTime = process.ExitTime - processStartTime; StandardOutput = standardOutput; StandardError = standardError; } public Process Process { get; } public int ExitCode { get; } public TimeSpan RunTime { get; } public string[] StandardOutput { get; } public string[] StandardError { get; } public void Dispose() { Process.Dispose(); } } }
using System; using System.Diagnostics; namespace RunProcessAsTask { public sealed class ProcessResults : IDisposable { /// <summary> /// Contains information about terminated process. /// </summary> public ProcessResults(Process process, DateTime processStartTime, string[] standardOutput, string[] standardError) { Process = process; ExitCode = process.ExitCode; RunTime = process.ExitTime - processStartTime; StandardOutput = standardOutput; StandardError = standardError; } public Process Process { get; } public int ExitCode { get; } public TimeSpan RunTime { get; } public string[] StandardOutput { get; } public string[] StandardError { get; } public void Dispose() { Process.Dispose(); } } }
mit
C#
c2f8a827bf176dc68301a7ea8777e4c6b4904c58
Remove unused namespaces
extremecodetv/SocksSharp
src/SocksSharp/Proxy/IProxySettings.cs
src/SocksSharp/Proxy/IProxySettings.cs
using System.Net; namespace SocksSharp.Proxy { public interface IProxySettings { NetworkCredential Credentials { get; set; } string Host { get; set; } int Port { get; set; } int ConnectTimeout { get; set; } int ReadWriteTimeOut { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace SocksSharp.Proxy { public interface IProxySettings { NetworkCredential Credentials { get; set; } string Host { get; set; } int Port { get; set; } int ConnectTimeout { get; set; } int ReadWriteTimeOut { get; set; } } }
mit
C#
1f3adeefdb4cb6107c4b76aff05008b1c1d8c164
Make limits long-er (#1192)
VSadov/corefxlab,Vedin/corefxlab,dotnet/corefxlab,ericstj/corefxlab,VSadov/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,whoisj/corefxlab,VSadov/corefxlab,Vedin/corefxlab,ericstj/corefxlab,Vedin/corefxlab,whoisj/corefxlab,joshfree/corefxlab,VSadov/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,hanblee/corefxlab,ericstj/corefxlab,benaadams/corefxlab,ericstj/corefxlab,VSadov/corefxlab,Vedin/corefxlab,stephentoub/corefxlab,benaadams/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,stephentoub/corefxlab,ahsonkhan/corefxlab,KrzysztofCwalina/corefxlab,stephentoub/corefxlab,joshfree/corefxlab,hanblee/corefxlab,adamsitnik/corefxlab,Vedin/corefxlab,ericstj/corefxlab,Vedin/corefxlab,KrzysztofCwalina/corefxlab,dotnet/corefxlab,VSadov/corefxlab,alexperovich/corefxlab,adamsitnik/corefxlab,ahsonkhan/corefxlab
src/System.IO.Pipelines/PipeOptions.cs
src/System.IO.Pipelines/PipeOptions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.IO.Pipelines { public class PipeOptions { public long MaximumSizeHigh { get; set; } public long MaximumSizeLow { get; set; } public IScheduler WriterScheduler { get; set; } public IScheduler ReaderScheduler { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace System.IO.Pipelines { public class PipeOptions { public int MaximumSizeHigh { get; set; } public int MaximumSizeLow { get; set; } public IScheduler WriterScheduler { get; set; } public IScheduler ReaderScheduler { get; set; } } }
mit
C#
393ccd3f469706f972cb5b70cfffeb0c708df64f
Add ReasonPhrase to RaygunWebApiHttpExceptions
articulate/raygun4net,articulate/raygun4net,tdiehl/raygun4net,ddunkin/raygun4net,nelsonsar/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,ddunkin/raygun4net,MindscapeHQ/raygun4net,tdiehl/raygun4net,nelsonsar/raygun4net
Mindscape.Raygun4Net45/WebApi/RaygunWebApiFilters.cs
Mindscape.Raygun4Net45/WebApi/RaygunWebApiFilters.cs
using System; using System.Collections.Generic; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Filters; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionFilter : ExceptionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnException(HttpActionExecutedContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception); } public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception), cancellationToken); } } public class RaygunWebApiActionFilter : ActionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiActionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnActionExecuted(HttpActionExecutedContext context) { base.OnActionExecuted(context); if (context != null && context.Response != null && (int)context.Response.StatusCode >= 400) { try { throw new RaygunWebApiHttpException( context.Response.StatusCode, context.Response.ReasonPhrase, string.Format("HTTP {0} returned while handling Request {2} {1}", (int)context.Response.StatusCode, context.Request.RequestUri, context.Request.Method)); } catch (RaygunWebApiHttpException e) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(e, null, new Dictionary<string, string> { { "ReasonCode", e.ReasonPhrase } }); } catch (Exception e) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(e); } } } } public class RaygunWebApiHttpException : Exception { public HttpStatusCode StatusCode { get; set; } public string ReasonPhrase { get; set; } public RaygunWebApiHttpException(HttpStatusCode statusCode, string reasonPhrase, string message) : base(message) { ReasonPhrase = reasonPhrase; StatusCode = statusCode; } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Filters; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionFilter : ExceptionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnException(HttpActionExecutedContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception); } public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception), cancellationToken); } } public class RaygunWebApiActionFilter : ActionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiActionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnActionExecuted(HttpActionExecutedContext context) { base.OnActionExecuted(context); if (context != null && context.Response != null && (int)context.Response.StatusCode >= 400) { try { throw new RaygunWebApiHttpException( context.Response.StatusCode, string.Format("HTTP {0} returned while handling Request {2} {1}", (int)context.Response.StatusCode, context.Request.RequestUri, context.Request.Method)); } catch (Exception e) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(e); } } } } public class RaygunWebApiHttpException : Exception { public HttpStatusCode StatusCode { get; set; } public RaygunWebApiHttpException(HttpStatusCode statusCode, string message) : base(message) { StatusCode = statusCode; } } }
mit
C#
420f1fb874a7823fdd50b6d936e644631f740632
Update HttpContextBaseExtension.cs
yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples,yuanrui/Examples
Simple.Common/Extensions/HttpContextBaseExtension.cs
Simple.Common/Extensions/HttpContextBaseExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Simple.Common.Extensions { public static class HttpContextBaseExtension { public static string GetClientIp(this HttpRequestBase request) { var ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { var addresses = ipAddress.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return request.ServerVariables["REMOTE_ADDR"]; } public static string GetClientIp(this HttpRequest request) { return GetClientIp(request.RequestContext.HttpContext.Request); } public static bool IsIE(this HttpRequestBase request) { var userAgent = request.UserAgent ?? string.Empty; var browser = request.Browser.Browser; if (string.Equals(browser, "IE", StringComparison.OrdinalIgnoreCase) || string.Equals(browser, "InternetExplorer", StringComparison.OrdinalIgnoreCase) || userAgent.IndexOf("msie", StringComparison.OrdinalIgnoreCase) > -1 || userAgent.IndexOf("rv:11.0", StringComparison.OrdinalIgnoreCase) > -1) { return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; namespace Simple.Common.Extensions { public static class HttpContextBaseExtension { public static string GetClientIp(this HttpRequestBase request) { string ip = string.Empty; try { if (request.IsSecureConnection) { ip = request.ServerVariables["REMOTE_ADDR"]; } if (string.IsNullOrEmpty(ip)) { ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ip)) { if (ip.Any(m => m == ',')) { ip = ip.Split(',').Last(); } } else { ip = request.UserHostAddress; } } } catch { ip = string.Empty; } return ip; } public static string GetClientIp(this HttpRequest request) { return GetClientIp(request.RequestContext.HttpContext.Request); } public static bool IsIE(this HttpRequestBase request) { var userAgent = request.UserAgent ?? string.Empty; var browser = request.Browser.Browser; if (string.Equals(browser, "IE", StringComparison.OrdinalIgnoreCase) || string.Equals(browser, "InternetExplorer", StringComparison.OrdinalIgnoreCase) || userAgent.IndexOf("msie", StringComparison.OrdinalIgnoreCase) > -1 || userAgent.IndexOf("rv:11.0", StringComparison.OrdinalIgnoreCase) > -1) { return true; } return false; } } }
apache-2.0
C#
88e5044a6b1e1d29134e400defceb73ad9519840
Remove 'using' directive from GC.cs
jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm
runtime/GC.cs
runtime/GC.cs
namespace __compiler_rt { /// <summary> /// Garbage collection functionality that can be used by the compiler. /// </summary> public static unsafe class GC { private static extern void* GC_malloc(ulong size); /// <summary> /// Allocates a region of storage that is the given number of bytes in size. /// The storage is zero-initialized. /// </summary> /// <param name="size">The number of bytes to allocate.</param> public static void* Allocate(ulong size) { return GC_malloc(size); } } }
using System.Runtime.InteropServices; namespace __compiler_rt { /// <summary> /// Garbage collection functionality that can be used by the compiler. /// </summary> public static unsafe class GC { private static extern void* GC_malloc(ulong size); /// <summary> /// Allocates a region of storage that is the given number of bytes in size. /// The storage is zero-initialized. /// </summary> /// <param name="size">The number of bytes to allocate.</param> public static void* Allocate(ulong size) { return GC_malloc(size); } } }
mit
C#
6cd440b1ef315553219b5a92e10a5459284d93f7
Make Release.lowest_price nullable
David-Desmaisons/DiscogsClient
DiscogsClient/Data/Result/DiscogsRelease.cs
DiscogsClient/Data/Result/DiscogsRelease.cs
using System; namespace DiscogsClient.Data.Result { public class DiscogsRelease : DiscogsReleaseBase { public DiscogsReleaseArtist[] extraartists { get; set; } public DiscogsReleaseLabel[] labels { get; set; } public DiscogsReleaseLabel[] companies { get; set; } public DiscogsFormat[] formats { get; set; } public DiscogsIdentifier[] identifiers { get; set; } public DiscogsCommunity community { get; set; } public DiscogsReleaseLabel[] series { get; set; } public string artists_sort { get; set; } public string catno { get; set; } public string country { get; set; } public DateTime date_added { get; set; } public DateTime date_changed { get; set; } /// <remarks>Grams</remarks> public int estimated_weight { get; set; } public int format_quantity { get; set; } public decimal? lowest_price { get; set; } public int master_id { get; set; } public string master_url { get; set; } public string notes { get; set; } public int num_for_sale { get; set; } public string released { get; set; } public string released_formatted { get; set; } public string status { get; set; } public string thumb { get; set; } } }
using System; namespace DiscogsClient.Data.Result { public class DiscogsRelease : DiscogsReleaseBase { public DiscogsReleaseArtist[] extraartists { get; set; } public DiscogsReleaseLabel[] labels { get; set; } public DiscogsReleaseLabel[] companies { get; set; } public DiscogsFormat[] formats { get; set; } public DiscogsIdentifier[] identifiers { get; set; } public DiscogsCommunity community { get; set; } public DiscogsReleaseLabel[] series { get; set; } public string artists_sort { get; set; } public string catno { get; set; } public string country { get; set; } public DateTime date_added { get; set; } public DateTime date_changed { get; set; } /// <remarks>Grams</remarks> public int estimated_weight { get; set; } public int format_quantity { get; set; } public decimal lowest_price { get; set; } public int master_id { get; set; } public string master_url { get; set; } public string notes { get; set; } public int num_for_sale { get; set; } public string released { get; set; } public string released_formatted { get; set; } public string status { get; set; } public string thumb { get; set; } } }
mit
C#
2e0057e477ef68dde4f8cefc9213a55c113fd318
Remove backpressure from benchmarks app (#2087)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
benchmarkapps/BenchmarkServer/Startup.cs
benchmarkapps/BenchmarkServer/Startup.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 BenchmarkServer.Hubs; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace BenchmarkServer { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(o => { o.EnableDetailedErrors = true; }) .AddMessagePackProtocol(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSignalR(routes => { routes.MapHub<EchoHub>("/echo", o => { // Remove backpressure for benchmarking o.TransportMaxBufferSize = 0; o.ApplicationMaxBufferSize = 0; }); }); } } }
// 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 BenchmarkServer.Hubs; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace BenchmarkServer { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR() .AddMessagePackProtocol(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseSignalR(routes => { routes.MapHub<EchoHub>("/echo"); }); } } }
apache-2.0
C#
a37d555d57256f75a75ef61a0c39f024fd8143ce
load categories from href
ArsenShnurkov/NS84.Syndication.Atom,jordanbtucker/NS84.Syndication.Atom
Publication/AtomPubOutOfLineCategories.cs
Publication/AtomPubOutOfLineCategories.cs
using System; using System.Diagnostics; using System.Xml.Linq; namespace NerdSince1984.Syndication.Atom.Publication { [DebuggerDisplay("Href = {Href}")] public class AtomPubOutOfLineCategories : AtomPubCategories { public AtomPubOutOfLineCategories(string href) { this.Href = href; } protected AtomPubOutOfLineCategories(XElement element) : base(element) { } public string Href { get { return (string)this.Element.Attribute("href"); } set { if(value == null) throw new ArgumentNullException("value"); if(value == "") throw new ArgumentException(Errors.EmptyString, "value"); this.Element.SetAttributeValue("href", value); } } public AtomPubInlineCategories Load() { return AtomPubCategories.Load(this.Href); } public static implicit operator AtomPubOutOfLineCategories(XElement element) { return element == null ? null : new AtomPubOutOfLineCategories(element); } } }
using System; using System.Diagnostics; using System.Xml.Linq; namespace NerdSince1984.Syndication.Atom.Publication { [DebuggerDisplay("Href = {Href}")] public class AtomPubOutOfLineCategories : AtomPubCategories { public AtomPubOutOfLineCategories(string href) { this.Href = href; } protected AtomPubOutOfLineCategories(XElement element) : base(element) { } public string Href { get { return (string)this.Element.Attribute("href"); } set { if(value == null) throw new ArgumentNullException("value"); if(value == "") throw new ArgumentException(Errors.EmptyString, "value"); this.Element.SetAttributeValue("href", value); } } public static implicit operator AtomPubOutOfLineCategories(XElement element) { return element == null ? null : new AtomPubOutOfLineCategories(element); } } }
mit
C#
c15804b7c73693d5ebe711c0af687e801707d614
Add license #region.
PenguinF/sandra-three
Sandra.UI.WF/Storage/SubFolderNameType.cs
Sandra.UI.WF/Storage/SubFolderNameType.cs
#region License /********************************************************************************* * SubFolderNameType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ #endregion using System; using System.IO; namespace Sandra.UI.WF.Storage { /// <summary> /// Specialized PType that only accepts a certain class of subfolder names. /// </summary> public sealed class SubFolderNameType : PType.Filter<string> { public static SubFolderNameType Instance = new SubFolderNameType(); private SubFolderNameType() : base(PType.CLR.String) { } public override bool IsValid(string folderPath) { if (!string.IsNullOrEmpty(folderPath) && folderPath.IndexOfAny(Path.GetInvalidPathChars()) < 0 && !Path.IsPathRooted(folderPath)) { var localApplicationFolder = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); var subFolder = new DirectoryInfo(Path.Combine(localApplicationFolder.FullName, folderPath)); for (var parentFolder = subFolder.Parent; parentFolder != null; parentFolder = parentFolder.Parent) { // Indeed a subfolder? if (localApplicationFolder.FullName == parentFolder.FullName) return true; } } return false; } } }
/********************************************************************************* * SubFolderNameType.cs * * Copyright (c) 2004-2018 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *********************************************************************************/ using System; using System.IO; namespace Sandra.UI.WF.Storage { /// <summary> /// Specialized PType that only accepts a certain class of subfolder names. /// </summary> public sealed class SubFolderNameType : PType.Filter<string> { public static SubFolderNameType Instance = new SubFolderNameType(); private SubFolderNameType() : base(PType.CLR.String) { } public override bool IsValid(string folderPath) { if (!string.IsNullOrEmpty(folderPath) && folderPath.IndexOfAny(Path.GetInvalidPathChars()) < 0 && !Path.IsPathRooted(folderPath)) { var localApplicationFolder = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)); var subFolder = new DirectoryInfo(Path.Combine(localApplicationFolder.FullName, folderPath)); for (var parentFolder = subFolder.Parent; parentFolder != null; parentFolder = parentFolder.Parent) { // Indeed a subfolder? if (localApplicationFolder.FullName == parentFolder.FullName) return true; } } return false; } } }
apache-2.0
C#
248842b242ca2ec9c37f34518a2777ff1cefdd7c
select editor empty option text fix
volkanceylan/Serenity,dfaruque/Serenity,TukekeSoft/Serenity,volkanceylan/Serenity,linpiero/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,TukekeSoft/Serenity,linpiero/Serenity,linpiero/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,linpiero/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,linpiero/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity
Serenity.Script.UI/Editor/SelectEditor.cs
Serenity.Script.UI/Editor/SelectEditor.cs
using jQueryApi; using Serenity.ComponentModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Serenity { [Editor, DisplayName("Açılır Liste"), OptionsType(typeof(SelectEditorOptions))] [Element("<input type=\"hidden\"/>")] public class SelectEditor : Select2Editor<SelectEditorOptions, Select2Item>, IStringValue { public SelectEditor(jQueryObject hidden, SelectEditorOptions opt) : base(hidden, opt) { UpdateItems(); } protected virtual List<object> GetItems() { return options.Items ?? new List<object>(); } protected override string EmptyItemText() { if (!string.IsNullOrEmpty(options.EmptyOptionText)) return options.EmptyOptionText; return base.EmptyItemText(); } protected virtual void UpdateItems() { var items = GetItems(); ClearItems(); if (items.Count > 0) { bool isStrings = Script.TypeOf(items[0]) == "string"; foreach (dynamic item in items) { string key = isStrings ? item : item[0]; string text = isStrings ? item : item[1] ?? item[0]; AddItem(key, text, item); } } } } [Serializable, Reflectable] public class SelectEditorOptions { public SelectEditorOptions() { Items = new List<object>(); } [Hidden] public List<object> Items { get; set; } [DisplayName("Boş Eleman Metni")] public string EmptyOptionText { get; set; } } }
using jQueryApi; using Serenity.ComponentModel; using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Serenity { [Editor, DisplayName("Açılır Liste"), OptionsType(typeof(SelectEditorOptions))] [Element("<input type=\"hidden\"/>")] public class SelectEditor : Select2Editor<SelectEditorOptions, Select2Item>, IStringValue { public SelectEditor(jQueryObject hidden, SelectEditorOptions opt) : base(hidden, opt) { UpdateItems(); } protected virtual List<object> GetItems() { return options.Items ?? new List<object>(); } protected override string EmptyItemText() { return options.EmptyOptionText; } protected virtual void UpdateItems() { var items = GetItems(); ClearItems(); if (items.Count > 0) { bool isStrings = Script.TypeOf(items[0]) == "string"; foreach (dynamic item in items) { string key = isStrings ? item : item[0]; string text = isStrings ? item : item[1] ?? item[0]; AddItem(key, text, item); } } } } [Serializable, Reflectable] public class SelectEditorOptions { public SelectEditorOptions() { EmptyOptionText = "--seçiniz--"; Items = new List<object>(); } [Hidden] public List<object> Items { get; set; } [DisplayName("Boş Eleman Metni")] public string EmptyOptionText { get; set; } } }
mit
C#
dc94f0501d7d2106007952e870140eb2b29a32e5
Add a 4th board cell status "Miss" to show that the user shoot to a blank spot.
vnads/Fight-Fleet,vnads/Fight-Fleet,vnads/Fight-Fleet
FightFleetApi/FightFleet/BoardCellStatus.cs
FightFleetApi/FightFleet/BoardCellStatus.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FightFleet { public enum BoardCellStatus { Blank = 0, Ship = 1, Hit = 2, Miss = 3 } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FightFleet { public enum BoardCellStatus { Blank = 0, Ship = 1, Hit = 2 } }
mit
C#
d1af5524b5c98c3ff894ea533d924a777a67c28e
Fix issue with specified Working folder on command line
michael-reichenauer/GitMind
GitMind/Installation/Private/CommandLine.cs
GitMind/Installation/Private/CommandLine.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace GitMind.Installation.Private { internal class CommandLine : ICommandLine { private readonly Lazy<IReadOnlyList<string>> lazyBranchNames; private readonly string[] args; public CommandLine() { args = Environment.GetCommandLineArgs(); lazyBranchNames = new Lazy<IReadOnlyList<string>>(GetBranchNames); } public bool IsSilent => args.Contains("/silent"); public bool IsInstall => args.Contains("/install") || IsSetupFile(); public bool IsUninstall => args.Contains("/uninstall"); public bool IsRunInstalled => args.Contains("/run"); public bool IsShowDiff => args.Length > 1 && args[1] == "diff"; public bool IsTest => args.Contains("/test"); public bool HasFolder => args.Any(a => a.StartsWith("/d:")) || IsTest; public string Folder => args.FirstOrDefault(a => a.StartsWith("/d:"))?.Substring(3); public IReadOnlyList<string> BranchNames => lazyBranchNames.Value; private bool IsSetupFile() { return Path.GetFileNameWithoutExtension( Assembly.GetEntryAssembly().Location).StartsWith("GitMindSetup"); } private IReadOnlyList<string> GetBranchNames() { List<string> branchNames = new List<string>(); foreach (string arg in args .SkipWhile(a => a != "show") .TakeWhile(a => !a.StartsWith("/"))) { branchNames.Add(arg); } return branchNames; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace GitMind.Installation.Private { internal class CommandLine : ICommandLine { private readonly Lazy<IReadOnlyList<string>> lazyBranchNames; private readonly string[] args; public CommandLine() { args = Environment.GetCommandLineArgs(); lazyBranchNames = new Lazy<IReadOnlyList<string>>(GetBranchNames); } public bool IsSilent => args.Contains("/silent"); public bool IsInstall => args.Contains("/install") || IsSetupFile(); public bool IsUninstall => args.Contains("/uninstall"); public bool IsRunInstalled => args.Contains("/run"); public bool IsShowDiff => args.Length > 1 && args[1] == "diff"; public bool IsTest => args.Contains("/test"); public bool HasFolder => args.Contains("/d:") || IsTest; public string Folder => args.FirstOrDefault(a => a.StartsWith("/d:"))?.Substring(3); public IReadOnlyList<string> BranchNames => lazyBranchNames.Value; private bool IsSetupFile() { return Path.GetFileNameWithoutExtension( Assembly.GetEntryAssembly().Location).StartsWith("GitMindSetup"); } private IReadOnlyList<string> GetBranchNames() { List<string> branchNames = new List<string>(); foreach (string arg in args .SkipWhile(a => a != "show") .TakeWhile(a => !a.StartsWith("/"))) { branchNames.Add(arg); } return branchNames; } } }
mit
C#
aa3cac58ac48c8ed2a4cc01eb066470cf23a654d
Update assembly file
mattiasnordqvist/SlackbotAnchor
SlackbotAnchor/Properties/AssemblyInfo.cs
SlackbotAnchor/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Slackbot Anchor")] [assembly: AssemblyDescription("Access your slackbot from .Net. Not created by, affiliated with, or supported by Slack Technologies, Inc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mattias Nordqvist")] [assembly: AssemblyCopyright("Copyright © Mattias Nordqvist")] [assembly: AssemblyProduct("Slackbot Anchor")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("6950db62-9f07-43cd-81ec-be2a900f940e")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Slackbot Anchor")] [assembly: AssemblyDescription("Access your slackbot from .Net. Not created by, affiliated with, or supported by Slack Technologies, Inc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Slackbot Anchor")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6950db62-9f07-43cd-81ec-be2a900f940e")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
df004d7a49e443cbd100e2e8bb5e2a9f9c8a090f
Adjust dialog text
UselessToucan/osu,EVAST9919/osu,ppy/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,NeoAdonis/osu,naoey/osu,peppy/osu-new,naoey/osu,smoogipoo/osu,DrabWeb/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,EVAST9919/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,ZLima12/osu,DrabWeb/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu
osu.Game/Overlays/Chat/ExternalLinkDialog.cs
osu.Game/Overlays/Chat/ExternalLinkDialog.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Graphics; using osu.Game.Overlays.Dialog; namespace osu.Game.Overlays.Chat { public class ExternalLinkDialog : PopupDialog { public ExternalLinkDialog(string url, Action openExternalLinkAction) { HeaderText = "Just checking..."; BodyText = $"You are about to leave osu! and open the following link in a web browser:\n\n{url}"; Icon = FontAwesome.fa_warning; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = openExternalLinkAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!" }, }; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Game.Graphics; using osu.Game.Overlays.Dialog; namespace osu.Game.Overlays.Chat { public class ExternalLinkDialog : PopupDialog { public ExternalLinkDialog(string url, Action openExternalLinkAction) { BodyText = url; Icon = FontAwesome.fa_warning; HeaderText = "Are you sure you want to open the following?"; Buttons = new PopupDialogButton[] { new PopupDialogOkButton { Text = @"Yes. Go for it.", Action = openExternalLinkAction }, new PopupDialogCancelButton { Text = @"No! Abort mission!" }, }; } } }
mit
C#
7b7129b2f647fdfc799e9df7ad4532f2c5d9f02c
Update ShellUserConfirmation.cs
tiksn/TIKSN-Framework
TIKSN.Core/Shell/ShellUserConfirmation.cs
TIKSN.Core/Shell/ShellUserConfirmation.cs
using TIKSN.Progress; namespace TIKSN.Shell { public class ShellUserConfirmation : IUserConfirmation { private readonly IShellCommandContext _shellCommandContext; public ShellUserConfirmation(IShellCommandContext shellCommandContext) => this._shellCommandContext = shellCommandContext; public bool ShouldContinue(string query, string caption) => this._shellCommandContext.ShouldContinue(query, caption); public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) => this._shellCommandContext.ShouldContinue(query, caption, ref yesToAll, ref noToAll); public bool ShouldProcess(string target) => this._shellCommandContext.ShouldProcess(target); public bool ShouldProcess(string target, string action) => this._shellCommandContext.ShouldProcess(target, action); public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) => this._shellCommandContext.ShouldProcess(verboseDescription, verboseWarning, caption); } }
using TIKSN.Progress; namespace TIKSN.Shell { public class ShellUserConfirmation : IUserConfirmation { private readonly IShellCommandContext _shellCommandContext; public ShellUserConfirmation(IShellCommandContext shellCommandContext) { _shellCommandContext = shellCommandContext; } public bool ShouldContinue(string query, string caption) { return _shellCommandContext.ShouldContinue(query, caption); } public bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll) { return _shellCommandContext.ShouldContinue(query, caption, ref yesToAll, ref noToAll); } public bool ShouldProcess(string target) { return _shellCommandContext.ShouldProcess(target); } public bool ShouldProcess(string target, string action) { return _shellCommandContext.ShouldProcess(target, action); } public bool ShouldProcess(string verboseDescription, string verboseWarning, string caption) { return _shellCommandContext.ShouldProcess(verboseDescription, verboseWarning, caption); } } }
mit
C#
27dadbb3cf021cc5dd3fc48fd05efabc751d5a58
Add test for resolving nested types with namespaces
furesoft/cecil,joj/cecil,kzu/cecil,SiliconStudio/Mono.Cecil,saynomoo/cecil,sailro/cecil,ttRevan/cecil,fnajera-rac-de/cecil,xen2/cecil,gluck/cecil,cgourlay/cecil,mono/cecil,jbevain/cecil
Test/Mono.Cecil.Tests/NestedTypesTests.cs
Test/Mono.Cecil.Tests/NestedTypesTests.cs
using System; using Mono.Cecil; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class NestedTypesTests : BaseTestFixture { [Test] public void NestedTypes () { TestCSharp ("NestedTypes.cs", module => { var foo = module.GetType ("Foo"); Assert.AreEqual ("Foo", foo.Name); Assert.AreEqual ("Foo", foo.FullName); Assert.AreEqual (module, foo.Module); Assert.AreEqual (1, foo.NestedTypes.Count); var bar = foo.NestedTypes [0]; Assert.AreEqual ("Bar", bar.Name); Assert.AreEqual ("Foo/Bar", bar.FullName); Assert.AreEqual (module, bar.Module); Assert.AreEqual (1, bar.NestedTypes.Count); var baz = bar.NestedTypes [0]; Assert.AreEqual ("Baz", baz.Name); Assert.AreEqual ("Foo/Bar/Baz", baz.FullName); Assert.AreEqual (module, baz.Module); }); } [Test] public void DirectNestedType () { TestCSharp ("NestedTypes.cs", module => { var bingo = module.GetType ("Bingo"); var get_fuel = bingo.GetMethod ("GetFuel"); Assert.AreEqual ("Bingo/Fuel", get_fuel.ReturnType.FullName); }); } [Test] public void NestedTypeWithOwnNamespace () { TestModule ("bug-185.dll", module => { var foo = module.GetType ("Foo"); var foo_child = foo.NestedTypes [0]; Assert.AreEqual ("<IFoo<System.Byte[]>", foo_child.Namespace); Assert.AreEqual ("Do>d__0", foo_child.Name); Assert.AreEqual ("Foo/<IFoo<System.Byte[]>.Do>d__0", foo_child.FullName); var foo_def = foo_child.Resolve (); Assert.IsNotNull (foo_def); Assert.AreEqual (foo_child.FullName, foo_def.FullName); }); } } }
using System; using Mono.Cecil; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class NestedTypesTests : BaseTestFixture { [Test] public void NestedTypes () { TestCSharp ("NestedTypes.cs", module => { var foo = module.GetType ("Foo"); Assert.AreEqual ("Foo", foo.Name); Assert.AreEqual ("Foo", foo.FullName); Assert.AreEqual (module, foo.Module); Assert.AreEqual (1, foo.NestedTypes.Count); var bar = foo.NestedTypes [0]; Assert.AreEqual ("Bar", bar.Name); Assert.AreEqual ("Foo/Bar", bar.FullName); Assert.AreEqual (module, bar.Module); Assert.AreEqual (1, bar.NestedTypes.Count); var baz = bar.NestedTypes [0]; Assert.AreEqual ("Baz", baz.Name); Assert.AreEqual ("Foo/Bar/Baz", baz.FullName); Assert.AreEqual (module, baz.Module); }); } [Test] public void DirectNestedType () { TestCSharp ("NestedTypes.cs", module => { var bingo = module.GetType ("Bingo"); var get_fuel = bingo.GetMethod ("GetFuel"); Assert.AreEqual ("Bingo/Fuel", get_fuel.ReturnType.FullName); }); } [Test] public void NestedTypeWithOwnNamespace () { TestModule ("bug-185.dll", module => { var foo = module.GetType ("Foo"); var foo_child = foo.NestedTypes [0]; Assert.AreEqual ("<IFoo<System.Byte[]>", foo_child.Namespace); Assert.AreEqual ("Do>d__0", foo_child.Name); Assert.AreEqual ("Foo/<IFoo<System.Byte[]>.Do>d__0", foo_child.FullName); }); } } }
mit
C#
d67106260fed69d8a4ca91999d51a60d0606e93f
remove IAfterLoadSetting and associated function. No need for it
a9261/Opserver,VictoriaD/Opserver,volkd/Opserver,Janiels/Opserver,mqbk/Opserver,baflynn/Opserver,dteg/Opserver,manesiotise/Opserver,agrath/Opserver,opserver/Opserver,maurobennici/Opserver,wuanunet/Opserver,vebin/Opserver,michaelholzheimer/Opserver,vbfox/Opserver,vbfox/Opserver,manesiotise/Opserver,baflynn/Opserver,hotrannam/Opserver,hotrannam/Opserver,Janiels/Opserver,opserver/Opserver,rducom/Opserver,IDisposable/Opserver,volkd/Opserver,maurobennici/Opserver,huoxudong125/Opserver,wuanunet/Opserver,opserver/Opserver,agrath/Opserver,GABeech/Opserver,geffzhang/Opserver,a9261/Opserver,mqbk/Opserver,geffzhang/Opserver,VictoriaD/Opserver,michaelholzheimer/Opserver,jeddytier4/Opserver,18098924759/Opserver,IDisposable/Opserver,vebin/Opserver,GABeech/Opserver,rducom/Opserver,dteg/Opserver,jeddytier4/Opserver,18098924759/Opserver,huoxudong125/Opserver,manesiotise/Opserver
Opserver.Core/Settings/PagerdutySettings.cs
Opserver.Core/Settings/PagerdutySettings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackExchange.Opserver { public class PagerDutySettings : Settings<PagerDutySettings> { public override bool Enabled { get { return APIKey.HasValue(); } } public string APIKey { get; set; } public string APIBaseURL { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StackExchange.Opserver { public class PagerDutySettings : Settings<PagerDutySettings>, IAfterLoadActions { public override bool Enabled { get { return APIKey.HasValue(); } } public string APIKey { get; set; } public string APIBaseURL { get; set; } public void AfterLoad() { } } }
mit
C#
039bf229742fd733ad4263c0ec3d15bdab5252f8
Make use of LanguageRouteConstraintOption to filter available related cultures in CultureItem.
Talagozis/Talagozis.Website,Talagozis/Talagozis.Website,Talagozis/Talagozis.Website
Talagozis.Website/Models/Cms/CultureItem.cs
Talagozis.Website/Models/Cms/CultureItem.cs
using System.Collections.Generic; using System.Globalization; using System.Linq; using Microsoft.Extensions.Options; using Piranha.Extend.Fields; using Talagozis.AspNetCore.Localization; namespace Talagozis.Website.Models.Cms { public class CultureItem { // The id of the page public string Id { get; set; } // The model public CultureInfo cultureInfo { get; set; } // Gets a single item with the provided id using the // injected services you specify. static CultureItem GetById(string id) { return new CultureItem { Id = id, cultureInfo = CultureInfo.GetCultureInfo(id) }; } // Gets all of the available items to choose from using // the injected services you specify. static IEnumerable<DataSelectFieldItem> GetList(IOptions<LanguageRouteConstraintOption> options) { return options.Value.getCultures().Select(c => new DataSelectFieldItem { Id = c.TwoLetterISOLanguageName, Name = $"{c.EnglishName} ({c.NativeName})" }); } } }
using System.Collections.Generic; using System.Globalization; using System.Linq; using Piranha.Extend.Fields; namespace Talagozis.Website.Models.Cms { public class CultureItem { // The id of the page public string Id { get; set; } // The model public CultureInfo cultureInfo { get; set; } // Gets a single item with the provided id using the // injected services you specify. static CultureItem GetById(string id) { return new CultureItem { Id = id, cultureInfo = CultureInfo.GetCultureInfo(id) }; } // Gets all of the available items to choose from using // the injected services you specify. static IEnumerable<DataSelectFieldItem> GetList() { return CultureInfo.GetCultures(CultureTypes.NeutralCultures).Select(c => new DataSelectFieldItem { Id = c.TwoLetterISOLanguageName, Name = $"{c.EnglishName} ({c.NativeName})" }); } } }
mit
C#
909792c866f362192e5a24769bb7c46fec15c68d
Test commit for jenkins
emilti/TravelAlbum,emilti/TravelAlbum,emilti/TravelAlbum
TravelCatalog/Controllers/HomeController.cs
TravelCatalog/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TravelCatalog.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "TEST!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 TravelCatalog.Controllers { public class HomeController : Controller { public ActionResult Index() { 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#
a05048fae4d636f6bf047fe7b1bd225daeceea02
use more descriptive generic type name
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/Services/SeedService.cs
src/FilterLists.Services/Services/SeedService.cs
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using FilterLists.Data; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.Services { public class SeedService { private readonly FilterListsDbContext filterListsDbContext; public SeedService(FilterListsDbContext filterListsDbContext) { this.filterListsDbContext = filterListsDbContext; } public async Task<IEnumerable<TSeedDto>> GetAll<TEntity, TSeedDto>() where TEntity : class { return await filterListsDbContext.Set<TEntity>().AsNoTracking().ProjectTo<TSeedDto>().ToArrayAsync(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using FilterLists.Data; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.Services { public class SeedService { private readonly FilterListsDbContext filterListsDbContext; public SeedService(FilterListsDbContext filterListsDbContext) { this.filterListsDbContext = filterListsDbContext; } public async Task<IEnumerable<TMapped>> GetAll<TEntity, TMapped>() where TEntity : class { return await filterListsDbContext.Set<TEntity>().AsNoTracking().ProjectTo<TMapped>().ToArrayAsync(); } } }
mit
C#
608ceaf520c4bc6e0ea70e239819179ad02c10d6
optimize async with automapper
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Services/Services/SeedService.cs
src/FilterLists.Services/Services/SeedService.cs
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper.QueryableExtensions; using FilterLists.Data; using FilterLists.Data.Entities; using FilterLists.Services.Models.Seed; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.Services { public class SeedService { private readonly FilterListsDbContext filterListsDbContext; public SeedService(FilterListsDbContext filterListsDbContext) { this.filterListsDbContext = filterListsDbContext; } public async Task<IEnumerable<FilterListSeedDto>> GetAllFilterLists() { return await filterListsDbContext.Set<FilterList>().ProjectTo<FilterListSeedDto>().ToListAsync(); } public async Task<IEnumerable<LanguageSeedDto>> GetAllLanguages() { return await filterListsDbContext.Set<Language>().ProjectTo<LanguageSeedDto>().ToListAsync(); } public async Task<IEnumerable<LicenseSeedDto>> GetAllLicenses() { return await filterListsDbContext.Set<License>().ProjectTo<LicenseSeedDto>().ToListAsync(); } public async Task<IEnumerable<MaintainerSeedDto>> GetAllMaintainers() { return await filterListsDbContext.Set<Maintainer>().ProjectTo<MaintainerSeedDto>().ToListAsync(); } public async Task<IEnumerable<SoftwareSeedDto>> GetAllSoftware() { return await filterListsDbContext.Set<Software>().ProjectTo<SoftwareSeedDto>().ToListAsync(); } public async Task<IEnumerable<SyntaxSeedDto>> GetAllSyntaxes() { return await filterListsDbContext.Set<Syntax>().ProjectTo<SyntaxSeedDto>().ToListAsync(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using AutoMapper.QueryableExtensions; using FilterLists.Data; using FilterLists.Data.Entities; using FilterLists.Services.Models.Seed; using Microsoft.EntityFrameworkCore; namespace FilterLists.Services.Services { public class SeedService { private readonly FilterListsDbContext filterListsDbContext; private readonly IMapper mapper; public SeedService(FilterListsDbContext filterListsDbContext, IMapper mapper) { this.filterListsDbContext = filterListsDbContext; this.mapper = mapper; } public async Task<IEnumerable<FilterListSeedDto>> GetAllFilterLists() { return await filterListsDbContext.Set<FilterList>().ProjectTo<FilterListSeedDto>().ToListAsync(); } public async Task<IEnumerable<LanguageSeedDto>> GetAllLanguages() { return await filterListsDbContext.Set<Language>().ProjectTo<LanguageSeedDto>().ToListAsync(); } public async Task<IEnumerable<LicenseSeedDto>> GetAllLicenses() { return await filterListsDbContext.Set<License>().ProjectTo<LicenseSeedDto>().ToListAsync(); } public async Task<IEnumerable<MaintainerSeedDto>> GetAllMaintainers() { return await filterListsDbContext.Set<Maintainer>().ProjectTo<MaintainerSeedDto>().ToListAsync(); } public async Task<IEnumerable<SoftwareSeedDto>> GetAllSoftware() { return await filterListsDbContext.Set<Software>().ProjectTo<SoftwareSeedDto>().ToListAsync(); } public async Task<IEnumerable<SyntaxSeedDto>> GetAllSyntaxes() { return await filterListsDbContext.Set<Syntax>().ProjectTo<SyntaxSeedDto>().ToListAsync(); } } }
mit
C#
2aabdbaabaf622ad927d2db1b64394bf42c0fd0d
Use request.IsSecureConnection if no 'X-Forwarded-Proto' header
funnelweblog/FunnelWeb,funnelweblog/FunnelWeb,funnelweblog/FunnelWeb
src/FunnelWeb/Utilities/HttpRequestExtensions.cs
src/FunnelWeb/Utilities/HttpRequestExtensions.cs
using System; using System.Web; namespace FunnelWeb.Utilities { public static class HttpRequestExtensions { public static Uri GetOriginalUrl(this HttpRequest request) { return GetOriginalUrl(new HttpRequestWrapper(request)); } public static Uri GetBaseUrl(this HttpRequestBase request) { return new Uri(new Uri(request.GetOriginalUrl().GetLeftPart(UriPartial.Authority)), request.ApplicationPath ?? ""); } public static Uri GetOriginalUrl(this HttpRequestBase request) { var hostUrl = new UriBuilder(); string hostHeader = request.Headers["Host"]; if (hostHeader.Contains(":")) { hostUrl.Host = hostHeader.Split(':')[0]; hostUrl.Port = Convert.ToInt32(hostHeader.Split(':')[1]); } else { hostUrl.Host = hostHeader; hostUrl.Port = -1; } Uri url = request.Url; var uriBuilder = new UriBuilder(url); // When the application is run behind a load-balancer (or forward proxy), request.IsSecureConnection returns 'true' or 'false' // based on the request from the load-balancer to the web server (e.g. IIS) and not the actual request to the load-balancer. // The same is also applied to request.Url.Scheme (or uriBuilder.Scheme, as in our case). bool isSecureConnection = string.IsNullOrWhiteSpace(request.Headers["X-Forwarded-Proto"]) ? request.IsSecureConnection : String.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase); if (isSecureConnection) { uriBuilder.Port = hostUrl.Port == -1 ? 443 : hostUrl.Port; uriBuilder.Scheme = "https"; } else { uriBuilder.Port = hostUrl.Port == -1 ? 80 : hostUrl.Port; uriBuilder.Scheme = "http"; } uriBuilder.Host = hostUrl.Host; return uriBuilder.Uri; } public static string GetOriginalUserHostAddress(this HttpRequest request) { return GetOriginalUserHostAddress(new HttpRequestWrapper(request)); } public static string GetOriginalUserHostAddress(this HttpRequestBase request) { var forwardedFor = request.Headers["X-Forwarded-For"]; if (String.IsNullOrEmpty(forwardedFor)) { return request.UserHostAddress; } return forwardedFor; } } }
using System; using System.Web; namespace FunnelWeb.Utilities { public static class HttpRequestExtensions { public static Uri GetOriginalUrl(this HttpRequest request) { return GetOriginalUrl(new HttpRequestWrapper(request)); } public static Uri GetBaseUrl(this HttpRequestBase request) { return new Uri(new Uri(request.GetOriginalUrl().GetLeftPart(UriPartial.Authority)), request.ApplicationPath ?? ""); } public static Uri GetOriginalUrl(this HttpRequestBase request) { var hostUrl = new UriBuilder(); string hostHeader = request.Headers["Host"]; if (hostHeader.Contains(":")) { hostUrl.Host = hostHeader.Split(':')[0]; hostUrl.Port = Convert.ToInt32(hostHeader.Split(':')[1]); } else { hostUrl.Host = hostHeader; hostUrl.Port = -1; } Uri url = request.Url; var uriBuilder = new UriBuilder(url); // When the application is run behind a load-balancer (or forward proxy), request.IsSecureConnection returns 'true' or 'false' // based on the request from the load-balancer to the web server (e.g. IIS) and not the actual request to the load-balancer. // The same is also applied to request.Url.Scheme (or uriBuilder.Scheme, as in our case). bool isSecureConnection = String.Equals(request.Headers["X-Forwarded-Proto"], "https", StringComparison.OrdinalIgnoreCase); if (isSecureConnection) { uriBuilder.Port = hostUrl.Port == -1 ? 443 : hostUrl.Port; uriBuilder.Scheme = "https"; } else { uriBuilder.Port = hostUrl.Port == -1 ? 80 : hostUrl.Port; uriBuilder.Scheme = "http"; } uriBuilder.Host = hostUrl.Host; return uriBuilder.Uri; } public static string GetOriginalUserHostAddress(this HttpRequest request) { return GetOriginalUserHostAddress(new HttpRequestWrapper(request)); } public static string GetOriginalUserHostAddress(this HttpRequestBase request) { var forwardedFor = request.Headers["X-Forwarded-For"]; if (String.IsNullOrEmpty(forwardedFor)) { return request.UserHostAddress; } return forwardedFor; } } }
bsd-3-clause
C#
a38fbcf1a56006aba73b34bf056d0c54938fee80
Bump version to 1.2.3
e-rik/XRoadLib,e-rik/XRoadLib,janno-p/XRoadLib
src/XRoadLib/Attributes/XRoadServiceAttribute.cs
src/XRoadLib/Attributes/XRoadServiceAttribute.cs
using System; using XRoadLib.Schema; using XRoadLib.Serialization.Mapping; namespace XRoadLib.Attributes { /// <summary> /// Defines operation method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class XRoadServiceAttribute : Attribute { private static readonly Type serviceMapType = typeof(ServiceMap); internal uint? addedInVersion; internal uint? removedInVersion; /// <summary> /// Operation name. /// </summary> public string Name { get; } /// <summary> /// ServiceMap type which implements operation definition. /// </summary> public virtual Type ServiceMapType => serviceMapType; /// <summary> /// Abstract operations do not define binding details. /// </summary> public virtual bool IsAbstract { get; set; } /// <summary> /// Hidden operations are not included in service description. /// </summary> public virtual bool IsHidden { get; set; } /// <summary> /// X-Road service version which first defined given operation. /// </summary> public virtual uint AddedInVersion { get => addedInVersion.GetValueOrDefault(1u); set => addedInVersion = value; } /// <summary> /// X-Road service version which removed given operation. /// </summary> public virtual uint RemovedInVersion { get => removedInVersion.GetValueOrDefault(uint.MaxValue); set => removedInVersion = value; } /// <summary> /// Provides extension specific customizations for the schema. /// </summary> public virtual ISchemaExporter SchemaExporter { get; } = null; /// <summary> /// Attachment serialization mode for service input. Available options are `Xml` (binary is serialized inside XML document /// using base64 encoding or MTOM optimization) or `Attachment` (binary is serialized as mime multipart attachment) /// </summary> public virtual BinaryMode InputBinaryMode { get; set; } = BinaryMode.Xml; /// <summary> /// Attachment serialization mode for service output. Available options are `Xml` (binary is serialized inside XML document /// using base64 encoding or MTOM optimization) or `Attachment` (binary is serialized as mime multipart attachment) /// </summary> public virtual BinaryMode OutputBinaryMode { get; set; }= BinaryMode.Xml; /// <summary> /// Initializes new operation definition. /// </summary> public XRoadServiceAttribute(string name) { Name = name; } } }
using System; using XRoadLib.Schema; using XRoadLib.Serialization.Mapping; namespace XRoadLib.Attributes { /// <summary> /// Defines operation method. /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class XRoadServiceAttribute : Attribute { private static readonly Type serviceMapType = typeof(ServiceMap); internal uint? addedInVersion; internal uint? removedInVersion; /// <summary> /// Operation name. /// </summary> public string Name { get; } /// <summary> /// ServiceMap type which implements operation definition. /// </summary> public virtual Type ServiceMapType => serviceMapType; /// <summary> /// Abstract operations do not define binding details. /// </summary> public virtual bool IsAbstract { get; set; } /// <summary> /// Hidden operations are not included in service description. /// </summary> public virtual bool IsHidden { get; set; } /// <summary> /// X-Road service version which first defined given operation. /// </summary> public virtual uint AddedInVersion { get => addedInVersion.GetValueOrDefault(1u); set => addedInVersion = value; } /// <summary> /// X-Road service version which removed given operation. /// </summary> public virtual uint RemovedInVersion { get => removedInVersion.GetValueOrDefault(uint.MaxValue); set => removedInVersion = value; } /// <summary> /// Provides extension specific customizations for the schema. /// </summary> public virtual ISchemaExporter SchemaExporter { get; } = null; /// <summary> /// Attachment serialization mode for service input. Available options are `Xml` (binary is serialized inside XML document /// using base64 encoding) or `Attachment` (binary is serialized using MTOM/XOP or mime multipart attachment) /// </summary> public virtual BinaryMode InputBinaryMode { get; set; } = BinaryMode.Xml; /// <summary> /// Attachment serialization mode for service output. Available options are `Xml` (binary is serialized inside XML document /// using base64 encoding) or `Attachment` (binary is serialized using MTOM/XOP or mime multipart attachment) /// </summary> public virtual BinaryMode OutputBinaryMode { get; set; }= BinaryMode.Xml; /// <summary> /// Initializes new operation definition. /// </summary> public XRoadServiceAttribute(string name) { Name = name; } } }
mit
C#
8df1a8b97abccec6e6beb0277cd5054cf9901204
update texture size
Flugmango/GlobeVR
Assets/OverlayHandler.cs
Assets/OverlayHandler.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OverlayHandler : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // adds Overlay to Globe // @param type type of overlay, "none" for no overlay (removing the actual one) public void addOverlay(string type) { string url = "http://localhost:3000/overlay/" + type; WWW www = new WWW(url); StartCoroutine(loadImage(www)); } IEnumerator loadImage(WWW www) { Texture2D tex; tex = new Texture2D(128, 256, TextureFormat.DXT1, false); yield return www; www.LoadImageIntoTexture(tex); //GetComponent<Renderer>().material.mainTexture = tex; GameObject globe = GameObject.FindGameObjectWithTag("Globe"); Renderer globeRenderer = globe.GetComponent<Renderer>(); Material globeMaterial = globeRenderer.material; globeMaterial.EnableKeyword("_EMISSION"); globeMaterial.SetTexture("_EMISSION", tex); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OverlayHandler : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } // adds Overlay to Globe // @param type type of overlay, "none" for no overlay (removing the actual one) public void addOverlay(string type) { string url = "http://localhost:3000/overlay/" + type; WWW www = new WWW(url); StartCoroutine(loadImage(www)); } IEnumerator loadImage(WWW www) { Texture2D tex; tex = new Texture2D(4, 4, TextureFormat.DXT1, false); yield return www; www.LoadImageIntoTexture(tex); //GetComponent<Renderer>().material.mainTexture = tex; GameObject globe = GameObject.FindGameObjectWithTag("Globe"); Renderer globeRenderer = globe.GetComponent<Renderer>(); Material globeMaterial = globeRenderer.material; globeMaterial.EnableKeyword("_EMISSION"); globeMaterial.SetTexture("_EMISSION", tex); } }
mit
C#
7e19a420faee575f8408c082910823466adcad09
Verify that type name matcher gets called with "help"
appharbor/appharbor-cli
src/AppHarbor.Tests/CommandDispatcherTest.cs
src/AppHarbor.Tests/CommandDispatcherTest.cs
using System; using System.Linq; using Castle.MicroKernel; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class CommandDispatcherTest { private static Type FooCommandType = typeof(FooCommand); public class FooCommand : ICommand { public virtual void Execute(string[] arguments) { } } [Theory, AutoCommandData] public void ShouldDispatchHelpWhenNoCommand( [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); commandDispatcher.Dispatch(new string[0]); typeNameMatcher.VerifyAll(); } [Theory] [InlineAutoCommandData("foo")] [InlineAutoCommandData("foo:bar")] public void ShouldDispatchCommandWithoutParameters( string argument, [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); var dispatchArguments = new string[] { argument }; commandDispatcher.Dispatch(dispatchArguments); command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any()))); } [Theory] [InlineAutoCommandData("foo:bar baz", "baz")] [InlineAutoCommandData("foo baz", "baz")] public void ShouldDispatchCommandWithParameter( string argument, string commandArgument, [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); commandDispatcher.Dispatch(argument.Split()); command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument)))); } } }
using System; using System.Linq; using Castle.MicroKernel; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class CommandDispatcherTest { private static Type FooCommandType = typeof(FooCommand); public class FooCommand : ICommand { public virtual void Execute(string[] arguments) { } } [Theory, AutoCommandData] public void ShouldDispatchHelpWhenNoCommand( [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType("help")).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); commandDispatcher.Dispatch(new string[0]); } [Theory] [InlineAutoCommandData("foo")] [InlineAutoCommandData("foo:bar")] public void ShouldDispatchCommandWithoutParameters( string argument, [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType(argument)).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); var dispatchArguments = new string[] { argument }; commandDispatcher.Dispatch(dispatchArguments); command.Verify(x => x.Execute(It.Is<string[]>(y => !y.Any()))); } [Theory] [InlineAutoCommandData("foo:bar baz", "baz")] [InlineAutoCommandData("foo baz", "baz")] public void ShouldDispatchCommandWithParameter( string argument, string commandArgument, [Frozen]Mock<ITypeNameMatcher> typeNameMatcher, [Frozen]Mock<IKernel> kernel, Mock<FooCommand> command, CommandDispatcher commandDispatcher) { typeNameMatcher.Setup(x => x.GetMatchedType(argument.Split().First())).Returns(FooCommandType); kernel.Setup(x => x.Resolve(FooCommandType)).Returns(command.Object); commandDispatcher.Dispatch(argument.Split()); command.Verify(x => x.Execute(It.Is<string[]>(y => y.Length == 1 && y.Any(z => z == commandArgument)))); } } }
mit
C#
088c404e70dbdabf8dbe44e27a6bdb1e83c5f2c6
Add required attribute to let a test pass
andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop
src/BloomTests/ProblemReporterDialogTests.cs
src/BloomTests/ProblemReporterDialogTests.cs
// Copyright (c) 2014-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Reflection; using NUnit.Framework; using Bloom.MiscUI; namespace BloomTests { [TestFixture] [Category("RequiresUI")] public class ProblemReporterDialogTests { class ProblemReporterDialogDouble: ProblemReporterDialog { public ProblemReporterDialogDouble(): base(null, null) { Success = true; _youTrackProjectKey = "AUT"; this.Load += (sender, e) => { _description.Text = "Created by unit test of " + Assembly.GetAssembly(this.GetType()).FullName; _okButton_Click(sender, e); }; } public bool Success { get; private set; } protected override void UpdateDisplay() { if (_state == State.Success) Close(); } protected override void ChangeState(State state) { if (state == State.CouldNotAutomaticallySubmit) { Success = false; Close(); } base.ChangeState(state); } } /// <summary> /// This is just a smoke-test that will notify us if youtrack stops working with the API we're relying on. /// It sends reports to the AUT project on youtrack /// </summary> [Test] [Category("SkipOnTeamCity")] //I don't know why this is blocked, probably we need a firewall opening [Platform(Exclude = "Linux", Reason = "YouTrackSharp is too Windows-centric")] [STAThread] public void CanSubmitProblemReportTestProject() { using (var dlg = new ProblemReporterDialogDouble()) { dlg.ShowDialog(); Assert.That(dlg.Success, Is.True, "Automatic submission of issue failed"); } } } }
// Copyright (c) 2014-2015 SIL International // This software is licensed under the MIT License (http://opensource.org/licenses/MIT) using System; using System.Reflection; using NUnit.Framework; using Bloom.MiscUI; namespace BloomTests { [TestFixture] [Category("RequiresUI")] public class ProblemReporterDialogTests { class ProblemReporterDialogDouble: ProblemReporterDialog { public ProblemReporterDialogDouble(): base(null, null) { Success = true; _youTrackProjectKey = "AUT"; this.Load += (sender, e) => { _description.Text = "Created by unit test of " + Assembly.GetAssembly(this.GetType()).FullName; _okButton_Click(sender, e); }; } public bool Success { get; private set; } protected override void UpdateDisplay() { if (_state == State.Success) Close(); } protected override void ChangeState(State state) { if (state == State.CouldNotAutomaticallySubmit) { Success = false; Close(); } base.ChangeState(state); } } /// <summary> /// This is just a smoke-test that will notify us if youtrack stops working with the API we're relying on. /// It sends reports to the AUT project on youtrack /// </summary> [Test] [Category("SkipOnTeamCity")] //I don't know why this is blocked, probably we need a firewall opening [Platform(Exclude = "Linux", Reason = "YouTrackSharp is too Windows-centric")] public void CanSubmitProblemReportTestProject() { using (var dlg = new ProblemReporterDialogDouble()) { dlg.ShowDialog(); Assert.That(dlg.Success, Is.True, "Automatic submission of issue failed"); } } } }
mit
C#
e2416efbe09dd08a9a7b4595fbe522173c74105a
Update RobinManuelThiel.cs (#193)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/RobinManuelThiel.cs
src/Firehose.Web/Authors/RobinManuelThiel.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class RobinManuelThiel : IWorkAtXamarinOrMicrosoft, IFilterMyBlogPosts { public bool Filter(SyndicationItem item) { return item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Where(i => i.Name.Equals("Xamarin", StringComparison.OrdinalIgnoreCase)).Any(); } public string FirstName => "Robin-Manuel"; public string LastName => "Thiel"; public string ShortBioOrTagLine => "Technical Evangelist at Microsoft by day, tinker and fiddler by night. Loves everything with a power plug or IP address."; public string StateOrRegion => "Munich, Germany"; public string EmailAddress => string.Empty; public string TwitterHandle => "einRobby"; public string GitHubHandle => "robinmanuelthiel"; public GeoPosition Position => new GeoPosition(48.177622, 11.5912643); public Uri WebSite => new Uri("http://pumpingco.de/"); public string GravatarHash => "1b8fabaa8d66250a7049bdb9ecf44397"; public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://pumpingco.de/feed/"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class RobinManuelThiel : IWorkAtXamarinOrMicrosoft, IFilterMyBlogPosts { public bool Filter(SyndicationItem item) { return item.Title.Text.ToLowerInvariant().Contains("xamarin") || item.Categories.Where(i => i.Name.Equals("Xamarin", StringComparison.OrdinalIgnoreCase)).Any(); } public string FirstName => "Robin-Manuel"; public string LastName => "Thiel"; public string ShortBioOrTagLine => ""; public string StateOrRegion => "Munich, Germany"; public string EmailAddress => string.Empty; public string TwitterHandle => "einRobby"; public Uri WebSite => new Uri("http://pumpingco.de/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://pumpingco.de/feed/"); } } public string GravatarHash => "1b8fabaa8d66250a7049bdb9ecf44397"; public string GitHubHandle => string.Empty; public GeoPosition Position => new GeoPosition(48.177622, 11.5912643); } }
mit
C#
3561dc9b9966056802916473f622eb07a88855c8
Update ISiteVar.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/api/ISiteVar.cs
src/api/ISiteVar.cs
// Copyright 2005-2006 University of Wisconsin // All rights reserved. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// Represents a variable with values for the sites on a landscape. /// </summary> public interface ISiteVar<T> : ISiteVariable { /// <summary> /// Gets or sets the value for a particular site. /// </summary> T this[Site site] { get; set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for the active sites to the same value. /// </summary> T ActiveSiteValues { set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for the inactive sites to the same value. /// </summary> T InactiveSiteValues { set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for both active and inactive sites to the same /// value. /// </summary> T SiteValues { set; } } }
// Copyright 2005-2006 University of Wisconsin // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// Represents a variable with values for the sites on a landscape. /// </summary> public interface ISiteVar<T> : ISiteVariable { /// <summary> /// Gets or sets the value for a particular site. /// </summary> T this[Site site] { get; set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for the active sites to the same value. /// </summary> T ActiveSiteValues { set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for the inactive sites to the same value. /// </summary> T InactiveSiteValues { set; } //--------------------------------------------------------------------- /// <summary> /// Sets all the values for both active and inactive sites to the same /// value. /// </summary> T SiteValues { set; } } }
apache-2.0
C#
c0f949fecf6a41b7e26f97d555c3e802141aa47e
Fix bug in assembly file versioning ("*" was included in file version string)
oysteinkrog/resharper-reformatutils,oysteinkrog/resharper-reformatutils
src/ReformatUtils/Properties/AssemblyInfo.cs
src/ReformatUtils/Properties/AssemblyInfo.cs
using System.Reflection; using JetBrains.ActionManagement; using JetBrains.Application.PluginSupport; // 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("Reformatting Utilities")] [assembly: AssemblyDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: AssemblyCompany("Øystein Krog")] [assembly: AssemblyProduct("ReformatUtils")] [assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.*")] // The following information is displayed by ReSharper in the Plugins dialog [assembly: PluginTitle("Reformatting Utilities")] [assembly: PluginDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: PluginVendor("Øystein Krog")]
using System.Reflection; using JetBrains.ActionManagement; using JetBrains.Application.PluginSupport; // 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("Reformatting Utilities")] [assembly: AssemblyDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: AssemblyCompany("Øystein Krog")] [assembly: AssemblyProduct("ReformatUtils")] [assembly: AssemblyCopyright("Copyright © Øystein Krog, 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.3.0.*")] [assembly: AssemblyFileVersion("1.3.0.*")] // The following information is displayed by ReSharper in the Plugins dialog [assembly: PluginTitle("Reformatting Utilities")] [assembly: PluginDescription( "A resharper plugin that provides actions and shortcuts for reformatting based on scope (e.g. reformat method)") ] [assembly: PluginVendor("Øystein Krog")]
mit
C#
1ccaefd941b87240e52a9204b368be7800b8b4a4
remove the try catch block; the error shouldn't be ignored
cloudfoundry-incubator/garden-windows,cloudfoundry-incubator/garden-windows,cloudfoundry/garden-windows,cloudfoundry/garden-windows,stefanschneider/garden-windows,cloudfoundry/garden-windows,cloudfoundry-incubator/garden-windows,stefanschneider/garden-windows,stefanschneider/garden-windows
Containerizer/Program.cs
Containerizer/Program.cs
using Microsoft.Owin.Hosting; using System; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using Owin.WebSocket; using Owin.WebSocket.Extensions; using System.Threading.Tasks; namespace Containerizer { public class Program { private static readonly ManualResetEvent ExitLatch = new ManualResetEvent(false); static void Main(string[] args) { var port = (args.Length == 1 ? args[0] : "80"); Console.CancelKeyPress += (s, e) => { e.Cancel = true; ExitLatch.Set(); }; // Start OWIN host using (WebApp.Start<Startup>("http://*:" + port + "/")) { Console.WriteLine("SUCCESS: started"); // Create HttpCient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync("http://localhost:" + port + "/api/ping").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.WriteLine("Control-C to quit."); ExitLatch.WaitOne(); } } } }
using Microsoft.Owin.Hosting; using System; using System.Net.Http; using System.Net.WebSockets; using System.Text; using System.Threading; using Owin.WebSocket; using Owin.WebSocket.Extensions; using System.Threading.Tasks; namespace Containerizer { public class Program { private static readonly ManualResetEvent ExitLatch = new ManualResetEvent(false); static void Main(string[] args) { var port = (args.Length == 1 ? args[0] : "80"); Console.CancelKeyPress += (s, e) => { e.Cancel = true; ExitLatch.Set(); }; // Start OWIN host try { using (WebApp.Start<Startup>("http://*:" + port + "/")) { Console.WriteLine("SUCCESS: started"); // Create HttpCient and make a request to api/values HttpClient client = new HttpClient(); var response = client.GetAsync("http://localhost:" + port + "/api/ping").Result; Console.WriteLine(response); Console.WriteLine(response.Content.ReadAsStringAsync().Result); Console.WriteLine("Control-C to quit."); ExitLatch.WaitOne(); } } catch (Exception ex) { Console.WriteLine("ERRROR: " + ex.Message); } } } }
apache-2.0
C#
2414e0da96e75668647baba6216ddcf4e844c1b1
Reset protagonist balance to 0
leodenault/Beautiful-Dream-Forever,leodenault/Beautiful-Dream-Forever,leodenault/Beautiful-Dream-Forever,leodenault/Beautiful-Dream-Forever
Assets/src/model/Protagonist.cs
Assets/src/model/Protagonist.cs
using System; class Protagonist { private static Protagonist INSTANCE; private static int MAX_MONEY = 99; private int balance; public int Balance { get { return balance; } } private Inventory inventory; public Inventory Inventory { get { return inventory; } } private Outfit outfit; private Protagonist() { balance = 0; outfit = new Outfit(); inventory = new Inventory(); } public static Protagonist GetInstance() { if (INSTANCE == null) { INSTANCE = new Protagonist(); } return INSTANCE; } public bool modifyBalance(int difference) { if (difference + balance < 0) { return false; } balance = Math.Min(balance + difference, MAX_MONEY); return true; } public bool CanPurchase(int price) { return (price >= 0) && balance - price >= 0; } }
using System; class Protagonist { private static Protagonist INSTANCE; private static int MAX_MONEY = 99; private int balance; public int Balance { get { return balance; } } private Inventory inventory; public Inventory Inventory { get { return inventory; } } private Outfit outfit; private Protagonist() { balance = 99; outfit = new Outfit(); inventory = new Inventory(); } public static Protagonist GetInstance() { if (INSTANCE == null) { INSTANCE = new Protagonist(); } return INSTANCE; } public bool modifyBalance(int difference) { if (difference + balance < 0) { return false; } balance = Math.Min(balance + difference, MAX_MONEY); return true; } public bool CanPurchase(int price) { return (price >= 0) && balance - price >= 0; } }
mit
C#
c918cb92395bcbe609f4c14d07178725194ff519
Update CreateAssetMenu for ScriptableObjectExample
madsbangh/EasyButtons
Assets/EasyButtons/ScriptableObjectExample.cs
Assets/EasyButtons/ScriptableObjectExample.cs
using UnityEngine; namespace EasyButtons { [CreateAssetMenu(fileName = "ScriptableObjectExample.asset", menuName = "EasyButtons/ScriptableObjectExample")] public class ScriptableObjectExample : ScriptableObject { [Button] public void SayHello() { Debug.Log("Hello"); } [Button(ButtonMode.DisabledInPlayMode)] public void SayHelloEditor() { Debug.Log("Hello from edit mode"); } [Button(ButtonMode.EnabledInPlayMode)] public void SayHelloPlayMode() { Debug.Log("Hello from play mode"); } } }
using UnityEngine; namespace EasyButtons { [CreateAssetMenu(fileName = "Example.asset", menuName = "New Example ScriptableObject")] public class ScriptableObjectExample : ScriptableObject { [Button] public void SayHello() { Debug.Log("Hello"); } [Button(ButtonMode.DisabledInPlayMode)] public void SayHelloEditor() { Debug.Log("Hello from edit mode"); } [Button(ButtonMode.EnabledInPlayMode)] public void SayHelloPlayMode() { Debug.Log("Hello from play mode"); } } }
mit
C#
d0ffe3ba52c4a210cd9b32aaff6a2b840e3fd948
Update Examples/.vs/Aspose.Email.Examples.CSharp/v15/Server/sqlite3/storage.ide-wal
aspose-email/Aspose.Email-for-.NET,asposeemail/Aspose_Email_NET
Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs
Examples/CSharp/Outlook/OLM/LoadAndReadOLMFile.cs
using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } }
using System; using Aspose.Email.Storage.Olm; using Aspose.Email.Mapi; namespace Aspose.Email.Examples.CSharp.Email.Outlook.OLM { class LoadAndReadOLMFile { public static void Run() { // The path to the File directory. string dataDir = RunExamples.GetDataDir_Outlook(); string dst = dataDir + "OutlookforMac.olm"; // ExStart:LoadAndReadOLMFile using (OlmStorage storage = new OlmStorage(dst)) { foreach (OlmFolder folder in storage.FolderHierarchy) { if (folder.HasMessages) { // extract messages from folder foreach (MapiMessage msg in storage.EnumerateMessages(folder)) { Console.WriteLine("Subject: " + msg.Subject); } } // read sub-folders if (folder.SubFolders.Count > 0) { foreach (OlmFolder sub_folder in folder.SubFolders) { Console.WriteLine("Subfolder: " + sub_folder.Name); } } } } // ExEnd:LoadAndReadOLMFile } } }
mit
C#
f26fd83575aa2174f4b1ad92a32792a7d790d334
Make VerseRefExtensionsTests.SendScrReference "By Hand Only"
sillsdev/Glyssen,sillsdev/Glyssen
GlyssenTests/Utilities/VerseRefExtensionsTests.cs
GlyssenTests/Utilities/VerseRefExtensionsTests.cs
using System; using System.Threading; using System.Windows.Forms; using Glyssen.Utilities; using NUnit.Framework; using Paratext; using SIL.Windows.Forms.Scripture; namespace GlyssenTests.Utilities { class VerseRefExtensionsTests { [Test, Ignore("By Hand Only")] public void SendScrReference() { DummyForm.Start(); // MAT 28:18 VerseRef vr = new VerseRef(040028018); vr.SendScrReference(); Thread.Sleep(1000); Assert.AreEqual(vr, DummyForm.MessageReceived); DummyForm.Stop(); } private class DummyForm : Form { public static VerseRef MessageReceived; private static DummyForm mInstance; public static void Start() { Thread t = new Thread(RunForm); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); } public static void Stop() { if (mInstance == null) throw new InvalidOperationException("Stop without Start"); mInstance.Invoke(new MethodInvoker(mInstance.EndForm)); } private static void RunForm() { Application.Run(new DummyForm()); } private void EndForm() { Close(); } protected override void SetVisibleCore(bool value) { // Prevent window getting visible if (mInstance == null) CreateHandle(); mInstance = this; value = false; base.SetVisibleCore(value); } protected override void WndProc(ref Message msg) { if (msg.Msg == SantaFeFocusMessageHandler.FocusMsg) { var verseRef = new VerseRef(SantaFeFocusMessageHandler.ReceiveFocusMessage(msg)); MessageReceived = verseRef; } base.WndProc(ref msg); } } } }
using System; using System.Threading; using System.Windows.Forms; using Glyssen.Utilities; using NUnit.Framework; using Paratext; using SIL.Windows.Forms.Scripture; namespace GlyssenTests.Utilities { class VerseRefExtensionsTests { [Test] public void SendScrReference() { DummyForm.Start(); // MAT 28:18 VerseRef vr = new VerseRef(040028018); vr.SendScrReference(); Thread.Sleep(2000); Assert.AreEqual(vr, DummyForm.MessageReceived); DummyForm.Stop(); } private class DummyForm : Form { public static VerseRef MessageReceived; private static DummyForm mInstance; public static void Start() { Thread t = new Thread(RunForm); t.SetApartmentState(ApartmentState.STA); t.IsBackground = true; t.Start(); } public static void Stop() { if (mInstance == null) throw new InvalidOperationException("Stop without Start"); mInstance.Invoke(new MethodInvoker(mInstance.EndForm)); } private static void RunForm() { Application.Run(new DummyForm()); } private void EndForm() { Close(); } protected override void SetVisibleCore(bool value) { // Prevent window getting visible if (mInstance == null) CreateHandle(); mInstance = this; value = false; base.SetVisibleCore(value); } protected override void WndProc(ref Message msg) { if (msg.Msg == SantaFeFocusMessageHandler.FocusMsg) { var verseRef = new VerseRef(SantaFeFocusMessageHandler.ReceiveFocusMessage(msg)); MessageReceived = verseRef; } base.WndProc(ref msg); } } } }
mit
C#
ec20bc8f1f5562e0bdfc731d2a98ace405174282
Remove unused variable
DaveSenn/Extend
PortableExtensions.Testing/System.DateTime/DateTime.StartOfWeek.Test.cs
PortableExtensions.Testing/System.DateTime/DateTime.StartOfWeek.Test.cs
#region Using using System; using NUnit.Framework; #endregion namespace PortableExtensions.Testing { [TestFixture] public partial class DateTimeExTest { [Test] public void StartOfWeekTestCase() { var dateTime = new DateTime(2014, 3, 27); var expected = new DateTime(2014, 3, 24); var actual = dateTime.StartOfWeek(); Assert.AreEqual(expected, actual); expected = new DateTime(2014, 3, 26); actual = dateTime.StartOfWeek(DayOfWeek.Wednesday); Assert.AreEqual(expected, actual); } [Test] public void StartOfWeekTestCase1() { var dateTime = new DateTime(2014, 3, 27); var expected = new DateTime(2014, 3, 26); var actual = dateTime.StartOfWeek(DayOfWeek.Wednesday); Assert.AreEqual(expected, actual); } [Test] public void StartOfWeekTestCase2() { var week = new DateTime(2014, 09, 21); var expected = new DateTime(2014, 09, 20); var actual = week.StartOfWeek(DayOfWeek.Saturday); Assert.AreEqual(expected, actual); } } }
#region Using using System; using NUnit.Framework; #endregion namespace PortableExtensions.Testing { [TestFixture] public partial class DateTimeExTest { [Test] public void StartOfWeekTestCase() { var dateTime = new DateTime(2014, 3, 27); var expected = new DateTime(2014, 3, 24); var actual = dateTime.StartOfWeek(); Assert.AreEqual(expected, actual); expected = new DateTime(2014, 3, 26); actual = dateTime.StartOfWeek(DayOfWeek.Wednesday); Assert.AreEqual(expected, actual); } [Test] public void StartOfWeekTestCase1() { var dateTime = new DateTime(2014, 3, 27); var expected = new DateTime(2014, 3, 26); var actual = dateTime.StartOfWeek(DayOfWeek.Wednesday); Assert.AreEqual(expected, actual); } [Test] public void StartOfWeekTestCase2() { var day = DayOfWeek.Sunday - DayOfWeek.Saturday; var week = new DateTime(2014, 09, 21); var expected = new DateTime(2014, 09, 20); var actual = week.StartOfWeek(DayOfWeek.Saturday); Assert.AreEqual(expected, actual); } } }
mit
C#
c10ececf7f0735a7b11859755204c33f312b28a9
Remove reference to obsolete `searchHighlight()` javascript function from ClearSilver footer template.
pkdevbox/trac,pkdevbox/trac,pkdevbox/trac,pkdevbox/trac
templates/footer.cs
templates/footer.cs
<?cs if:len(chrome.links.alternate) ?> <div id="altlinks"><h3>Download in other formats:</h3><ul><?cs each:link = chrome.links.alternate ?><?cs set:isfirst = name(link) == 0 ?><?cs set:islast = name(link) == len(chrome.links.alternate) - 1?><li<?cs if:isfirst || islast ?> class="<?cs if:isfirst ?>first<?cs /if ?><?cs if:isfirst && islast ?> <?cs /if ?><?cs if:islast ?>last<?cs /if ?>"<?cs /if ?>><a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a></li><?cs /each ?></ul></div><?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.org/"><img src="<?cs var:htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs var:trac.version ?></strong></a><br /> By <a href="http://www.edgewall.org/">Edgewall Software</a>. </p> <p class="right"> <?cs var:project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html>
<script type="text/javascript">searchHighlight()</script><?cs if:len(chrome.links.alternate) ?> <div id="altlinks"><h3>Download in other formats:</h3><ul><?cs each:link = chrome.links.alternate ?><?cs set:isfirst = name(link) == 0 ?><?cs set:islast = name(link) == len(chrome.links.alternate) - 1?><li<?cs if:isfirst || islast ?> class="<?cs if:isfirst ?>first<?cs /if ?><?cs if:isfirst && islast ?> <?cs /if ?><?cs if:islast ?>last<?cs /if ?>"<?cs /if ?>><a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a></li><?cs /each ?></ul></div><?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.org/"><img src="<?cs var:htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs var:trac.version ?></strong></a><br /> By <a href="http://www.edgewall.org/">Edgewall Software</a>. </p> <p class="right"> <?cs var:project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html>
bsd-3-clause
C#
37cab4d3d0d2bfffe3aa15f41fa0314c52d7c91c
fix the back link to return to the metadata page
MindTouch/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,ZocDoc/ServiceStack,nataren/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,MindTouch/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,NServiceKit/NServiceKit,timba/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit,timba/NServiceKit,ZocDoc/ServiceStack
src/ServiceStack/WebHost.Endpoints/Support/Metadata/Controls/OperationControl.cs
src/ServiceStack/WebHost.Endpoints/Support/Metadata/Controls/OperationControl.cs
using System.Web; using System.Web.UI; using ServiceStack.Common; using ServiceStack.ServiceHost; using ServiceStack.WebHost.Endpoints.Support.Templates; namespace ServiceStack.WebHost.Endpoints.Support.Metadata.Controls { public class OperationControl { public ServiceEndpointsMetadataConfig MetadataConfig { get; set; } public Format Format { set { this.ContentType = Common.Web.ContentType.ToContentType(value); this.ContentFormat = Common.Web.ContentType.GetContentFormat(value); } } public IHttpRequest HttpRequest { get; set; } public string ContentType { get; set; } public string ContentFormat { get; set; } public string Title { get; set; } public string OperationName { get; set; } public string HostName { get; set; } public string RequestMessage { get; set; } public string ResponseMessage { get; set; } public string MetadataHtml { get; set; } public virtual string RequestUri { get { var endpointConfig = MetadataConfig.GetEndpointConfig(ContentType); var endpontPath = ResponseMessage != null ? endpointConfig.SyncReplyUri : endpointConfig.AsyncOneWayUri; return string.Format("{0}/{1}", endpontPath, OperationName); } } public void Render(HtmlTextWriter output) { var baseUrl = HttpRequest.GetParentAbsolutePath().ToParentPath(); if (string.IsNullOrEmpty(baseUrl)) baseUrl = "/"; // use a fully qualified path if WebHostUrl is set if (EndpointHost.Config.WebHostUrl != null) { baseUrl = EndpointHost.Config.WebHostUrl.CombineWith(baseUrl); } var renderedTemplate = HtmlTemplates.Format(HtmlTemplates.OperationControlTemplate, Title, baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, HttpRequestTemplate, ResponseTemplate, MetadataHtml); output.Write(renderedTemplate); } public virtual string HttpRequestTemplate { get { return string.Format( @"POST {0} HTTP/1.1 Host: {1} Content-Type: {2} Content-Length: <span class=""value"">length</span> {3}", RequestUri, HostName, ContentType, HttpUtility.HtmlEncode(RequestMessage)); } } public virtual string ResponseTemplate { get { var httpResponse = this.HttpResponseTemplate; return string.IsNullOrEmpty(httpResponse) ? null : string.Format(@" <div class=""response""> <pre> {0} </pre> </div> ", httpResponse); } } public virtual string HttpResponseTemplate { get { if (string.IsNullOrEmpty(ResponseMessage)) return null; return string.Format( @"HTTP/1.1 200 OK Content-Type: {0} Content-Length: length {1}", ContentType, HttpUtility.HtmlEncode(ResponseMessage)); } } } }
using System.Web; using System.Web.UI; using ServiceStack.Common; using ServiceStack.ServiceHost; using ServiceStack.WebHost.Endpoints.Support.Templates; namespace ServiceStack.WebHost.Endpoints.Support.Metadata.Controls { public class OperationControl { public ServiceEndpointsMetadataConfig MetadataConfig { get; set; } public Format Format { set { this.ContentType = Common.Web.ContentType.ToContentType(value); this.ContentFormat = Common.Web.ContentType.GetContentFormat(value); } } public IHttpRequest HttpRequest { get; set; } public string ContentType { get; set; } public string ContentFormat { get; set; } public string Title { get; set; } public string OperationName { get; set; } public string HostName { get; set; } public string RequestMessage { get; set; } public string ResponseMessage { get; set; } public string MetadataHtml { get; set; } public virtual string RequestUri { get { var endpointConfig = MetadataConfig.GetEndpointConfig(ContentType); var endpontPath = ResponseMessage != null ? endpointConfig.SyncReplyUri : endpointConfig.AsyncOneWayUri; return string.Format("{0}/{1}", endpontPath, OperationName); } } public void Render(HtmlTextWriter output) { // use a fully qualified path if WebHostUrl is set string baseUrl = HttpRequest.GetParentAbsolutePath(); if (EndpointHost.Config.WebHostUrl != null) { baseUrl = EndpointHost.Config.WebHostUrl.CombineWith(baseUrl); } var renderedTemplate = HtmlTemplates.Format(HtmlTemplates.OperationControlTemplate, Title, baseUrl.CombineWith(MetadataConfig.DefaultMetadataUri), ContentFormat.ToUpper(), OperationName, HttpRequestTemplate, ResponseTemplate, MetadataHtml); output.Write(renderedTemplate); } public virtual string HttpRequestTemplate { get { return string.Format( @"POST {0} HTTP/1.1 Host: {1} Content-Type: {2} Content-Length: <span class=""value"">length</span> {3}", RequestUri, HostName, ContentType, HttpUtility.HtmlEncode(RequestMessage)); } } public virtual string ResponseTemplate { get { var httpResponse = this.HttpResponseTemplate; return string.IsNullOrEmpty(httpResponse) ? null : string.Format(@" <div class=""response""> <pre> {0} </pre> </div> ", httpResponse); } } public virtual string HttpResponseTemplate { get { if (string.IsNullOrEmpty(ResponseMessage)) return null; return string.Format( @"HTTP/1.1 200 OK Content-Type: {0} Content-Length: length {1}", ContentType, HttpUtility.HtmlEncode(ResponseMessage)); } } } }
bsd-3-clause
C#
3283770ff3b4bf49d16a3b6e6b1710362110571c
allow the base url to be over ridden
bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather,bellrichm/weather
api/smoke/BellRichM.Identity.Api.Smoke/Controllers/UserControllerSetupTearDown.cs
api/smoke/BellRichM.Identity.Api.Smoke/Controllers/UserControllerSetupTearDown.cs
using FluentAssertions; using Machine.Specifications; using System; using System.Net.Http; namespace BellRichM.Identity.Api.Smoke.Controllers { public class UserControllerSetupTearDown : IAssemblyContext { public void OnAssemblyStart() { var baseURL = Environment.GetEnvironmentVariable("SMOKE_BASEURL"); if (baseURL != null) { var spHandler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; } }; UserControllerSmoke.Client = new HttpClient(spHandler); } else { baseURL = "http://bellrichm-weather.azurewebsites.net"; UserControllerSmoke.Client = new HttpClient(); } #pragma warning disable S1075 UserControllerSmoke.Client.BaseAddress = new Uri(baseURL); #pragma warning disable S1075 } public void OnAssemblyComplete() { UserControllerSmoke.Client.Dispose(); } } }
using FluentAssertions; using Machine.Specifications; using System; using System.Net.Http; namespace BellRichM.Identity.Api.Smoke.Controllers { public class UserControllerSetupTearDown : IAssemblyContext { public void OnAssemblyStart() { UserControllerSmoke.Client = new HttpClient(); #pragma warning disable S1075 UserControllerSmoke.Client.BaseAddress = new Uri("http://bellrichm-weather.azurewebsites.net"); #pragma warning disable S1075 } public void OnAssemblyComplete() { UserControllerSmoke.Client.Dispose(); } } }
mit
C#
527ba28039ef473c0801d7fdd3881f880be9afc1
Fix parse error handling.
impworks/lens
Lens/LensCompiler.cs
Lens/LensCompiler.cs
using System; using System.Collections.Generic; using System.Reflection; using Lens.Parser; using Lens.SyntaxTree; using Lens.SyntaxTree.Compiler; using Lens.SyntaxTree.SyntaxTree; namespace Lens { /// <summary> /// LENS main compiler class. /// https://github.com/impworks/lens /// </summary> public class LensCompiler : IDisposable { public LensCompiler(LensCompilerOptions opts = null) { m_Context = new Context(opts); } public void Dispose() { GlobalPropertyHelper.UnregisterContext(m_Context.ContextId); } private Context m_Context; /// <summary> /// Register a type to be used by LENS script. /// </summary> public void RegisterType(Type type) { RegisterType(type != null ? type.Name : null, type); } /// <summary> /// Registers an aliased type to be used by LENS script. /// </summary> public void RegisterType(string alias, Type type) { if (type == null) throw new ArgumentNullException("type"); m_Context.ImportType(alias, type); } /// <summary> /// Registers a method to be used by LENS script. /// </summary> public void RegisterFunction(string name, MethodInfo method) { m_Context.ImportFunction(name, method); } /// <summary> /// Registers a dynamic property to be used by LENS script. /// </summary> public void RegisterProperty<T>(string name, Func<T> getter, Action<T> setter = null) { m_Context.ImportProperty(name, getter, setter); } /// <summary> /// Compile the script for many invocations. /// </summary> public Func<object> Compile(string src) { IEnumerable<NodeBase> nodes; var t = DateTime.Now; try { nodes = new TreeBuilder().Parse(src); } catch (LensCompilerException) { throw; } catch (Exception ex) { throw new LensCompilerException(ex.Message); } Console.WriteLine("Parsing: {0:0.00} ms", (DateTime.Now - t).TotalMilliseconds); t = DateTime.Now; var x = Compile(nodes); Console.WriteLine("Compiling: {0:0.00} ms", (DateTime.Now - t).TotalMilliseconds); return x; } /// <summary> /// Compile the script for many invocations. /// </summary> public Func<object> Compile(IEnumerable<NodeBase> nodes) { var script = m_Context.Compile(nodes); return script.Run; } /// <summary> /// Run the script and get a return value. /// </summary> public object Run(string src) { return Compile(src)(); } /// <summary> /// Run the script and get a return value. /// </summary> public object Run(IEnumerable<NodeBase> nodes) { return Compile(nodes)(); } } }
using System; using System.Collections.Generic; using System.Reflection; using Lens.Parser; using Lens.SyntaxTree; using Lens.SyntaxTree.Compiler; using Lens.SyntaxTree.SyntaxTree; namespace Lens { /// <summary> /// LENS main compiler class. /// https://github.com/impworks/lens /// </summary> public class LensCompiler : IDisposable { public LensCompiler(LensCompilerOptions opts = null) { m_Context = new Context(opts); } public void Dispose() { GlobalPropertyHelper.UnregisterContext(m_Context.ContextId); } private Context m_Context; /// <summary> /// Register a type to be used by LENS script. /// </summary> public void RegisterType(Type type) { RegisterType(type != null ? type.Name : null, type); } /// <summary> /// Registers an aliased type to be used by LENS script. /// </summary> public void RegisterType(string alias, Type type) { if (type == null) throw new ArgumentNullException("type"); m_Context.ImportType(alias, type); } /// <summary> /// Registers a method to be used by LENS script. /// </summary> public void RegisterFunction(string name, MethodInfo method) { m_Context.ImportFunction(name, method); } /// <summary> /// Registers a dynamic property to be used by LENS script. /// </summary> public void RegisterProperty<T>(string name, Func<T> getter, Action<T> setter = null) { m_Context.ImportProperty(name, getter, setter); } /// <summary> /// Compile the script for many invocations. /// </summary> public Func<object> Compile(string src) { IEnumerable<NodeBase> nodes; var t = DateTime.Now; try { nodes = new TreeBuilder().Parse(src); } catch(Exception ex) { throw new LensCompilerException(ex.Message); } Console.WriteLine("Parsing: {0:0.00} ms", (DateTime.Now - t).TotalMilliseconds); t = DateTime.Now; var x = Compile(nodes); Console.WriteLine("Compiling: {0:0.00} ms", (DateTime.Now - t).TotalMilliseconds); return x; } /// <summary> /// Compile the script for many invocations. /// </summary> public Func<object> Compile(IEnumerable<NodeBase> nodes) { var script = m_Context.Compile(nodes); return script.Run; } /// <summary> /// Run the script and get a return value. /// </summary> public object Run(string src) { return Compile(src)(); } /// <summary> /// Run the script and get a return value. /// </summary> public object Run(IEnumerable<NodeBase> nodes) { return Compile(nodes)(); } } }
mit
C#
33e7272168fb0103dc7140856b04c6f93525aacc
Fix AutMap.
FiniteElement/reflector
Reflector/Program.cs
Reflector/Program.cs
using System; namespace Reflector { class Test { public String Member = "Simple member!"; public Test[] Elements { get; set; } public Test Property { get; set; } public String Leaf { get; set; } public String Method () { return "Method!"; } public String MethodWithParam (int a) { return a.ToString (); } } class MainClass { public static void Main (string[] args) { var root1 = Reflector.CreateRootReflector<Test> (); Console.WriteLine ("Key of root1: {0}", root1.Key); root1 ["Leaf"].Value = "Banán"; Console.WriteLine (root1 ["Member"].Info); Console.WriteLine (root1 ["Member"].Value); Console.WriteLine (root1 ["Method"].Info); Console.WriteLine (root1 ["Method"].Invoke ()); Console.WriteLine (root1 ["MethodWithParam"].Info); Console.WriteLine (root1 ["MethodWithParam"].Invoke (3)); Console.WriteLine ((root1.Value as Test).Leaf); var obj = new Test (); obj.Leaf = "Körte"; var root2 = Reflector.CreateRootReflector (obj); root2.AutoMap = false; root2.Map ("Leaf"); Console.WriteLine ((root2.Value as Test).Leaf); var Property = Reflector.CreateReflector ("Property", obj); Property.AutoMap = false; Console.WriteLine ("Key of Property: {0}", Property.Key); var Leaf = Reflector.CreateReflector ("Leaf", obj); Leaf.AutoMap = false; Leaf.Value = "Cica"; Property.Default (); Property.Map ("Property"); Property ["Property"].Default (); Property ["Property"].Map ("Leaf"); Property ["Property"] ["Leaf"].Value = "Alma"; Property.Map ("Elements"); Console.WriteLine (obj.Property.Property.Leaf); Property ["Elements"].Default (1); Property ["Elements"].CastValue<object[]> () [0] = obj.Property.Property; Console.WriteLine (obj.Property.Elements [0].Leaf); } } }
using System; namespace Reflector { class Test { public String Member = "Simple member!"; public Test[] Elements { get; set; } public Test Property { get; set; } public String Leaf { get; set; } public String Method () { return "Method!"; } public String MethodWithParam (int a) { return a.ToString (); } } class MainClass { public static void Main (string[] args) { var root1 = Reflector.CreateRootReflector<Test> (); Console.WriteLine ("Key of root1: {0}", root1.Key); //root1.AutoMap = true; //root1.Map("Leaf"); root1 ["Leaf"].Value = "Banán"; //root1.Map("Method"); //root1.Map("MethodWithParam"); //root1.Map("Member"); Console.WriteLine (root1 ["Member"].Info); Console.WriteLine (root1 ["Member"].Value); Console.WriteLine (root1 ["Method"].Info); Console.WriteLine (root1 ["Method"].Invoke ()); Console.WriteLine (root1 ["MethodWithParam"].Info); Console.WriteLine (root1 ["MethodWithParam"].Invoke (3)); Console.WriteLine ((root1.Value as Test).Leaf); var obj = new Test (); obj.Leaf = "Körte"; var root2 = Reflector.CreateRootReflector (obj); root2.Map ("Leaf"); Console.WriteLine ((root2.Value as Test).Leaf); var Property = Reflector.CreateReflector ("Property", obj); Console.WriteLine ("Key of Property: {0}", Property.Key); var Leaf = Reflector.CreateReflector ("Leaf", obj); Leaf.Value = "Cica"; Property.Default (); Property.Map ("Property"); Property ["Property"].Default (); Property ["Property"].Map ("Leaf"); Property ["Property"] ["Leaf"].Value = "Alma"; Property.Map ("Elements"); Console.WriteLine (obj.Property.Property.Leaf); Property ["Elements"].Default (1); Property ["Elements"].CastValue<object[]> () [0] = obj.Property.Property; Console.WriteLine (obj.Property.Elements [0].Leaf); } } }
mit
C#
827360388fd600dd9bd5ff104d18fa849260dda7
Update NumberNode.cs
dmanning23/Equationator
Source/NumberNode.cs
Source/NumberNode.cs
using System.Collections.Generic; using System.Diagnostics; using System; using System.Globalization; namespace Equationator { /// <summary> /// This a node in the equation that holds a number. /// </summary> public class NumberNode : BaseNode { #region Members /// <summary> /// The actual number value of this node /// </summary> /// <value>The number value.</value> private float _num; /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> public float NumberValue { get { return _num; } set { _num = value; } } #endregion Members #region Methods /// <summary> /// Initializes a new instance of the <see cref="Equationator.NumberNode"/> class. /// </summary> public NumberNode() { OrderOfOperationsValue = PemdasValue.Value; _num = 0.0f; } /// <summary> /// Parse the specified tokenList and curIndex. /// overloaded by child types to do there own specific parsing. /// </summary> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index.</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> protected override void ParseToken(List<Token> tokenList, ref int curIndex, Equation owner) { Debug.Assert(null != tokenList); Debug.Assert(null != owner); Debug.Assert(curIndex < tokenList.Count); //get the number out of the list if (!float.TryParse(tokenList[curIndex].TokenText, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out _num)) { throw new FormatException("Could not parse \"" + tokenList[curIndex].TokenText.ToString() + "\" into a number."); } //increment the current index since we consumed the number token curIndex++; } /// <summary> /// Solve the equation! /// This method recurses into the whole tree and returns a result from the equation. /// </summary> /// <param name="paramCallback">Parameter callback that will be used to get teh values of parameter nodes.</param> /// <returns>The solution of this node and all its subnodes!</returns> public override float Solve(ParamDelegate paramCallback) { //Return our number return NumberValue; } #endregion Methods } }
using System.Collections.Generic; using System.Diagnostics; using System; namespace Equationator { /// <summary> /// This a node in the equation that holds a number. /// </summary> public class NumberNode : BaseNode { #region Members /// <summary> /// The actual number value of this node /// </summary> /// <value>The number value.</value> private float _num; /// <summary> /// Gets or sets the number. /// </summary> /// <value>The number.</value> public float NumberValue { get { return _num; } set { _num = value; } } #endregion Members #region Methods /// <summary> /// Initializes a new instance of the <see cref="Equationator.NumberNode"/> class. /// </summary> public NumberNode() { OrderOfOperationsValue = PemdasValue.Value; _num = 0.0f; } /// <summary> /// Parse the specified tokenList and curIndex. /// overloaded by child types to do there own specific parsing. /// </summary> /// <param name="tokenList">Token list.</param> /// <param name="curIndex">Current index.</param> /// <param name="owner">the equation that this node is part of. required to pull function delegates out of the dictionary</param> protected override void ParseToken(List<Token> tokenList, ref int curIndex, Equation owner) { Debug.Assert(null != tokenList); Debug.Assert(null != owner); Debug.Assert(curIndex < tokenList.Count); //get the number out of the list if (!float.TryParse(tokenList[curIndex].TokenText, out _num)) { throw new FormatException("Could not parse \"" + tokenList[curIndex].TokenText.ToString() + "\" into a number."); } //increment the current index since we consumed the number token curIndex++; } /// <summary> /// Solve the equation! /// This method recurses into the whole tree and returns a result from the equation. /// </summary> /// <param name="paramCallback">Parameter callback that will be used to get teh values of parameter nodes.</param> /// <returns>The solution of this node and all its subnodes!</returns> public override float Solve(ParamDelegate paramCallback) { //Return our number return NumberValue; } #endregion Methods } }
mit
C#
d2a347e344b0e5898bb6997265b940883d909e0c
Update AddingLabelControl.cs
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,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,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Charts/InsertingControlsintoCharts/AddingLabelControl.cs
Examples/CSharp/Charts/InsertingControlsintoCharts/AddingLabelControl.cs
using System.IO; using Aspose.Cells; using System.Drawing; namespace Aspose.Cells.Examples.Charts.InsertingControlsintoCharts { public class AddingLabelControl { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook. //Open the existing file. Workbook workbook = new Workbook(dataDir + "chart.xls"); //Get the designer chart in the second sheet. Worksheet sheet = workbook.Worksheets[1]; Aspose.Cells.Charts.Chart chart = sheet.Charts[0]; //Add a new label to the chart. Aspose.Cells.Drawing.Label label = chart.Shapes.AddLabelInChart(100, 100, 350, 900); //Set the caption of the label. label.Text = "A Label In Chart"; //Set the Placement Type, the way the //label is attached to the cells. label.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating; //Set the fill color of the label. label.FillFormat.ForeColor = Color.Azure; //Save the excel file. workbook.Save(dataDir + "chart.out.xls"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System.Drawing; namespace Aspose.Cells.Examples.Charts.InsertingControlsintoCharts { public class AddingLabelControl { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook. //Open the existing file. Workbook workbook = new Workbook(dataDir + "chart.xls"); //Get the designer chart in the second sheet. Worksheet sheet = workbook.Worksheets[1]; Aspose.Cells.Charts.Chart chart = sheet.Charts[0]; //Add a new label to the chart. Aspose.Cells.Drawing.Label label = chart.Shapes.AddLabelInChart(100, 100, 350, 900); //Set the caption of the label. label.Text = "A Label In Chart"; //Set the Placement Type, the way the //label is attached to the cells. label.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating; //Set the fill color of the label. label.FillFormat.ForeColor = Color.Azure; //Save the excel file. workbook.Save(dataDir + "chart.out.xls"); } } }
mit
C#
f99561cc816d5b16414d6b5bfcd4880c9a7b178e
Update ConvertWorksheettoImageFile.cs
asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/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,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Articles/ConvertingWorksheetToImage/ConvertWorksheettoImageFile.cs
Examples/CSharp/Articles/ConvertingWorksheetToImage/ConvertWorksheettoImageFile.cs
using System.IO; using Aspose.Cells; using Aspose.Cells.Rendering; using System.Drawing; namespace Aspose.Cells.Examples.Articles.ConvertingWorksheetToImage { public class ConvertWorksheettoImageFile { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(dataDir+ "Testbook.xlsx"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(dataDir+ "SheetImage.out.jpg"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using Aspose.Cells.Rendering; using System.Drawing; namespace Aspose.Cells.Examples.Articles.ConvertingWorksheetToImage { public class ConvertWorksheettoImageFile { public static void Main(string[] args) { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Create a new Workbook object //Open a template excel file Workbook book = new Workbook(dataDir+ "Testbook.xlsx"); //Get the first worksheet. Worksheet sheet = book.Worksheets[0]; //Define ImageOrPrintOptions ImageOrPrintOptions imgOptions = new ImageOrPrintOptions(); //Specify the image format imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; //Render the sheet with respect to specified image/print options SheetRender sr = new SheetRender(sheet, imgOptions); //Render the image for the sheet Bitmap bitmap = sr.ToImage(0); //Save the image file bitmap.Save(dataDir+ "SheetImage.out.jpg"); } } }
mit
C#
c772f00b6a88027e655f09dba616ef7cf60303fe
add urls
faniereynders/PokeApp
src/PokeApp.Api/Program.cs
src/PokeApp.Api/Program.cs
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using System.IO; namespace PokeApp.Api { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseUrls("http://*:5000") .UseKestrel() .UseStartup<Startup>() .CaptureStartupErrors(true) .Build(); host.Run(); } } }
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Builder; using System.IO; namespace PokeApp.Api { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel() .UseStartup<Startup>() .CaptureStartupErrors(true) .Build(); host.Run(); } } }
mit
C#
fc3a20282c73f2b4a5c582c0e3be441d7301b4d8
Simplify ProcessorCount tests to fix sporadic failures (#35465)
wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,BrennanConroy/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,ViktorHofer/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,ptoonen/corefx,shimingsg/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx
src/System.Runtime.Extensions/tests/System/Environment.ProcessorCount.cs
src/System.Runtime.Extensions/tests/System/Environment.ProcessorCount.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public class EnvironmentProcessorCount { [Fact] public void ProcessorCount_IsPositive() { Assert.InRange(Environment.ProcessorCount, 1, int.MaxValue); } [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get processor information [Fact] public void ProcessorCount_Windows_MatchesGetSystemInfo() { GetSystemInfo(out SYSTEM_INFO sysInfo); Assert.Equal(sysInfo.dwNumberOfProcessors, Environment.ProcessorCount); } [DllImport("kernel32.dll", SetLastError = true)] internal static extern void GetSystemInfo(out SYSTEM_INFO lpSystemInfo); [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_INFO { internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs. internal int dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal int dwNumberOfProcessors; internal int dwProcessorType; internal int dwAllocationGranularity; internal short wProcessorLevel; internal short wProcessorRevision; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using Xunit; namespace System.Tests { public class EnvironmentProcessorCount { [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get processor information [Fact] public void Windows_ProcessorCountTest() { //arrange SYSTEM_INFO sysInfo = new SYSTEM_INFO(); GetSystemInfo(ref sysInfo); int expected = sysInfo.dwNumberOfProcessors; //act int actual = Environment.ProcessorCount; //assert Assert.True(actual > 0); Assert.Equal(expected, actual); } #if Unix [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes to get processor information [Fact] public void Unix_ProcessorCountTest() { //arrange int SYSCONF_GET_NUMPROCS; if (RuntimeInformation.ProcessArchitecture == Architecture.Arm || RuntimeInformation.ProcessArchitecture == Architecture.Arm64) { SYSCONF_GET_NUMPROCS = /* _SC_NPROCESSORS_CONF */ RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 83 : RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")) ? 1001 : 57; } else { SYSCONF_GET_NUMPROCS = /* _SC_NPROCESSORS_ONLN */ RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 84 : RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD")) ? 1002 : 58; } int expected = (int)sysconf(SYSCONF_GET_NUMPROCS); //act int actual = Environment.ProcessorCount; //assert Assert.True(actual > 0); Assert.Equal(expected, actual); } [DllImport("libc")] private static extern long sysconf(int name); #endif [DllImport("kernel32.dll", SetLastError = true)] internal static extern void GetSystemInfo(ref SYSTEM_INFO lpSystemInfo); [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_INFO { internal int dwOemId; // This is a union of a DWORD and a struct containing 2 WORDs. internal int dwPageSize; internal IntPtr lpMinimumApplicationAddress; internal IntPtr lpMaximumApplicationAddress; internal IntPtr dwActiveProcessorMask; internal int dwNumberOfProcessors; internal int dwProcessorType; internal int dwAllocationGranularity; internal short wProcessorLevel; internal short wProcessorRevision; } } }
mit
C#
012b98985f943933a186f752978a8225f626129c
Set window title for authentication
github-for-unity/Unity,mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationWindow.cs
src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationWindow.cs
using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { // Set window title titleContent = new GUIContent("Sign in", Styles.SmallLogo); Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); authView.Initialize(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } }
using System; using UnityEditor; using UnityEngine; namespace GitHub.Unity { [Serializable] class AuthenticationWindow : BaseWindow { [SerializeField] private AuthenticationView authView; [MenuItem("GitHub/Authenticate")] public static void Launch() { Open(); } public static IView Open(Action<bool> onClose = null) { AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>(); if (onClose != null) authWindow.OnClose += onClose; authWindow.minSize = new Vector2(290, 290); authWindow.Show(); return authWindow; } public override void OnGUI() { authView.OnGUI(); } public override void Refresh() { authView.Refresh(); } public override void OnEnable() { Utility.UnregisterReadyCallback(CreateViews); Utility.RegisterReadyCallback(CreateViews); Utility.UnregisterReadyCallback(ShowActiveView); Utility.RegisterReadyCallback(ShowActiveView); } private void CreateViews() { if (authView == null) authView = new AuthenticationView(); authView.Initialize(this); } private void ShowActiveView() { authView.OnShow(); Refresh(); } public override void Finish(bool result) { Close(); base.Finish(result); } } }
mit
C#
f3265e11e87caf84c9716ed8064c6be6c02fb928
Use IConfiguration first, and the IConfigurationRoot.
schambers/fluentmigrator,igitur/fluentmigrator,amroel/fluentmigrator,eloekset/fluentmigrator,stsrki/fluentmigrator,spaccabit/fluentmigrator,eloekset/fluentmigrator,fluentmigrator/fluentmigrator,igitur/fluentmigrator,schambers/fluentmigrator,fluentmigrator/fluentmigrator,spaccabit/fluentmigrator,stsrki/fluentmigrator,amroel/fluentmigrator
src/FluentMigrator.Runner.Core/Initialization/ConfigurationConnectionStringReader.cs
src/FluentMigrator.Runner.Core/Initialization/ConfigurationConnectionStringReader.cs
#region License // Copyright (c) 2018, FluentMigrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FluentMigrator.Runner.Initialization { /// <summary> /// Implementation of <see cref="IConnectionStringReader"/> that interprets tries to /// get the connection string from an <see cref="IConfiguration"/> or <see cref="IConfigurationRoot"/>. /// </summary> public class ConfigurationConnectionStringReader : IConnectionStringReader { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initializes a new instance of the <see cref="ConfigurationConnectionStringReader"/> class. /// </summary> /// <param name="serviceProvider">The service provider to get the configuration interface from</param> public ConfigurationConnectionStringReader(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc /> public int Priority { get; } = 100; /// <inheritdoc /> public string GetConnectionString(string connectionStringOrName) { if (_serviceProvider == null) return null; var cfgRoot = _serviceProvider.GetService<IConfigurationRoot>(); var cfg = _serviceProvider.GetService<IConfiguration>(); return cfg?.GetConnectionString(connectionStringOrName) ?? cfgRoot?.GetConnectionString(connectionStringOrName); } } }
#region License // Copyright (c) 2018, FluentMigrator Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FluentMigrator.Runner.Initialization { public class ConfigurationConnectionStringReader : IConnectionStringReader { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initializes a new instance of the <see cref="ConfigurationConnectionStringReader"/> class. /// </summary> /// <param name="serviceProvider">The service provider to get the configuration interface from</param> public ConfigurationConnectionStringReader(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc /> public int Priority { get; } = 100; /// <inheritdoc /> public string GetConnectionString(string connectionStringName) { if (_serviceProvider == null) return null; var cfg = _serviceProvider.GetService<IConfigurationRoot>() ?? _serviceProvider.GetService<IConfiguration>(); if (cfg == null) return null; return cfg.GetConnectionString(connectionStringName) ?? cfg.GetConnectionString(connectionStringName); } } }
apache-2.0
C#
74b2b6b232aafb9dd40179278574841427de26bd
Set Program class as public in standalone project template
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Blazor.Templates/content/BlazorStandalone.CSharp/Program.cs
src/Microsoft.AspNetCore.Blazor.Templates/content/BlazorStandalone.CSharp/Program.cs
using Microsoft.AspNetCore.Blazor.Browser.Rendering; using Microsoft.AspNetCore.Blazor.Browser.Services; using Microsoft.Extensions.DependencyInjection; using System; namespace BlazorStandalone.CSharp { public class Program { static void Main(string[] args) { var serviceProvider = new BrowserServiceProvider(services => { // Add any custom services here }); new BrowserRenderer(serviceProvider).AddComponent<App>("app"); } } }
using Microsoft.AspNetCore.Blazor.Browser.Rendering; using Microsoft.AspNetCore.Blazor.Browser.Services; using Microsoft.Extensions.DependencyInjection; using System; namespace BlazorStandalone.CSharp { class Program { static void Main(string[] args) { var serviceProvider = new BrowserServiceProvider(services => { // Add any custom services here }); new BrowserRenderer(serviceProvider).AddComponent<App>("app"); } } }
apache-2.0
C#
a4fc1d78bb1e31a67bd228cf0b35410933997947
Remove unneeded methods from model
dukemiller/twitch-tv-viewer
twitch-tv-viewer/Models/TwitchChannel.cs
twitch-tv-viewer/Models/TwitchChannel.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace twitch_tv_viewer.Models { public class TwitchChannel : IComparable { public TwitchChannel() { } public TwitchChannel(JToken data) { var channel = data["channel"]; Name = channel["display_name"]?.ToString() ?? "no name"; Game = channel["game"]?.ToString() ?? "no game"; Status = channel["status"]?.ToString().Trim() ?? "no status"; Viewers = data["viewers"]?.ToString() ?? "???"; } public string Name { get; set; } public string Game { get; set; } public string Status { get; set; } public string Viewers { get; set; } public int CompareTo(object obj) { var that = obj as TwitchChannel; if (that == null) return 0; return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal); } } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace twitch_tv_viewer.Models { public class TwitchChannel : IComparable { public TwitchChannel() { } public TwitchChannel(JToken data) { var channel = data["channel"]; Name = channel["display_name"]?.ToString() ?? "no name"; Game = channel["game"]?.ToString() ?? "no game"; Status = channel["status"]?.ToString().Trim() ?? "no status"; Viewers = data["viewers"]?.ToString() ?? "???"; } public string Name { get; set; } public string Game { get; set; } public string Status { get; set; } public string Viewers { get; set; } public int CompareTo(object obj) { var that = obj as TwitchChannel; if (that == null) return 0; return string.Compare(Name.ToLower(), that.Name.ToLower(), StringComparison.Ordinal); } public async Task<string> StartStream() { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{Name} high", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public void OpenChatroom() => Process.Start($"http://twitch.tv/{Name}/chat?popout="); } }
mit
C#
1a3bd54aff539bac974d3f354f1783cd7d75dc7d
Remove unnecessary exception variable.
maraf/WebCamImageCollector
src/WebCamImageCollector.RemoteControl.UI/ViewModels/Commands/CheckStatusCommand.cs
src/WebCamImageCollector.RemoteControl.UI/ViewModels/Commands/CheckStatusCommand.cs
using Neptuo; using Neptuo.Observables.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WebCamImageCollector.RemoteControl.Services; using Windows.UI.Popups; namespace WebCamImageCollector.RemoteControl.ViewModels.Commands { public class CheckStatusCommand : AsyncCommand { private readonly IClient client; private readonly ClientOverviewViewModel viewModel; public CheckStatusCommand(IClient client, ClientOverviewViewModel viewModel) { Ensure.NotNull(client, "client"); Ensure.NotNull(viewModel, "viewModel"); this.client = client; this.viewModel = viewModel; } protected override bool CanExecuteOverride() { return !viewModel.IsStatusLoading; } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { try { viewModel.IsStatusLoading = true; ClientRunningInfo response = await client.IsRunningAsync(cancellationToken); viewModel.IsRunning = response.Running; } catch (ClientException) { viewModel.IsRunning = null; throw; } finally { viewModel.IsStatusLoading = false; } } } }
using Neptuo; using Neptuo.Observables.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using WebCamImageCollector.RemoteControl.Services; using Windows.UI.Popups; namespace WebCamImageCollector.RemoteControl.ViewModels.Commands { public class CheckStatusCommand : AsyncCommand { private readonly IClient client; private readonly ClientOverviewViewModel viewModel; public CheckStatusCommand(IClient client, ClientOverviewViewModel viewModel) { Ensure.NotNull(client, "client"); Ensure.NotNull(viewModel, "viewModel"); this.client = client; this.viewModel = viewModel; } protected override bool CanExecuteOverride() { return !viewModel.IsStatusLoading; } protected override async Task ExecuteAsync(CancellationToken cancellationToken) { try { viewModel.IsStatusLoading = true; ClientRunningInfo response = await client.IsRunningAsync(cancellationToken); viewModel.IsRunning = response.Running; } catch (ClientException e) { viewModel.IsRunning = null; throw; } finally { viewModel.IsStatusLoading = false; } } } }
apache-2.0
C#
819837f7a1e07bd3742581b957074eed8e282b5c
Use EventArgs.Empty in DelegateCommand (#3179)
Livit/CefSharp,Livit/CefSharp,Livit/CefSharp,Livit/CefSharp
CefSharp.Wpf/DelegateCommand.cs
CefSharp.Wpf/DelegateCommand.cs
// Copyright © 2013 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Input; namespace CefSharp.Wpf { /// <summary> /// DelegateCommand /// </summary> /// <seealso cref="System.Windows.Input.ICommand" /> internal class DelegateCommand : ICommand { /// <summary> /// The command handler /// </summary> private readonly Action commandHandler; /// <summary> /// The can execute handler /// </summary> private readonly Func<bool> canExecuteHandler; /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Initializes a new instance of the <see cref="DelegateCommand"/> class. /// </summary> /// <param name="commandHandler">The command handler.</param> /// <param name="canExecuteHandler">The can execute handler.</param> public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> public void Execute(object parameter) { commandHandler(); } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } /// <summary> /// Raises the can execute changed. /// </summary> public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } } } }
// Copyright © 2013 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows.Input; namespace CefSharp.Wpf { /// <summary> /// DelegateCommand /// </summary> /// <seealso cref="System.Windows.Input.ICommand" /> internal class DelegateCommand : ICommand { /// <summary> /// The command handler /// </summary> private readonly Action commandHandler; /// <summary> /// The can execute handler /// </summary> private readonly Func<bool> canExecuteHandler; /// <summary> /// Occurs when changes occur that affect whether or not the command should execute. /// </summary> public event EventHandler CanExecuteChanged; /// <summary> /// Initializes a new instance of the <see cref="DelegateCommand"/> class. /// </summary> /// <param name="commandHandler">The command handler.</param> /// <param name="canExecuteHandler">The can execute handler.</param> public DelegateCommand(Action commandHandler, Func<bool> canExecuteHandler = null) { this.commandHandler = commandHandler; this.canExecuteHandler = canExecuteHandler; } /// <summary> /// Defines the method to be called when the command is invoked. /// </summary> /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> public void Execute(object parameter) { commandHandler(); } /// <summary> /// Defines the method that determines whether the command can execute in its current state. /// </summary> /// <param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to null.</param> /// <returns>true if this command can be executed; otherwise, false.</returns> public bool CanExecute(object parameter) { return canExecuteHandler == null || canExecuteHandler(); } /// <summary> /// Raises the can execute changed. /// </summary> public void RaiseCanExecuteChanged() { if (CanExecuteChanged != null) { CanExecuteChanged(this, new EventArgs()); } } } }
bsd-3-clause
C#
8afad4b8583bb8ea77e42c9248c1f0b9468314ce
Refactor Add public JSON property
jazd/Business,jazd/Business,jazd/Business
CSharp/Core/Profile/Profile.cs
CSharp/Core/Profile/Profile.cs
using System; using System.IO; namespace Business.Core.Profile { public class Profile { public ILog Log { get; set; } public string SQLiteDatabasePath { get { String path; if (String.IsNullOrEmpty(SQLiteProfile.Path)) path = "sandbox/Business/business.sqlite3"; else path = SQLiteProfile.Path; return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), path); } } public SQLite SQLiteProfile { get; set; } public NuoDB NuoDBProfile { get; set; } public PostgreSQL PostgreSQLProfile { get; set; } public string ProfilePath { get { return GetBasePath() + "profile.json"; } } public Newtonsoft.Json.Linq.JObject JSON { get { if(json == null) json = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(ProfilePath)); return json; } set { json = value; } } Newtonsoft.Json.Linq.JObject json; public Profile() { SQLiteProfile = new SQLite(); NuoDBProfile = new NuoDB(); PostgreSQLProfile = new PostgreSQL(); try { var sqlite = JSON["SQLite"]; if(sqlite != null) { SQLiteProfile = sqlite.ToObject<SQLite>(); SQLiteProfile.Active = true; } var nuoDb = JSON["NuoDb"]; if (nuoDb != null) { NuoDBProfile = nuoDb.ToObject<NuoDB>(); NuoDBProfile.Active = true; } var postgreSQL = JSON["PostgreSQL"]; if (postgreSQL != null) { PostgreSQLProfile = postgreSQL.ToObject<PostgreSQL>(); PostgreSQLProfile.Active = true; } } catch (Exception e) { throw e; // Use the profile object defaults } } public virtual string GetBasePath() { return AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; } } public class SQLite { public Boolean Active { get; set; } = true; public string Path { get; set; } } public class NuoDB { public Boolean Active { get; set; } = false; public string Server { get; set; } = "nuodb"; public string Database { get; set; } = "MyCo"; public string User { get; set; } = "test"; public string Password { get; set; } = "secret"; } public class PostgreSQL { public Boolean Active { get; set; } = false; public string Host { get; set; } = "postgresql"; public string Database { get; set; } = "MyCo"; public string User { get; set; } = "test"; } }
using System; using System.IO; namespace Business.Core.Profile { public class Profile { public ILog Log { get; set; } public string SQLiteDatabasePath { get { String path; if (String.IsNullOrEmpty(SQLiteProfile.Path)) path = "sandbox/Business/business.sqlite3"; else path = SQLiteProfile.Path; return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), path); } } public SQLite SQLiteProfile { get; set; } public NuoDB NuoDBProfile { get; set; } public PostgreSQL PostgreSQLProfile { get; set; } public Profile() { SQLiteProfile = new SQLite(); NuoDBProfile = new NuoDB(); PostgreSQLProfile = new PostgreSQL(); var filePath = GetBasePath() + "profile.json"; try { Newtonsoft.Json.Linq.JObject profileJSON = Newtonsoft.Json.Linq.JObject.Parse(File.ReadAllText(filePath)); var sqlite = profileJSON["SQLite"]; if(sqlite != null) { SQLiteProfile = sqlite.ToObject<SQLite>(); SQLiteProfile.Active = true; } var nuoDb = profileJSON["NuoDb"]; if (nuoDb != null) { NuoDBProfile = nuoDb.ToObject<NuoDB>(); NuoDBProfile.Active = true; } var postgreSQL = profileJSON["PostgreSQL"]; if (postgreSQL != null) { PostgreSQLProfile = postgreSQL.ToObject<PostgreSQL>(); PostgreSQLProfile.Active = true; } } catch { // Use the profile object defaults } } public static string GetBasePath() { return AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory; } } public class SQLite { public Boolean Active { get; set; } = true; public string Path { get; set; } } public class NuoDB { public Boolean Active { get; set; } = false; public string Server { get; set; } = "nuodb"; public string Database { get; set; } = "MyCo"; public string User { get; set; } = "test"; public string Password { get; set; } = "secret"; } public class PostgreSQL { public Boolean Active { get; set; } = false; public string Host { get; set; } = "postgresql"; public string Database { get; set; } = "MyCo"; public string User { get; set; } = "test"; } }
mit
C#
63363aee08ff995f076c11829df2586e91e175f4
Use Invoke
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
Core2D/Core/ObservableObject.cs
Core2D/Core/ObservableObject.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Core2D { /// <summary> /// Base class for objects with observable property changes. /// </summary> public abstract class ObservableObject : INotifyPropertyChanged { /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify observers about property changes. /// </summary> /// <param name="propertyName">The property name that changed.</param> public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Update property backing field and notify observers about property change. /// </summary> /// <typeparam name="T">The type of field.</typeparam> /// <param name="field">The field to update.</param> /// <param name="value">The new field value.</param> /// <param name="propertyName">The property name that changed.</param> public void Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; Notify(propertyName); } } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Core2D { /// <summary> /// Base class for objects with observable property changes. /// </summary> public abstract class ObservableObject : INotifyPropertyChanged { /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify observers about property changes. /// </summary> /// <param name="propertyName">The property name that changed.</param> public void Notify([CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// Update property backing field and notify observers about property change. /// </summary> /// <typeparam name="T">The type of field.</typeparam> /// <param name="field">The field to update.</param> /// <param name="value">The new field value.</param> /// <param name="propertyName">The property name that changed.</param> public void Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; Notify(propertyName); } } } }
mit
C#
83704faa263810dfc0c5ec293aea219f7bde94e0
Add endpoints for controlling game speed.
Rychard/GnomeServer,Rychard/GnomeServer,Rychard/GnomeServer,Rychard/GnomeServer
GnomeServer/Controllers/GameController.cs
GnomeServer/Controllers/GameController.cs
using System.Globalization; using System.Net; using Game; using GnomeServer.Routing; namespace GnomeServer.Controllers { [Route("Game")] public sealed class GameController : ConventionRoutingController { [HttpGet] [Route("Speed")] public IResponseFormatter GetSpeed() { var world = GnomanEmpire.Instance.World; var speed = new { Speed = world.GameSpeed.Value.ToString(CultureInfo.InvariantCulture), IsPaused = world.Paused.Value.ToString(CultureInfo.InvariantCulture) }; return JsonResponse(speed); } [HttpPost] [Route("Speed")] public IResponseFormatter PostSpeed(int speed) { GnomanEmpire.Instance.World.GameSpeed.Value = speed; return BlankResponse(HttpStatusCode.NoContent); } [HttpPost] [Route("Pause")] public IResponseFormatter PostPause() { GnomanEmpire.Instance.World.Paused.Value = true; return BlankResponse(HttpStatusCode.NoContent); } [HttpPost] [Route("Play")] public IResponseFormatter PostPlay() { GnomanEmpire.Instance.World.Paused.Value = false; return BlankResponse(HttpStatusCode.NoContent); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Game; using GnomeServer.Extensions; using GnomeServer.Routing; namespace GnomeServer.Controllers { [Route("Game")] public sealed class GameController : ConventionRoutingController { [HttpGet] [Route("")] public IResponseFormatter Get(int speed) { GnomanEmpire.Instance.World.GameSpeed.Value = speed; String content = String.Format("Game Speed set to '{0}'", speed); return JsonResponse(content); } public IResponseFormatter Test() { BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; var fields = typeof(Character).GetFields(bindFlags); var behaviorTypeFields = fields.Where(obj => obj.FieldType == typeof(BehaviorType)).ToList(); List<TestResponse> testResponses = new List<TestResponse>(); var members = GnomanEmpire.Instance.GetGnomes(); foreach (var characterKey in members) { var character = characterKey.Value; var name = character.NameAndTitle(); foreach (var fieldInfo in behaviorTypeFields) { var val = (BehaviorType)(fieldInfo.GetValue(character)); testResponses.Add(new TestResponse { Name = name, Value = val.ToString(), }); } } return JsonResponse(testResponses); } private class TestResponse { public String Name { get; set; } public String Value { get; set; } } } }
mit
C#
37f874a853ddba8569498edc9f4e179de16cc2f7
use settings in TestAsyncMethodRenameChecker
BigBabay/AsyncConverter,BigBabay/AsyncConverter
AsyncConverter/AsyncHelpers/RenameCheckers/TestAsyncMethodRenameChecker.cs
AsyncConverter/AsyncHelpers/RenameCheckers/TestAsyncMethodRenameChecker.cs
using System.Collections.Generic; using System.Linq; using AsyncConverter.Settings; using JetBrains.Application.Settings; using JetBrains.Metadata.Reader.Impl; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; using JetBrains.ReSharper.Psi.Tree; namespace AsyncConverter.AsyncHelpers.RenameCheckers { [SolutionComponent] internal class TestRenameChecker : IConcreateRenameChecker { private readonly HashSet<ClrTypeName> testAttributesClass = new HashSet<ClrTypeName> { new ClrTypeName("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute"), new ClrTypeName("Xunit.FactAttribute"), new ClrTypeName("Xunit.TheoryAttribute"), new ClrTypeName("NUnit.Framework.TestAttribute"), new ClrTypeName("NUnit.Framework.TestCaseAttribute"), }; public bool SkipRename(IMethodDeclaration method) { if (method.AttributeSectionList == null) return false; var excludeTestMethods = method.GetSettingsStore().GetValue(AsyncSuffixSettingsAccessor.ExcludeTestMethodsFromAnalysis); if (!excludeTestMethods) return false; return method .AttributeSectionList .AttributesEnumerable .Select(attribute => attribute.Name.Reference.Resolve().DeclaredElement) .OfType<IClass>() .Select(attributeClass => attributeClass.GetClrName()) .Any(clrTypeName => testAttributesClass.Contains(clrTypeName)); } } }
using System.Collections.Generic; using System.Linq; using JetBrains.Metadata.Reader.Impl; using JetBrains.ProjectModel; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace AsyncConverter.AsyncHelpers.RenameCheckers { [SolutionComponent] internal class TestRenameChecker : IConcreateRenameChecker { private readonly HashSet<ClrTypeName> testAttributesClass = new HashSet<ClrTypeName> { new ClrTypeName("Microsoft.VisualStudio.TestTools.UnitTesting.TestMethodAttribute"), new ClrTypeName("Xunit.FactAttribute"), new ClrTypeName("Xunit.TheoryAttribute"), new ClrTypeName("NUnit.Framework.TestAttribute"), new ClrTypeName("NUnit.Framework.TestCaseAttribute"), }; public bool SkipRename(IMethodDeclaration method) { if (method.AttributeSectionList == null) return false; return method .AttributeSectionList .AttributesEnumerable .Select(attribute => attribute.Name.Reference.Resolve().DeclaredElement) .OfType<IClass>() .Select(attributeClass => attributeClass.GetClrName()) .Any(clrTypeName => testAttributesClass.Contains(clrTypeName)); } } }
mit
C#
7cfe1aca0af242e5d68971b67bf2c21874ba5109
Address review feedback.
dotnet/wcf,imcarolwang/wcf,imcarolwang/wcf,mconnew/wcf,StephenBonikowsky/wcf,imcarolwang/wcf,StephenBonikowsky/wcf,mconnew/wcf,dotnet/wcf,dotnet/wcf,mconnew/wcf
src/System.ServiceModel.Security/tests/ServiceModel/BinarySecretSecurityTokenTest.cs
src/System.ServiceModel.Security/tests/ServiceModel/BinarySecretSecurityTokenTest.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IdentityModel.Tokens; using System.ServiceModel.Security.Tokens; using Infrastructure.Common; using Xunit; public static class BinarySecretSecurityTokenTest { [WcfFact] public static void Ctor_Default_Properties() { string id = "test id"; byte[] keyBytes = new byte[128]; Random rnd = new Random(); rnd.NextBytes(keyBytes); BinarySecretSecurityToken bsst = new BinarySecretSecurityToken(keyBytes); Assert.NotNull(bsst); Assert.NotNull(bsst.Id); Assert.NotNull(bsst.SecurityKeys); Assert.Single(bsst.SecurityKeys); Assert.Equal(DateTime.UtcNow.Date, bsst.ValidFrom.Date); Assert.Equal(DateTime.MaxValue, bsst.ValidTo); Assert.Equal(keyBytes.Length * 8, bsst.KeySize); Assert.Equal(keyBytes, bsst.GetKeyBytes()); BinarySecretSecurityToken bsst2 = new BinarySecretSecurityToken(id, keyBytes); Assert.NotNull(bsst2); Assert.Equal(id, bsst2.Id); Assert.NotNull(bsst2.SecurityKeys); Assert.Single(bsst2.SecurityKeys); Assert.Equal(DateTime.UtcNow.Date, bsst2.ValidFrom.Date); Assert.Equal(DateTime.MaxValue, bsst2.ValidTo); Assert.Equal(keyBytes.Length * 8, bsst2.KeySize); Assert.Equal(keyBytes, bsst2.GetKeyBytes()); } [WcfFact] public static void Ctor_Default_IdIsUnique() { byte[] keyBytes = new byte[128]; Random rnd = new Random(); rnd.NextBytes(keyBytes); BinarySecretSecurityToken bsst = new BinarySecretSecurityToken(keyBytes); BinarySecretSecurityToken bsst2 = new BinarySecretSecurityToken(keyBytes); Assert.NotEqual(bsst.Id, bsst2.Id); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IdentityModel.Tokens; using System.ServiceModel.Security.Tokens; using Infrastructure.Common; using Xunit; public static class BinarySecretSecurityTokenTest { [WcfFact] public static void Ctor_Default_Properties() { string id = "test id"; byte[] keyBytes = new byte[128]; Random rnd = new Random(); rnd.NextBytes(keyBytes); BinarySecretSecurityToken bsst = new BinarySecretSecurityToken(keyBytes); Assert.NotNull(bsst); Assert.NotNull(bsst.Id); Assert.NotNull(bsst.SecurityKeys); Assert.Equal(DateTime.UtcNow.Date, bsst.ValidFrom.Date); Assert.Equal(DateTime.MaxValue, bsst.ValidTo); Assert.Equal(keyBytes.Length * 8, bsst.KeySize); Assert.Equal(keyBytes, bsst.GetKeyBytes()); BinarySecretSecurityToken bsst2 = new BinarySecretSecurityToken(id, keyBytes); Assert.NotNull(bsst2); Assert.Equal(id, bsst2.Id); Assert.NotNull(bsst2.SecurityKeys); Assert.Equal(DateTime.UtcNow.Date, bsst2.ValidFrom.Date); Assert.Equal(DateTime.MaxValue, bsst2.ValidTo); Assert.Equal(keyBytes.Length * 8, bsst2.KeySize); Assert.Equal(keyBytes, bsst2.GetKeyBytes()); } }
mit
C#
3c2723fb509f8be68913b200f167539028460010
Use convention model builder.
OmniSharp/omnisharp-scaffolding,OmniSharp/omnisharp-scaffolding
test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs
test/Microsoft.Framework.CodeGeneration.EntityFramework.Test/TestModels/TestModel.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity.Metadata; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var model = new Model(); var builder = new ModelBuilderFactory().CreateConventionBuilder(model); builder.Entity<Product>(); builder.Entity<Category>(); return model; } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.Data.Entity.Metadata; namespace Microsoft.Framework.CodeGeneration.EntityFramework.Test.TestModels { public static class TestModel { public static IModel Model { get { var model = new Model(); var builder = new ModelBuilder(model); builder.Entity<Product>(); builder.Entity<Category>(); return model; } } } }
mit
C#
8d1cba35df3750b7cb9740270739bcad21f14772
Add CancelTransfersTest
jzebedee/lcapi
LCAPI/LcapiTests/AccountTest.cs
LCAPI/LcapiTests/AccountTest.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LendingClub; using Xunit; namespace LcapiTests { public class AccountTest { private KeyValuePair<string, string> GetTestCredentials() { var lines = File.ReadLines(@"C:\Dropbox\Data\LocalRepos\lcapi\LCAPI\testCredentials.txt").ToList(); return new KeyValuePair<string, string>(lines.First(), lines.Last()); } private Account CreateApiObject() { var cred = GetTestCredentials(); var apiKey = cred.Key; var investorId = cred.Value; return new Account(investorId, apiKey); } [Fact] public void SummaryTest() { var api = CreateApiObject(); var task = api.GetSummaryAsync(); var result = task.Result; Assert.NotNull(result); } [Fact] public void AddFundsTest() { var api = CreateApiObject(); var task = api.AddFundsScheduledAsync(1.23m, DateTime.Parse("02/01/2040")); var result = task.Result; Assert.NotNull(result); } [Fact] public void WithdrawFundsTest() { var api = CreateApiObject(); var task = api.WithdrawFundsAsync(1.23m); var result = task.Result; Assert.NotNull(result); } [Fact] public void PendingTransfersTest() { var api = CreateApiObject(); var task = api.GetPendingTransfersAsync(); var result = task.Result; Assert.NotNull(result); } [Fact] public void CancelTransfersTest() { var api = CreateApiObject(); var task = api.GetPendingTransfersAsync(); var result = task.Result; var toCancel = result.FirstOrDefault(r => r.Cancellable); var cancelTask = api.CancelTransferAsync(toCancel.TransferId); var cancelResult = cancelTask.Result; Assert.NotNull(cancelResult); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using LendingClub; using Xunit; namespace LcapiTests { public class AccountTest { private KeyValuePair<string, string> GetTestCredentials() { var lines = File.ReadLines(@"C:\Dropbox\Data\LocalRepos\lcapi\LCAPI\testCredentials.txt").ToList(); return new KeyValuePair<string, string>(lines.First(), lines.Last()); } private Account CreateApiObject() { var cred = GetTestCredentials(); var apiKey = cred.Key; var investorId = cred.Value; return new Account(investorId, apiKey); } [Fact] public void SummaryTest() { var api = CreateApiObject(); var task = api.GetSummaryAsync(); var result = task.Result; Assert.NotNull(result); } [Fact] public void AddFundsTest() { var api = CreateApiObject(); var task = api.AddFundsScheduledAsync(1.23m, DateTime.Parse("02/01/2040")); var result = task.Result; Assert.NotNull(result); } [Fact] public void WithdrawFundsTest() { var api = CreateApiObject(); var task = api.WithdrawFundsAsync(1.23m); var result = task.Result; Assert.NotNull(result); } [Fact] public void PendingTransfersTest() { var api = CreateApiObject(); var task = api.GetPendingTransfersAsync(); var result = task.Result; Assert.NotNull(result); } } }
agpl-3.0
C#
852b94729a7ac564b6dd7caeefa24430964ca005
Fix version number
x335/scriptsharp,nikhilk/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp,nikhilk/scriptsharp,x335/scriptsharp
src/ScriptSharp.cs
src/ScriptSharp.cs
// ScriptSharp.cs // Script#/Common // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://www.scriptsharp.com")] [assembly: AssemblyProduct("Script#")] [assembly: AssemblyCopyright("Copyright 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.5.0")] [assembly: CLSCompliant(true)]
// ScriptSharp.cs // Script#/Common // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://www.scriptsharp.com")] [assembly: AssemblyProduct("Script#")] [assembly: AssemblyCopyright("Copyright 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.7.0.0")] [assembly: AssemblyFileVersion("0.7.4.0")] [assembly: CLSCompliant(true)]
apache-2.0
C#
7aa3d4b6b08078dc9046f1417ce5e23404412da3
Use async/await on integration tests
marcbarbosa/remember
Remember.Tests/RememberTests.cs
Remember.Tests/RememberTests.cs
using System; using System.Runtime.Caching; using System.Threading.Tasks; using Xunit; namespace Remember.Tests { public class RememberTests { public class Integration : IDisposable { private readonly IRemember remember = Remember.Instance; [Fact] public async Task CallingAllMethods() { var cacheKey = "user@domain.com"; var expectedInnerUser = new User { Email = "inneruser@domain.com", Password = "Akcjhs876482u3jhKJc8d6f87234j2Bkjshdi==" }; var expectedUser = new User { Email = cacheKey, Password = "Akcjhs876482u3jhKJc8d6f87234j2Bkjshdi==", InnerUser = expectedInnerUser }; var actual = await remember.GetAsync<User>(cacheKey); Assert.Null(actual); await remember.SaveAsync<User>(cacheKey, expectedUser); actual = await remember.GetAsync<User>(cacheKey); Assert.NotNull(actual); Assert.NotNull(actual.InnerUser); Assert.Equal(expectedUser.Email, actual.Email); Assert.Equal(expectedUser.Password, actual.Password); Assert.Equal(expectedInnerUser.Email, actual.InnerUser.Email); Assert.Equal(expectedInnerUser.Password, actual.InnerUser.Password); MemoryCache.Default.Remove(cacheKey); actual = await remember.GetAsync<User>(cacheKey); Assert.NotNull(actual); await remember.DeleteAsync(cacheKey); actual = await remember.GetAsync<User>(cacheKey); Assert.Null(actual); } public class User { public string Email { get; set; } public string Password { get; set; } public User InnerUser { get; set; } } public void Dispose() { remember.Dispose(); } } } }
using System; using System.Runtime.Caching; using Xunit; namespace Remember.Tests { public class RememberTests { public class Integration : IDisposable { private readonly IRemember remember = Remember.Instance; [Fact] public void CallingAllMethods() { var cacheKey = "user@domain.com"; var expectedInnerUser = new User { Email = "inneruser@domain.com", Password = "Akcjhs876482u3jhKJc8d6f87234j2Bkjshdi==" }; var expectedUser = new User { Email = cacheKey, Password = "Akcjhs876482u3jhKJc8d6f87234j2Bkjshdi==", InnerUser = expectedInnerUser }; var actual = remember.GetAsync<User>(cacheKey).Result; Assert.Null(actual); remember.SaveAsync<User>(cacheKey, expectedUser).Wait(); actual = remember.GetAsync<User>(cacheKey).Result; Assert.NotNull(actual); Assert.NotNull(actual.InnerUser); Assert.Equal(expectedUser.Email, actual.Email); Assert.Equal(expectedUser.Password, actual.Password); Assert.Equal(expectedInnerUser.Email, actual.InnerUser.Email); Assert.Equal(expectedInnerUser.Password, actual.InnerUser.Password); MemoryCache.Default.Remove(cacheKey); actual = remember.GetAsync<User>(cacheKey).Result; Assert.NotNull(actual); remember.DeleteAsync(cacheKey).Wait(); actual = remember.GetAsync<User>(cacheKey).Result; Assert.Null(actual); } public class User { public string Email { get; set; } public string Password { get; set; } public User InnerUser { get; set; } } public void Dispose() { remember.Dispose(); } } } }
mit
C#
71546c641c8705a7ad7d20c18cfabb600345d588
Fix bad unit tests.
bchavez/Dwolla
source/Dwolla.Checkout.Tests/ValidationTests/DwollaServerCheckoutApiValidatorTests.cs
source/Dwolla.Checkout.Tests/ValidationTests/DwollaServerCheckoutApiValidatorTests.cs
using System; using Dwolla.Checkout.Validators; using FluentAssertions; using FluentValidation; using NUnit.Framework; namespace Dwolla.Checkout.Tests.ValidationTests { [TestFixture] public class DwollaServerCheckoutApiValidatorTests { private DwollaServerCheckoutApiValidator validator; [SetUp] public void BeforeEachTest() { validator = new DwollaServerCheckoutApiValidator(); } [Test] public void should_throw_with_null_api_key() { new Action( () => new DwollaServerCheckoutApi( null, "secret") ) .ShouldThrow<ArgumentException>(); } [Test] public void should_throw_with_null_api_secret() { new Action( () => new DwollaServerCheckoutApi( "key", null) ) .ShouldThrow<ArgumentException>(); } } }
using System; using Dwolla.Checkout.Validators; using FluentAssertions; using FluentValidation; using NUnit.Framework; namespace Dwolla.Checkout.Tests.ValidationTests { [TestFixture] public class DwollaServerCheckoutApiValidatorTests { private DwollaServerCheckoutApiValidator validator; [SetUp] public void BeforeEachTest() { validator = new DwollaServerCheckoutApiValidator(); } [Test] public void should_throw_with_null_api_key() { new Action( () => new DwollaServerCheckoutApi( null, "secret") ) .ShouldThrow<ValidationException>(); } [Test] public void should_throw_with_null_api_secret() { new Action( () => new DwollaServerCheckoutApi( "key", null) ) .ShouldThrow<ValidationException>(); } } }
mit
C#
186255add4a1f9cd9ffd7108a9a291f51f4b618f
improve XML document to clarify.
jwChung/Experimentalism,jwChung/Experimentalism
src/Experimental/TheoremAttribute.cs
src/Experimental/TheoremAttribute.cs
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; using Xunit.Sdk; namespace Jwc.Experimental { /// <summary> /// 이 attribute는 method위에 선언되어 해당 method가 test-case라는 것을 /// 지칭하게 되며, non-parameterized test 뿐 아니라 parameterized test에도 /// 사용될 수 있다. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class TheoremAttribute : FactAttribute { /// <summary> /// Enumerates the test commands represented by this test method. /// Derived classes should override this method to return instances of /// <see cref="ITestCommand" />, one per execution of a test method. /// </summary> /// <param name="method">The test method</param> /// <returns> /// The test commands which will execute the test runs for the given method /// </returns> protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { return !method.MethodInfo.IsDefined(typeof(DataAttribute), false) ? base.EnumerateTestCommands(method) : new TheoryAttribute().CreateTestCommands(method); } } }
using System; using System.Collections.Generic; using Xunit; using Xunit.Extensions; using Xunit.Sdk; namespace Jwc.Experimental { /// <summary> /// 테스트 메소드를 지칭하는 어트리뷰트로써, test runner에 의해 실행된다. /// </summary> [AttributeUsage(AttributeTargets.Method)] public sealed class TheoremAttribute : FactAttribute { /// <summary> /// Enumerates the test commands represented by this test method. /// Derived classes should override this method to return instances of /// <see cref="ITestCommand" />, one per execution of a test method. /// </summary> /// <param name="method">The test method</param> /// <returns> /// The test commands which will execute the test runs for the given method /// </returns> protected override IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo method) { return !method.MethodInfo.IsDefined(typeof(DataAttribute), false) ? base.EnumerateTestCommands(method) : new TheoryAttribute().CreateTestCommands(method); } } }
mit
C#
91a0f528daa75c90a1c12309ea5723083fb79eee
Bump v2.4.0
Gizeta/KanColleCacher
KanColleCacher/Properties/AssemblyInfo.cs
KanColleCacher/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.4.0.50"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using d_f_32.KanColleCacher; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle(AssemblyInfo.Title)] [assembly: AssemblyDescription(AssemblyInfo.Description)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct(AssemblyInfo.Name)] [assembly: AssemblyCopyright(AssemblyInfo.Copyright)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID //[assembly: Guid("7909a3f7-15a8-4ee5-afc5-11a7cfa40576")] [assembly: Guid("DA0FF655-A2CA-40DC-A78B-6DC85C2D448B")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion(AssemblyInfo.Version)] [assembly: AssemblyFileVersion(AssemblyInfo.Version)] namespace d_f_32.KanColleCacher { public static class AssemblyInfo { public const string Name = "KanColleCacher"; public const string Version = "2.3.2.46"; public const string Author = "d.f.32"; public const string Copyright = "©2014 - d.f.32"; #if DEBUG public const string Title = "提督很忙!缓存工具 (DEBUG)"; #else public const string Title = "提督很忙!缓存工具"; #endif public const string Description = "通过创建本地缓存以加快游戏加载速度(并支持魔改)"; } }
mit
C#
1a66f6f76050ec3320e06aece392e10a133df39c
update alert tests; auto-reset alerts
ceee/UptimeSharp
UptimeSharp.Tests/AlertsTest.cs
UptimeSharp.Tests/AlertsTest.cs
using System.Linq; using System.Threading.Tasks; using UptimeSharp.Models; using Xunit; namespace UptimeSharp.Tests { public class AlertsTest : TestsBase { public AlertsTest() : base() { } [Fact] public async Task AddInvalidAlertWithTypeSms() { await ThrowsAsync<UptimeSharpException>(async () => { await client.AddAlert(Models.AlertType.SMS, "+436601289172"); }); } [Fact] public async Task AddInvalidAlertWithTypeTwitter() { await ThrowsAsync<UptimeSharpException>(async () => { await client.AddAlert(Models.AlertType.Twitter, "artistandsocial"); }); } [Fact] public async Task AddAndRemoveAlerts() { string email = "example@ceecore.com"; Assert.NotNull(await client.AddAlert(AlertType.Email, email)); Alert origin = await GetOriginAlert(email); Assert.Equal(email, origin.Value); Assert.Equal(AlertType.Email, origin.Type); await client.DeleteAlert(origin); origin = await GetOriginAlert(email); Assert.Null(origin); } [Fact] public async Task AddAndRetrieveSpecificAlerts() { Alert alert1; Alert alert2; Assert.NotNull(alert1 = await client.AddAlert(AlertType.Email, "example1@ceecore.com")); Assert.NotNull(alert2 = await client.AddAlert(AlertType.Boxcar, "example2@ceecore.com")); try { await client.DeleteAlert(alert1); await client.DeleteAlert(alert2); } catch { } } private async Task<Alert> GetOriginAlert(string value) { return (await client.GetAlerts()).FirstOrDefault(item => item.Value == value); } } }
using System.Collections.Generic; using System.Threading.Tasks; using UptimeSharp.Models; using Xunit; namespace UptimeSharp.Tests { public class AlertsTest : TestsBase { public AlertsTest() : base() { } [Fact] public async Task AddInvalidAlertWithTypeSms() { await ThrowsAsync<UptimeSharpException>(async () => { await client.AddAlert(Models.AlertType.SMS, "+436601289172"); }); } [Fact] public async Task AddInvalidAlertWithTypeTwitter() { await ThrowsAsync<UptimeSharpException>(async () => { await client.AddAlert(Models.AlertType.Twitter, "artistandsocial"); }); } [Fact] public async Task AddAndRemoveAlerts() { string email = "example@ceecore.com"; Assert.NotNull(await client.AddAlert(AlertType.Email, email)); Alert origin = await GetOriginAlert(email); Assert.Equal(email, origin.Value); Assert.Equal(AlertType.Email, origin.Type); await client.DeleteAlert(origin); origin = await GetOriginAlert(email); Assert.Null(origin); } [Fact] public async Task AddAndRetrieveSpecificAlerts() { Assert.NotNull(await client.AddAlert(AlertType.Email, "example1@ceecore.com")); Assert.NotNull(await client.AddAlert(AlertType.Boxcar, "example2@ceecore.com")); List<Alert> alerts = await client.GetAlerts(); Assert.InRange(alerts.Count, 2, 100); List<Alert> specificAlerts = await client.GetAlerts(new string[] { alerts[0].ID, alerts[1].ID }); Assert.Equal(2, specificAlerts.Count); await ResetAlerts(); } private async Task<Alert> GetOriginAlert(string value) { List<Alert> alerts = await client.GetAlerts(); Alert origin = null; alerts.ForEach(alert => { if (alert.Value == value) { origin = alert; } }); return origin; } private async Task ResetAlerts() { try { List<Alert> alerts = await client.GetAlerts(); await client.DeleteAlert(alerts[0]); await client.DeleteAlert(alerts[1]); await client.DeleteAlert(alerts[2]); } catch { } } } }
mit
C#
5f69604921150fa457b79ead2e0708dd3fa4fbee
update to 1.0.3.1
rkttu/System.Net.FtpClient.Async,rkttu/System.Net.FtpClient.Async
System.Net.FtpClient.Async/System.Net.FtpClient.Async/Properties/AssemblyInfo.cs
System.Net.FtpClient.Async/System.Net.FtpClient.Async/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다. // 어셈블리와 관련된 정보를 수정하려면 // 이 특성 값을 변경하십시오. [assembly: AssemblyTitle("System.Net.FtpClient.Async Extensions")] [assembly: AssemblyDescription("This component provides async extensions for System.Net.FtpClient library.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ClouDeveloper")] [assembly: AssemblyProduct("System.Net.FtpClient.Async")] [assembly: AssemblyCopyright("(c) ClouDeveloper, All rights reserved.")] [assembly: AssemblyTrademark("ClouDeveloper")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("94b211a9-0c6a-4d46-85f4-67b30b694fdf")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리의 일반 정보는 다음 특성 집합을 통해 제어됩니다. // 어셈블리와 관련된 정보를 수정하려면 // 이 특성 값을 변경하십시오. [assembly: AssemblyTitle("System.Net.FtpClient.Async Extensions")] [assembly: AssemblyDescription("This component provides async extensions for System.Net.FtpClient library.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ClouDeveloper")] [assembly: AssemblyProduct("System.Net.FtpClient.Async")] [assembly: AssemblyCopyright("(c) ClouDeveloper, All rights reserved.")] [assembly: AssemblyTrademark("ClouDeveloper")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하십시오. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("94b211a9-0c6a-4d46-85f4-67b30b694fdf")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 버전이 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.0")]
mit
C#
bae25095951c1684627d186c83483688f137eaf3
Correct the Example Name in Comment
asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/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
Examples/CSharp/Articles/LoadWorkbookWithSpecificCultureInfoNumberFormat.cs
Examples/CSharp/Articles/LoadWorkbookWithSpecificCultureInfoNumberFormat.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Aspose.Cells.Examples.CSharp.Articles { public class LoadWorkbookWithSpecificCultureInfoNumberFormat { public static void Run() { // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat using (var inputStream = new MemoryStream()) { using (var writer = new StreamWriter(inputStream)) { writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>"); writer.Flush(); var culture = new CultureInfo("en-GB"); culture.NumberFormat.NumberDecimalSeparator = ","; culture.DateTimeFormat.DateSeparator = "-"; culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; LoadOptions options = new LoadOptions(LoadFormat.Html); options.CultureInfo = culture; using (var workbook = new Workbook(inputStream, options)) { var cell = workbook.Worksheets[0].Cells["A1"]; Assert.AreEqual(CellValueType.IsNumeric, cell.Type); Assert.AreEqual(1234.56, cell.DoubleValue); } } } // ExEnd:LoadWorkbookWithSpecificCultureInfoNumberFormat } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Aspose.Cells.Examples.CSharp.Articles { public class LoadWorkbookWithSpecificCultureInfoNumberFormat { public static void Run() { // ExStart:LoadWorkbookWithSpecificCultureInfoNumberFormat using (var inputStream = new MemoryStream()) { using (var writer = new StreamWriter(inputStream)) { writer.WriteLine("<html><head><title>Test Culture</title></head><body><table><tr><td>1234,56</td></tr></table></body></html>"); writer.Flush(); var culture = new CultureInfo("en-GB"); culture.NumberFormat.NumberDecimalSeparator = ","; culture.DateTimeFormat.DateSeparator = "-"; culture.DateTimeFormat.ShortDatePattern = "dd-MM-yyyy"; LoadOptions options = new LoadOptions(LoadFormat.Html); options.CultureInfo = culture; using (var workbook = new Workbook(inputStream, options)) { var cell = workbook.Worksheets[0].Cells["A1"]; Assert.AreEqual(CellValueType.IsNumeric, cell.Type); Assert.AreEqual(1234.56, cell.DoubleValue); } } } // ExEnd:LoadWorkbookWithSpecificCultureInfo } } }
mit
C#
523e40a03b08f6d8887238c81beaf01d92fe7865
Update IInputGrid.cs
LANDIS-II-Foundation/Landis-Spatial-Modeling-Library
src/api/IInputGrid.cs
src/api/IInputGrid.cs
// Copyright 2005-2006 University of Wisconsin // All rights reserved. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// An input grid of data values that are read from the upper-left corner /// to the lower-right corner in row-major order. /// </summary> public interface IInputGrid<TValue> : IGrid, System.IDisposable { /// <summary> /// Reads the next data value from the grid. /// </summary> /// <exception cref="System.IO.EndOfStreamException"> /// Thrown when there are no more data values left to read. /// </exception> TValue ReadValue(); //--------------------------------------------------------------------- /// <summary> /// Closes the input grid. /// </summary> void Close(); } }
// Copyright 2005-2006 University of Wisconsin // All rights reserved. // // The copyright holders license this file under the New (3-clause) BSD // License (the "License"). You may not use this file except in // compliance with the License. A copy of the License is available at // // http://www.opensource.org/licenses/BSD-3-Clause // // and is included in the NOTICE.txt file distributed with this work. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab namespace Landis.SpatialModeling { /// <summary> /// An input grid of data values that are read from the upper-left corner /// to the lower-right corner in row-major order. /// </summary> public interface IInputGrid<TValue> : IGrid, System.IDisposable { /// <summary> /// Reads the next data value from the grid. /// </summary> /// <exception cref="System.IO.EndOfStreamException"> /// Thrown when there are no more data values left to read. /// </exception> TValue ReadValue(); //--------------------------------------------------------------------- /// <summary> /// Closes the input grid. /// </summary> void Close(); } }
apache-2.0
C#
e4cc29d0c42bc6c062c3d777f3a95d2ab1e29762
Update ViewBase.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D.Editor/ViewBase.cs
src/Core2D.Editor/ViewBase.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Editor.Views.Interfaces; namespace Core2D.Editor { /// <summary> /// View base class. /// </summary> /// <typeparam name="T">The type of <see cref="ViewBase{T}.Context"/> property.</typeparam> public abstract class ViewBase<T> : ObservableObject, IView { /// <inheritdoc/> public abstract string Title { get; } /// <inheritdoc/> public abstract object Context { get; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Editor.Views.Interfaces; namespace Core2D.Editor { /// <summary> /// View base class. /// </summary> /// <typeparam name="T">The type of <see cref="ViewBase{T}.Context"/> property.</typeparam> public abstract class ViewBase<T> : ObservableObject, IView { /// <inheritdoc/> public abstract override string Name { get; set; } /// <inheritdoc/> public abstract object Context { get; set; } } }
mit
C#
3e889faea8ccd0de23f42899edd99ff39942757d
fix the empty space in the icon list of the Bit.BlazorUI demo project #2462 (#2490)
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/BlazorUI/Playground/Bit.BlazorUI.Playground/Web/Pages/IconPage.razor.cs
src/BlazorUI/Playground/Bit.BlazorUI.Playground/Web/Pages/IconPage.razor.cs
using System; using System.Collections.Generic; using System.Linq; namespace Bit.BlazorUI.Playground.Web.Pages; public partial class IconPage { private List<string> allIcons; private List<string> filteredIcons; private string searchText = string.Empty; protected override void OnInitialized() { allIcons = Enum.GetValues(typeof(BitIconName)) .Cast<BitIconName>() .Select(i => i.GetName()) .Where(n => n is not null) .ToList(); HandleClear(); base.OnInitialized(); } private void HandleClear() { filteredIcons = allIcons; } private void HandleChange(string text) { HandleClear(); searchText = text; if (string.IsNullOrEmpty(text)) return; filteredIcons = allIcons.FindAll(icon => string.IsNullOrEmpty(icon) is false && icon.Contains(text, StringComparison.InvariantCultureIgnoreCase)); } }
using System; using System.Collections.Generic; using System.Linq; namespace Bit.BlazorUI.Playground.Web.Pages; public partial class IconPage { private List<string> allIcons; private List<string> filteredIcons; private string searchText = string.Empty; protected override void OnInitialized() { allIcons = Enum.GetValues(typeof(BitIconName)) .Cast<BitIconName>() .Select(v => v.GetName()) .ToList(); HandleClear(); base.OnInitialized(); } private void HandleClear() { filteredIcons = allIcons; } private void HandleChange(string text) { HandleClear(); searchText = text; if (string.IsNullOrEmpty(text)) return; filteredIcons = allIcons.FindAll(icon => string.IsNullOrEmpty(icon) is false && icon.Contains(text, StringComparison.InvariantCultureIgnoreCase)); } }
mit
C#
a62ffada4cbd6a6ad52122051d00c8deab0090ff
add indexor to simplify access to child tag content e.g. person["FirstName"]
mvbalaw/LinqToHtml
src/LinqToHtml/HTMLTag.cs
src/LinqToHtml/HTMLTag.cs
using System.Collections.Generic; using System.Linq; using System.Xml; namespace LinqToHtml { public class HTMLTag { private readonly XmlNode _node; public HTMLTag(XmlNode node) { _node = node; } public IEnumerable<HTMLTagAttribute> Attributes { get { if (_node.Attributes == null) { yield break; } foreach (var attribute in _node.Attributes .Cast<XmlAttribute>() .Select(x => new HTMLTagAttribute(x))) { yield return attribute; } } } public IEnumerable<HTMLTag> ChildTags { get { if (!_node.HasChildNodes) { yield break; } var childXmlNodes = _node.ChildXmlNodes(); foreach (var tag in childXmlNodes.Select(item => new HTMLTag(item))) { yield return tag; } } } public string Content { get { return _node.InnerText; } } public IEnumerable<HTMLTag> DescendantTags { get { if (!_node.HasChildNodes) { yield break; } var xmlNodes = _node.ChildXmlNodes(); var allXmlNodes = xmlNodes.Flatten(); foreach (var tag in allXmlNodes.Select(item => new HTMLTag(item))) { yield return tag; } } } public string this [string key] { get { var child = ChildTags.FirstOrDefault(x => x.Type == key); if (child == null) { return null; } return child.Content; } } public HTMLTag Parent { get { return new HTMLTag(_node.ParentNode); } } public string RawContent { get { return _node.InnerXml; } } public string Type { get { return _node.Name; } } public void MapTo<T>(T destination) { var properties = destination .GetType() .GetProperties() .Where(x => x.CanWrite) .ToDictionary(x => x.Name.ToLower()); var attributes = Attributes .ToDictionary(x => x.Name.ToLower(), x => x.Value); var matches = attributes.Where(x => properties.ContainsKey(x.Key)); foreach (var match in matches) { var property = properties[match.Key]; PropertySetter .GetFor(property.PropertyType) .SetValue(destination, property, match.Value); } } } }
using System.Collections.Generic; using System.Linq; using System.Xml; namespace LinqToHtml { public class HTMLTag { private readonly XmlNode _node; public HTMLTag(XmlNode node) { _node = node; } public IEnumerable<HTMLTagAttribute> Attributes { get { if (_node.Attributes == null) { yield break; } foreach (var attribute in _node.Attributes .Cast<XmlAttribute>() .Select(x => new HTMLTagAttribute(x))) { yield return attribute; } } } public IEnumerable<HTMLTag> ChildTags { get { if (!_node.HasChildNodes) { yield break; } var childXmlNodes = _node.ChildXmlNodes(); foreach (var tag in childXmlNodes.Select(item => new HTMLTag(item))) { yield return tag; } } } public string Content { get { return _node.InnerText; } } public IEnumerable<HTMLTag> DescendantTags { get { if (!_node.HasChildNodes) { yield break; } var xmlNodes = _node.ChildXmlNodes(); var allXmlNodes = xmlNodes.Flatten(); foreach (var tag in allXmlNodes.Select(item => new HTMLTag(item))) { yield return tag; } } } public HTMLTag Parent { get { return new HTMLTag(_node.ParentNode); } } public string RawContent { get { return _node.InnerXml; } } public string Type { get { return _node.Name; } } public void MapTo<T>(T destination) { var properties = destination .GetType() .GetProperties() .Where(x => x.CanWrite) .ToDictionary(x => x.Name.ToLower()); var attributes = Attributes .ToDictionary(x => x.Name.ToLower(), x => x.Value); var matches = attributes.Where(x => properties.ContainsKey(x.Key)); foreach (var match in matches) { var property = properties[match.Key]; PropertySetter .GetFor(property.PropertyType) .SetValue(destination, property, match.Value); } } } }
mit
C#
8e267a4e203057326600c28711d8ae22d3abd093
Update SimpleKalmanFilter.cs
joaopedronardari/SimpleKalmanFilter
src/SimpleKalmanFilter.cs
src/SimpleKalmanFilter.cs
class SimpleKalmanFilter { private double Q = 0.00001; private double R = 0.01; private double P = 1, X = 0, K; private void MeasurementUpdate() { K = (P + Q) / (P + Q + R); P = R * K; } public double Update(double measurement) { MeasurementUpdate(); double result = X + (measurement - X) * K; X = result; return result; } public double UpdateRounding(double measurement) { return Math.Round(Update(measurement)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SimpleKalmanFilterApplication { class SimpleKalmanFilter { private double Q = 0.00001; private double R = 0.01; private double P = 1, X = 0, K; private void MeasurementUpdate() { K = (P + Q) / (P + Q + R); P = R * K; } public double Update(double measurement) { MeasurementUpdate(); double result = X + (measurement - X) * K; X = result; return result; } public double UpdateRounding(double measurement) { return Math.Round(Update(measurement)); } } }
mit
C#
43148ffc23cdaffc4a09fef8d1fd08f4d8dd5764
Update svn properties.
TomDataworks/opensim,TomDataworks/opensim,Michelle-Argus/ArribasimExtract,zekizeki/agentservice,OpenSimian/opensimulator,RavenB/opensim,N3X15/VoxelSim,TomDataworks/opensim,RavenB/opensim,ft-/arribasim-dev-tests,TechplexEngineer/Aurora-Sim,rryk/omp-server,AlexRa/opensim-mods-Alex,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,zekizeki/agentservice,intari/OpenSimMirror,QuillLittlefeather/opensim-1,AlexRa/opensim-mods-Alex,bravelittlescientist/opensim-performance,AlexRa/opensim-mods-Alex,OpenSimian/opensimulator,cdbean/CySim,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,justinccdev/opensim,M-O-S-E-S/opensim,Michelle-Argus/ArribasimExtract,zekizeki/agentservice,intari/OpenSimMirror,AlphaStaxLLC/taiga,N3X15/VoxelSim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,AlphaStaxLLC/taiga,M-O-S-E-S/opensim,rryk/omp-server,N3X15/VoxelSim,ft-/opensim-optimizations-wip-extras,AlexRa/opensim-mods-Alex,ft-/opensim-optimizations-wip-tests,allquixotic/opensim-autobackup,intari/OpenSimMirror,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,AlphaStaxLLC/taiga,AlphaStaxLLC/taiga,ft-/opensim-optimizations-wip,cdbean/CySim,TechplexEngineer/Aurora-Sim,bravelittlescientist/opensim-performance,ft-/opensim-optimizations-wip-tests,OpenSimian/opensimulator,N3X15/VoxelSim,AlphaStaxLLC/taiga,allquixotic/opensim-autobackup,zekizeki/agentservice,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,cdbean/CySim,RavenB/opensim,AlexRa/opensim-mods-Alex,justinccdev/opensim,TechplexEngineer/Aurora-Sim,bravelittlescientist/opensim-performance,M-O-S-E-S/opensim,intari/OpenSimMirror,ft-/opensim-optimizations-wip-tests,bravelittlescientist/opensim-performance,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,N3X15/VoxelSim,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,justinccdev/opensim,BogusCurry/arribasim-dev,intari/OpenSimMirror,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-extras,RavenB/opensim,AlphaStaxLLC/taiga,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,rryk/omp-server,N3X15/VoxelSim,M-O-S-E-S/opensim,zekizeki/agentservice,QuillLittlefeather/opensim-1,AlexRa/opensim-mods-Alex,rryk/omp-server,TomDataworks/opensim,M-O-S-E-S/opensim,TomDataworks/opensim,cdbean/CySim,cdbean/CySim,allquixotic/opensim-autobackup,bravelittlescientist/opensim-performance,RavenB/opensim,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,N3X15/VoxelSim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TechplexEngineer/Aurora-Sim,AlphaStaxLLC/taiga,allquixotic/opensim-autobackup,ft-/opensim-optimizations-wip,N3X15/VoxelSim,ft-/arribasim-dev-extras,RavenB/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-extras,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,bravelittlescientist/opensim-performance,ft-/arribasim-dev-tests,justinccdev/opensim,QuillLittlefeather/opensim-1,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-extras,cdbean/CySim,intari/OpenSimMirror,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,TomDataworks/opensim,justinccdev/opensim,ft-/opensim-optimizations-wip-tests,rryk/omp-server,AlphaStaxLLC/taiga,OpenSimian/opensimulator,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,M-O-S-E-S/opensim,allquixotic/opensim-autobackup,rryk/omp-server,ft-/arribasim-dev-tests,OpenSimian/opensimulator,zekizeki/agentservice,QuillLittlefeather/opensim-1,justinccdev/opensim,ft-/arribasim-dev-extras
OpenSim/Region/Environment/Modules/Terrain/TerrainUtil.cs
OpenSim/Region/Environment/Modules/Terrain/TerrainUtil.cs
using System; using OpenSim.Region.Environment.Interfaces; namespace OpenSim.Region.Environment.Modules.Terrain { public static class TerrainUtil { public static double MetersToSphericalStrength(double size) { return Math.Pow(2, size); } public static double SphericalFactor(double x, double y, double rx, double ry, double size) { return size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry)); } public static double GetBilinearInterpolate(double x, double y, ITerrainChannel map) { int w = map.Width; int h = map.Height; if (x > w - 2.0) x = w - 2.0; if (y > h - 2.0) y = h - 2.0; if (x < 0.0) x = 0.0; if (y < 0.0) y = 0.0; int stepSize = 1; double h00 = map[(int)x, (int)y]; double h10 = map[(int)x + stepSize, (int)y]; double h01 = map[(int)x, (int)y + stepSize]; double h11 = map[(int)x + stepSize, (int)y + stepSize]; double h1 = h00; double h2 = h10; double h3 = h01; double h4 = h11; double a00 = h1; double a10 = h2 - h1; double a01 = h3 - h1; double a11 = h1 - h2 - h3 + h4; double partialx = x - (int)x; double partialz = y - (int)y; double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz); return hi; } } }
using System; using OpenSim.Region.Environment.Interfaces; namespace OpenSim.Region.Environment.Modules.Terrain { public static class TerrainUtil { public static double MetersToSphericalStrength(double size) { return Math.Pow(2, size); } public static double SphericalFactor(double x, double y, double rx, double ry, double size) { return size * size - ((x - rx) * (x - rx) + (y - ry) * (y - ry)); } public static double GetBilinearInterpolate(double x, double y, ITerrainChannel map) { int w = map.Width; int h = map.Height; if (x > w - 2.0) x = w - 2.0; if (y > h - 2.0) y = h - 2.0; if (x < 0.0) x = 0.0; if (y < 0.0) y = 0.0; int stepSize = 1; double h00 = map[(int)x, (int)y]; double h10 = map[(int)x + stepSize, (int)y]; double h01 = map[(int)x, (int)y + stepSize]; double h11 = map[(int)x + stepSize, (int)y + stepSize]; double h1 = h00; double h2 = h10; double h3 = h01; double h4 = h11; double a00 = h1; double a10 = h2 - h1; double a01 = h3 - h1; double a11 = h1 - h2 - h3 + h4; double partialx = x - (int)x; double partialz = y - (int)y; double hi = a00 + (a10 * partialx) + (a01 * partialz) + (a11 * partialx * partialz); return hi; } } }
bsd-3-clause
C#
ccc4bc0992c07bd616720772c9dafea4bc530b28
refactor RegistryBackedDictionary
JLospinoso/beamgun
BeamgunApp/Models/RegistryBackedDictionary.cs
BeamgunApp/Models/RegistryBackedDictionary.cs
using System; using Microsoft.Win32; namespace BeamgunApp.Models { public interface IDynamicDictionary { Guid GetWithDefault(string key, Guid defaultValue); bool GetWithDefault(string key, bool defaultValue); string GetWithDefault(string key, string defaultValue); uint GetWithDefault(string key, uint defaultValue); double GetWithDefault(string key, double defaultValue); void Set<T>(string key, T value); } public class RegistryBackedDictionary : IDynamicDictionary { public Action<string> BadCastReport; public const string BeamgunBaseKey = @"HKEY_CURRENT_USER\SOFTWARE\Beamgun"; public string GetWithDefault(string key, string defaultValue) { return GetRegistryValue(key, defaultValue) ?? defaultValue; } public double GetWithDefault(string key, double defaultValue) { return double.TryParse(GetRegistryValue(key, defaultValue), out var result) ? result : defaultValue; } public uint GetWithDefault(string key, uint defaultValue) { return uint.TryParse(GetRegistryValue(key, defaultValue), out var result) ? result : defaultValue; } public Guid GetWithDefault(string key, Guid defaultValue) { return Guid.TryParse(GetRegistryValue(key, defaultValue), out var result) ? result : defaultValue; } public bool GetWithDefault(string key, bool defaultValue) { return (GetRegistryValue(key, defaultValue) ?? "True") == "True"; } public void Set<T>(string key, T value) { Registry.SetValue(BeamgunBaseKey, key, value); } private string GetRegistryValue(string key, object defaultValue) { return Registry.GetValue(BeamgunBaseKey, key, defaultValue)?.ToString(); } } }
using System; using Microsoft.Win32; namespace BeamgunApp.Models { public interface IDynamicDictionary { Guid GetWithDefault(string key, Guid defaultValue); bool GetWithDefault(string key, bool defaultValue); string GetWithDefault(string key, string defaultValue); uint GetWithDefault(string key, uint defaultValue); double GetWithDefault(string key, double defaultValue); void Set<T>(string key, T value); } public class RegistryBackedDictionary : IDynamicDictionary { public Action<string> BadCastReport; public const string BeamgunBaseKey = "HKEY_CURRENT_USER\\SOFTWARE\\Beamgun"; public string GetWithDefault(string key, string defaultValue) { try { return (string)Registry.GetValue(BeamgunBaseKey, key, defaultValue); } catch (InvalidCastException) { BadCastReport($"Could not parse {BeamgunBaseKey} {key}. Using default {defaultValue}."); return defaultValue; } } public double GetWithDefault(string key, double defaultValue) { return double.TryParse(Registry.GetValue(BeamgunBaseKey, key, defaultValue)?.ToString(), out var result) ? result : defaultValue; } public uint GetWithDefault(string key, uint defaultValue) { return uint.TryParse(Registry.GetValue(BeamgunBaseKey, key, defaultValue)?.ToString(), out var result) ? result : defaultValue; } public Guid GetWithDefault(string key, Guid defaultValue) { return Guid.TryParse(Registry.GetValue(BeamgunBaseKey, key, defaultValue)?.ToString(), out var result) ? result : defaultValue; } public bool GetWithDefault(string key, bool defaultValue) { return Registry.GetValue(BeamgunBaseKey, key, defaultValue ? "True" : "False").ToString() == "True"; } public void Set<T>(string key, T value) { Registry.SetValue(BeamgunBaseKey, key, value); } } }
agpl-3.0
C#
b3850cefb1dd60ff79bd1ea8fc55004ec11b7ad1
Update ExtractPhase.cs
Desolath/Confuserex
Confuser.Protections/Compress/ExtractPhase.cs
Confuser.Protections/Compress/ExtractPhase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; namespace Confuser.Protections.Compress { internal class ExtractPhase : ProtectionPhase { public ExtractPhase(Compressor parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info extraction"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { if (context.Packer == null) return; bool isExe = context.CurrentModule.Kind == ModuleKind.Windows || context.CurrentModule.Kind == ModuleKind.Console; if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null) { if (isExe) { context.Logger.Error("Too many executable modules!"); throw new ConfuserException(null); } return; } if (isExe) { var ctx = new CompressorContext { ModuleIndex = context.CurrentModuleIndex, Assembly = context.CurrentModule.Assembly, CompatMode = parameters.GetParameter(context, null, "compat", false) }; context.Annotations.Set(context, Compressor.ContextKey, ctx); ctx.ModuleName = context.CurrentModule.Name; ctx.EntryPoint = context.CurrentModule.EntryPoint; ctx.Kind = context.CurrentModule.Kind; if (!ctx.CompatMode) { context.CurrentModule.Name = "jQnxycrb"; context.CurrentModule.EntryPoint = null; context.CurrentModule.Kind = ModuleKind.NetModule; } context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent; } } class ResourceRecorder { readonly CompressorContext ctx; ModuleDef targetModule; public ResourceRecorder(CompressorContext ctx, ModuleDef module) { this.ctx = ctx; targetModule = module; } public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { if (e.WriterEvent == ModuleWriterEvent.MDEndAddResources) { var writer = (ModuleWriterBase)sender; ctx.ManifestResources = new List<Tuple<uint, uint, string>>(); Dictionary<uint, byte[]> stringDict = writer.MetaData.StringsHeap.GetAllRawData().ToDictionary(pair => pair.Key, pair => pair.Value); foreach (RawManifestResourceRow resource in writer.MetaData.TablesHeap.ManifestResourceTable) ctx.ManifestResources.Add(Tuple.Create(resource.Offset, resource.Flags, Encoding.UTF8.GetString(stringDict[resource.Name]))); ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; namespace Confuser.Protections.Compress { internal class ExtractPhase : ProtectionPhase { public ExtractPhase(Compressor parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info extraction"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { if (context.Packer == null) return; bool isExe = context.CurrentModule.Kind == ModuleKind.Windows || context.CurrentModule.Kind == ModuleKind.Console; if (context.Annotations.Get<CompressorContext>(context, Compressor.ContextKey) != null) { if (isExe) { context.Logger.Error("Too many executable modules!"); throw new ConfuserException(null); } return; } if (isExe) { var ctx = new CompressorContext { ModuleIndex = context.CurrentModuleIndex, Assembly = context.CurrentModule.Assembly, CompatMode = parameters.GetParameter(context, null, "compat", false) }; context.Annotations.Set(context, Compressor.ContextKey, ctx); ctx.ModuleName = context.CurrentModule.Name; ctx.EntryPoint = context.CurrentModule.EntryPoint; ctx.Kind = context.CurrentModule.Kind; if (!ctx.CompatMode) { context.CurrentModule.Name = "koi"; context.CurrentModule.EntryPoint = null; context.CurrentModule.Kind = ModuleKind.NetModule; } context.CurrentModuleWriterListener.OnWriterEvent += new ResourceRecorder(ctx, context.CurrentModule).OnWriterEvent; } } class ResourceRecorder { readonly CompressorContext ctx; ModuleDef targetModule; public ResourceRecorder(CompressorContext ctx, ModuleDef module) { this.ctx = ctx; targetModule = module; } public void OnWriterEvent(object sender, ModuleWriterListenerEventArgs e) { if (e.WriterEvent == ModuleWriterEvent.MDEndAddResources) { var writer = (ModuleWriterBase)sender; ctx.ManifestResources = new List<Tuple<uint, uint, string>>(); Dictionary<uint, byte[]> stringDict = writer.MetaData.StringsHeap.GetAllRawData().ToDictionary(pair => pair.Key, pair => pair.Value); foreach (RawManifestResourceRow resource in writer.MetaData.TablesHeap.ManifestResourceTable) ctx.ManifestResources.Add(Tuple.Create(resource.Offset, resource.Flags, Encoding.UTF8.GetString(stringDict[resource.Name]))); ctx.EntryPointToken = writer.MetaData.GetToken(ctx.EntryPoint).Raw; } } } } }
mit
C#
5c5b70d41972551f0b6686cb137835103a1e0c04
Use FileShare.Read option in IHttpResponseExtensions.WriteFile
zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb,303248153/ZKWeb,zkweb-framework/ZKWeb,zkweb-framework/ZKWeb
ZKWeb/ZKWebStandard/Extensions/IHttpResponseExtensions.cs
ZKWeb/ZKWebStandard/Extensions/IHttpResponseExtensions.cs
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using ZKWebStandard.Web; namespace ZKWebStandard.Extensions { /// <summary> /// Http response extension methods /// </summary> public static class IHttpResponseExtensions { /// <summary> /// Redirect to url by javascript /// Use it instead of 301 redirect can make browser send the referer header /// </summary> /// <param name="response">Http response</param> /// <param name="url">Url</param> public static void RedirectByScript(this IHttpResponse response, string url) { var urlJson = JsonConvert.SerializeObject(url); response.ContentType = "text/html"; response.Write($@"<script type='text/javascript'>location.href = {urlJson};</script>"); response.Body.Flush(); response.End(); } /// <summary> /// Set last modified time to http response /// </summary> /// <param name="response">Http response</param> /// <param name="date">Last modified time</param> public static void SetLastModified(this IHttpResponse response, DateTime date) { var value = date.ToUniversalTime().ToString("R", DateTimeFormatInfo.InvariantInfo); response.AddHeader("Last-Modified", value); } /// <summary> /// Write string to http response /// </summary> /// <param name="response">Http response</param> /// <param name="value">String value</param> public static void Write(this IHttpResponse response, string value) { var writer = new StreamWriter(response.Body); writer.Write(value); writer.Flush(); } /// <summary> /// Write file to http response /// </summary> /// <param name="response">Http response</param> /// <param name="path">File path</param> public static void WriteFile(this IHttpResponse response, string path) { using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) { stream.CopyTo(response.Body); } response.Body.Flush(); } } }
using Newtonsoft.Json; using System; using System.Globalization; using System.IO; using ZKWebStandard.Web; namespace ZKWebStandard.Extensions { /// <summary> /// Http response extension methods /// </summary> public static class IHttpResponseExtensions { /// <summary> /// Redirect to url by javascript /// Use it instead of 301 redirect can make browser send the referer header /// </summary> /// <param name="response">Http response</param> /// <param name="url">Url</param> public static void RedirectByScript(this IHttpResponse response, string url) { var urlJson = JsonConvert.SerializeObject(url); response.ContentType = "text/html"; response.Write($@"<script type='text/javascript'>location.href = {urlJson};</script>"); response.Body.Flush(); response.End(); } /// <summary> /// Set last modified time to http response /// </summary> /// <param name="response">Http response</param> /// <param name="date">Last modified time</param> public static void SetLastModified(this IHttpResponse response, DateTime date) { var value = date.ToUniversalTime().ToString("R", DateTimeFormatInfo.InvariantInfo); response.AddHeader("Last-Modified", value); } /// <summary> /// Write string to http response /// </summary> /// <param name="response">Http response</param> /// <param name="value">String value</param> public static void Write(this IHttpResponse response, string value) { var writer = new StreamWriter(response.Body); writer.Write(value); writer.Flush(); } /// <summary> /// Write file to http response /// </summary> /// <param name="response">Http response</param> /// <param name="path">File path</param> public static void WriteFile(this IHttpResponse response, string path) { using (var stream = new FileStream(path, FileMode.Open)) { stream.CopyTo(response.Body); } response.Body.Flush(); } } }
mit
C#
064af123c9fbf2d3701265c8d6407a70853d95ad
Add size constant
ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework
osu.Framework/Audio/Track/BassAmplitudes.cs
osu.Framework/Audio/Track/BassAmplitudes.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. // 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 ManagedBass; namespace osu.Framework.Audio.Track { /// <summary> /// Computes and caches amplitudes for a bass channel. /// </summary> public class BassAmplitudes { private int channel; private TrackAmplitudes currentAmplitudes; public TrackAmplitudes CurrentAmplitudes => currentAmplitudes; private const int size = 256; // should be half of the FFT length provided to ChannelGetData. private static readonly TrackAmplitudes empty = new TrackAmplitudes { FrequencyAmplitudes = new float[size] }; public BassAmplitudes(int channel) { this.channel = channel; } public void SetChannel(int channel) { if (this.channel != 0) // just for simple thread safety. limitation can be easily removed later if required. throw new InvalidOperationException("Can only set channel to non-zero value once"); if (channel == 0) throw new ArgumentException("Channel must be non-zero", nameof(channel)); this.channel = channel; } public void Update() { if (channel == 0) return; bool active = Bass.ChannelIsActive(channel) == PlaybackState.Playing; var leftChannel = active ? Bass.ChannelGetLevelLeft(channel) / 32768f : -1; var rightChannel = active ? Bass.ChannelGetLevelRight(channel) / 32768f : -1; if (leftChannel >= 0 && rightChannel >= 0) { currentAmplitudes.LeftChannel = leftChannel; currentAmplitudes.RightChannel = rightChannel; float[] tempFrequencyData = new float[size]; Bass.ChannelGetData(channel, tempFrequencyData, (int)DataFlags.FFT512); currentAmplitudes.FrequencyAmplitudes = tempFrequencyData; } else { currentAmplitudes.LeftChannel = 0; currentAmplitudes.RightChannel = 0; currentAmplitudes.FrequencyAmplitudes = empty.FrequencyAmplitudes; } } } }
// 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. // 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 ManagedBass; namespace osu.Framework.Audio.Track { /// <summary> /// Computes and caches amplitudes for a bass channel. /// </summary> public class BassAmplitudes { private int channel; private TrackAmplitudes currentAmplitudes; public TrackAmplitudes CurrentAmplitudes => currentAmplitudes; private static readonly TrackAmplitudes empty = new TrackAmplitudes { FrequencyAmplitudes = new float[256] }; public BassAmplitudes(int channel) { this.channel = channel; } public void SetChannel(int channel) { if (this.channel != 0) // just for simple thread safety. limitation can be easily removed later if required. throw new InvalidOperationException("Can only set channel to non-zero value once"); if (channel == 0) throw new ArgumentException("Channel must be non-zero", nameof(channel)); this.channel = channel; } public void Update() { if (channel == 0) return; bool active = Bass.ChannelIsActive(channel) == PlaybackState.Playing; var leftChannel = active ? Bass.ChannelGetLevelLeft(channel) / 32768f : -1; var rightChannel = active ? Bass.ChannelGetLevelRight(channel) / 32768f : -1; if (leftChannel >= 0 && rightChannel >= 0) { currentAmplitudes.LeftChannel = leftChannel; currentAmplitudes.RightChannel = rightChannel; float[] tempFrequencyData = new float[256]; Bass.ChannelGetData(channel, tempFrequencyData, (int)DataFlags.FFT512); currentAmplitudes.FrequencyAmplitudes = tempFrequencyData; } else { currentAmplitudes.LeftChannel = 0; currentAmplitudes.RightChannel = 0; currentAmplitudes.FrequencyAmplitudes = empty.FrequencyAmplitudes; } } } }
mit
C#
596f4f7d2e6c62c7a4c3fa43ce161c5b71c388d8
use spinner's clock to drive spinner
peppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,smoogipooo/osu,ppy/osu,ppy/osu,peppy/osu-new,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu
osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs
osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.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 System.Collections.Generic; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects { public override string Name => "Spun Out"; public override string Acronym => "SO"; public override IconUsage? Icon => OsuIcon.ModSpunout; public override ModType Type => ModType.Automation; public override string Description => @"Spinners will be automatically completed."; public override double ScoreMultiplier => 0.9; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) }; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var hitObject in drawables) { if (hitObject is DrawableSpinner spinner) { spinner.Disc.Enabled = false; spinner.Disc.OnUpdate += d => { var s = d as SpinnerDisc; if (s.Valid) s.Rotate(180 / MathF.PI * (float)s.Clock.ElapsedFrameTime / 40); }; } } } } }
// 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 System.Collections.Generic; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects, IUpdatableByPlayfield { public override string Name => "Spun Out"; public override string Acronym => "SO"; public override IconUsage? Icon => OsuIcon.ModSpunout; public override ModType Type => ModType.Automation; public override string Description => @"Spinners will be automatically completed."; public override double ScoreMultiplier => 0.9; public override bool Ranked => true; public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) }; private double lastFrameTime; private float frameDelay; public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables) { foreach (var hitObject in drawables) { if (hitObject is DrawableSpinner spinner) { spinner.Disc.Enabled = false; spinner.Disc.OnUpdate += d => { var s = d as SpinnerDisc; if (s.Valid) s.Rotate(180 / MathF.PI * frameDelay / 40); }; } } } public void Update(Playfield playfield) { frameDelay = (float)(playfield.Time.Current - lastFrameTime); lastFrameTime = playfield.Time.Current; } } }
mit
C#
fa33e0bd6bc5c8abb6e88938c206bad2691ba0c7
Fix background brightness being adjusted globally
peppy/osu,ppy/osu,naoey/osu,DrabWeb/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,2yangk23/osu,peppy/osu,DrabWeb/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,DrabWeb/osu,NeoAdonis/osu,peppy/osu,naoey/osu,NeoAdonis/osu,smoogipoo/osu,ZLima12/osu,smoogipoo/osu,naoey/osu,johnneijzen/osu,EVAST9919/osu
osu.Game/Graphics/Backgrounds/Background.cs
osu.Game/Graphics/Backgrounds/Background.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; namespace osu.Game.Graphics.Backgrounds { public class Background : BufferedContainer { public Sprite Sprite; private readonly string textureName; public Background(string textureName = @"") { CacheDrawnFrameBuffer = true; this.textureName = textureName; RelativeSizeAxes = Axes.Both; Add(Sprite = new Sprite { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, FillMode = FillMode.Fill, }); } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { if (!string.IsNullOrEmpty(textureName)) Sprite.Texture = textures.Get(textureName); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using OpenTK.Graphics; namespace osu.Game.Graphics.Backgrounds { public class Background : BufferedContainer { public Sprite Sprite; private readonly string textureName; public Background(string textureName = @"") { CacheDrawnFrameBuffer = true; this.textureName = textureName; RelativeSizeAxes = Axes.Both; Add(Sprite = new Sprite { RelativeSizeAxes = Axes.Both, Anchor = Anchor.Centre, Origin = Anchor.Centre, Colour = Color4.DarkGray, FillMode = FillMode.Fill, }); } [BackgroundDependencyLoader] private void load(LargeTextureStore textures) { if (!string.IsNullOrEmpty(textureName)) Sprite.Texture = textures.Get(textureName); } } }
mit
C#
ac9cb8ab49504fabe0ef5aad5c43c2da3a264c87
Fix sorting on VoiceActorInformationGrid
sillsdev/Glyssen,sillsdev/Glyssen
Glyssen/Controls/VoiceActorInformationGrid.cs
Glyssen/Controls/VoiceActorInformationGrid.cs
using System.ComponentModel; using System.Linq; using System.Windows.Forms; using Glyssen.VoiceActor; using L10NSharp; using SIL.ObjectModel; namespace Glyssen.Controls { public partial class VoiceActorInformationGrid : UserControl { public event DataGridViewRowsRemovedEventHandler RowsRemoved; public event DataGridViewRowEventHandler UserAddedRow; private int m_currentId; private Project m_project; private SortableBindingList<VoiceActorEntity> m_bindingList; public VoiceActorInformationGrid() { InitializeComponent(); m_currentId = 0; m_dataGrid.UserAddedRow += HandleUserAddedRow; m_dataGrid.RowsRemoved += HandleRowsRemoved; } public void Initialize(Project project) { m_project = project; LoadVoiceActorInformation(); } public void SaveVoiceActorInformation() { m_project.SaveVoiceActorInformationData(); } private void LoadVoiceActorInformation() { var actors = m_project.VoiceActorList.Actors; if (actors.Any()) m_currentId = actors.Max(a => a.Id) + 1; m_bindingList = new SortableBindingList<VoiceActorEntity>(actors); m_dataGrid.DataSource = m_bindingList; m_bindingList.AddingNew += HandleAddingNew; } private void HandleAddingNew(object sender, AddingNewEventArgs e) { e.NewObject = new VoiceActorEntity { Id = m_currentId++ }; } private void RemoveSelectedRows(bool confirmWithUser) { bool deleteConfirmed = !confirmWithUser; if (confirmWithUser) { string dlgMessage = LocalizationManager.GetString("DialogBoxes.VoiceActorInformation.DeleteRowsDialog.Message", "Are you sure you want to delete the selected rows?"); string dlgTitle = LocalizationManager.GetString("DialogBoxes.VoiceActorInformation.DeleteRowsDialog.Title", "Confirm"); deleteConfirmed = MessageBox.Show(dlgMessage, dlgTitle, MessageBoxButtons.YesNo) == DialogResult.Yes; } if (deleteConfirmed) { for (int i = m_dataGrid.SelectedRows.Count - 1; i >= 0; i--) { m_dataGrid.Rows.Remove(m_dataGrid.SelectedRows[i]); } } } private void contextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem == toolStripMenuItem1) { RemoveSelectedRows(true); } } private void HandleKeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Delete) { RemoveSelectedRows(true); } } private void HandleUserAddedRow(object sender, DataGridViewRowEventArgs e) { DataGridViewRowEventHandler handler = UserAddedRow; if (handler != null) handler(sender, e); } private void HandleRowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { DataGridViewRowsRemovedEventHandler handler = RowsRemoved; if (handler != null) handler(sender, e); } } }
using System.ComponentModel; using System.Linq; using System.Windows.Forms; using Glyssen.VoiceActor; using L10NSharp; namespace Glyssen.Controls { public partial class VoiceActorInformationGrid : UserControl { public event DataGridViewRowsRemovedEventHandler RowsRemoved; public event DataGridViewRowEventHandler UserAddedRow; private int m_currentId; private Project m_project; private BindingList<VoiceActorEntity> m_bindingList; public VoiceActorInformationGrid() { InitializeComponent(); m_currentId = 0; m_dataGrid.UserAddedRow += HandleUserAddedRow; m_dataGrid.RowsRemoved += HandleRowsRemoved; } public void Initialize(Project project) { m_project = project; LoadVoiceActorInformation(); } public void SaveVoiceActorInformation() { m_project.SaveVoiceActorInformationData(); } private void LoadVoiceActorInformation() { var actors = m_project.VoiceActorList.Actors; if (actors.Any()) m_currentId = actors.Max(a => a.Id) + 1; m_bindingList = new BindingList<VoiceActorEntity>(actors); m_dataGrid.DataSource = m_bindingList; m_bindingList.AddingNew += HandleAddingNew; } private void HandleAddingNew(object sender, AddingNewEventArgs e) { e.NewObject = new VoiceActorEntity { Id = m_currentId++ }; } private void RemoveSelectedRows(bool confirmWithUser) { bool deleteConfirmed = !confirmWithUser; if (confirmWithUser) { string dlgMessage = LocalizationManager.GetString("DialogBoxes.VoiceActorInformation.DeleteRowsDialog.Message", "Are you sure you want to delete the selected rows?"); string dlgTitle = LocalizationManager.GetString("DialogBoxes.VoiceActorInformation.DeleteRowsDialog.Title", "Confirm"); deleteConfirmed = MessageBox.Show(dlgMessage, dlgTitle, MessageBoxButtons.YesNo) == DialogResult.Yes; } if (deleteConfirmed) { for (int i = m_dataGrid.SelectedRows.Count - 1; i >= 0; i--) { m_dataGrid.Rows.Remove(m_dataGrid.SelectedRows[i]); } } } private void contextMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem == toolStripMenuItem1) { RemoveSelectedRows(true); } } private void HandleKeyDown(object sender, KeyEventArgs e) { if (e.KeyData == Keys.Delete) { RemoveSelectedRows(true); } } private void HandleUserAddedRow(object sender, DataGridViewRowEventArgs e) { DataGridViewRowEventHandler handler = UserAddedRow; if (handler != null) handler(sender, e); } private void HandleRowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { DataGridViewRowsRemovedEventHandler handler = RowsRemoved; if (handler != null) handler(sender, e); } } }
mit
C#
0360fafb38905ade054bc82c864ae62998ae97d2
add import prototype
0xFireball/KJade,0xFireball/KJade
KJade/src/KJade.ViewEngine/KJadeViewEngine.cs
KJade/src/KJade.ViewEngine/KJadeViewEngine.cs
using KJade.Compiler.Html; using Nancy; using Nancy.Responses; using Nancy.ViewEngines; using Nancy.ViewEngines.SuperSimpleViewEngine; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; namespace KJade.ViewEngine { public class KJadeViewEngine : IViewEngine { private readonly SuperSimpleViewEngine engineWrapper; public KJadeViewEngine(SuperSimpleViewEngine engineWrapper) { this.engineWrapper = engineWrapper; } public IEnumerable<string> Extensions => new[] { "jade", "kjade", "kade", }; public void Initialize(ViewEngineStartupContext viewEngineStartupContext) { //Nothing to really do here } private static readonly Regex ImportRegex = new Regex(@"@import\s(?<ViewName>\w+)", RegexOptions.Compiled); public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var response = new HtmlResponse(); var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result => { return EvaluateKJade(viewLocationResult, model, renderContext); }); var renderedHtml = html; response.Contents = stream => { var writer = new StreamWriter(stream); writer.Write(renderedHtml); writer.Flush(); }; return response; } private string EvaluateKJade(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { string content; using (var reader = viewLocationResult.Contents.Invoke()) { content = reader.ReadToEnd(); } //Recursively replace @import content = ImportRegex.Replace(content, m => { var partialViewName = m.Groups["ViewName"].Value; var partialModel = model; return EvaluateKJade(renderContext.LocateView(partialViewName, partialModel), model, renderContext); }); var jadeCompiler = new JadeHtmlCompiler(); var compiledHtml = jadeCompiler.Compile(content, model); return compiledHtml.Value.ToString(); } } }
using KJade.Compiler.Html; using Nancy; using Nancy.Responses; using Nancy.ViewEngines; using Nancy.ViewEngines.SuperSimpleViewEngine; using System.Collections.Generic; using System.IO; namespace KJade.ViewEngine { public class KJadeViewEngine : IViewEngine { private readonly SuperSimpleViewEngine engineWrapper; public KJadeViewEngine(SuperSimpleViewEngine engineWrapper) { this.engineWrapper = engineWrapper; } public IEnumerable<string> Extensions => new[] { "jade", "kjade", "kade", }; public void Initialize(ViewEngineStartupContext viewEngineStartupContext) { //Nothing to really do here } public Response RenderView(ViewLocationResult viewLocationResult, dynamic model, IRenderContext renderContext) { var response = new HtmlResponse(); var html = renderContext.ViewCache.GetOrAdd(viewLocationResult, result => { return EvaluateKJade(viewLocationResult, model); }); var renderedHtml = html; response.Contents = stream => { var writer = new StreamWriter(stream); writer.Write(renderedHtml); writer.Flush(); }; return response; } private string EvaluateKJade(ViewLocationResult viewLocationResult, dynamic model) { string content; using (var reader = viewLocationResult.Contents.Invoke()) { content = reader.ReadToEnd(); } var jadeCompiler = new JadeHtmlCompiler(); var compiledHtml = jadeCompiler.Compile(content, model); return compiledHtml.Value.ToString(); } } }
apache-2.0
C#
4419b61e48ff3a71fab37e891cedf34c06388637
Drop in other CRUD methods
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/ACFTController.cs
Battery-Commander.Web/Controllers/ACFTController.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { public class ACFTController : Controller { private readonly Database db; public ACFTController(Database db) { this.db = db; } public async Task<IActionResult> Index() { return Content("Coming soon!"); } public async Task<IActionResult> Details(int id) { return View(await Get(db, id)); } public async Task<IActionResult> New(int soldier = 0) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View(nameof(Edit), new APFT { SoldierId = soldier }); } public async Task<IActionResult> Edit(int id) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View(await Get(db, id)); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Save(ACFT model) { if (!ModelState.IsValid) { ViewBag.Soldiers = await SoldiersController.GetDropDownList(db, SoldierService.Query.ALL); return View("Edit", model); } if (await db.ACFTs.AnyAsync(apft => apft.Id == model.Id) == false) { db.ACFTs.Add(model); } else { db.ACFTs.Update(model); } await db.SaveChangesAsync(); return RedirectToAction(nameof(Details), new { model.Id }); } [HttpPost, ValidateAntiForgeryToken] public async Task<IActionResult> Delete(int id) { var test = await Get(db, id); db.ACFTs.Remove(test); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } public static async Task<ACFT> Get(Database db, int id) { return await db .ACFTs .Include(_ => _.Soldier) .ThenInclude(_ => _.Unit) .Where(_ => _.Id == id) .SingleOrDefaultAsync(); } } }
using BatteryCommander.Web.Models; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { public class ACFTController : Controller { private readonly Database db; public ACFTController(Database db) { this.db = db; } public async Task<IActionResult> Index() { return Content("Coming soon!"); } } }
mit
C#
424f6bd17426c17f6720a5eb82eb0b047af7c905
Add ActionResulta carousel()
fmassaretto/formacao-talentos,fmassaretto/formacao-talentos,fmassaretto/formacao-talentos
Fatec.Treinamento.Web/Controllers/HomeController.cs
Fatec.Treinamento.Web/Controllers/HomeController.cs
using Fatec.Treinamento.Data.Repositories; using System.Web.Mvc; namespace Fatec.Treinamento.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public PartialViewResult MenuAssuntos() { using(AssuntoRepository repo = new AssuntoRepository()) { // Obter a lista de assuntos var model = repo.ListarTotalCursosPorAssunto(); return PartialView("~/Views/Shared/ItensMenuAssuntos.cshtml", model); } } public ActionResult Carousel() { return PartialView("~/Views/Shared/_Carousel.cshtml"); } } }
using Fatec.Treinamento.Data.Repositories; using System.Web.Mvc; namespace Fatec.Treinamento.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public PartialViewResult MenuAssuntos() { using(AssuntoRepository repo = new AssuntoRepository()) { // Obter a lista de assuntos var model = repo.ListarTotalCursosPorAssunto(); return PartialView("~/Views/Shared/ItensMenuAssuntos.cshtml", model); } } } }
apache-2.0
C#
fa1f4304f6e7d9bdd1b3a84be3a4fc102ccc8a01
Remove usings
ZLima12/osu,peppy/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,2yangk23/osu,ppy/osu,ZLima12/osu,smoogipooo/osu,UselessToucan/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,naoey/osu,Frontear/osuKyzer,Nabile-Rahmani/osu,NeoAdonis/osu,peppy/osu-new,naoey/osu,naoey/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,peppy/osu
osu.Game/Screens/Play/HotkeyRetryOverlay.cs
osu.Game/Screens/Play/HotkeyRetryOverlay.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Allocation; using System; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; using OpenTK.Graphics; namespace osu.Game.Screens.Play { public class HotkeyRetryOverlay : Container, IKeyBindingHandler<GlobalAction> { public Action Action; private Box overlay; private const int activate_delay = 400; private const int fadeout_delay = 200; private bool fired; [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.Both; AlwaysPresent = true; Children = new Drawable[] { overlay = new Box { Alpha = 0, Colour = Color4.Black, RelativeSizeAxes = Axes.Both, } }; } public bool OnPressed(GlobalAction action) { if (action != GlobalAction.QuickRetry) return false; overlay.FadeIn(activate_delay, Easing.Out); return true; } public bool OnReleased(GlobalAction action) { if (action != GlobalAction.QuickRetry) return false; overlay.FadeOut(fadeout_delay, Easing.Out); return true; } protected override void Update() { base.Update(); if (!fired && overlay.Alpha == 1) { fired = true; Action?.Invoke(); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Input; using OpenTK.Input; using osu.Framework.Allocation; using System; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics; using osu.Framework.Graphics.Shapes; using osu.Framework.Input.Bindings; using osu.Game.Input.Bindings; using OpenTK.Graphics; namespace osu.Game.Screens.Play { public class HotkeyRetryOverlay : Container, IKeyBindingHandler<GlobalAction> { public Action Action; private Box overlay; private const int activate_delay = 400; private const int fadeout_delay = 200; private bool fired; [BackgroundDependencyLoader] private void load() { RelativeSizeAxes = Axes.Both; AlwaysPresent = true; Children = new Drawable[] { overlay = new Box { Alpha = 0, Colour = Color4.Black, RelativeSizeAxes = Axes.Both, } }; } public bool OnPressed(GlobalAction action) { if (action != GlobalAction.QuickRetry) return false; overlay.FadeIn(activate_delay, Easing.Out); return true; } public bool OnReleased(GlobalAction action) { if (action != GlobalAction.QuickRetry) return false; overlay.FadeOut(fadeout_delay, Easing.Out); return true; } protected override void Update() { base.Update(); if (!fired && overlay.Alpha == 1) { fired = true; Action?.Invoke(); } } } }
mit
C#
bf4dd33fffb878bccce8048d7119b907bed56117
Update applicationconfig.cs
StefH/KendoGridBinderEx
KendoGridBinderEx.Examples.MVC/ApplicationConfig.cs
KendoGridBinderEx.Examples.MVC/ApplicationConfig.cs
using System.Collections.Specialized; using System.Configuration; namespace KendoGridBinderEx.Examples.MVC { public static class ApplicationConfig { private static readonly NameValueCollection Config = ConfigurationManager.AppSettings; public static bool MiniProfilerEnabled { get { return bool.Parse(Config["MiniProfiler.Enabled"]); } } } }
using System.Collections.Specialized; using System.Configuration; namespace KendoGridBinderEx.Examples.MVC { public static class ApplicationConfig { private static readonly NameValueCollection Config = ConfigurationManager.AppSettings; public static bool RepositoryDeleteAllowed { get { return bool.Parse(Config["Repository.ChangeAllowed"]); } } public static bool RepositoryInsertAllowed { get { return bool.Parse(Config["Repository.ChangeAllowed"]); } } public static bool RepositoryUpdateAllowed { get { return bool.Parse(Config["Repository.ChangeAllowed"]); } } public static bool MiniProfilerEnabled { get { return bool.Parse(Config["MiniProfiler.Enabled"]); } } public static bool DatabaseInit { get { return bool.Parse(Config["Database.Init"]); } } } }
mit
C#
f8df0d58f7f09af0212e8219b6b06b8e1158ed17
handle write errors
tawnkramer/sdsandbox,tawnkramer/sdsandbox
sdsim/Assets/Scripts/Race/RaceSummary.cs
sdsim/Assets/Scripts/Race/RaceSummary.cs
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class RaceSummary : MonoBehaviour { public Transform racerLayoutGroup; public GameObject racerSummaryPrefab; int race_heat = 1; public void Init() { //clean out any previous summary... int count = racerLayoutGroup.childCount; for(int i = count - 1; i >= 0; i--) { Transform child = racerLayoutGroup.transform.GetChild(i); Destroy(child.gameObject); } // Now add one summary object per LapTimer LapTimer[] timers = GameObject.FindObjectsOfType<LapTimer>(); // But first sort things according to place. Array.Sort(timers); List<string> summary_text = new List<string>(); summary_text.Add("Heat " + race_heat.ToString()); summary_text.Add("Place,Name,Best,Lap1,Lap2,Lap3,Total"); for(int iT = 0; iT < timers.Length; iT++) { GameObject go = Instantiate(racerSummaryPrefab) as GameObject; RacerSummary s = go.GetComponent<RacerSummary>(); s.Init(timers[iT], iT + 1, summary_text); go.transform.SetParent(racerLayoutGroup); } try { WriteHeatSummary(summary_text); } catch (Exception e) { Debug.LogError("Troubles writing heat summary: " + e); } race_heat += 1; } string GetLogPath() { if(GlobalState.log_path != "default") return GlobalState.log_path + "/"; return Application.dataPath + "/../log/"; } void WriteHeatSummary(List<string> summary_text) { string filename = GetLogPath() + "HeatLog_" + race_heat.ToString() + ".csv"; StreamWriter writer = new StreamWriter(filename); foreach(String line in summary_text) { writer.WriteLine(line); } writer.Close(); } public void Close() { this.gameObject.SetActive(false); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class RaceSummary : MonoBehaviour { public Transform racerLayoutGroup; public GameObject racerSummaryPrefab; int race_heat = 1; public void Init() { //clean out any previous summary... int count = racerLayoutGroup.childCount; for(int i = count - 1; i >= 0; i--) { Transform child = racerLayoutGroup.transform.GetChild(i); Destroy(child.gameObject); } // Now add one summary object per LapTimer LapTimer[] timers = GameObject.FindObjectsOfType<LapTimer>(); // But first sort things according to place. Array.Sort(timers); List<string> summary_text = new List<string>(); summary_text.Add("Heat " + race_heat.ToString()); summary_text.Add("Place,Name,Best,Lap1,Lap2,Lap3,Total"); for(int iT = 0; iT < timers.Length; iT++) { GameObject go = Instantiate(racerSummaryPrefab) as GameObject; RacerSummary s = go.GetComponent<RacerSummary>(); s.Init(timers[iT], iT + 1, summary_text); go.transform.SetParent(racerLayoutGroup); } WriteHeatSummary(summary_text); race_heat += 1; } string GetLogPath() { if(GlobalState.log_path != "default") return GlobalState.log_path + "/"; return Application.dataPath + "/../log/"; } void WriteHeatSummary(List<string> summary_text) { string filename = GetLogPath() + "HeatLog_" + race_heat.ToString() + ".csv"; StreamWriter writer = new StreamWriter(filename); foreach(String line in summary_text) { writer.WriteLine(line); } writer.Close(); } public void Close() { this.gameObject.SetActive(false); } }
bsd-3-clause
C#
20906116e634ae2b9056ebd4deed3569d1b938fc
Fix fast Circle vs Circle test
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/Physics/Collider/CirclevsCircle.cs
MadCat/NutEngine/Physics/Collider/CirclevsCircle.cs
using Microsoft.Xna.Framework; using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<Circle> a, IBody<Circle> b, out IntersectionArea intersection) { // Probably here should be the sector collisions check, // but it needs additional method without manifolds // // "There is only one god, and His name is Code. // And there is only one thing we say to Code: 'not today'." var normal = b.Position - a.Position; float radius = a.Shape.Radius + b.Shape.Radius; if (normal.LengthSquared() >= radius * radius) { intersection = null; return false; // Circles doesn't collide } else { float distance = normal.Length(); if (distance == 0) { intersection = new IntersectionArea() { Depth = a.Shape.Radius, Normal = Vector2.UnitX, }; } else { var normalizable = normal / distance; intersection = new IntersectionArea() { Depth = radius - distance, Normal = normalizable, }; } return true; } } public static bool Collide(IBody<Circle> a, IBody<Circle> b) { var rSquare = (a.Shape.Radius + b.Shape.Radius) * (a.Shape.Radius + b.Shape.Radius); return rSquare > (a.Position.X - b.Position.X) * (a.Position.X - b.Position.X) + (a.Position.Y - b.Position.Y) * (a.Position.Y - b.Position.Y); } } }
using Microsoft.Xna.Framework; using NutEngine.Physics.Shapes; namespace NutEngine.Physics { public static partial class Collider { public static bool Collide(IBody<Circle> a, IBody<Circle> b, out IntersectionArea intersection) { // Probably here should be the sector collisions check, // but it needs additional method without manifolds // // "There is only one god, and His name is Code. // And there is only one thing we say to Code: 'not today'." var normal = b.Position - a.Position; float radius = a.Shape.Radius + b.Shape.Radius; if (normal.LengthSquared() >= radius * radius) { intersection = null; return false; // Circles doesn't collide } else { float distance = normal.Length(); if (distance == 0) { intersection = new IntersectionArea() { Depth = a.Shape.Radius, Normal = Vector2.UnitX, }; } else { var normalizable = normal / distance; intersection = new IntersectionArea() { Depth = radius - distance, Normal = normalizable, }; } return true; } } public static bool Collide(IBody<Circle> a, IBody<Circle> b) { var rSquare = (a.Shape.Radius + b.Shape.Radius) * (a.Shape.Radius + b.Shape.Radius); return rSquare < (a.Position.X - b.Position.X) * (a.Position.X - b.Position.X) + (a.Position.Y - b.Position.Y) * (a.Position.Y - b.Position.Y); } } }
mit
C#
db718f3c283c48c513afc354d6e291d6ed5829cf
Use 'o' format for date. Fixed splitting problem with backtrace.
mroach/exceptional-net,mroach/exceptional-net
src/Exceptional.Core/ExceptionSummary.cs
src/Exceptional.Core/ExceptionSummary.cs
using System; using System.Globalization; using System.Linq; using Newtonsoft.Json; namespace Exceptional.Core { public class ExceptionSummary { [JsonProperty(PropertyName = "occurred_at")] public string OccurredAt { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "backtrace")] public string[] Backtrace { get; set; } [JsonProperty(PropertyName = "exception_class")] public string ExceptionClass { get; set; } public ExceptionSummary() { OccurredAt = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture); } public static ExceptionSummary CreateFromException(Exception ex) { var summary = new ExceptionSummary(); summary.Message = ex.Message; summary.Backtrace = ex.StackTrace.Split(new[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries).Select(line => line.Trim()).ToArray(); summary.ExceptionClass = ex.GetType().Name; return summary; } } }
using System; using System.Linq; using Newtonsoft.Json; namespace Exceptional.Core { public class ExceptionSummary { [JsonProperty(PropertyName = "occurred_at")] public DateTime OccurredAt { get; set; } [JsonProperty(PropertyName = "message")] public string Message { get; set; } [JsonProperty(PropertyName = "backtrace")] public string[] Backtrace { get; set; } [JsonProperty(PropertyName = "exception_class")] public string ExceptionClass { get; set; } public ExceptionSummary() { OccurredAt = DateTime.UtcNow; } public static ExceptionSummary CreateFromException(Exception ex) { var summary = new ExceptionSummary(); summary.Message = ex.Message; summary.Backtrace = ex.StackTrace.Split('\r', '\n').Select(line => line.Trim()).ToArray(); summary.ExceptionClass = ex.GetType().Name; return summary; } } }
apache-2.0
C#
32e4f1cbf14550c59c95ec402255f11851089bc3
Fix incorrect AssemblyInformationalVersion.
dlemstra/OmniKassa
src/OmniKassa/Properties/AssemblyInfo.cs
src/OmniKassa/Properties/AssemblyInfo.cs
// Copyright 2017 Dirk Lemstra (https://github.com/dlemstra/OmniKassa). // Licensed under the MIT License. using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("C# API for OmniKassa")] [assembly: AssemblyCompany("Dirk Lemstra")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyProduct("OmniKassa")] [assembly: AssemblyCopyright("Copyright 2017 Dirk Lemstra")] [assembly: AssemblyTitle("OmniKassa")] [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.1")] [assembly: AssemblyInformationalVersion("1.0.1")] #if NET35 [assembly: InternalsVisibleTo("OmniKassa.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003748ed84631cfec3a61aa2371cabf4e3c6a8d208a1d9320ccfb83aa604f24c12e8cbfde1836e6dbf9a13d306247559edb6aa2ffca5bc2ed4315db707a8ecd716f84ed6d6fd6796d91f46d324005f0663f555286ef78d0a3abf1f1e23529cc2ff0ec2682353706b6aec39fb20c7cbac9305192beae3640f04ee61a8cdc5e392c3")] #else [assembly: InternalsVisibleTo("OmniKassa.Tests")] #endif
// Copyright 2017 Dirk Lemstra (https://github.com/dlemstra/OmniKassa). // Licensed under the MIT License. using System.Reflection; using System.Runtime.CompilerServices; [assembly: AssemblyDescription("C# API for OmniKassa")] [assembly: AssemblyCompany("Dirk Lemstra")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyProduct("OmniKassa")] [assembly: AssemblyCopyright("Copyright 2017 Dirk Lemstra")] [assembly: AssemblyTitle("OmniKassa")] [assembly: AssemblyVersion("1.0.1")] [assembly: AssemblyFileVersion("1.0.1")] [assembly: AssemblyInformationalVersion("1.0.1-alpha1")] #if NET35 [assembly: InternalsVisibleTo("OmniKassa.Tests, PublicKey=00240000048000009400000006020000002400005253413100040000010001003748ed84631cfec3a61aa2371cabf4e3c6a8d208a1d9320ccfb83aa604f24c12e8cbfde1836e6dbf9a13d306247559edb6aa2ffca5bc2ed4315db707a8ecd716f84ed6d6fd6796d91f46d324005f0663f555286ef78d0a3abf1f1e23529cc2ff0ec2682353706b6aec39fb20c7cbac9305192beae3640f04ee61a8cdc5e392c3")] #else [assembly: InternalsVisibleTo("OmniKassa.Tests")] #endif
mit
C#
2ceee43d9430309c2e63206947483c4391cc8e0d
fix syntax error from PR
IdentityModel/IdentityModel,IdentityModel/IdentityModel
src/Jwk/JsonWebKeySet.cs
src/Jwk/JsonWebKeySet.cs
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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.Text.Json; using System.Text.Json.Serialization; namespace IdentityModel.Jwk; /// <summary> /// Contains a collection of <see cref="JsonWebKey"/> that can be populated from a json string. /// </summary> public class JsonWebKeySet { /// <summary> /// Initializes an new instance of <see cref="JsonWebKeySet"/>. /// </summary> public JsonWebKeySet() { } /// <summary> /// Initializes an new instance of <see cref="JsonWebKeySet"/> from a json string. /// </summary> /// <param name="json">a json string containing values.</param> /// <exception cref="ArgumentNullException">if 'json' is null or whitespace.</exception> public JsonWebKeySet(string json) { if (string.IsNullOrWhiteSpace(json)) throw new ArgumentNullException(nameof(json)); var jwebKeys = JsonSerializer.Deserialize<JsonWebKeySet>(json); Keys = jwebKeys.Keys; RawData = json; } /// <summary> /// A list of JSON web keys /// </summary> [JsonPropertyName("keys")] public List<JsonWebKey> Keys { get; set; } = new(); /// <summary> /// The JSON string used to deserialize this object /// </summary> [JsonIgnore] public string RawData { get; set; } }
//------------------------------------------------------------------------------ // // Copyright (c) Microsoft Corporation. // All rights reserved. // // This code is licensed under the MIT License. // // 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.Text.Json; using System.Text.Json.Serialization; namespace IdentityModel.Jwk; /// <summary> /// Contains a collection of <see cref="JsonWebKey"/> that can be populated from a json string. /// </summary> public class JsonWebKeySet { /// <summary> /// Initializes an new instance of <see cref="JsonWebKeySet"/>. /// </summary> public JsonWebKeySet() { } /// <summary> /// Initializes an new instance of <see cref="JsonWebKeySet"/> from a json string. /// </summary> /// <param name="json">a json string containing values.</param> /// <exception cref="ArgumentNullException">if 'json' is null or whitespace.</exception> public JsonWebKeySet(string json) { if (string.IsNullOrWhiteSpace(json)) throw new ArgumentNullException(nameof(json)); var jwebKeys = JsonSerializer.Deserialize<JsonWebKeySet>(json); Keys = jwebKeys.Keys; RawData = json; } /// <summary> /// A list of JSON web keys /// </summary> [JsonPropertyName("keys")] public List<JsonWebKey> Keys { get; set; } = new(); /// <summary> /// The JSON string used to deserialize this object /// </summary> [JsonIgnore] public string RawData { get; set; }; }
apache-2.0
C#
b567cfb6106e2f48f552057e0e21c06d24c27bd5
Verify should accept a guid activationKey
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
SnittListan.Test/RoutesTest.cs
SnittListan.Test/RoutesTest.cs
using System; using System.Web.Routing; using MvcContrib.TestHelper; using SnittListan.Controllers; using Xunit; using System.Web.Mvc; namespace SnittListan.Test { public class RoutesTest : IDisposable { public RoutesTest() { new RouteConfigurator(RouteTable.Routes).Configure(); } public void Dispose() { RouteTable.Routes.Clear(); } [Fact] public void DefaultRoute() { "~/".ShouldMapTo<HomeController>(c => c.Index()); } [Fact] public void LowerCaseRoutes() { "~/account/register".ShouldMapTo<AccountController>(c => c.Register()); } [Fact] public void Shortcuts() { "~/register".ShouldMapTo<AccountController>(c => c.Register()); "~/logon".ShouldMapTo<AccountController>(c => c.LogOn()); "~/about".ShouldMapTo<HomeController>(c => c.About()); } [Fact] public void Verify() { var verify = "~/verify".WithMethod(HttpVerbs.Post); var guid = Guid.NewGuid(); verify.Values["activationKey"] = guid.ToString(); verify.ShouldMapTo<AccountController>(c => c.Verify(guid)); } } }
using System; using System.Web.Routing; using MvcContrib.TestHelper; using SnittListan.Controllers; using Xunit; namespace SnittListan.Test { public class RoutesTest : IDisposable { public RoutesTest() { new RouteConfigurator(RouteTable.Routes).Configure(); } public void Dispose() { RouteTable.Routes.Clear(); } [Fact] public void DefaultRoute() { "~/".ShouldMapTo<HomeController>(c => c.Index()); } [Fact] public void LowerCaseRoutes() { "~/account/register".ShouldMapTo<AccountController>(c => c.Register()); } [Fact] public void Shortcuts() { "~/register".ShouldMapTo<AccountController>(c => c.Register()); "~/logon".ShouldMapTo<AccountController>(c => c.LogOn()); "~/about".ShouldMapTo<HomeController>(c => c.About()); } } }
mit
C#
1235d2192601b02dfa55076f35e5163059512a79
Update Expertise.cs
datanets/kask-kiosk,datanets/kask-kiosk
Models/Expertise.cs
Models/Expertise.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Expertise { public int Applicant_ID { get; set; } public int Skill_ID { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Empty.Models { public class Expertise { public int applicant_ID { get; set; } public int skill_ID { get; set; } } }
mit
C#
0ae28f2acff7b98c98cc85631643265159df5f0e
Remove override methods from Interactive Element Inspector
killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/SDK/Editor/Inspectors/UX/InteractiveElement/InteractiveElementInspector.cs
Assets/MRTK/SDK/Editor/Inspectors/UX/InteractiveElement/InteractiveElementInspector.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License using Microsoft.MixedReality.Toolkit.UI.Interaction; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Custom inspector for an InteractiveElement. /// </summary> [CustomEditor(typeof(InteractiveElement))] public class InteractiveElementInspector : BaseInteractiveElementInspector { // Interactive Element is a place holder class } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License using Microsoft.MixedReality.Toolkit.UI.Interaction; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.Editor { /// <summary> /// Custom inspector for an InteractiveElement. /// </summary> [CustomEditor(typeof(InteractiveElement))] public class InteractiveElementInspector : BaseInteractiveElementInspector { protected override void OnEnable() { base.OnEnable(); } public override void OnInspectorGUI() { // Interactive Element is a place holder class base.OnInspectorGUI(); } } }
mit
C#
b4b869a42902431f40766ec0ed276cf2c2db6b18
Fix after event were renamed
SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia
samples/ControlCatalog/Pages/PointersPage.xaml.cs
samples/ControlCatalog/Pages/PointersPage.xaml.cs
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; namespace ControlCatalog.Pages; public class PointersPage : UserControl { public PointersPage() { this.InitializeComponent(); var border1 = this.Get<Border>("BorderCapture1"); var border2 = this.Get<Border>("BorderCapture2"); border1.PointerPressed += Border_PointerPressed; border1.PointerReleased += Border_PointerReleased; border1.PointerCaptureLost += Border_PointerCaptureLost; border1.PointerMoved += Border_PointerUpdated; border1.PointerEntered += Border_PointerUpdated; border1.PointerExited += Border_PointerUpdated; border2.PointerPressed += Border_PointerPressed; border2.PointerReleased += Border_PointerReleased; border2.PointerCaptureLost += Border_PointerCaptureLost; border2.PointerMoved += Border_PointerUpdated; border2.PointerEntered += Border_PointerUpdated; border2.PointerExited += Border_PointerUpdated; } private void Border_PointerUpdated(object sender, PointerEventArgs e) { var textBlock = (TextBlock)((Border)sender).Child; var position = e.GetPosition((Border)sender); textBlock.Text = @$"Captured: {e.Pointer.Captured == sender} PointerId: {e.Pointer.Id} Position: {(int)position.X} {(int)position.Y}"; e.Handled = true; } private void Border_PointerCaptureLost(object sender, PointerCaptureLostEventArgs e) { var textBlock = (TextBlock)((Border)sender).Child; textBlock.Text = @$"Captured: {e.Pointer.Captured == sender} PointerId: {e.Pointer.Id} Position: ??? ???"; e.Handled = true; } private void Border_PointerReleased(object sender, PointerReleasedEventArgs e) { if (e.Pointer.Captured == sender) { e.Pointer.Capture(null); e.Handled = true; } else { throw new InvalidOperationException("How?"); } } private void Border_PointerPressed(object sender, PointerPressedEventArgs e) { e.Pointer.Capture((Border)sender); e.Handled = true; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } }
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; namespace ControlCatalog.Pages; public class PointersPage : UserControl { public PointersPage() { this.InitializeComponent(); var border1 = this.Get<Border>("BorderCapture1"); var border2 = this.Get<Border>("BorderCapture2"); border1.PointerPressed += Border_PointerPressed; border1.PointerReleased += Border_PointerReleased; border1.PointerCaptureLost += Border_PointerCaptureLost; border1.PointerMoved += Border_PointerUpdated; border1.PointerEnter += Border_PointerUpdated; border1.PointerLeave += Border_PointerUpdated; border2.PointerPressed += Border_PointerPressed; border2.PointerReleased += Border_PointerReleased; border2.PointerCaptureLost += Border_PointerCaptureLost; border2.PointerMoved += Border_PointerUpdated; border2.PointerEnter += Border_PointerUpdated; border2.PointerLeave += Border_PointerUpdated; } private void Border_PointerUpdated(object sender, PointerEventArgs e) { var textBlock = (TextBlock)((Border)sender).Child; var position = e.GetPosition((Border)sender); textBlock.Text = @$"Captured: {e.Pointer.Captured == sender} PointerId: {e.Pointer.Id} Position: {(int)position.X} {(int)position.Y}"; e.Handled = true; } private void Border_PointerCaptureLost(object sender, PointerCaptureLostEventArgs e) { var textBlock = (TextBlock)((Border)sender).Child; textBlock.Text = @$"Captured: {e.Pointer.Captured == sender} PointerId: {e.Pointer.Id} Position: ??? ???"; e.Handled = true; } private void Border_PointerReleased(object sender, PointerReleasedEventArgs e) { if (e.Pointer.Captured == sender) { e.Pointer.Capture(null); e.Handled = true; } else { throw new InvalidOperationException("How?"); } } private void Border_PointerPressed(object sender, PointerPressedEventArgs e) { e.Pointer.Capture((Border)sender); e.Handled = true; } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } }
mit
C#
b7c6768af7c4461eef65fbc90483ecf50b3c9f28
Update Delete.cshtml
Franklin89/Blog,Franklin89/Blog
src/MLSoftware.Web/Views/Post/Delete.cshtml
src/MLSoftware.Web/Views/Post/Delete.cshtml
@model MLSoftware.Web.ViewModels.PostViewModel <ol class="breadcrumb"> <li><a asp-controller="Home" asp-action="Index">Home</a></li> @if (Model.IsDraft) { <li><a asp-controller="Draft" asp-action="Index">Drafts</a></li> } <li class="active">@Model.Title</li> </ol> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <h2>Delete post</h2> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <span>Are you sure you want to delete the post: <strong>@Model.Title</strong>?</span> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <form asp-controller="Post" asp-action="Delete" method="post" class="form-horizontal" role="form"> <input type="hidden" asp-for="Id" /> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="Delete" class="btn btn-default" /> <a asp-controller="Post" asp-action="Details" asp-route-id="@Model.Id" class="btn btn-default"> Cancel </a> </div> </div> </div> </form> </div> </div>
@model MLSoftware.Web.ViewModels.PostViewModel <ol class="breadcrumb"> <li><a asp-controller="Home" asp-action="Index">Home</a></li> @if (Model.IsDraft) { <li><a asp-controller="Draft" asp-action="Index">Drafts</a></li> } <li class="active">@Model.Title</li> </ol> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <h2>Delete Contact</h2> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <span>Are you sure you want to delete the post: <strong>@Model.Title</strong>?</span> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1"> <form asp-controller="Post" asp-action="Delete" method="post" class="form-horizontal" role="form"> <input type="hidden" asp-for="Id" /> <div class="form-horizontal"> <div class="form-group"> <div class="col-md-10"> <input type="submit" value="Delete" class="btn btn-default" /> <a asp-controller="Post" asp-action="Details" asp-route-id="@Model.Id" class="btn btn-default"> Cancel </a> </div> </div> </div> </form> </div> </div>
mit
C#
7f8cc2ba88eb3ba758285f15ada221708d55f5ce
Update HoldsValue property in MultiSchema.cs
EdonGashi/WpfMaterialForms
src/MaterialForms/DataSchema/MultiSchema.cs
src/MaterialForms/DataSchema/MultiSchema.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using MaterialForms.Controls; namespace MaterialForms { /// <summary> /// Allows adding multiple schemas within the same row. /// </summary> public class MultiSchema : SchemaBase { public MultiSchema(params SchemaBase[] schemas) { if (schemas == null || schemas.Length < 2) { throw new ArgumentException("A minimum of two schemas is required."); } Schemas = schemas; } /// <summary> /// Gets the schemas being presented. /// </summary> public SchemaBase[] Schemas { get; } /// <summary> /// Gets the star size width of each schema in their respective index. /// Default width for each element is one unit. /// </summary> public IEnumerable<double> RelativeColumnWidths { get; set; } public override UserControl CreateView() { var columnWidths = RelativeColumnWidths as double[] ?? RelativeColumnWidths?.ToArray() ?? new double[0]; return new MultiSchemaControl(Schemas, columnWidths); } public override bool HoldsValue => Schemas.Any(schema => schema.HoldsValue); protected override bool OnValidation() { var isValid = true; foreach (var schema in Schemas) { if (schema == null) { continue; } isValid &= schema.Validate(); } return isValid; } public override object GetValue() => GetForm(); public MaterialForm GetForm() { return new MaterialForm(Schemas); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using MaterialForms.Controls; namespace MaterialForms { /// <summary> /// Allows adding multiple schemas within the same row. /// </summary> public class MultiSchema : SchemaBase { public MultiSchema(params SchemaBase[] schemas) { if (schemas == null || schemas.Length < 2) { throw new ArgumentException("A minimum of two schemas is required."); } Schemas = schemas; } /// <summary> /// Gets the schemas being presented. /// </summary> public SchemaBase[] Schemas { get; } /// <summary> /// Gets the star size width of each schema in their respective index. /// Default width for each element is one unit. /// </summary> public IEnumerable<double> RelativeColumnWidths { get; set; } public override UserControl CreateView() { var columnWidths = RelativeColumnWidths as double[] ?? RelativeColumnWidths?.ToArray() ?? new double[0]; return new MultiSchemaControl(Schemas, columnWidths); } public override bool HoldsValue => true; protected override bool OnValidation() { var isValid = true; foreach (var schema in Schemas) { if (schema == null) { continue; } isValid &= schema.Validate(); } return isValid; } public override object GetValue() => GetForm(); public MaterialForm GetForm() { return new MaterialForm(Schemas); } } }
mit
C#
fb4c950e8af57189278aad9f3cc8185fb22ec92a
Add key binding set to loop i/o params
reubeno/NClap
src/NClap/Repl/LoopInputOutputParameters.cs
src/NClap/Repl/LoopInputOutputParameters.cs
using System.IO; using NClap.ConsoleInput; using NClap.Utilities; namespace NClap.Repl { /// <summary> /// Parameters for constructing a loop with advanced line input. The /// parameters indicate how the loop's textual input and output should /// be implemented. /// </summary> public class LoopInputOutputParameters { /// <summary> /// Optionally provides a writer to use for error output. /// </summary> public TextWriter ErrorWriter { get; set; } /// <summary> /// Line input object to use, or null for a default one to be /// constructed. /// </summary> public IConsoleLineInput LineInput { get; set; } /// <summary> /// The console input interface to use, or null to use the default one. /// </summary> public IConsoleInput ConsoleInput { get; set; } /// <summary> /// The console output interface to use, or null to use the default one. /// </summary> public IConsoleOutput ConsoleOutput { get; set; } /// <summary> /// The console key binding set to use, or null to use the default one. /// </summary> public IReadOnlyConsoleKeyBindingSet KeyBindingSet { get; set; } /// <summary> /// Input prompt, or null to use the default one. /// </summary> public ColoredString Prompt { get; set; } } }
using System.IO; using NClap.ConsoleInput; using NClap.Utilities; namespace NClap.Repl { /// <summary> /// Parameters for constructing a loop with advanced line input. The /// parameters indicate how the loop's textual input and output should /// be implemented. /// </summary> public class LoopInputOutputParameters { /// <summary> /// Writer to use for error output. /// </summary> public TextWriter ErrorWriter { get; set; } /// <summary> /// Line input object to use. /// </summary> public IConsoleLineInput LineInput { get; set; } /// <summary> /// The console input interface to use. /// </summary> public IConsoleInput ConsoleInput { get; set; } /// <summary> /// The console output interface to use. /// </summary> public IConsoleOutput ConsoleOutput { get; set; } /// <summary> /// Input prompt. /// </summary> public ColoredString Prompt { get; set; } } }
mit
C#
13e66d39182d57f86644e09501a3e606814fef26
use NRT
sharwell/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,dotnet/roslyn,diryboy/roslyn,weltkante/roslyn,wvdd007/roslyn,weltkante/roslyn,diryboy/roslyn,physhi/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,physhi/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,mavasani/roslyn,mavasani/roslyn,dotnet/roslyn,wvdd007/roslyn,sharwell/roslyn,bartdesmet/roslyn,diryboy/roslyn,eriawan/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,sharwell/roslyn
src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/ExtendedSyntaxNode.cs
src/Features/Core/Portable/ConvertLinq/ConvertForEachToLinqQuery/ExtendedSyntaxNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery { internal readonly struct ExtendedSyntaxNode { public SyntaxNode Node { get; } public ImmutableArray<SyntaxTrivia> ExtraLeadingComments { get; } public ImmutableArray<SyntaxTrivia> ExtraTrailingComments { get; } public ExtendedSyntaxNode( SyntaxNode node, IEnumerable<SyntaxToken> extraLeadingTokens, IEnumerable<SyntaxToken> extraTrailingTokens) : this(node, extraLeadingTokens.GetTrivia(), extraTrailingTokens.GetTrivia()) { } public ExtendedSyntaxNode( SyntaxNode node, IEnumerable<SyntaxTrivia> extraLeadingComments, IEnumerable<SyntaxTrivia> extraTrailingComments) { Node = node; ExtraLeadingComments = extraLeadingComments.ToImmutableArray(); ExtraTrailingComments = extraTrailingComments.ToImmutableArray(); } } }
// 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. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery { internal readonly struct ExtendedSyntaxNode { public SyntaxNode Node { get; } public ImmutableArray<SyntaxTrivia> ExtraLeadingComments { get; } public ImmutableArray<SyntaxTrivia> ExtraTrailingComments { get; } public ExtendedSyntaxNode( SyntaxNode node, IEnumerable<SyntaxToken> extraLeadingTokens, IEnumerable<SyntaxToken> extraTrailingTokens) : this(node, extraLeadingTokens.GetTrivia(), extraTrailingTokens.GetTrivia()) { } public ExtendedSyntaxNode( SyntaxNode node, IEnumerable<SyntaxTrivia> extraLeadingComments, IEnumerable<SyntaxTrivia> extraTrailingComments) { Node = node; ExtraLeadingComments = extraLeadingComments.ToImmutableArray(); ExtraTrailingComments = extraTrailingComments.ToImmutableArray(); } } }
mit
C#
64cd1c6545d5e463fc07d688daaa715f5b46f595
Fix build of test case
Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla51642.xaml.cs
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla51642.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)] public partial class Bugzilla51642 : ContentPage { #if APP public Bugzilla51642 () { InitializeComponent (); LoadDelayedVM(); BoundPicker.SelectedIndexChanged += (s, e) => { SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString(); }; } public async void LoadDelayedVM() { await Task.Delay(1000); Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM()); } #endif } [Preserve(AllMembers=true)] class Bz51642VM { public IList<string> Items { get { return new List<String> { "Foo", "Bar", "Baz" }; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; namespace Xamarin.Forms.Controls.Issues { [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 51642, "Delayed BindablePicker UWP", PlatformAffected.All)] public partial class Bugzilla51642 : ContentPage { public Bugzilla51642 () { InitializeComponent (); LoadDelayedVM(); BoundPicker.SelectedIndexChanged += (s, e) => { SelectedItemLabel.Text = BoundPicker.SelectedItem.ToString(); }; } public async void LoadDelayedVM() { await Task.Delay(1000); Device.BeginInvokeOnMainThread(() => BindingContext = new Bz51642VM()); } } [Preserve(AllMembers=true)] class Bz51642VM { public IList<string> Items { get { return new List<String> { "Foo", "Bar", "Baz" }; } } } }
mit
C#