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
751d692dbda5877f0cf269ea47cc5c97dac5f504
Fix compiler warning
domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/Generator/IDocumentFilter.cs
src/Swashbuckle.AspNetCore.SwaggerGen/Generator/IDocumentFilter.cs
using Microsoft.AspNetCore.Mvc.ApiExplorer; using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; namespace Swashbuckle.AspNetCore.SwaggerGen { public interface IDocumentFilter { void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context); } public class DocumentFilterContext { public DocumentFilterContext( ApiDescriptionGroupCollection apiDescriptionsGroups, IEnumerable<ApiDescription> apiDescriptions, ISchemaRegistry schemaRegistry) { #pragma warning disable CS0618 // Type or member is obsolete ApiDescriptionsGroups = apiDescriptionsGroups; #pragma warning restore CS0618 // Type or member is obsolete ApiDescriptions = apiDescriptions; SchemaRegistry = schemaRegistry; } [Obsolete("Deprecated: Use ApiDescriptions")] public ApiDescriptionGroupCollection ApiDescriptionsGroups { get; private set; } public IEnumerable<ApiDescription> ApiDescriptions { get; private set; } public ISchemaRegistry SchemaRegistry { get; private set; } } }
using Microsoft.AspNetCore.Mvc.ApiExplorer; using Swashbuckle.AspNetCore.Swagger; using System; using System.Collections.Generic; namespace Swashbuckle.AspNetCore.SwaggerGen { public interface IDocumentFilter { void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context); } public class DocumentFilterContext { public DocumentFilterContext( ApiDescriptionGroupCollection apiDescriptionsGroups, IEnumerable<ApiDescription> apiDescriptions, ISchemaRegistry schemaRegistry) { ApiDescriptionsGroups = apiDescriptionsGroups; ApiDescriptions = apiDescriptions; SchemaRegistry = schemaRegistry; } [Obsolete("Deprecated: Use ApiDescriptions")] public ApiDescriptionGroupCollection ApiDescriptionsGroups { get; private set; } public IEnumerable<ApiDescription> ApiDescriptions { get; private set; } public ISchemaRegistry SchemaRegistry { get; private set; } } }
mit
C#
e907669dddbef2c6901863325f36073101ffd3c1
Update AssemblyResolverHelper.cs
GeertvanHorrik/Fody,Fody/Fody
FodyIsolated/AssemblyResolverHelper.cs
FodyIsolated/AssemblyResolverHelper.cs
using Mono.Cecil; public static class AssemblyResolverHelper { public static AssemblyDefinition? Resolve(this IAssemblyResolver resolver, string assemblyName) { return resolver.Resolve(new AssemblyNameReference(assemblyName, null)); } }
using Mono.Cecil; public static class AssemblyResolverHelper { public static AssemblyDefinition? Resolve(this IAssemblyResolver resolver, string assemblyName) { return resolver.Resolve(new AssemblyNameReference(assemblyName, null)); } }
mit
C#
7dc552a5dd4f2c0c64beb485e439d87b7836f91e
revert cancellation grain placement
creyke/Orleans.Sagas
Orleans.Sagas/SagaCancellationGrain.cs
Orleans.Sagas/SagaCancellationGrain.cs
using Orleans.Placement; using System.Threading.Tasks; namespace Orleans.Sagas { [PreferLocalPlacement] public class SagaCancellationGrain : Grain<SagaCancellationGrainState>, ISagaCancellationGrain { public async Task RequestAbort() { if (!State.AbortRequested) { State.AbortRequested = true; await WriteStateAsync(); } } public Task<bool> HasAbortBeenRequested() { return Task.FromResult(State.AbortRequested); } } }
using Orleans.Placement; using System.Threading.Tasks; namespace Orleans.Sagas { public class SagaCancellationGrain : Grain<SagaCancellationGrainState>, ISagaCancellationGrain { public async Task RequestAbort() { if (!State.AbortRequested) { State.AbortRequested = true; await WriteStateAsync(); } } public Task<bool> HasAbortBeenRequested() { return Task.FromResult(State.AbortRequested); } } }
mit
C#
14f6fbfa928e34023fbc35b1f5a77d935f287309
Update version to first main alpha!
adesbro/PinPayments-dotnet
PinPayments/Properties/AssemblyInfo.cs
PinPayments/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PinPayments")] [assembly: AssemblyDescription("A simple .NET client for Pin Payments web API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adrian Brown")] [assembly: AssemblyProduct("PinPayments")] [assembly: AssemblyCopyright("Copyright © 2014 Adrian Brown")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4b60df7a-af48-4a9a-9395-244cc7124a8e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0-alpha")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PinPayments")] [assembly: AssemblyDescription("A simple .NET client for Pin Payments web API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Adrian Brown")] [assembly: AssemblyProduct("PinPayments")] [assembly: AssemblyCopyright("Copyright © 2014 Adrian Brown")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4b60df7a-af48-4a9a-9395-244cc7124a8e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.*")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0")]
mit
C#
ec8f5650b85be8e13f03ed6b97d96949fc0b7fcb
Update tạm fix lỗi Home/Index
shortgiraffe4/MomWorld,shortgiraffe4/MomWorld,shortgiraffe4/MomWorld
MomWorld/Controllers/HomeController.cs
MomWorld/Controllers/HomeController.cs
using MomWorld.DataContexts; using MomWorld.Entities; using MomWorld.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } else { //Fix sau ViewData["CurrentUser"] = new ApplicationUser(); } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }
using MomWorld.DataContexts; using MomWorld.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace MomWorld.Controllers { public class HomeController : Controller { private ArticleDb articleDb = new ArticleDb(); private IdentityDb identityDb = new IdentityDb(); public ActionResult Index() { List<Article> articles = articleDb.Articles.OrderBy(art=>art.PostedDate).Take(5).ToList(); ViewData["Top5Articles"] = articles; if (User.Identity.IsAuthenticated) { var user = identityDb.Users.FirstOrDefault(u => u.UserName.Equals(User.Identity.Name)); ViewData["CurrentUser"] = user; } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [HttpPost] public void uploadnow(HttpPostedFileWrapper upload) { if (upload != null) { string ImageName = upload.FileName; string path = System.IO.Path.Combine(Server.MapPath("~/Images/uploads"), ImageName); upload.SaveAs(path); } } } }
mit
C#
3f71d04d2afd1d9c2c236699013630b0e9256a7d
Change logger extension namespace
RoamingLost/Chimera.Extensions.Logging.Log4Net
src/Chimera.Extensions.Logging.Log4Net/Log4NetLoggerFactoryExtensions.cs
src/Chimera.Extensions.Logging.Log4Net/Log4NetLoggerFactoryExtensions.cs
namespace Microsoft.Extensions.Logging { using System; using Chimera.Extensions.Logging.Log4Net; /// <summary> /// LoggerFactory extensions for log4net. /// </summary> public static class Log4NetLoggerFactoryExtensions { /// <summary> /// Adds the log4net logger to the logger factory. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <returns>The logger factory.</returns> /// /// <exception cref="ArgumentNullException">loggerFactory</exception> public static ILoggerFactory AddLog4Net(this ILoggerFactory loggerFactory) { return AddLog4Net(loggerFactory, Log4NetSettings.Default); } /// <summary> /// Adds the log4net logger to the logger factory. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <param name="settings">The log4net settings.</param> /// <returns>The logger factory.</returns> /// <exception cref="ArgumentNullException">loggerFactory or settings</exception> public static ILoggerFactory AddLog4Net(this ILoggerFactory loggerFactory, Log4NetSettings settings) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var container = new Log4NetContainer(settings); container.Initialize(); loggerFactory.AddProvider(new Log4NetProvider(container)); return loggerFactory; } } }
namespace Chimera.Extensions.Logging.Log4Net { using System; using Microsoft.Extensions.Logging; /// <summary> /// LoggerFactory extensions for log4net. /// </summary> public static class Log4NetLoggerFactoryExtensions { /// <summary> /// Adds the log4net logger to the logger factory. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <returns>The logger factory.</returns> /// /// <exception cref="ArgumentNullException">loggerFactory</exception> public static ILoggerFactory AddLog4Net(this ILoggerFactory loggerFactory) { return AddLog4Net(loggerFactory, Log4NetSettings.Default); } /// <summary> /// Adds the log4net logger to the logger factory. /// </summary> /// <param name="loggerFactory">The logger factory.</param> /// <param name="settings">The log4net settings.</param> /// <returns>The logger factory.</returns> /// <exception cref="ArgumentNullException">loggerFactory or settings</exception> public static ILoggerFactory AddLog4Net(this ILoggerFactory loggerFactory, Log4NetSettings settings) { if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var container = new Log4NetContainer(settings); container.Initialize(); loggerFactory.AddProvider(new Log4NetProvider(container)); return loggerFactory; } } }
mit
C#
2c3969b6befa49c76505b9b250231d04ee8b61cb
Comment for Operationmonitor
dbaeck/ai-playground,dbaeck/ai-playground,dbaeck/ai-playground,dbaeck/ai-playground
AIPlayground/CLI/Program.cs
AIPlayground/CLI/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using AIPlayground.Search.Algorithm; using Common; namespace CLI { class Program { static void Main(string[] args) { //TODO: Insert Problem here! using (new OperationMonitor("sender", "sleep",time)) { //the using block measures the time for exec this and calls the time-callback } Console.In.Read(); } private static void time(string result) { Console.Out.WriteLine(result); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using AIPlayground.Search.Algorithm; using Common; namespace CLI { class Program { static void Main(string[] args) { //TODO: Insert Problem here! using (new OperationMonitor("sender", "sleep",time)) { } Console.In.Read(); } private static void time(string result) { Console.Out.WriteLine(result); } } }
mit
C#
f4bcfc28e6647e44368674a7bf670d32578a2d04
Update RoboCopyExitCodes.cs
tjscience/RoboSharp,tjscience/RoboSharp
RoboSharp/Results/RoboCopyExitCodes.cs
RoboSharp/Results/RoboCopyExitCodes.cs
using System; namespace RoboSharp.Results { /// <summary> /// RoboCopy Exit Codes /// </summary> /// <remarks><see href="https://ss64.com/nt/robocopy-exit.html"/></remarks> [Flags] public enum RoboCopyExitCodes { /// <summary>No Files Copied, No Errors Occured</summary> NoErrorNoCopy = 0x0, /// <summary>One or more files were copied successfully</summary> FilesCopiedSuccessful = 0x1, /// <summary> /// Some Extra files or directories were detected.<br/> /// Examine the output log for details. /// </summary> ExtraFilesOrDirectoriesDetected = 0x2, /// <summary> /// Some Mismatched files or directories were detected.<br/> /// Examine the output log. Housekeeping might be required. /// </summary> MismatchedDirectoriesDetected = 0x4, /// <summary> /// Some files or directories could not be copied <br/> /// (copy errors occurred and the retry limit was exceeded). /// Check these errors further. /// </summary> SomeFilesOrDirectoriesCouldNotBeCopied = 0x8, /// <summary> /// Serious error. Robocopy did not copy any files.<br/> /// Either a usage error or an error due to insufficient access privileges on the source or destination directories. /// </summary> SeriousErrorOccoured = 0x10, /// <summary>The Robocopy process exited prior to completion</summary> Cancelled = -1, } }
using System; namespace RoboSharp.Results { /// <summary> /// RoboCopy Exit Codes /// </summary> /// <remarks><see href="https://ss64.com/nt/robocopy-exit.html"/></remarks> [Flags] public enum RoboCopyExitCodes { /// <summary>No Files Copied, No Errors Occured</summary> NoErrorNoCopy = 0x0, /// <summary>One or more files were copied successfully</summary> FilesCopiedSuccessful = 0x1, /// <summary> /// Some Extra files or directories were detected.<br/> /// Examine the output log for details. /// </summary> ExtraFilesOrDirectoriesDetected = 0x2, /// <summary> /// Some Mismatched files or directories were detected.<br/> /// Examine the output log. Housekeeping might be required. /// </summary> MismatchedDirectoriesDetected = 0x4, /// <summary> /// Some files or directories could not be copied <br/> /// (copy errors occurred and the retry limit was exceeded). /// Check these errors further. /// </summary> SomeFilesOrDirectoriesCouldNotBeCopied = 0x8, /// <summary> /// Serious error. Robocopy did not copy any files.<br/> /// Either a usage error or an error due to insufficient access privileges on the source or destination directorie /// </summary> SeriousErrorOccoured = 0x10, /// <summary>The Robocopy process exited prior to completion</summary> Cancelled = -1, } }
mit
C#
86e3d1d2a778607dda713daa97a098c80d03a51e
refactor the requisitions list page
ndrmc/cats,ndrmc/cats,ndrmc/cats
Web/Areas/EarlyWarning/Views/ReliefRequisition/_RequisitionsFilter.cshtml
Web/Areas/EarlyWarning/Views/ReliefRequisition/_RequisitionsFilter.cshtml
 @model Cats.Areas.EarlyWarning.Models.SearchRequistionViewModel @using Cats.Helpers; @{ const string PAGE_NAME = "Request.Index.RequestFilter"; } @using (Html.BeginForm()) { <div class=""> <div class="span3"> <div class="form-inline"> @*<button type="submit" class="btn btn-sm" value="Search"><i class="icon-search"></i></button>*@ <input id="search" type="text" class="input-large search-query" placeholder="Search by reference"> </div> </div> <div class="span9"> <div class="input-prepend"> <span class="add-on">Region</span> @Html.DropDownList("RegionID", null, new { @class = "" }) </div> <div class="input-prepend"> <span class="add-on">Program</span> @Html.DropDownList("ProgramID", null, new { @class = "" }) </div> <div class="input-prepend"> <span class="add-on">Status</span> @Html.DropDownList("StatusID", null, new { @class = "" }) </div> <div class="input-append"> <button type="submit" class="btn btn-sm" value="Search"><i class="icon-search"></i></button> </div> </div> @*<div class="span3"> <div class="control-group"> <div class="control-label"> <label>&nbsp;</label> </div> <div class="controls"> <button type="submit" class="btn btn-sm" value="Search"><i class="icon-search"></i></button> </div> </div> </div>*@ <div style="clear:both;"> </div> </div> <hr> }
 @model Cats.Areas.EarlyWarning.Models.SearchRequistionViewModel @using Cats.Helpers; @{ const string PAGE_NAME = "Request.Index.RequestFilter"; } @using (Html.BeginForm()) { <div class=""> <div class="span3"> <div class="control-group"> <div class="control-label"> <label>Region:</label> </div> <div class="controls "> @Html.DropDownList("RegionID", null, new { @class = "input-large" }) </div> </div> </div> <div class="span3"> <div class="control-group"> <div class="control-label"> <label>Program:</label> </div> <div class="controls "> @Html.DropDownList("ProgramID", null, new { @class = "input-large" }) </div> </div> </div> <div class="span3"> <div class="control-group"> <div class="control-label"> <label>Status:</label> </div> <div class="controls "> @Html.DropDownList("StatusID", null, new { @class = "input-large" }) </div> </div> </div> <div class="span3"> <div class="control-group"> <div class="control-label"> <label>&nbsp;</label> </div> <div class="controls"> <button type="submit" class="btn btn-sm" value="Search"><i class="icon-search"></i></button> </div> </div> </div> <div style="clear:both;"> </div> </div> }
apache-2.0
C#
3b206abffc71d42f4641ae6773bf4ef89d186e94
Update fog values (new maps are bigger)
terahxluna/Merlin
Merlin/Extensions/WeatherExtensions.cs
Merlin/Extensions/WeatherExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Merlin.Extensions { public static class WeatherExtensions { public static void EnableFog(this Weather weather) { weather.fogSummer = new MinMax(4f, 54f); weather.fogWinter = new MinMax(0f, 45f); weather.fogMapSelect = new MinMax(8f, 70f); weather.fogNormalRain = new MinMax(1f, 50f); weather.fogHeavyRain = new MinMax(0f, 45f); } public static void DisableFog(this Weather weather) { weather.fogSummer = new MinMax(150, 150); weather.fogWinter = new MinMax(150, 150); weather.fogMapSelect = new MinMax(150, 150); weather.fogNormalRain = new MinMax(150, 150); weather.fogHeavyRain = new MinMax(150, 150); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Merlin.Extensions { public static class WeatherExtensions { public static void EnableFog(this Weather weather) { weather.fogSummer = new MinMax(4f, 54f); weather.fogWinter = new MinMax(0f, 45f); weather.fogMapSelect = new MinMax(8f, 70f); weather.fogNormalRain = new MinMax(1f, 50f); weather.fogHeavyRain = new MinMax(0f, 45f); } public static void DisableFog(this Weather weather) { weather.fogSummer = new MinMax(100, 100); weather.fogWinter = new MinMax(100, 100); weather.fogMapSelect = new MinMax(100, 100); weather.fogHeavyRain = new MinMax(100, 100); } } }
mit
C#
fda426a6524626250df8b954d0c2e43fbe0b19f5
add GetState to Internal for create native parser
acple/ParsecSharp
ParsecSharp/Parser/Internal/Builder.cs
ParsecSharp/Parser/Internal/Builder.cs
using System; using System.Runtime.CompilerServices; namespace ParsecSharp.Internal { public static class Builder { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Create<TToken, T>(Func<IParsecStateStream<TToken>, Result<TToken, T>> function) => new Single<TToken, T>(function); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TResult> ModifyResult<TToken, T, TResult>(this Parser<TToken, T> parser, Func<IParsecStateStream<TToken>, Fail<TToken, T>, Result<TToken, TResult>> fail, Func<IParsecStateStream<TToken>, Success<TToken, T>, Result<TToken, TResult>> success) => new ModifyResult<TToken, T, TResult>(parser, fail, success); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, IParsecStateStream<TToken>> GetState<TToken>() => Builder.Create<TToken, IParsecStateStream<TToken>>(state => Result.Success(state, state)); } }
using System; using System.Runtime.CompilerServices; namespace ParsecSharp.Internal { public static class Builder { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, T> Create<TToken, T>(Func<IParsecStateStream<TToken>, Result<TToken, T>> function) => new Single<TToken, T>(function); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Parser<TToken, TResult> ModifyResult<TToken, T, TResult>(this Parser<TToken, T> parser, Func<IParsecStateStream<TToken>, Fail<TToken, T>, Result<TToken, TResult>> fail, Func<IParsecStateStream<TToken>, Success<TToken, T>, Result<TToken, TResult>> success) => new ModifyResult<TToken, T, TResult>(parser, fail, success); } }
mit
C#
2b4804af7d68c59afe490c58ff290a728ca6bd44
Clean up code in CustomCode/.
Tirael/UnitsNet,BrandonLWhite/UnitsNet,maherkassim/UnitsNet,maherkassim/UnitsNet,anjdreas/UnitsNet,BoGrevyDynatest/UnitsNet,neutmute/UnitsNet,BrandonLWhite/UnitsNet,anjdreas/UnitsNet
Src/UnitsNet/CustomCode/Force.extra.cs
Src/UnitsNet/CustomCode/Force.extra.cs
// Copyright © 2007 by Initial Force AS. All rights reserved. // https://github.com/InitialForce/UnitsNet // // 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. // ReSharper disable once CheckNamespace namespace UnitsNet { public partial struct Force { public static Force FromPressureByArea(Pressure p, Length2d area) { double metersSquared = area.Meters.X*area.Meters.Y; double newtons = p.Pascals*metersSquared; return new Force(newtons); } public static Force FromPressureByArea(Pressure p, Area area) { double newtons = p.Pascals*area.SquareMeters; return new Force(newtons); } public static Force FromMassByAcceleration(Mass mass, double metersPerSecondSquared) { return new Force(mass.Kilograms*metersPerSecondSquared); } } }
// Copyright © 2007 by Initial Force AS. All rights reserved. // https://github.com/InitialForce/UnitsNet // // 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. // ReSharper disable once CheckNamespace namespace UnitsNet { public partial struct Force { public static Force FromPressureByArea(Pressure p, Length2d area) { double metersSquared = area.Meters.X * area.Meters.Y; double newtons = p.Pascals * metersSquared; return new Force(newtons); } public static Force FromPressureByArea(Pressure p, Area area) { double newtons = p.Pascals * area.SquareMeters; return new Force(newtons); } public static Force FromMassByAcceleration(Mass mass, double metersPerSecondSquared) { return new Force(mass.Kilograms * metersPerSecondSquared); } } }
mit
C#
595264853608ccebd5c1698ed084656c2e220395
remove comments
davemfletcher/ProjectEuler
ProjectEuler/Problem.cs
ProjectEuler/Problem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler { public abstract class Problem { //protected Answer Answer { get; set; } public abstract Answer GetAnswer(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ProjectEuler { public abstract class Problem { //protected Answer Answer { get; set; } public abstract Answer GetAnswer(); //public override string ToString() //{ // return Answer.Description; //} } }
mit
C#
202362ad4fe7629fbd3c04a284e5a7d4d1df728d
remove unnecessary code
miridfd/MassTransit.Automatonymous.UnityIntegration
UnityStateMachineLoadSagaExtensions.cs
UnityStateMachineLoadSagaExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Practices.Unity; using Automatonymous; using MassTransit.Internals.Extensions; namespace MassTransit.Automatonymous.UnityIntegration { public static class UnityStateMachineLoadSagaExtensions { /// <summary> /// Scans the lifetime scope and registers any state machines sagas which are found in the scope using the Unity saga repository /// and the appropriate state machine saga repository under the hood. /// </summary> /// <param name="configurator"></param> /// <param name="container"></param> /// <param name="name"></param> public static void LoadStateMachineSagas(this IReceiveEndpointConfigurator configurator, IUnityContainer container, string name = "message") { IList<Type> sagaTypes = FindStateMachineSagaTypes(container); foreach (var sagaType in sagaTypes) { StateMachineSagaConfiguratorCache.Configure(sagaType, configurator, container, name); } } public static IList<Type> FindStateMachineSagaTypes(IUnityContainer container) { return container.Registrations .Where(r => r.MappedToType.HasInterface(typeof(SagaStateMachine<>))) .Select(rs => rs.MappedToType.GetClosingArguments(typeof(SagaStateMachine<>)).Single()) .Distinct() .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Practices.Unity; using Automatonymous; using MassTransit.Internals.Extensions; namespace MassTransit.Automatonymous.UnityIntegration { public static class UnityStateMachineLoadSagaExtensions { /// <summary> /// Scans the lifetime scope and registers any state machines sagas which are found in the scope using the Unity saga repository /// and the appropriate state machine saga repository under the hood. /// </summary> /// <param name="configurator"></param> /// <param name="container"></param> /// <param name="name"></param> public static void LoadStateMachineSagas(this IReceiveEndpointConfigurator configurator, IUnityContainer container, string name = "message") { //var scope = context.Container.Resolve<IUnityContainer>(); IList<Type> sagaTypes = FindStateMachineSagaTypes(container); foreach (var sagaType in sagaTypes) { StateMachineSagaConfiguratorCache.Configure(sagaType, configurator, container, name); } } public static IList<Type> FindStateMachineSagaTypes(IUnityContainer container) { Type type = typeof(SagaStateMachine<>); bool hasInterface = type.HasInterface(typeof(StateMachine)); return container.Registrations .Where(r => r.MappedToType.HasInterface(typeof(SagaStateMachine<>))) .Select(rs => rs.MappedToType.GetClosingArguments(typeof(SagaStateMachine<>)).Single()) .Distinct() .ToList(); } } }
apache-2.0
C#
39be9b265c3313fe1dd50a7f8f2df743763ebca9
Use dotnet test runner
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents
Util/Xamarin.Build.Download/build.cake
Util/Xamarin.Build.Download/build.cake
var TARGET = Argument ("t", Argument ("target", "ci")); var SOURCE_COMMIT = EnvironmentVariable("BUILD_SOURCEVERSION") ?? ""; var SOURCE_BRANCH = EnvironmentVariable("BUIlD_SOURCEBRANCHNAME") ?? ""; Task("libs") .Does(() => { MSBuild("./source/Xamarin.Build.Download.sln", c => { c.Configuration = "Release"; c.Restore = true; }); }); Task("nuget") .IsDependentOn("libs") .Does(() => { MSBuild ("./source/Xamarin.Build.Download.sln", c => { c.Configuration = "Release"; c.Restore = true; c.Targets.Clear(); c.Targets.Add("Pack"); c.Properties.Add("PackageOutputPath", new [] { MakeAbsolute(new FilePath("./output")).FullPath }); if (!string.IsNullOrEmpty(SOURCE_BRANCH)) c.Properties.Add("RepositoryBranch", new [] { SOURCE_BRANCH }); if (!string.IsNullOrEmpty(SOURCE_COMMIT)) c.Properties.Add("RepositoryCommit", new [] { SOURCE_COMMIT }); }); }); Task("tests") .IsDependentOn("nuget") .Does(() => { DotNetCoreTest("./source/Xamarin.Build.Download.Tests/", new DotNetCoreTestSettings { Configuration = "Release", OutputDirectory = "./output", ResultsDirectory = "./output", VSTestReportPath = "./output/tests/TestResults.xml" }); }); Task ("clean") .Does (() => { CleanDirectories ("./source/**/bin"); CleanDirectories ("./source/**/obj"); }); Task ("ci") .IsDependentOn("tests"); RunTarget (TARGET);
var TARGET = Argument ("t", Argument ("target", "ci")); var SOURCE_COMMIT = EnvironmentVariable("BUILD_SOURCEVERSION") ?? ""; var SOURCE_BRANCH = EnvironmentVariable("BUIlD_SOURCEBRANCHNAME") ?? ""; Task("libs") .Does(() => { MSBuild("./source/Xamarin.Build.Download.sln", c => { c.Configuration = "Release"; c.Restore = true; }); }); Task("nuget") .IsDependentOn("libs") .Does(() => { MSBuild ("./source/Xamarin.Build.Download.sln", c => { c.Configuration = "Release"; c.Restore = true; c.Targets.Clear(); c.Targets.Add("Pack"); c.Properties.Add("PackageOutputPath", new [] { MakeAbsolute(new FilePath("./output")).FullPath }); if (!string.IsNullOrEmpty(SOURCE_BRANCH)) c.Properties.Add("RepositoryBranch", new [] { SOURCE_BRANCH }); if (!string.IsNullOrEmpty(SOURCE_COMMIT)) c.Properties.Add("RepositoryCommit", new [] { SOURCE_COMMIT }); }); }); Task("tests") .IsDependentOn("nuget") .Does(() => { XUnit2("./source/Xamarin.Build.Download.Tests/bin/**/Release/**/*.Tests.dll", new XUnit2Settings { OutputDirectory = "./output" }); }); Task ("clean") .Does (() => { CleanDirectories ("./source/**/bin"); CleanDirectories ("./source/**/obj"); }); Task ("ci") .IsDependentOn("tests"); RunTarget (TARGET);
mit
C#
c14061cbed9945927cd648fb819679061f862c52
Update Visma.net/lib/ShipmentActionResult.cs
ON-IT/Visma.Net
Visma.net/lib/ShipmentActionResult.cs
Visma.net/lib/ShipmentActionResult.cs
using Newtonsoft.Json; using System; namespace ONIT.VismaNetApi.Lib { public class CreateShipmentActionResult : VismaActionResult { [JsonProperty("referenceNumber")] public string referenceNumber { get; internal set; } [JsonProperty("shipmentDto")] public Models.Shipment shipment { get; internal set; } } }
using Newtonsoft.Json; using System; namespace ONIT.VismaNetApi.Lib { public class CreateShipmentActionResult : VismaActionResult { [JsonProperty("referenceNumber")] public string ReferenceNumber { get; internal set; } [JsonProperty("shipmentDto")] public Models.Shipment shipment { get; internal set; } } }
mit
C#
6ed8526454cf58c840a128b4fd951a28f3cbd7b6
Correct Copyright in Assembly info
haesemeyer/ZebraTrack
ZebraTrack/Properties/AssemblyInfo.cs
ZebraTrack/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ZebraTrack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HarvardUniversity")] [assembly: AssemblyProduct("ZebraTrack")] [assembly: AssemblyCopyright("Copyright © Martin Haesemeyer 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ZebraTrack")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HarvardUniversity")] [assembly: AssemblyProduct("ZebraTrack")] [assembly: AssemblyCopyright("Copyright © HarvardUniversity 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
61f25604d97e5e1bfaeee74690482927e6033465
Move version forward
Abc-Arbitrage/ZeroLog
ZeroLog/Properties/AssemblyInfo.cs
ZeroLog/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ZeroLog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ZeroLog")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34665a87-497b-4c4e-928e-1dfbeb3f7441")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.1")] [assembly: AssemblyFileVersion("1.0.0.1")] [assembly:InternalsVisibleTo("ZeroLog.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ZeroLog")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ZeroLog")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("34665a87-497b-4c4e-928e-1dfbeb3f7441")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly:InternalsVisibleTo("ZeroLog.Tests")]
mit
C#
dfdcfe7ed082ea3249a4fc72242c39abc9026506
Use the assembly short name to find the embedded Python.Runtime (other assemblies may reference it with the full name).
QuantConnect/pythonnet,pythonnet/pythonnet,denfromufa/pythonnet,yagweb/pythonnet,Konstantin-Posudevskiy/pythonnet,vmuriart/pythonnet,AlexCatarino/pythonnet,vmuriart/pythonnet,dmitriyse/pythonnet,denfromufa/pythonnet,denfromufa/pythonnet,dmitriyse/pythonnet,pythonnet/pythonnet,vmuriart/pythonnet,Konstantin-Posudevskiy/pythonnet,AlexCatarino/pythonnet,AlexCatarino/pythonnet,dmitriyse/pythonnet,Konstantin-Posudevskiy/pythonnet,AlexCatarino/pythonnet,yagweb/pythonnet,QuantConnect/pythonnet,yagweb/pythonnet,pythonnet/pythonnet,yagweb/pythonnet,QuantConnect/pythonnet
pythonnet/src/console/pythonconsole.cs
pythonnet/src/console/pythonconsole.cs
// ========================================================================== // This software is subject to the provisions of the Zope Public License, // Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED // WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS // FOR A PARTICULAR PURPOSE. // ========================================================================== using System; using System.Reflection; using System.Collections.Generic; using Python.Runtime; namespace Python.Runtime { public sealed class PythonConsole { private PythonConsole() {} [STAThread] public static int Main(string[] args) { // reference the static assemblyLoader to stop it being optimized away AssemblyLoader a = assemblyLoader; string [] cmd = Environment.GetCommandLineArgs(); PythonEngine.Initialize(); int i = Runtime.Py_Main(cmd.Length, cmd); PythonEngine.Shutdown(); return i; } // Register a callback function to load embedded assmeblies. // (Python.Runtime.dll is included as a resource) private sealed class AssemblyLoader { Dictionary<string, Assembly> loadedAssemblies; public AssemblyLoader() { loadedAssemblies = new Dictionary<string, Assembly>(); AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { string shortName = args.Name.Split(',')[0]; String resourceName = shortName + ".dll"; if (loadedAssemblies.ContainsKey(resourceName)) { return loadedAssemblies[resourceName]; } // looks for the assembly from the resources and load it using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { if (stream != null) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); Assembly assembly = Assembly.Load(assemblyData); loadedAssemblies[resourceName] = assembly; return assembly; } } return null; }; } }; private static AssemblyLoader assemblyLoader = new AssemblyLoader(); }; }
// ========================================================================== // This software is subject to the provisions of the Zope Public License, // Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. // THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED // WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS // FOR A PARTICULAR PURPOSE. // ========================================================================== using System; using System.Reflection; using System.Collections.Generic; using Python.Runtime; namespace Python.Runtime { public sealed class PythonConsole { private PythonConsole() {} [STAThread] public static int Main(string[] args) { // reference the static assemblyLoader to stop it being optimized away AssemblyLoader a = assemblyLoader; string [] cmd = Environment.GetCommandLineArgs(); PythonEngine.Initialize(); int i = Runtime.Py_Main(cmd.Length, cmd); PythonEngine.Shutdown(); return i; } // Register a callback function to load embedded assmeblies. // (Python.Runtime.dll is included as a resource) private sealed class AssemblyLoader { Dictionary<string, Assembly> loadedAssemblies; public AssemblyLoader() { loadedAssemblies = new Dictionary<string, Assembly>(); AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => { String resourceName = new AssemblyName(args.Name).Name + ".dll"; if (loadedAssemblies.ContainsKey(resourceName)) { return loadedAssemblies[resourceName]; } // looks for the assembly from the resources and load it using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) { if (stream != null) { Byte[] assemblyData = new Byte[stream.Length]; stream.Read(assemblyData, 0, assemblyData.Length); Assembly assembly = Assembly.Load(assemblyData); loadedAssemblies[resourceName] = assembly; return assembly; } } return null; }; } }; private static AssemblyLoader assemblyLoader = new AssemblyLoader(); }; }
mit
C#
e40ac2e9e6134b15151fe0314a2f957a4802fb0c
Fix IT with google
maximn/google-maps,maximn/google-maps
GoogleMapsApi.Test/IntegrationTests/PlacesTextTests.cs
GoogleMapsApi.Test/IntegrationTests/PlacesTextTests.cs
using System.Linq; using GoogleMapsApi.Entities.PlacesText.Request; using GoogleMapsApi.Entities.PlacesText.Response; using NUnit.Framework; namespace GoogleMapsApi.Test.IntegrationTests { [TestFixture] public class PlacesTextTests : BaseTestIntegration { [Test] public void ReturnsFormattedAddress() { var request = new PlacesTextRequest { ApiKey = ApiKey, Query = "1 smith st parramatta", Types = "address" }; PlacesTextResponse result = GoogleMaps.PlacesText.Query(request); if (result.Status == Status.OVER_QUERY_LIMIT) Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit."); Assert.AreEqual(Status.OK, result.Status); Assert.AreEqual("1 Smith St, Parramatta NSW 2150, Australia", result.Results.First().FormattedAddress); } [Test] public void ReturnsPhotos() { var request = new PlacesTextRequest { ApiKey = ApiKey, Query = "1600 Pennsylvania Ave NW", Types = "address" }; PlacesTextResponse result = GoogleMaps.PlacesText.Query(request); if (result.Status == Status.OVER_QUERY_LIMIT) Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit."); Assert.AreEqual(Status.OK, result.Status); Assert.That(result.Results, Is.Not.Null.And.Not.Empty); } } }
using System.Linq; using GoogleMapsApi.Entities.PlacesText.Request; using GoogleMapsApi.Entities.PlacesText.Response; using NUnit.Framework; namespace GoogleMapsApi.Test.IntegrationTests { [TestFixture] public class PlacesTextTests : BaseTestIntegration { [Test] public void ReturnsFormattedAddress() { var request = new PlacesTextRequest { ApiKey = ApiKey, Query = "1 smith st parramatta", Types = "address" }; PlacesTextResponse result = GoogleMaps.PlacesText.Query(request); if (result.Status == Status.OVER_QUERY_LIMIT) Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit."); Assert.AreEqual(Status.OK, result.Status); Assert.AreEqual("1 Smith St, Parramatta NSW 2150, Australia", result.Results.First().FormattedAddress); } [Test] public void ReturnsPhotos() { var request = new PlacesTextRequest { ApiKey = ApiKey, Query = "1600 Pennsylvania Ave NW", Types = "address" }; PlacesTextResponse result = GoogleMaps.PlacesText.Query(request); if (result.Status == Status.OVER_QUERY_LIMIT) Assert.Inconclusive("Cannot run test since you have exceeded your Google API query limit."); Assert.AreEqual(Status.OK, result.Status); Assert.That(result.Results.First().Photos, Is.Not.Null.And.Not.Empty); } } }
bsd-2-clause
C#
8aeef5f6ea5f8846237046ccccedef0bef65c160
Fix url
GambitKZ/MangaRipper,NguyenDanPhuong/MangaRipper
MangaRipper.Core/FilenameDetectors/FilenameDetector.cs
MangaRipper.Core/FilenameDetectors/FilenameDetector.cs
using System; using System.IO; using System.Net.Http.Headers; namespace MangaRipper.Core.FilenameDetectors { public class FilenameDetector { private readonly GoogleProxyFilenameDetector googleProxyFilenameParser; public FilenameDetector(GoogleProxyFilenameDetector googleProxyFilenameParser) { this.googleProxyFilenameParser = googleProxyFilenameParser; } public string GetFilename(string url, HttpContentHeaders headers) { var fileNameFromServer = headers.ContentDisposition?.FileName?.Trim().Trim(new char[] { '"' }); if (!string.IsNullOrEmpty(fileNameFromServer)) { var googleProxyName = googleProxyFilenameParser.ParseFilename(url); if (!string.IsNullOrEmpty(googleProxyName)) { return googleProxyName; } return fileNameFromServer; } else { var uri = new Uri(url); return Path.GetFileName(uri.LocalPath); } } } }
using System.IO; using System.Net.Http.Headers; namespace MangaRipper.Core.FilenameDetectors { public class FilenameDetector { private readonly GoogleProxyFilenameDetector googleProxyFilenameParser; public FilenameDetector(GoogleProxyFilenameDetector googleProxyFilenameParser) { this.googleProxyFilenameParser = googleProxyFilenameParser; } public string GetFilename(string url, HttpContentHeaders headers) { var fileNameFromServer = headers.ContentDisposition?.FileName?.Trim().Trim(new char[] { '"' }); if (!string.IsNullOrEmpty(fileNameFromServer)) { var googleProxyName = googleProxyFilenameParser.ParseFilename(url); if (!string.IsNullOrEmpty(googleProxyName)) { return googleProxyName; } return fileNameFromServer; } else { return Path.GetFileName(url); } } } }
mit
C#
89ebe87fefc3ee7bfab46269ff5bdfa07362b9d2
Fix page titles for ContentPages module
synhershko/NSemble,synhershko/NSemble
NSemble.Web/Modules/ContentPages/ContentPagesModule.cs
NSemble.Web/Modules/ContentPages/ContentPagesModule.cs
using System; using NSemble.Core.Models; using NSemble.Core.Nancy; using NSemble.Modules.ContentPages.Models; using Raven.Client; namespace NSemble.Modules.ContentPages { public class ContentPagesModule : NSembleModule { public static readonly string HomepageSlug = "home"; public ContentPagesModule(IDocumentSession session) : base("ContentPages") { Get["/{slug?" + HomepageSlug + "}"] = p => { var slug = (string)p.slug; // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably // much shorter for readability. var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug)); if (cp == null) return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes... Model.ContentPage = cp; ((PageModel) Model.Page).Title = cp.Title; return View["Read", Model]; }; Get["/error"] = o => { throw new NotSupportedException("foo"); }; } } }
using System; using NSemble.Core.Nancy; using NSemble.Modules.ContentPages.Models; using Raven.Client; namespace NSemble.Modules.ContentPages { public class ContentPagesModule : NSembleModule { public static readonly string HomepageSlug = "home"; public ContentPagesModule(IDocumentSession session) : base("ContentPages") { Get["/{slug?" + HomepageSlug + "}"] = p => { var slug = (string)p.slug; // For fastest loading, we define the content page ID to be the slug. Therefore, slugs have to be < 50 chars, probably // much shorter for readability. var cp = session.Load<ContentPage>(DocumentPrefix + ContentPage.FullContentPageId(slug)); if (cp == null) return "<p>The requested content page was not found</p>"; // we will return a 404 instead once the system stabilizes... Model.ContentPage = cp; return View["Read", Model]; }; Get["/error"] = o => { throw new NotSupportedException("foo"); }; } } }
apache-2.0
C#
c10c3528e652ebe3fb776d7e8532045ab766396c
Update TypeExtension.cs
NMSLanX/Natasha
Natasha/Engine/ScriptModule/Extension/TypeExtension.cs
Natasha/Engine/ScriptModule/Extension/TypeExtension.cs
using System; using System.Collections.Generic; namespace Natasha { public static class TypeExtension { public static bool IsImplementFrom(this Type type,Type iType) { HashSet<Type> types = new HashSet<Type>(type.GetInterfaces()); return types.Contains(iType); } public static bool IsImplementFrom<T>(this Type type) { HashSet<Type> types = new HashSet<Type>(type.GetInterfaces()); return types.Contains(typeof(T)); } public static List<Type> GetAllGenericTypes(this Type type) { List<Type> result = new List<Type>(); result.Add(type); if (type.IsGenericType && type.FullName != null) { foreach (var item in type.GetGenericArguments()) { result.AddRange(item.GetAllGenericTypes()); } } return result; } public static List<Type> GetAllGenericTypes<T>() { return typeof(T).GetAllGenericTypes(); } public static string GetAvailableName(this Type type) { return AvailableNameReverser.GetName(type); } public static string GetDevelopName(this Type type) { return ClassNameReverser.GetName(type); } public static Type With(this Type type,params Type[] types) { return type.MakeGenericType(types); } public static bool IsOnceType(this Type type) { if (type==null){return false;} return type.IsPrimitive || type == typeof(string) || type == typeof(Delegate) || type.IsEnum || type == typeof(object) || (!type.IsClass && !type.IsInterface); } } }
using System; using System.Collections.Generic; namespace Natasha { public static class TypeExtension { public static bool IsImplementFrom(this Type type,Type iType) { HashSet<Type> types = new HashSet<Type>(type.GetInterfaces()); return types.Contains(iType); } public static bool IsImplementFrom<T>(this Type type) { HashSet<Type> types = new HashSet<Type>(type.GetInterfaces()); return types.Contains(typeof(T)); } public static List<Type> GetAllGenericTypes(this Type type) { List<Type> result = new List<Type>(); result.Add(type); if (type.IsGenericType && type.FullName != null) { foreach (var item in type.GetGenericArguments()) { result.AddRange(item.GetAllGenericTypes()); } } return result; } public static List<Type> GetAllGenericTypes<T>() { return typeof(T).GetAllGenericTypes(); } public static string GetAvailableName(this Type type) { return AvailableNameReverser.GetName(type); } public static string GetDevelopName(this Type type) { return ClassNameReverser.GetName(type); } public static Type With(this Type type,params Type[] types) { return type.MakeGenericType(types); } public static bool IsOnceType(this Type type) { if (type==null){return false;} return type.IsPrimitive || type == typeof(string) || type == typeof(Delegate) || type.IsEnum || (!type.IsClass && !type.IsInterface); } } }
mpl-2.0
C#
c7db9e202e5c6964a3f096b9f73a4437c0f59a4e
Revert "David/Clare #780 Reformat CSP and remove if statement"
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml
src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml
@using System.Threading.Tasks @using StockportWebapp.FeatureToggling @inject FeatureToggles FeatureToggles @{ var host = Context.Request.Host.Host; } @if (host.StartsWith("www") || host.StartsWith("int-") || host.StartsWith("qa-") || host.StartsWith("stage-")) { <meta http-equiv="Content-Security-Policy" content="default-src https:; font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; img-src 'self' geo0.ggpht.com geo1.ggpht.com geo2.ggpht.com geo3.ggpht.com cbks0.googleapis.com csi.gstatic.com maps.gstatic.com maps.googleapis.com images.contentful.com/ www.google-analytics.com/r/collect www.google-analytics.com/collect stats.g.doubleclick.net/r/collect s3-eu-west-1.amazonaws.com/share.typeform.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; style-src 'self' 'unsafe-inline' *.cludo.com/css/ s3-eu-west-1.amazonaws.com/share.typeform.com/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ maps.googleapis.com m.addthisedge.com/live/boost/ www.google-analytics.com/analytics.js api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; object-src 'self' https://www.youtube.com http://www.youtube.com" /> }
@using System.Threading.Tasks @using StockportWebapp.FeatureToggling @inject FeatureToggles FeatureToggles @{ var host = Context.Request.Host.Host; } <meta http-equiv="Content-Security-Policy" content="default-src https:; " + _ "font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; " + _ "img-src 'self' khms0.googleapis.com khms1.googleapis.comgeo0.ggpht.com geo1.ggpht.com geo2.ggpht.com geo3.ggpht.com cbks0.googleapis.com csi.gstatic.com maps.gstatic.com maps.googleapis.com images.contentful.com/ www.google-analytics.com/r/collect www.google-analytics.com/collect stats.g.doubleclick.net/r/collect s3-eu-west-1.amazonaws.com/share.typeform.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; " + _ "style-src 'self' 'unsafe-inline' *.cludo.com/css/ s3-eu-west-1.amazonaws.com/share.typeform.com/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; " + _ "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ maps.googleapis.com m.addthisedge.com/live/boost/ www.google-analytics.com/analytics.js api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; " + _ "connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; " + _ "media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; " + _ "object-src 'self' https://www.youtube.com http://www.youtube.com" />
mit
C#
2f7416189e18c140e7b42cf3b10ce2e170e3a2a9
Refactor tests to use AutoFixture
appharbor/appharbor-cli
src/AppHarbor.Tests/ApplicationConfigurationTest.cs
src/AppHarbor.Tests/ApplicationConfigurationTest.cs
using System; using System.IO; using System.Text; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { public static string ConfigurationFile = Path.GetFullPath(".appharbor"); [Theory, AutoCommandData] public void ShouldReturnApplicationIdIfConfigurationFileExists(Mock<IFileSystem> fileSystem, string applicationName) { var configurationFile = ConfigurationFile; var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object, null); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } [Theory, AutoCommandData] public void ShouldThrowIfApplicationFileDoesNotExist(InMemoryFileSystem fileSystem, IGitExecutor gitExecutor) { var applicationConfiguration = new ApplicationConfiguration(fileSystem, gitExecutor); var exception = Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId()); Assert.Equal("Application is not configured", exception.Message); } [Theory, AutoCommandData] public void ShouldTryAndSetUpGitRemoteIfPossible([Frozen]Mock<IGitExecutor> gitExecutor, [Frozen]Mock<IAppHarborClient> client, ApplicationConfiguration applicationConfiguration, User user, string id) { using (var writer = new StringWriter()) { Console.SetOut(writer); applicationConfiguration.SetupApplication(id, user); Assert.Contains("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master", writer.ToString()); } var gitCommand = string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id); gitExecutor.Verify(x => x.Execute(gitCommand, It.Is<DirectoryInfo>(y => y.FullName == Directory.GetCurrentDirectory())), Times.Once()); } [Theory, AutoCommandData] public void ShouldShowRepositoryUrlIfGitSetupFailed([Frozen]Mock<IGitExecutor> gitExecutor, ApplicationConfiguration applicationConfiguration, User user, string id) { gitExecutor.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<DirectoryInfo>())).Throws<InvalidOperationException>(); using (var writer = new StringWriter()) { Console.SetOut(writer); applicationConfiguration.SetupApplication(id, user); Assert.Contains(string.Format("Couldn't add appharbor repository as a git remote. Repository URL is: https://{0}@appharbor.com/{1}.git", user.Username, id), writer.ToString()); } } } }
using System; using System.IO; using System.Text; using AppHarbor.Model; using Moq; using Ploeh.AutoFixture.Xunit; using Xunit; using Xunit.Extensions; namespace AppHarbor.Tests { public class ApplicationConfigurationTest { public static string ConfigurationFile = Path.GetFullPath(".appharbor"); [Fact] public void ShouldReturnApplicationIdIfConfigurationFileExists() { var fileSystem = new Mock<IFileSystem>(); var applicationName = "bar"; var configurationFile = ConfigurationFile; var stream = new MemoryStream(Encoding.Default.GetBytes(applicationName)); fileSystem.Setup(x => x.OpenRead(configurationFile)).Returns(stream); var applicationConfiguration = new ApplicationConfiguration(fileSystem.Object, null); Assert.Equal(applicationName, applicationConfiguration.GetApplicationId()); } [Fact] public void ShouldThrowIfApplicationFileDoesNotExist() { var fileSystem = new InMemoryFileSystem(); var applicationConfiguration = new ApplicationConfiguration(fileSystem, null); var exception = Assert.Throws<ApplicationConfigurationException>(() => applicationConfiguration.GetApplicationId()); Assert.Equal("Application is not configured", exception.Message); } [Theory, AutoCommandData] public void ShouldTryAndSetUpGitRemoteIfPossible([Frozen]Mock<IGitExecutor> gitExecutor, [Frozen]Mock<IAppHarborClient> client, ApplicationConfiguration applicationConfiguration, User user, string id) { using (var writer = new StringWriter()) { Console.SetOut(writer); applicationConfiguration.SetupApplication(id, user); Assert.Contains("Added \"appharbor\" as a remote repository. Push to AppHarbor with git push appharbor master", writer.ToString()); } var gitCommand = string.Format("remote add appharbor https://{0}@appharbor.com/{1}.git", user.Username, id); gitExecutor.Verify(x => x.Execute(gitCommand, It.Is<DirectoryInfo>(y => y.FullName == Directory.GetCurrentDirectory())), Times.Once()); } [Theory, AutoCommandData] public void ShouldShowRepositoryUrlIfGitSetupFailed([Frozen]Mock<IGitExecutor> gitExecutor, ApplicationConfiguration applicationConfiguration, User user, string id) { gitExecutor.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<DirectoryInfo>())).Throws<InvalidOperationException>(); using (var writer = new StringWriter()) { Console.SetOut(writer); applicationConfiguration.SetupApplication(id, user); Assert.Contains(string.Format("Couldn't add appharbor repository as a git remote. Repository URL is: https://{0}@appharbor.com/{1}.git", user.Username, id), writer.ToString()); } } } }
mit
C#
a76a0e775ac10cf3e4bc318336668c5dc1c49f7b
make `ProfilePayload` safer
zentuit/unity3d-profile,vedi/unity3d-profile,vedi/unity3d-profile,zentuit/unity3d-profile,zentuit/unity3d-profile,vedi/unity3d-profile,zentuit/unity3d-profile,vedi/unity3d-profile,zentuit/unity3d-profile,vedi/unity3d-profile
Soomla/Assets/Plugins/Soomla/Profile/ProfilePayload.cs
Soomla/Assets/Plugins/Soomla/Profile/ProfilePayload.cs
/// Copyright (C) 2012-2014 Soomla Inc. /// /// 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 UnityEngine; namespace Soomla.Profile { /// <summary> /// This class represents the profile payload which is based on /// the user payload and additional information. /// </summary> internal static class ProfilePayload { public static JSONObject ToJSONObj(string userPayload, string rewardId = "") { JSONObject obj = new JSONObject(JSONObject.Type.OBJECT); obj.AddField(USER_PAYLOAD, userPayload); obj.AddField(REWARD_ID, rewardId); return obj; } public static string GetUserPayload(JSONObject profilePayloadJson) { return profilePayloadJson != null && profilePayloadJson[USER_PAYLOAD] != null ? profilePayloadJson[USER_PAYLOAD].str : ""; } public static string GetRewardId(JSONObject profilePayloadJson) { return profilePayloadJson != null && profilePayloadJson[REWARD_ID] != null ? profilePayloadJson[REWARD_ID].str : ""; } private const string USER_PAYLOAD = "userPayload"; private const string REWARD_ID = "rewardId"; } }
/// Copyright (C) 2012-2014 Soomla Inc. /// /// 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 UnityEngine; namespace Soomla.Profile { /// <summary> /// This class represents the profile payload which is based on /// the user payload and additional information. /// </summary> internal static class ProfilePayload { public static JSONObject ToJSONObj(string userPayload, string rewardId = "") { JSONObject obj = new JSONObject(JSONObject.Type.OBJECT); obj.AddField(USER_PAYLOAD, userPayload); obj.AddField(REWARD_ID, rewardId); return obj; } public static string GetUserPayload(JSONObject profilePayloadJson) { return profilePayloadJson [USER_PAYLOAD].str; } public static string GetRewardId(JSONObject profilePayloadJson) { return profilePayloadJson [REWARD_ID].str; } private const string USER_PAYLOAD = "userPayload"; private const string REWARD_ID = "rewardId"; } }
apache-2.0
C#
114ea0f6a2703d445e2f21a690f4586ece0b21a1
Fix interval nodes; refresh nodes
DMagic1/KSP_Contract_Window
Source/ContractsWindow.Unity/Unity/CW_IntervalTypes.cs
Source/ContractsWindow.Unity/Unity/CW_IntervalTypes.cs
using System; using System.Collections.Generic; using ContractsWindow.Unity.Interfaces; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Unity { public class CW_IntervalTypes : MonoBehaviour { [SerializeField] private Text IntervalType = null; [SerializeField] private GameObject IntervalPrefab = null; [SerializeField] private Transform IntervalTransform = null; [SerializeField] private Toggle IntervalToggle = null; private List<CW_IntervalNode> nodes = new List<CW_IntervalNode>(); private IIntervalNode intervalInterface; public IIntervalNode IntervalInterface { get { return intervalInterface; } } public void setIntervalType(IIntervalNode node) { if (node == null) return; intervalInterface = node; if (IntervalType != null) IntervalType.text = node.NodeTitle; CreateIntervalNodes(node); } public void Refresh() { if (IntervalToggle != null && IntervalToggle.isOn) NodesOn(true); } public void NodesOn(bool isOn) { if (intervalInterface == null) return; if (!intervalInterface.IsReached) return; for (int i = nodes.Count - 1; i >= 0; i--) { CW_IntervalNode node = nodes[i]; if (node == null) continue; node.UpdateText(); node.gameObject.SetActive(isOn && intervalInterface.NodeInterval > i + 1); } } private void CreateIntervalNodes(IIntervalNode node) { if (node == null) return; for (int i = 1; i <= node.Intervals; i++) { CreateIntervalNode(node, i); } } private void CreateIntervalNode(IIntervalNode node, int i) { if (IntervalTransform == null || IntervalPrefab == null) return; GameObject obj = Instantiate(IntervalPrefab); if (obj == null) return; obj.transform.SetParent(IntervalTransform, false); CW_IntervalNode nodeObject = obj.GetComponent<CW_IntervalNode>(); if (nodeObject == null) return; nodeObject.setNode(node, i); nodes.Add(nodeObject); nodeObject.gameObject.SetActive(false); } } }
using System; using System.Collections.Generic; using ContractsWindow.Unity.Interfaces; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Unity { public class CW_IntervalTypes : MonoBehaviour { [SerializeField] private Text IntervalType = null; [SerializeField] private GameObject IntervalPrefab = null; [SerializeField] private Transform IntervalTransform = null; private List<CW_IntervalNode> nodes = new List<CW_IntervalNode>(); private IIntervalNode intervalInterface; public IIntervalNode IntervalInterface { get { return intervalInterface; } } public void setIntervalType(IIntervalNode node) { if (node == null) return; intervalInterface = node; if (IntervalType != null) IntervalType.text = node.NodeTitle; CreateIntervalNodes(node); } public void NodesOn(bool isOn) { if (intervalInterface == null) return; if (!intervalInterface.IsReached) return; for (int i = nodes.Count - 1; i >= 0; i--) { CW_IntervalNode node = nodes[i]; if (node == null) continue; node.UpdateText(); node.gameObject.SetActive(isOn && intervalInterface.NodeInterval >= i - 1); } } private void CreateIntervalNodes(IIntervalNode node) { if (node == null) return; for (int i = 1; i <= node.Intervals; i++) { CreateIntervalNode(node, i); } } private void CreateIntervalNode(IIntervalNode node, int i) { if (IntervalTransform == null || IntervalPrefab == null) return; GameObject obj = Instantiate(IntervalPrefab); if (obj == null) return; obj.transform.SetParent(IntervalTransform, false); CW_IntervalNode nodeObject = obj.GetComponent<CW_IntervalNode>(); if (nodeObject == null) return; nodeObject.setNode(node, i); nodes.Add(nodeObject); nodeObject.gameObject.SetActive(false); } } }
mit
C#
f7a8ad3b59b7271b20c12e2f2423e2deef52e511
Refactor Add Doubles Operation to use GetValues and CloneWithValues
ajlopez/TensorSharp
Src/TensorSharp/Operations/AddDoubleDoubleOperation.cs
Src/TensorSharp/Operations/AddDoubleDoubleOperation.cs
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { double[] values1 = tensor1.GetValues(); int l = values1.Length; double[] values2 = tensor2.GetValues(); double[] newvalues = new double[l]; for (int k = 0; k < l; k++) newvalues[k] = values1[k] + values2[k]; return tensor1.CloneWithNewValues(newvalues); } } }
namespace TensorSharp.Operations { using System; using System.Collections.Generic; using System.Linq; using System.Text; public class AddDoubleDoubleOperation : IBinaryOperation<double, double, double> { public Tensor<double> Evaluate(Tensor<double> tensor1, Tensor<double> tensor2) { Tensor<double> result = new Tensor<double>(); result.SetValue(tensor1.GetValue() + tensor2.GetValue()); return result; } } }
mit
C#
f74efa17cc264e88be434b0b3b903e63bc56c316
remove unused code
tparnell8/XamarinAdmobTutorial,tparnell8/XamarinAdmobTutorial,tparnell8/XamarinAdmobTutorial
admobDemo.AndroidPhone/ad/AdWrapper.cs
admobDemo.AndroidPhone/ad/AdWrapper.cs
// Author: Tommy James Parnell // notes: Tutorial to show how admob works in xamarin // email: tparnell8@gmail.com, parnell.tommy@hotmail.com using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Gms.Ads; namespace admobDemo.AndroidPhone.ad { public static class AdWrapper { public static InterstitialAd ConstructFullPageAdd(Context con, string UnitID) { var ad = new InterstitialAd(con); ad.AdUnitId = UnitID; return ad; } public static AdView ConstructStandardBanner(Context con, AdSize adsize, string UnitID) { var ad = new AdView(con); ad.AdSize = adsize; ad.AdUnitId = UnitID; return ad; } public static InterstitialAd CustomBuild(this InterstitialAd ad) { var requestbuilder = new AdRequest.Builder(); ad.LoadAd(requestbuilder.Build()); return ad; } public static AdView CustomBuild(this AdView ad) { var requestbuilder = new AdRequest.Builder(); ad.LoadAd(requestbuilder.Build()); return ad; } } }
// Author: Tommy James Parnell // notes: Tutorial to show how admob works in xamarin // email: tparnell8@gmail.com, parnell.tommy@hotmail.com using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Gms.Ads; namespace admobDemo.AndroidPhone.ad { public static class AdWrapper { public static InterstitialAd ConstructFullPageAdd(Context con, string UnitID) { var ad = new InterstitialAd(con); ad.AdUnitId = UnitID; var requestbuilder = new AdRequest.Builder(); return ad; } public static AdView ConstructStandardBanner(Context con, AdSize adsize, string UnitID) { var ad = new AdView(con); ad.AdSize = adsize; ad.AdUnitId = UnitID; return ad; } public static InterstitialAd CustomBuild(this InterstitialAd ad) { var requestbuilder = new AdRequest.Builder(); ad.LoadAd(requestbuilder.Build()); return ad; } public static AdView CustomBuild(this AdView ad) { var requestbuilder = new AdRequest.Builder(); ad.LoadAd(requestbuilder.Build()); return ad; } } }
unlicense
C#
6406f1d06f89e6d7f2675ec8b59f1da6ae93e9eb
Change server port
ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot
TokenServer/src/Main.cs
TokenServer/src/Main.cs
using System; using System.Threading; using System.Threading.Tasks; namespace UKahoot { class MainClass { public static string[] Hosts = { "tokenserver.ukahoot.it", "http://tokenserver.ukahoot.it", "https://tokenserver.ukahoot.it", "http://www.tokenserver.ukahoot.it", "https://www.tokenserver.ukahoot.it" }; public static int Port = 443; public static TokenServer ts; public static void Main(string[] args) { ts = new TokenServer(Hosts, Port); ts.Init(); Console.WriteLine("Token server started."); Console.WriteLine("Port: " + Port); Console.WriteLine("Hosts: " + Hosts.Length); Console.WriteLine("Press any key to terminate the server."); Console.ReadKey(); return; } } }
using System; using System.Threading; using System.Threading.Tasks; namespace UKahoot { class MainClass { public static string[] Hosts = { "tokenserver.ukahoot.it", "http://tokenserver.ukahoot.it", "https://tokenserver.ukahoot.it", "http://www.tokenserver.ukahoot.it", "https://www.tokenserver.ukahoot.it" }; public static int Port = 5556; public static TokenServer ts; public static void Main(string[] args) { ts = new TokenServer(Hosts, Port); ts.Init(); Console.WriteLine("Token server started."); Console.WriteLine("Port: " + Port); Console.WriteLine("Hosts: " + Hosts.Length); Console.WriteLine("Press any key to terminate the server."); Console.ReadKey(); return; } } }
mit
C#
374cd53dc22284e395c54305c4ca418a0a51aff8
Update ExtentionMethods.cs
giorgalis/skroutz.gr
skroutz.gr/Shared/ExtentionMethods.cs
skroutz.gr/Shared/ExtentionMethods.cs
using System; namespace skroutz.gr.Shared { /// <summary> /// Class ExtentionMethods. /// </summary> public static class ExtentionMethods { /// <summary> /// Converts the Unix time to standard date time. /// </summary> /// <param name="unixTime">The unix time to convert.</param> /// <returns><see cref="DateTime"/>.</returns> public static DateTime UnixTimeToDateTime(this long unixTime) { var timeInTicks = unixTime * TimeSpan.TicksPerSecond; return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks); } /// <summary> /// Converts the specified string to title case. /// </summary> /// <param name="s">The string to convert.</param> /// <returns>System.String.</returns> public static string ToTitleCase(this string s) { if (string.IsNullOrEmpty(s)) return s; string[] textArray = s.Split(' '); for (int i = 0; i < textArray.Length; i++) { switch (textArray[i].Length) { case 1: break; default: textArray[i] = char.ToUpper(textArray[i][0]) + textArray[i].Substring(1); break; } } return string.Join(" ", textArray); } } }
using System; namespace skroutz.gr.Shared { /// <summary> /// Class ExtentionMethods. /// </summary> public static class ExtentionMethods { /// <summary> /// Converts the Unix time to standard date time. /// </summary> /// <param name="unixTime">The unix time to convert.</param> /// <returns><see cref="DateTime"/>.</returns> public static DateTime UnixTimeToDateTime(this long unixTime) { var timeInTicks = unixTime * TimeSpan.TicksPerSecond; return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks); } /// <summary> /// Converts the specified string to title case. /// </summary> /// <param name="s">The string to convert.</param> /// <returns>System.String.</returns> public static string ToTitleCase(this string s) { if (string.IsNullOrEmpty(s)) return s; string[] textArray = s.Split(' '); for (int i = 0; i < textArray.Length; i++) { switch (textArray[i].Length) { case 1: break; default: textArray[i] = char.ToUpper(textArray[i][0]) + textArray[i].Substring(1); break; } } return string.Join(" ", textArray); } } }
mit
C#
64fa09b7fd364782e1345ffadea44023d61b1640
put semicolon between ConcatenatedScript parts to avoid javascript errors with certain minified files
rolembergfilho/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity
Serenity.Web/DynamicScript/DynamicScriptTypes/ConcatenatedScript.cs
Serenity.Web/DynamicScript/DynamicScriptTypes/ConcatenatedScript.cs
using System; using System.Collections.Generic; using System.Text; namespace Serenity.Web { public class ConcatenatedScript : DynamicScript { private IEnumerable<Func<string>> scriptParts; public ConcatenatedScript(IEnumerable<Func<string>> scriptParts) { Check.NotNull(scriptParts, "scriptParts"); this.scriptParts = scriptParts; } public override string GetScript() { StringBuilder sb = new StringBuilder(); foreach (var part in scriptParts) { string partSource = part(); sb.AppendLine(partSource); sb.AppendLine("\r\n;\r\n"); } return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Serenity.Web { public class ConcatenatedScript : DynamicScript { private IEnumerable<Func<string>> scriptParts; public ConcatenatedScript(IEnumerable<Func<string>> scriptParts) { Check.NotNull(scriptParts, "scriptParts"); this.scriptParts = scriptParts; } public override string GetScript() { StringBuilder sb = new StringBuilder(); foreach (var part in scriptParts) { string partSource = part(); sb.AppendLine(partSource); sb.AppendLine("\r\n\r\n"); } return sb.ToString(); } } }
mit
C#
6ccbd1bcb9fa4c4441a7e624ed36a0a7543906d0
Fix ReSharper error messages
Convey-Compliance/ExcelDataReader,Convey-Compliance/ExcelDataReader
Excel/ExcelReaderFactory.cs
Excel/ExcelReaderFactory.cs
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Excel { /// <summary> /// The ExcelReader Factory /// </summary> public static class ExcelReaderFactory { /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream) { IExcelDataReader reader = new ExcelBinaryReader(); reader.Initialize(fileStream); return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <param name="option">Read option.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, ReadOption option) { IExcelDataReader reader = new ExcelBinaryReader(option); reader.Initialize(fileStream); return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <param name="convertOADate">Convert OADate flag.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate) { IExcelDataReader reader = CreateBinaryReader(fileStream); ((ExcelBinaryReader) reader).ConvertOaDate = convertOADate; return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <param name="convertOADate">Convert OADate flag.</param> /// <param name="readOption">Read option.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate, ReadOption readOption) { IExcelDataReader reader = CreateBinaryReader(fileStream, readOption); ((ExcelBinaryReader)reader).ConvertOaDate = convertOADate; return reader; } /// <summary> /// Creates an instance of <see cref="ExcelOpenXmlReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateOpenXmlReader(Stream fileStream) { IExcelDataReader reader = new ExcelOpenXmlReader(); reader.Initialize(fileStream); return reader; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Excel { /// <summary> /// The ExcelReader Factory /// </summary> public static class ExcelReaderFactory { /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream) { IExcelDataReader reader = new ExcelBinaryReader(); reader.Initialize(fileStream); return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, ReadOption option) { IExcelDataReader reader = new ExcelBinaryReader(option); reader.Initialize(fileStream); return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate) { IExcelDataReader reader = CreateBinaryReader(fileStream); ((ExcelBinaryReader) reader).ConvertOaDate = convertOADate; return reader; } /// <summary> /// Creates an instance of <see cref="ExcelBinaryReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateBinaryReader(Stream fileStream, bool convertOADate, ReadOption readOption) { IExcelDataReader reader = CreateBinaryReader(fileStream, readOption); ((ExcelBinaryReader)reader).ConvertOaDate = convertOADate; return reader; } /// <summary> /// Creates an instance of <see cref="ExcelOpenXmlReader"/> /// </summary> /// <param name="fileStream">The file stream.</param> /// <returns></returns> public static IExcelDataReader CreateOpenXmlReader(Stream fileStream) { IExcelDataReader reader = new ExcelOpenXmlReader(); reader.Initialize(fileStream); return reader; } } }
mit
C#
b988d5c490c18ebb70950cc63f93ca83d61b7539
Fix warnings
NickRusinov/CodeContracts.Fody
TestFoundations/TestFoundations.UnitTests/ConcreteClassWithField.cs
TestFoundations/TestFoundations.UnitTests/ConcreteClassWithField.cs
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestFoundations.UnitTests { public class ConcreteClassWithField { private readonly Field field = new Field(); [CustomContract] private readonly Field fieldWithAttribute = new Field(); } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestFoundations.UnitTests { public class ConcreteClassWithField { private readonly Field field; [CustomContract] private readonly Field fieldWithAttribute; } }
mit
C#
f36d917c99ee062d2a33e628af3054d0f8c94ce3
correct main form variable reference
KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,KN4CK3R/ReClass.NET,jesterret/ReClass.NET,jesterret/ReClass.NET,jesterret/ReClass.NET
Program.cs
Program.cs
using System; using System.Globalization; using System.Windows.Forms; using Microsoft.SqlServer.MessageBox; using ReClassNET.Core; using ReClassNET.Forms; using ReClassNET.Logger; using ReClassNET.Native; using ReClassNET.UI; namespace ReClassNET { static class Program { public static Settings Settings { get; private set; } public static ILogger Logger { get; private set; } public static Random GlobalRandom { get; } = new Random(); public static MainForm MainForm { get; private set; } public static bool DesignMode { get; private set; } = true; [STAThread] static void Main() { DesignMode = false; // The designer doesn't call Main() try { DpiUtil.ConfigureProcess(); } catch { } NativeMethods.EnableDebugPrivileges(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; Settings = Settings.Load(Constants.SettingsFile); Logger = new GuiLogger(); #if DEBUG using (var coreFunctions = new CoreFunctionsManager()) { MainForm = new MainForm(coreFunctions); Application.Run(MainForm); } #else try { using (var nativeHelper = new CoreFunctionsManager()) { MainForm = new MainForm(nativeHelper); Application.Run(MainForm); } } catch (Exception ex) { ShowException(ex); } #endif Settings.Save(Settings, Constants.SettingsFile); } /// <summary>Shows the exception in a special form.</summary> /// <param name="ex">The exception.</param> public static void ShowException(Exception ex) { ex.HelpLink = Constants.HelpUrl; var msg = new ExceptionMessageBox(ex) { ShowToolBar = true, Symbol = ExceptionMessageBoxSymbol.Error }; msg.Show(null); } } }
using System; using System.Globalization; using System.Windows.Forms; using Microsoft.SqlServer.MessageBox; using ReClassNET.Core; using ReClassNET.Forms; using ReClassNET.Logger; using ReClassNET.Native; using ReClassNET.UI; namespace ReClassNET { static class Program { public static Settings Settings { get; private set; } public static ILogger Logger { get; private set; } public static Random GlobalRandom { get; } = new Random(); public static MainForm MainForm { get; private set; } public static bool DesignMode { get; private set; } = true; [STAThread] static void Main() { DesignMode = false; // The designer doesn't call Main() try { DpiUtil.ConfigureProcess(); } catch { } NativeMethods.EnableDebugPrivileges(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; Settings = Settings.Load(Constants.SettingsFile); Logger = new GuiLogger(); #if DEBUG using (var coreFunctions = new CoreFunctionsManager()) { MainForm = new MainForm(coreFunctions); Application.Run(MainForm); } #else try { using (var nativeHelper = new CoreFunctionsManager()) { mainForm = new MainForm(nativeHelper); Application.Run(mainForm); } } catch (Exception ex) { ShowException(ex); } #endif Settings.Save(Settings, Constants.SettingsFile); } /// <summary>Shows the exception in a special form.</summary> /// <param name="ex">The exception.</param> public static void ShowException(Exception ex) { ex.HelpLink = Constants.HelpUrl; var msg = new ExceptionMessageBox(ex) { ShowToolBar = true, Symbol = ExceptionMessageBoxSymbol.Error }; msg.Show(null); } } }
mit
C#
5de3b59c1435f14014a3e8866ec2cdc092a330d6
add meta robots noindex
sbaechler/cafe-international,sbaechler/cafe-international
Views/Home/Index.cshtml
Views/Home/Index.cshtml
@using System.Web.Optimization @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <link href='http://fonts.googleapis.com/css?family=Overlock:400,700|Lobster+Two:700italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="@Url.Content("~/Scripts/client.css")"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <meta name="robots" content="noindex,nofollow" /> <title>Index</title> </head> <body> <div id="wrapper"> <div id="content"></div> </div> <script type="text/javascript"> var countries = @Html.Raw(Model.Countries); var cups = @Html.Raw(Model.Cups); </script> @Scripts.Render("~/bundles/react") <script src="@Url.Content("~/Scripts/client.bundle.js")" type="text/javascript"></script> </body> </html>
@using System.Web.Optimization @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <link href='http://fonts.googleapis.com/css?family=Overlock:400,700|Lobster+Two:700italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="@Url.Content("~/Scripts/client.css")"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Index</title> </head> <body> <div id="wrapper"> <div id="content"></div> </div> <script type="text/javascript"> var countries = @Html.Raw(Model.Countries); var cups = @Html.Raw(Model.Cups); </script> @Scripts.Render("~/bundles/react") <script src="@Url.Content("~/Scripts/client.bundle.js")" type="text/javascript"></script> </body> </html>
agpl-3.0
C#
558c0c440abd1bbb63a7324d22602941b84cf8fd
Update Label
philphilphil/WikiCore,philphilphil/WikiCore,philphilphil/WikiCore
Views/Misc/Index.cshtml
Views/Misc/Index.cshtml
@model WikiCore.Models.MiscModel @{ ViewData["Title"] = "Miscellaneous"; } <h2>Tags</h2> <h4>Remove</h4> <form method="post" asp-action="DeleteTag" asp-controller="Misc"> <div class="ui labeled input"> <div class="ui label"> Tag </div> <select asp-for="TagId" asp-items="@Model.TagsSelect" class="ui dropdown"></select> </div> <button type="submit" class="ui primary button">Remove</button> Tag will be deleted and removed from all pages. </form> <h2>All pages:</h2> @foreach (var page in Model.Pages) { <p> @Html.ActionLink(page.Title, "Index", "Home", new { id = page.PageId }) </p> }
@model WikiCore.Models.MiscModel @{ ViewData["Title"] = "Miscellaneous"; } <h2>Tags</h2> <h4>Remove</h4> <form method="post" asp-action="DeleteTag" asp-controller="Misc"> <div class="ui labeled input"> <div class="ui label"> Tag </div> <select asp-for="TagId" asp-items="@Model.TagsSelect" class="ui dropdown"></select> </div> <button type="submit" class="ui primary button">Remove</button> Tag will be removed from all pages and deleted. </form> <h2>All pages:</h2> @foreach (var page in Model.Pages) { <p> @Html.ActionLink(page.Title, "Index", "Home", new { id = page.PageId }) </p> }
mit
C#
96b4876793448290d4a12a30a07aae2d1df4828f
Remove unnecessary try-catch in Worker template
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Worker.cs
namespace Company.Application1; public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); await Task.Delay(1000, stoppingToken); } } }
namespace Company.Application1; public class Worker : BackgroundService { private readonly ILogger<Worker> _logger; public Worker(ILogger<Worker> logger) { _logger = logger; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); try { await Task.Delay(1000, stoppingToken); } catch (OperationCanceledException) { return; } } } }
apache-2.0
C#
1e4948ce4df60f1407926675952c955a49b30c2e
Add full description for a method
pardeike/Harmony
Harmony/Tools/Extensions.cs
Harmony/Tools/Extensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Harmony { public static class GeneralExtensions { public static string Description(this Type[] parameters) { var types = parameters.Select(p => p == null ? "null" : p.FullName); return "(" + types.Aggregate("", (s, x) => s.Length == 0 ? x : s + ", " + x) + ")"; } public static string FullDescription(this MethodBase method) { return method.DeclaringType.FullName + "." + method.Name + method.GetParameters().Select(p => p.ParameterType).ToArray().Description(); } public static Type[] Types(this ParameterInfo[] pinfo) { return pinfo.Select(pi => pi.ParameterType).ToArray(); } public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key) { T result; if (dictionary.TryGetValue(key, out result)) return result; return default(T); } public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key) { object result; if (dictionary.TryGetValue(key, out result)) if (result is T) return (T)result; return default(T); } } public static class CollectionExtensions { public static void Do<T>(this IEnumerable<T> sequence, Action<T> action) { if (sequence == null) return; var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) action(enumerator.Current); } public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action) { sequence.Where(condition).Do(action); } public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item) { return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item }); } public static T[] AddRangeToArray<T>(this T[] sequence, T[] items) { return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray(); } public static T[] AddToArray<T>(this T[] sequence, T item) { return Add(sequence, item).ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Harmony { public static class GeneralExtensions { public static string Description(this Type[] parameters) { var types = parameters.Select(p => p == null ? "null" : p.FullName); return "(" + types.Aggregate("", (s, x) => s.Length == 0 ? x : s + ", " + x) + ")"; } public static Type[] Types(this ParameterInfo[] pinfo) { return pinfo.Select(pi => pi.ParameterType).ToArray(); } public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key) { T result; if (dictionary.TryGetValue(key, out result)) return result; return default(T); } public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key) { object result; if (dictionary.TryGetValue(key, out result)) if (result is T) return (T)result; return default(T); } } public static class CollectionExtensions { public static void Do<T>(this IEnumerable<T> sequence, Action<T> action) { if (sequence == null) return; var enumerator = sequence.GetEnumerator(); while (enumerator.MoveNext()) action(enumerator.Current); } public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action) { sequence.Where(condition).Do(action); } public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item) { return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item }); } public static T[] AddRangeToArray<T>(this T[] sequence, T[] items) { return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray(); } public static T[] AddToArray<T>(this T[] sequence, T item) { return Add(sequence, item).ToArray(); } } }
mit
C#
50126af061e4f9cb23034aa47c72730fb81da202
Update CommonAssemblyInfo.cs
AzureAD/microsoft-authentication-library-for-dotnet,LucVK/azure-activedirectory-library-for-dotnet,bjartebore/azure-activedirectory-library-for-dotnet,AndyZhao/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,AzureAD/azure-activedirectory-library-for-dotnet,AzureAD/microsoft-authentication-library-for-dotnet,yamamoWorks/azure-activedirectory-library-for-dotnet,makhdumi/azure-activedirectory-library-for-dotnet,zbrad/azure-activedirectory-library-for-dotnet
src/ADAL.Common/CommonAssemblyInfo.cs
src/ADAL.Common/CommonAssemblyInfo.cs
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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.Reflection; [assembly: AssemblyProduct("Active Directory Authentication Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Microsoft Open Technologies")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("2.8.0.0")] // Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion. // Build and revision numbers are replaced on build machine for official builds. [assembly: AssemblyFileVersion("2.8.00000.0000")] // On official build, attribute AssemblyInformationalVersionAttribute is added as well // with its value equal to the hash of the last commit to the git branch. // e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
//---------------------------------------------------------------------- // Copyright (c) Microsoft Open Technologies, Inc. // All Rights Reserved // Apache License 2.0 // // 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.Reflection; [assembly: AssemblyProduct("Active Directory Authentication Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCulture("")] [assembly: AssemblyCompany("Microsoft Open Technologies")] [assembly: AssemblyCopyright("Copyright (c) Microsoft Open Technologies. All rights reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("2.7.0.0")] // Keep major and minor versions in AssemblyFileVersion in sync with AssemblyVersion. // Build and revision numbers are replaced on build machine for official builds. [assembly: AssemblyFileVersion("2.7.00000.0000")] // On official build, attribute AssemblyInformationalVersionAttribute is added as well // with its value equal to the hash of the last commit to the git branch. // e.g.: [assembly: AssemblyInformationalVersionAttribute("4392c9835a38c27516fc0cd7bad7bccdcaeab161")]
mit
C#
adce870eda221c01329c6243248a35a91b0ee6ca
Fix bug in displaying zoom control on Linux (BL-8360)
StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,gmartin7/myBloomFork,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop
src/BloomExe/Workspace/ZoomControl.cs
src/BloomExe/Workspace/ZoomControl.cs
using System; using System.Drawing; using System.Windows.Forms; namespace Bloom.Workspace { public partial class ZoomControl : UserControl { public const int kMinimumZoom = 30; // 30% - 300% matches FireFox public const int kMaximumZoom = 300; private int _zoom; public ZoomControl() { InitializeComponent(); if (SIL.PlatformUtilities.Platform.IsLinux) { // Work around a bug in Mono 5 (and Mono 6?). // See https://issues.bloomlibrary.org/youtrack/issue/BL-8360. this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this._minusButton.Location = new System.Drawing.Point(0, -8); // restore original locations this._percentLabel.Location = new System.Drawing.Point(20, 4); this._plusButton.Location = new System.Drawing.Point(58, -8); } Zoom = 100; _plusButton.ForeColor = Color.FromKnownColor(KnownColor.MenuText); _plusButton.FlatAppearance.MouseOverBackColor = SystemColors.GradientActiveCaption; _minusButton.ForeColor = Color.FromKnownColor(KnownColor.MenuText); _minusButton.FlatAppearance.MouseOverBackColor = SystemColors.GradientActiveCaption; _percentLabel.ForeColor = Color.FromKnownColor(KnownColor.MenuText); } public int Zoom { get { return _zoom; } set { var newValue = Math.Min(Math.Max(value, kMinimumZoom), kMaximumZoom); if (newValue == _zoom) return; _zoom = newValue; _percentLabel.Text = _zoom + @"%"; ZoomChanged?.Invoke(this, new EventArgs()); } } public event EventHandler<EventArgs> ZoomChanged; private void _minusButton_Click(object sender, EventArgs e) { Zoom = Zoom - 10; } private void _plusButton_Click(object sender, EventArgs e) { Zoom = Zoom + 10; } } }
using System; using System.Drawing; using System.Windows.Forms; namespace Bloom.Workspace { public partial class ZoomControl : UserControl { public const int kMinimumZoom = 30; // 30% - 300% matches FireFox public const int kMaximumZoom = 300; private int _zoom; public ZoomControl() { InitializeComponent(); Zoom = 100; _plusButton.ForeColor = Color.FromKnownColor(KnownColor.MenuText); _plusButton.FlatAppearance.MouseOverBackColor = SystemColors.GradientActiveCaption; _minusButton.ForeColor = Color.FromKnownColor(KnownColor.MenuText); _minusButton.FlatAppearance.MouseOverBackColor = SystemColors.GradientActiveCaption; _percentLabel.ForeColor = Color.FromKnownColor(KnownColor.MenuText); } public int Zoom { get { return _zoom; } set { var newValue = Math.Min(Math.Max(value, kMinimumZoom), kMaximumZoom); if (newValue == _zoom) return; _zoom = newValue; _percentLabel.Text = _zoom + @"%"; ZoomChanged?.Invoke(this, new EventArgs()); } } public event EventHandler<EventArgs> ZoomChanged; private void _minusButton_Click(object sender, EventArgs e) { Zoom = Zoom - 10; } private void _plusButton_Click(object sender, EventArgs e) { Zoom = Zoom + 10; } } }
mit
C#
33163aeb4db80455ca3d1e40e01958167c140c22
remove time messure
juwens/yamaha-vtuner-server-aspnet-core
src/Controllers/StationsController.cs
src/Controllers/StationsController.cs
using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using VtnrNetRadioServer.Contract; using VtnrNetRadioServer.Repositories; namespace VtnrNetRadioServer.Controllers { /* * Used for UserInterface to CRUD Stations */ public class StationsController : Controller { private readonly IStationsRepository _stationsRepo; private readonly ILogger<StationsController> _logger; public StationsController(IStationsRepository sationsRepo, ILogger<StationsController> logger) { this._stationsRepo = sationsRepo; this._logger = logger; } public async Task<ViewResult> Index() { var stations = await _stationsRepo.GetAllAsync(); return View(stations); } [HttpPost] public async Task<IActionResult> Add(string name, string url) { await _stationsRepo.AddAsync(name, url); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Delete(string id) { await _stationsRepo.DeleteAsync(id); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Up(string id) { await _stationsRepo.MoveUpAsync(id); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Down(string id) { await _stationsRepo.MoveDownAsync(id); return Redirect(nameof(Index)); } [HttpGet] public async Task<ViewResult> Edit(string id) { var item = (await _stationsRepo.GetAllAsync()).Single(x => x.Key == id); return View(item.Item); } [HttpPost] public async Task<IActionResult> Edit(string id, ListOfItemsItem item) { await _stationsRepo.UpdateAsync(id, item); return RedirectToAction(nameof(Index)); } } }
using System; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using VtnrNetRadioServer.Contract; using VtnrNetRadioServer.Repositories; namespace VtnrNetRadioServer.Controllers { /* * Used for UserInterface to CRUD Stations */ public class StationsController : Controller { private readonly IStationsRepository _stationsRepo; private readonly ILogger<StationsController> _logger; public StationsController(IStationsRepository sationsRepo, ILogger<StationsController> logger) { this._stationsRepo = sationsRepo; this._logger = logger; } public async Task<ViewResult> Index() { var sw = Stopwatch.StartNew(); var stations = await _stationsRepo.GetAllAsync(); sw.Stop(); _logger.LogCritical("GetAll ms: " + sw.ElapsedMilliseconds); return View(stations); } [HttpPost] public async Task<IActionResult> Add(string name, string url) { await _stationsRepo.AddAsync(name, url); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Delete(string id) { await _stationsRepo.DeleteAsync(id); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Up(string id) { await _stationsRepo.MoveUpAsync(id); return Redirect(nameof(Index)); } [HttpPost] public async Task<IActionResult> Down(string id) { await _stationsRepo.MoveDownAsync(id); return Redirect(nameof(Index)); } [HttpGet] public async Task<ViewResult> Edit(string id) { var item = (await _stationsRepo.GetAllAsync()).Single(x => x.Key == id); return View(item.Item); } [HttpPost] public async Task<IActionResult> Edit(string id, ListOfItemsItem item) { await _stationsRepo.UpdateAsync(id, item); return RedirectToAction(nameof(Index)); } } }
apache-2.0
C#
17a38a87ce3558dcdeec62a55a55227820a5a17f
add SqlEmiterTest
sdcb/sdmap
sdmap/test/sdmap.ext.test/SmokeTest.cs
sdmap/test/sdmap.ext.test/SmokeTest.cs
using sdmap.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace sdmap.ext.test { public class SmokeTest { private class SimpleSqlEmiter : ISqlEmiter { public string EmitSql(string sqlId, object queryObject) { return "Simple"; } } [Fact] public void SqlEmiterTest() { SdmapExtensions.SetSqlEmiter(new SimpleSqlEmiter()); var actual = SdmapExtensions.EmitSql("test", null); Assert.Equal("Simple", actual); } [Fact] public void WatchSmoke() { Directory.CreateDirectory("sqls"); var tempFile = @"sqls\test.sdmap"; File.WriteAllText(tempFile, "sql Hello{Hello}"); SdmapExtensions.SetSqlDirectoryAndWatch(@".\sqls"); try { File.WriteAllText(tempFile, "sql Hello{Hello2}"); Thread.Sleep(30); var text = SdmapExtensions.EmitSql("Hello", null); Assert.Equal("Hello2", text); } finally { File.Delete(tempFile); Directory.Delete("sqls"); } } } }
using sdmap.Extensions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace sdmap.ext.test { public class SmokeTest { [Fact] public void WatchSmoke() { Directory.CreateDirectory("sqls"); var tempFile = @"sqls\test.sdmap"; File.WriteAllText(tempFile, "sql Hello{Hello}"); SdmapExtensions.SetSqlDirectoryAndWatch(@".\sqls"); try { File.WriteAllText(tempFile, "sql Hello{Hello2}"); Thread.Sleep(30); var text = SdmapExtensions.EmitSql("Hello", null); Assert.Equal("Hello2", text); } finally { File.Delete(tempFile); Directory.Delete("sqls"); } } } }
mit
C#
06deb65ed844fb59fde48c0a8de1a5260748ba48
comment about flaw
nerai/CMenu
src/ExampleMenu/Procedures/MI_Call.cs
src/ExampleMenu/Procedures/MI_Call.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ConsoleMenu; namespace ExampleMenu { public class MI_Call : CMenuItem { private readonly CMenu _Menu; private readonly ProcManager _Mgr; public MI_Call (CMenu menu, ProcManager mgr) : base ("call") { _Menu = menu; _Mgr = mgr; } public override MenuResult Execute (string arg) { // todo error checks var lines = _Mgr.Procs[arg]; IO.AddInput (CreateInput (lines)); return MenuResult.Normal; } private IEnumerable<string> CreateInput (List<string> lines) { foreach (var line in lines) { yield return line; if (_Mgr.ShouldReturn) { _Mgr.ShouldReturn = false; break; } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ConsoleMenu; namespace ExampleMenu { public class MI_Call : CMenuItem { private readonly CMenu _Menu; private readonly ProcManager _Mgr; public MI_Call (CMenu menu, ProcManager mgr) : base ("call") { _Menu = menu; _Mgr = mgr; } public override MenuResult Execute (string arg) { var lines = _Mgr.Procs[arg]; IO.AddInput (CreateInput (lines)); return MenuResult.Normal; } private IEnumerable<string> CreateInput (List<string> lines) { foreach (var line in lines) { yield return line; if (_Mgr.ShouldReturn) { _Mgr.ShouldReturn = false; break; } } } } }
mit
C#
517906529caf351ccd158cca1547fa566d8eabc5
Improve throughput
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle012.cs
src/ProjectEuler/Puzzles/Puzzle012.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int divisors) || divisors < 1) { Console.WriteLine("The specified number of divisors is invalid."); return -1; } long triangleNumber = 0; for (int n = 1; ; n++) { triangleNumber += n; int numberOfFactors = 0; using var enumerator = Maths.GetFactorsUnordered(triangleNumber).GetEnumerator(); while (enumerator.MoveNext() && numberOfFactors < divisors) { numberOfFactors++; } if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=12</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle012 : Puzzle { /// <inheritdoc /> public override string Question => "What is the value of the first triangle number to have the specified number of divisors?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int divisors) || divisors < 1) { Console.WriteLine("The specified number of divisors is invalid."); return -1; } long triangleNumber = 0; for (int n = 1; ; n++) { triangleNumber += n; int numberOfFactors = Maths.GetFactorsUnordered(triangleNumber).Count(); if (numberOfFactors >= divisors) { Answer = triangleNumber; break; } } return 0; } } }
apache-2.0
C#
cb60f4e948698dad985255aee1892d748e858427
Remove copy
martincostello/project-euler
src/ProjectEuler/Puzzles/Puzzle031.cs
src/ProjectEuler/Puzzles/Puzzle031.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=31</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle031 : Puzzle { /// <summary> /// The coins, in pence, available in GBP. This field is read-only. /// </summary> private static readonly int[] Coins = new[] { 1, 2, 5, 10, 20, 50, 100, 200 }; /// <inheritdoc /> public override string Question => "How many different ways can the specified amount of money, in pence, be made using any number of coins?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int target) || target < 1) { Console.WriteLine("The specified total is invalid."); return -1; } // Array containing the number of ways there are to // make 1p up to the target using the avaiable coins. int[] ways = new int[target + 1]; // There is one way to make 1p ways[0] = 1; // Loop through each value of coin for (int coin = 0; coin < Coins.Length; coin++) { int coinValue = Coins[coin]; if (coinValue > target) { break; } // For each value from the coin's value to the target // find how many ways there are to create that value. for (int j = coinValue; j <= target; j++) { int valueRemaining = j - coinValue; ways[j] += ways[valueRemaining]; } } Answer = ways[target]; return 0; } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.ProjectEuler.Puzzles { using System; using System.Linq; /// <summary> /// A class representing the solution to <c>https://projecteuler.net/problem=31</c>. This class cannot be inherited. /// </summary> public sealed class Puzzle031 : Puzzle { /// <summary> /// The coins, in pence, available in GBP. This field is read-only. /// </summary> private static readonly int[] Coins = new[] { 1, 2, 5, 10, 20, 50, 100, 200 }; /// <inheritdoc /> public override string Question => "How many different ways can the specified amount of money, in pence, be made using any number of coins?"; /// <inheritdoc /> protected override int MinimumArguments => 1; /// <inheritdoc /> protected override int SolveCore(string[] args) { if (!TryParseInt32(args[0], out int target) || target < 1) { Console.WriteLine("The specified total is invalid."); return -1; } // Filter out the coins that are bigger than the target int[] usefulCoins = Coins .Where((p) => p <= target) .ToArray(); // Array containing the number of ways there are to // make 1p up to the target using the avaiable coins. int[] ways = new int[target + 1]; // There is one way to make 1p ways[0] = 1; // Loop through each value of coin for (int coin = 0; coin < usefulCoins.Length; coin++) { int coinValue = usefulCoins[coin]; // For each value from the coin's value to the target // find how many ways there are to create that value. for (int j = coinValue; j <= target; j++) { int valueRemaining = j - coinValue; ways[j] += ways[valueRemaining]; } } Answer = ways[target]; return 0; } } }
apache-2.0
C#
e7602e2b8299a22605eb66ffa58452067510ea5c
Use fixture path
AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS
src/R/Core/Test/Utility/ParseFiles.cs
src/R/Core/Test/Utility/ParseFiles.cs
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using FluentAssertions; using Microsoft.Common.Core.Test.Utility; using Microsoft.R.Core.AST; using Microsoft.R.Core.Parser; using Microsoft.R.Core.Utility; namespace Microsoft.R.Core.Test.Utility { [ExcludeFromCodeCoverage] public class ParseFiles { // change to true in debugger if you want all baseline tree files regenerated private static bool _regenerateBaselineFiles = false; public static void ParseFile(CoreTestFilesFixture fixture, string name) { Action a = () => ParseFileImplementation(fixture, name); a.ShouldNotThrow(); } private static void ParseFileImplementation(CoreTestFilesFixture fixture, string name) { string testFile = fixture.GetDestinationPath(name); string baselineFile = testFile + ".tree"; string text = fixture.LoadDestinationFile(name); AstRoot actualTree = RParser.Parse(text); AstWriter astWriter = new AstWriter(); string actual = astWriter.WriteTree(actualTree); if (_regenerateBaselineFiles) { // Update this to your actual enlistment if you need to update baseline baselineFile = Path.Combine(fixture.SourcePath, name) + ".tree"; TestFiles.UpdateBaseline(baselineFile, actual); } else { TestFiles.CompareToBaseLine(baselineFile, actual); } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using FluentAssertions; using Microsoft.Common.Core.Test.Utility; using Microsoft.R.Core.AST; using Microsoft.R.Core.Parser; using Microsoft.R.Core.Utility; namespace Microsoft.R.Core.Test.Utility { [ExcludeFromCodeCoverage] public class ParseFiles { // change to true in debugger if you want all baseline tree files regenerated private static bool _regenerateBaselineFiles = false; public static void ParseFile(CoreTestFilesFixture fixture, string name) { Action a = () => ParseFileImplementation(fixture, name); a.ShouldNotThrow(); } private static void ParseFileImplementation(CoreTestFilesFixture fixture, string name) { string testFile = fixture.GetDestinationPath(name); string baselineFile = testFile + ".tree"; string text = fixture.LoadDestinationFile(name); AstRoot actualTree = RParser.Parse(text); AstWriter astWriter = new AstWriter(); string actual = astWriter.WriteTree(actualTree); if (_regenerateBaselineFiles) { // Update this to your actual enlistment if you need to update baseline string enlistmentPath = @"C:\RTVS-Main\src\R\Core\Test\Files\Parser"; baselineFile = Path.Combine(enlistmentPath, Path.GetFileName(testFile)) + ".tree"; TestFiles.UpdateBaseline(baselineFile, actual); } else { TestFiles.CompareToBaseLine(baselineFile, actual); } } } }
mit
C#
6cd0d3f8d3876e2a2fca2cd7c56168097813570f
Add Users and Roles to DiplomContext
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.DataLayer/DiplomContext.cs
src/Diploms.DataLayer/DiplomContext.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Diploms.Core; namespace Diploms.DataLayer { public class DiplomContext : DbContext { public DbSet<Department> Departments { get; set; } public DbSet<User> Users { get; set; } public DbSet<Role> Roles { get; set; } public DiplomContext() : base() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //TODO: Use appsettings.json or environment variable, not the string here. optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Diploms.Core; namespace Diploms.DataLayer { public class DiplomContext : DbContext { public DbSet<Department> Departments { get; set; } public DiplomContext() : base() { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //TODO: Use appsettings.json or environment variable, not the string here. optionsBuilder.UseNpgsql(@"Host=localhost;Port=5432;Database=diploms;UserId=postgres;Password=12345678;Pooling=true"); } } }
mit
C#
54f31ef6d2e36149fbb591f5b90c58227851885d
add Runtime Serialization lib
varj888/amos-ss17-projSivantos
raspberry-uc-system/RaspberryUserControlSystem/RaspberryBackend/Request.cs
raspberry-uc-system/RaspberryUserControlSystem/RaspberryBackend/Request.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.Serialization; namespace HelloWorld { /// <summary> /// Unit of transfer by the RequestConnClient Class /// is only as a container for the two variables methodName and parameter /// note: this class uses the default contract namespace /// </summary> [DataContract] public class Request { public Request(string methodName, Object parameter) { this.methodName = methodName; this.parameter = parameter; } [DataMember] public string methodName; [DataMember] public Object parameter; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HelloWorld { /// <summary> /// Unit of transfer by the RequestConnClient Class /// is only as a container for the two variables methodName and parameter /// note: this class uses the default contract namespace /// </summary> [DataContract] public class Request { public Request(string methodName, Object parameter) { this.methodName = methodName; this.parameter = parameter; } [DataMember] public string methodName; [DataMember] public Object parameter; } }
apache-2.0
C#
6e6f8704679fc037a5b337f94246607fbc6acd0c
Check if data dir is present in the PE.
Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver,Washi1337/AsmResolver
src/AsmResolver.PE/PEImageInternal.cs
src/AsmResolver.PE/PEImageInternal.cs
// AsmResolver - Executable file format inspection library // Copyright (C) 2016-2019 Washi // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3.0 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using AsmResolver.PE.File; using AsmResolver.PE.File.Headers; using AsmResolver.PE.Imports; using AsmResolver.PE.Imports.Internal; using AsmResolver.PE.Win32Resources; using AsmResolver.PE.Win32Resources.Internal; namespace AsmResolver.PE { internal class PEImageInternal : PEImageBase { private readonly PEFile _peFile; public PEImageInternal(PEFile peFile) { _peFile = peFile ?? throw new ArgumentNullException(nameof(peFile)); } protected override IList<ModuleImportEntryBase> GetImports() { var dataDirectory = _peFile.OptionalHeader.DataDirectories[OptionalHeader.ImportDirectoryIndex]; if (!dataDirectory.IsPresentInPE) return new List<ModuleImportEntryBase>(); var directoryReader = _peFile.CreateDataDirectoryReader(dataDirectory); return new ModuleImportEntryList(_peFile, directoryReader); } protected override ResourceDirectoryBase GetResources() { var dataDirectory = _peFile.OptionalHeader.DataDirectories[OptionalHeader.ResourceDirectoryIndex]; if (!dataDirectory.IsPresentInPE) return null; var directoryReader = _peFile.CreateDataDirectoryReader(dataDirectory); return new ResourceDirectoryInternal(_peFile, null, directoryReader); } } }
// AsmResolver - Executable file format inspection library // Copyright (C) 2016-2019 Washi // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 3.0 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA using System; using System.Collections.Generic; using AsmResolver.PE.File; using AsmResolver.PE.File.Headers; using AsmResolver.PE.Imports; using AsmResolver.PE.Imports.Internal; using AsmResolver.PE.Win32Resources; using AsmResolver.PE.Win32Resources.Internal; namespace AsmResolver.PE { internal class PEImageInternal : PEImageBase { private readonly PEFile _peFile; public PEImageInternal(PEFile peFile) { _peFile = peFile ?? throw new ArgumentNullException(nameof(peFile)); } protected override IList<ModuleImportEntryBase> GetImports() { var importDirectory = _peFile.OptionalHeader.DataDirectories[OptionalHeader.ImportDirectoryIndex]; var directoryReader = _peFile.CreateDataDirectoryReader(importDirectory); return new ModuleImportEntryList(_peFile, directoryReader); } protected override ResourceDirectoryBase GetResources() { var resourceDirectory = _peFile.OptionalHeader.DataDirectories[OptionalHeader.ResourceDirectoryIndex]; var directoryReader = _peFile.CreateDataDirectoryReader(resourceDirectory); return new ResourceDirectoryInternal(_peFile, null, directoryReader); } } }
mit
C#
d38b0a685f3479915238f5055f1a052e809a511f
add client secret prop to OAuthConfig
solomobro/Instagram,solomobro/Instagram,solomobro/Instagram
src/Solomobro.Instagram/OAuthConfig.cs
src/Solomobro.Instagram/OAuthConfig.cs
using System; using System.Collections.Generic; namespace Solomobro.Instagram { /// <summary> /// Defines the configuration parameters required to authorize your app /// </summary> public class OAuthConfig { private readonly HashSet<string> _scopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public string ClientId { get; } public string ClientSecret { get; } public string RedirectUri { get; } /// <summary> /// The authentication method to use. Default: Explicit (server-side) /// </summary> public AuthenticationMethod AuthMethod { get; } = AuthenticationMethod.Explicit; public IEnumerable<string> Scopes { get { return _scopes; } } /// <summary> /// Initialize a new Auth configuration with default authentication method and basic scope /// </summary> /// <param name="clientId">The client id for your app</param> /// <param name="clientSecret">The clien secret for you app</param> /// <param name="redirectUri"> /// The URI where the user is redirected after authorization. /// This must match the exact URI registered for your app in the Instagram dev console /// </param> public OAuthConfig(string clientId, string clientSecret, string redirectUri) { ClientId = clientId; ClientSecret = clientSecret; RedirectUri = redirectUri; } /// <summary> /// Initialize a new Auth confiuration with basic scope /// </summary> /// <param name="clientId">The client id for your app</param> /// <param name="clientSecret">The client secret for your app</param> /// <param name="redirectUri"> /// The URI where the user is redirected after authorization. /// This must match the exact URI registered for your app in the Instagram dev console /// </param> /// <param name="authMethod">The authentication flow to use during the authorization process</param> public OAuthConfig(string clientId, string clientSecret, string redirectUri, AuthenticationMethod authMethod) : this(clientId, clientSecret, redirectUri) { AuthMethod = authMethod; } /// <summary> /// Add scopes to the configuration /// </summary> /// <param name="scopes">one or more scopes</param> /// <see cref="OAuthScope"/> public void AddScopes(params string[] scopes) { foreach (var scope in scopes) { _scopes.Add(scope); } } } }
using System; using System.Collections.Generic; namespace Solomobro.Instagram { /// <summary> /// Defines the configuration parameters required to authorize your app /// </summary> public class OAuthConfig { private readonly HashSet<string> _scopes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public string ClientId { get; } public string RedirectUri { get; } /// <summary> /// The authentication method to use. Default: Explicit (server-side) /// </summary> public AuthenticationMethod AuthMethod { get; } = AuthenticationMethod.Explicit; public IEnumerable<string> Scopes { get { return _scopes; } } /// <summary> /// Initialize a new Auth configuration with default authentication method and basic scope /// </summary> /// <param name="clientId">The client id for your app</param> /// <param name="redirectUri"> /// The URI where the user is redirected after authorization. /// This must match the exact URI registered for your app in the Instagram dev console /// </param> public OAuthConfig(string clientId, string redirectUri) { ClientId = clientId; RedirectUri = redirectUri; } /// <summary> /// Initialize a new Auth confiuration with basic scope /// </summary> /// <param name="clientId">The client id for your app</param> /// <param name="redirectUri"> /// The URI where the user is redirected after authorization. /// This must match the exact URI registered for your app in the Instagram dev console /// </param> /// <param name="authMethod">The authentication flow to use during the authorization process</param> public OAuthConfig(string clientId, string redirectUri, AuthenticationMethod authMethod) : this(clientId, redirectUri) { AuthMethod = authMethod; } /// <summary> /// Add scopes to the configuration /// </summary> /// <param name="scopes">one or more scopes</param> /// <see cref="OAuthScope"/> public void AddScopes(params string[] scopes) { foreach (var scope in scopes) { _scopes.Add(scope); } } } }
apache-2.0
C#
d82f5727e108ba443d33d4df646a29a0bc91e538
Update version.
NForza/transit-csharp
src/Transit/Properties/AssemblyInfo.cs
src/Transit/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Transit")] [assembly: AssemblyDescription("Transit is a data format and a set of libraries for conveying values between applications written in different languages. This library provides support for marshalling Transit data to/from .NET.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NForza")] [assembly: AssemblyProduct("Transit")] [assembly: AssemblyCopyright("NForza 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.*")] [assembly: AssemblyFileVersion("0.8.0.0")] [assembly: AssemblyInformationalVersion("0.8.2-beta")] // For tests: [assembly: InternalsVisibleTo("Transit.Tests")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Transit")] [assembly: AssemblyDescription("Transit is a data format and a set of libraries for conveying values between applications written in different languages. This library provides support for marshalling Transit data to/from .NET.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("NForza")] [assembly: AssemblyProduct("Transit")] [assembly: AssemblyCopyright("NForza 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.8.*")] [assembly: AssemblyFileVersion("0.8.0.0")] [assembly: AssemblyInformationalVersion("0.8.1-alpha")] // For tests: [assembly: InternalsVisibleTo("Transit.Tests")]
apache-2.0
C#
75ca181231352565ba160b79968e72c2cb551318
write API key to Console
ericnewton76/gmaps-api-net
src/Google.Maps.Test/SigningHelper.cs
src/Google.Maps.Test/SigningHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Google.Maps { public static class SigningHelper { static SigningHelper() { //during testing, get api key from the GOOGLE_API_KEY environment variable, to enable more flexibility and try to prevent OverQuotaLimit S_ApiKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY"); //Log.Info("GetEnvironmentVariable(\"GOOGLE_API_KEY\")='{0}'.",S_ApiKey); //for local testing, you can either use the Debugger to modify the S_ApiKey static variable //or set the Debugging Environment variable via the Visual Stdio Debugging properties dialog. //for more info, see https://stackoverflow.com/a/155363/323456 //for nunit test, might need to use the NUnit Test Settings file //if env["GOOGLE_API_KEY"] is empty, use a default key if(string.IsNullOrEmpty(S_ApiKey)) { //Log.Info("Setting ApiKey to a default key."); //this api key can be used for individual developer machines //you may get OverQueryLimit responses though S_ApiKey = "AIzaSyDV-0ftj1tsjfd6GnEbtbxwHXnv6iR3UEU"; } //Log.Info("Using ApiKey '{0}' for testing.", S_ApiKey); Console.WriteLine("Using ApiKey '{0}' for testing.", S_ApiKey); } /// <summary>Holds the ApiKey used for testing</summary> private static string S_ApiKey; public static GoogleSigned GetPrivateKey() { throw new NotImplementedException(); } public static GoogleSigned GetApiKey() { return new GoogleSigned(S_ApiKey); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Google.Maps { public static class SigningHelper { static SigningHelper() { //during testing, get api key from the GOOGLE_API_KEY environment variable, to enable more flexibility and try to prevent OverQuotaLimit S_ApiKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY"); //Log.Info("GetEnvironmentVariable(\"GOOGLE_API_KEY\")='{0}'.",S_ApiKey); //for local testing, you can either use the Debugger to modify the S_ApiKey static variable //or set the Debugging Environment variable via the Visual Stdio Debugging properties dialog. //for more info, see https://stackoverflow.com/a/155363/323456 //for nunit test, might need to use the NUnit Test Settings file //if env["GOOGLE_API_KEY"] is empty, use a default key if(string.IsNullOrEmpty(S_ApiKey)) { //Log.Info("Setting ApiKey to a default key."); //this api key can be used for individual developer machines //you may get OverQueryLimit responses though S_ApiKey = "AIzaSyDV-0ftj1tsjfd6GnEbtbxwHXnv6iR3UEU"; } //Log.Info("Using ApiKey '{0}' for testing.", S_ApiKey); } /// <summary>Holds the ApiKey used for testing</summary> private static string S_ApiKey; public static GoogleSigned GetPrivateKey() { throw new NotImplementedException(); } public static GoogleSigned GetApiKey() { return new GoogleSigned(S_ApiKey); } } }
apache-2.0
C#
3addd8488aa494298e181f140b2356376e18eb13
add ConnectedComponentsAlgorithmsTypes' new values
shimat/opencvsharp,shimat/opencvsharp,shimat/opencvsharp
src/OpenCvSharp/Modules/imgproc/Enum/ConnectedComponentsAlgorithmsTypes.cs
src/OpenCvSharp/Modules/imgproc/Enum/ConnectedComponentsAlgorithmsTypes.cs
// ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming namespace OpenCvSharp { /// <summary> /// connected components algorithm /// </summary> public enum ConnectedComponentsAlgorithmsTypes { /// <summary> /// SAUF algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> WU = 0, /// <summary> /// BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> Default = -1, /// <summary> /// BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> GRANA = 1, /// <summary> /// Spaghetti @cite Bolelli2019 algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity. /// </summary> BOLELLI = 2, /// <summary> /// Same as CCL_WU. It is preferable to use the flag with the name of the algorithm (CCL_SAUF) rather than the one with the name of the first author (CCL_WU). /// </summary> SAUF = 3, /// <summary> /// Same as CCL_GRANA. It is preferable to use the flag with the name of the algorithm (CCL_BBDT) rather than the one with the name of the first author (CCL_GRANA). /// </summary> BBDT = 4, /// <summary> /// Same as CCL_BOLELLI. It is preferable to use the flag with the name of the algorithm (CCL_SPAGHETTI) rather than the one with the name of the first author (CCL_BOLELLI). /// </summary> SPAGHETTI = 5, } }
// ReSharper disable IdentifierTypo // ReSharper disable InconsistentNaming namespace OpenCvSharp { /// <summary> /// connected components algorithm /// </summary> public enum ConnectedComponentsAlgorithmsTypes { /// <summary> /// SAUF algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> WU = 0, /// <summary> /// BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> Default = -1, /// <summary> /// BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity /// </summary> GRANA = 1 } }
apache-2.0
C#
d0fa4c2a7b97e8dc1f8ef5a4649847b2a230ceca
Add description to docstring
ilovepi/Compiler,ilovepi/Compiler
compiler/middleend/ir/DominatorNode.cs
compiler/middleend/ir/DominatorNode.cs
using System; using System.Collections.Generic; using compiler.middleend.ir; namespace compiler { class DominatorNode { /// <summary> /// The basic block of the node /// </summary> public BasicBlock BB { get; set; } /// <summary> /// The parent of this node /// </summary> public DominatorNode Parent { get; set; } /// <summary> /// The Nodes which this basic block directly dominates /// </summary> public List<DominatorNode> Children; /// <summary> /// constructor /// </summary> /// <param name="pBB">The basic block of the node</param> public DominatorNode(BasicBlock pBB) { BB = pBB; Parent = null; Children = new List<DominatorNode>(); } /// <summary> /// Checks if this node is a root node /// </summary> /// <returns>True if this node is a root, with no parents</returns> public bool IsRoot() { return (Parent == null); } /// <summary> /// Adds a new subtree to this node. /// </summary> /// <param name="other">The root of the subtree to insert</param> public virtual void InsertChild(DominatorNode other) { // detatch other's subtree from any tree it previously belonged to if (!other.IsRoot()) { other.Parent.RemoveChild(other); } // add other to this subtree Children.Add(other); other.Parent = this; } //TODO: Do we need this method? virtual public void UpdateParent(DominatorNode other) { Parent = other; } /// <summary> /// Removes a node from this subtree /// </summary> /// <param name="other"> the root of the subtree to remove</param> /// <returns>True if a node was removed, false if the node was not found</returns> public bool RemoveChild(DominatorNode other) { return Children.Remove(other); } } }
using System; using System.Collections.Generic; using compiler.middleend.ir; namespace compiler { class DominatorNode { /// <summary> /// The basic block of the node /// </summary> public BasicBlock BB { get; set; } /// <summary> /// The parent of this node /// </summary> public DominatorNode Parent { get; set; } /// <summary> /// The Nodes which this basic block directly dominates /// </summary> public List<DominatorNode> Children; /// <summary> /// constructor /// </summary> /// <param name="pBB">The basic block of the node</param> public DominatorNode(BasicBlock pBB) { BB = pBB; Parent = null; Children = new List<DominatorNode>(); } /// <summary> /// Checks if this node is a root node /// </summary> /// <returns>True if this node is a root, with no parents</returns> public bool IsRoot() { return (Parent == null); } /// <summary> /// Adds a new subtree to this node. /// </summary> /// <param name="other"></param> public virtual void InsertChild(DominatorNode other) { // detatch other's subtree from any tree it previously belonged to if (!other.IsRoot()) { other.Parent.RemoveChild(other); } // add other to this subtree Children.Add(other); other.Parent = this; } //TODO: Do we need this method? virtual public void UpdateParent(DominatorNode other) { Parent = other; } /// <summary> /// Removes a node from this subtree /// </summary> /// <param name="other"> the root of the subtree to remove</param> /// <returns>True if a node was removed, false if the node was not found</returns> public bool RemoveChild(DominatorNode other) { return Children.Remove(other); } } }
mit
C#
d51f253aff31e63f49ae56cd86fd5a3d2cfadac7
Fix DebugLog formatting
SharpeRAD/Cake.WebDeploy,SharpeRAD/Cake.WebDeploy,SharpeRAD/Cake.WebDeploy
src/WebDeploy.Tests/Utils/DebugLog.cs
src/WebDeploy.Tests/Utils/DebugLog.cs
#region Using Statements using System.Diagnostics; using System.Collections.Generic; using Cake.Core.Diagnostics; #endregion namespace Cake.WebDeploy.Tests { /// <summary> /// A log that outputs messages to debug /// </summary> internal class DebugLog : ICakeLog { /// <summary> /// Gets the verbosity. /// </summary> /// <value>The verbosity.</value> public static IList<string> Lines { get; set; } /// <summary> /// Gets the verbosity. /// </summary> /// <value>The verbosity.</value> public Verbosity Verbosity { get { return Verbosity.Diagnostic; } } /// <summary> /// Writes the text representation of the specified array of objects to the /// log using the specified verbosity, log level and format information. /// </summary> /// <param name="verbosity">The verbosity.</param> /// <param name="level">The log level.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An array of objects to write using format.</param> public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { try { if (DebugLog.Lines == null) { DebugLog.Lines = new List<string>(); } format = String.Format(format, args); DebugLog.Lines.Add(format); if (Debugger.IsAttached) { Debug.WriteLine(format); } else { Console.WriteLine(format); } } catch { } } } }
#region Using Statements using System.Diagnostics; using System.Collections.Generic; using Cake.Core.Diagnostics; #endregion namespace Cake.WebDeploy.Tests { /// <summary> /// A log that outputs messages to debug /// </summary> internal class DebugLog : ICakeLog { /// <summary> /// Gets the verbosity. /// </summary> /// <value>The verbosity.</value> public static IList<string> Lines { get; set; } /// <summary> /// Gets the verbosity. /// </summary> /// <value>The verbosity.</value> public Verbosity Verbosity { get { return Verbosity.Diagnostic; } } /// <summary> /// Writes the text representation of the specified array of objects to the /// log using the specified verbosity, log level and format information. /// </summary> /// <param name="verbosity">The verbosity.</param> /// <param name="level">The log level.</param> /// <param name="format">A composite format string.</param> /// <param name="args">An array of objects to write using format.</param> public void Write(Verbosity verbosity, LogLevel level, string format, params object[] args) { try { if (DebugLog.Lines == null) { DebugLog.Lines = new List<string>(); } DebugLog.Lines.Add(format); Debug.WriteLine(format); } catch { } } } }
mit
C#
a51e5a1b0d08f5eb619f0c4437250054da115904
Extend ZipException as per FxCop suggestion
McNeight/SharpZipLib
src/Zip/ZipException.cs
src/Zip/ZipException.cs
// ZipException.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; #if !COMPACT_FRAMEWORK using System.Runtime.Serialization; #endif namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// Represents errors specific to Zip file handling /// </summary> #if !COMPACT_FRAMEWORK [Serializable] #endif public class ZipException : SharpZipBaseException { #if !COMPACT_FRAMEWORK /// <summary> /// Deserialization constructor /// </summary> /// <param name="info"><see cref="SerializationInfo"/> for this constructor</param> /// <param name="context"><see cref="StreamingContext"/> for this constructor</param> protected ZipException(SerializationInfo info, StreamingContext context ) : base( info, context ) { } #endif /// <summary> /// Initializes a new instance of the ZipException class. /// </summary> public ZipException() { } /// <summary> /// Initializes a new instance of the ZipException class with a specified error message. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> public ZipException(string message) : base(message) { } /// <summary> /// Initialise a new instance of ZipException. /// </summary> /// <param name="message">A message describing the error.</param> /// <param name="exception">The exception that is the cause of the current exception.</param> public ZipException(string message, Exception exception) : base(message, exception) { } } }
// ZipException.cs // // Copyright (C) 2001 Mike Krueger // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 1998, 1999, 2000, 2001 Free Software Foundation, Inc. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; #if !COMPACT_FRAMEWORK using System.Runtime.Serialization; #endif namespace ICSharpCode.SharpZipLib.Zip { /// <summary> /// Represents errors specific to Zip file handling /// </summary> #if !COMPACT_FRAMEWORK [Serializable] #endif public class ZipException : SharpZipBaseException { #if !COMPACT_FRAMEWORK /// <summary> /// Deserialization constructor /// </summary> /// <param name="info"><see cref="SerializationInfo"/> for this constructor</param> /// <param name="context"><see cref="StreamingContext"/> for this constructor</param> protected ZipException(SerializationInfo info, StreamingContext context ) : base( info, context ) { } #endif /// <summary> /// Initializes a new instance of the ZipException class. /// </summary> public ZipException() { } /// <summary> /// Initializes a new instance of the ZipException class with a specified error message. /// </summary> public ZipException(string msg) : base(msg) { } } }
mit
C#
15bf66e0ddbf8e4af45f8337124c49d09718bd38
Change to array
nunit/nunit,mjedrzejek/nunit,mjedrzejek/nunit,nunit/nunit
src/NUnitFramework/framework/Constraints/Comparers/ComparisonState.cs
src/NUnitFramework/framework/Constraints/Comparers/ComparisonState.cs
using System.Collections.Generic; namespace NUnit.Framework.Constraints.Comparers { internal struct ComparisonState { /// <summary> /// Flag indicating whether or not this is the top level comparison. /// </summary> public readonly bool TopLevelComparison; /// <summary> /// A list of tracked comparisons /// </summary> private readonly Comparison[] _comparisons; public ComparisonState(bool topLevelComparison) { TopLevelComparison = topLevelComparison; _comparisons = new Comparison[0]; } private ComparisonState(bool topLevelComparison, Comparison[] comparisons) { TopLevelComparison = topLevelComparison; _comparisons = comparisons; } public ComparisonState PushComparison(bool topLevelComparison, object x, object y) { var comparisons = new Comparison[_comparisons.Length + 1]; _comparisons.CopyTo(comparisons, 0); comparisons[_comparisons.Length] = new Comparison(x, y); return new ComparisonState( topLevelComparison, comparisons ); } public bool DidCompare(object x, object y) { for(var i = 0; i < _comparisons.Length; i++) if (_comparisons[i].X == x && _comparisons[i].Y == y) return true; return false; } private struct Comparison { public object X { get; } public object Y { get; } public Comparison(object x, object y) { X = x; Y = y; } } } }
using System.Collections.Generic; namespace NUnit.Framework.Constraints.Comparers { internal struct ComparisonState { /// <summary> /// Flag indicating whether or not this is the top level comparison. /// </summary> public readonly bool TopLevelComparison; /// <summary> /// A list of tracked comparisons /// </summary> private readonly List<Comparison> _comparisons; public ComparisonState(bool topLevelComparison) { TopLevelComparison = topLevelComparison; _comparisons = new List<Comparison>(); } private ComparisonState(bool topLevelComparison, List<Comparison> comparisons) { TopLevelComparison = topLevelComparison; _comparisons = comparisons; } public ComparisonState PushComparison(bool topLevelComparison, object x, object y) { var comparisons = new List<Comparison>(); comparisons.AddRange(_comparisons); comparisons.Add(new Comparison(x, y)); return new ComparisonState( topLevelComparison, comparisons ); } public bool DidCompare(object x, object y) { foreach (var item in _comparisons) if (item.X == x && item.Y == y) return true; return false; } private struct Comparison { public object X { get; } public object Y { get; } public Comparison(object x, object y) { X = x; Y = y; } } } }
mit
C#
42477f5a34b7bb813450a6ebaba20386eafde14c
Remove unused using
ludwigjossieaux/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,picklesdoc/pickles,picklesdoc/pickles,magicmonty/pickles,magicmonty/pickles,magicmonty/pickles,magicmonty/pickles,dirkrombauts/pickles,dirkrombauts/pickles
src/Pickles/Pickles.TestFrameworks/MsTest/MsTestSingleResultLoader.cs
src/Pickles/Pickles.TestFrameworks/MsTest/MsTestSingleResultLoader.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MsTestSingleResultLoader.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO.Abstractions; namespace PicklesDoc.Pickles.TestFrameworks.MsTest { public class MsTestSingleResultLoader : ISingleResultLoader { private readonly XDocumentLoader documentLoader = new XDocumentLoader(); public SingleTestRunBase Load(FileInfoBase fileInfo) { return new MsTestSingleResults(this.documentLoader.Load(fileInfo)); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MsTestSingleResultLoader.cs" company="PicklesDoc"> // Copyright 2011 Jeffrey Cameron // Copyright 2012-present PicklesDoc team and community contributors // // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.IO.Abstractions; using PicklesDoc.Pickles.ObjectModel; namespace PicklesDoc.Pickles.TestFrameworks.MsTest { public class MsTestSingleResultLoader : ISingleResultLoader { private readonly XDocumentLoader documentLoader = new XDocumentLoader(); public SingleTestRunBase Load(FileInfoBase fileInfo) { return new MsTestSingleResults(this.documentLoader.Load(fileInfo)); } } }
apache-2.0
C#
04471959736ebf8f16d4c42317a33415dc200554
Update FSharpCompletionOptions.cs
agocke/roslyn,mgoertz-msft/roslyn,physhi/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,weltkante/roslyn,sharwell/roslyn,bartdesmet/roslyn,aelij/roslyn,wvdd007/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,dotnet/roslyn,davkean/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,brettfo/roslyn,abock/roslyn,tmat/roslyn,AmadeusW/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,diryboy/roslyn,agocke/roslyn,panopticoncentral/roslyn,diryboy/roslyn,aelij/roslyn,gafter/roslyn,AmadeusW/roslyn,abock/roslyn,aelij/roslyn,sharwell/roslyn,brettfo/roslyn,tmat/roslyn,heejaechang/roslyn,dotnet/roslyn,weltkante/roslyn,eriawan/roslyn,stephentoub/roslyn,stephentoub/roslyn,physhi/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,heejaechang/roslyn,gafter/roslyn,davkean/roslyn,bartdesmet/roslyn,dotnet/roslyn,AmadeusW/roslyn,genlu/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,genlu/roslyn,brettfo/roslyn,genlu/roslyn,AlekseyTs/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,physhi/roslyn,eriawan/roslyn,agocke/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,nguerrera/roslyn,davkean/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,jmarolf/roslyn,abock/roslyn,tannergooding/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,gafter/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,wvdd007/roslyn
src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs
src/Tools/ExternalAccess/FSharp/Completion/FSharpCompletionOptions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCompletionOptions { public static PerLanguageOption<bool> BlockForCompletionItems => Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Completion { internal static class FSharpCompletionOptions { public static PerLanguageOption<bool> BlockForCompletionItems = Microsoft.CodeAnalysis.Completion.CompletionOptions.BlockForCompletionItems; } }
mit
C#
ef4ee8eca8c3dc923e68e6d8faee511ca179a25e
update ForwardedTypes.cs
stanley-cheung/grpc,pszemus/grpc,ejona86/grpc,stanley-cheung/grpc,donnadionne/grpc,grpc/grpc,donnadionne/grpc,vjpai/grpc,donnadionne/grpc,sreecha/grpc,jboeuf/grpc,jtattermusch/grpc,stanley-cheung/grpc,jtattermusch/grpc,sreecha/grpc,firebase/grpc,jboeuf/grpc,stanley-cheung/grpc,jboeuf/grpc,ejona86/grpc,jtattermusch/grpc,nicolasnoble/grpc,vjpai/grpc,pszemus/grpc,ctiller/grpc,firebase/grpc,ctiller/grpc,nicolasnoble/grpc,firebase/grpc,grpc/grpc,muxi/grpc,grpc/grpc,jboeuf/grpc,grpc/grpc,firebase/grpc,muxi/grpc,vjpai/grpc,nicolasnoble/grpc,pszemus/grpc,grpc/grpc,ejona86/grpc,vjpai/grpc,firebase/grpc,pszemus/grpc,ejona86/grpc,grpc/grpc,nicolasnoble/grpc,grpc/grpc,ejona86/grpc,ctiller/grpc,pszemus/grpc,firebase/grpc,grpc/grpc,jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,vjpai/grpc,pszemus/grpc,vjpai/grpc,pszemus/grpc,vjpai/grpc,vjpai/grpc,jtattermusch/grpc,muxi/grpc,vjpai/grpc,pszemus/grpc,jtattermusch/grpc,stanley-cheung/grpc,ejona86/grpc,sreecha/grpc,sreecha/grpc,stanley-cheung/grpc,muxi/grpc,donnadionne/grpc,pszemus/grpc,firebase/grpc,jtattermusch/grpc,sreecha/grpc,donnadionne/grpc,firebase/grpc,jtattermusch/grpc,stanley-cheung/grpc,sreecha/grpc,jtattermusch/grpc,vjpai/grpc,nicolasnoble/grpc,donnadionne/grpc,muxi/grpc,muxi/grpc,donnadionne/grpc,donnadionne/grpc,jboeuf/grpc,pszemus/grpc,muxi/grpc,ctiller/grpc,nicolasnoble/grpc,jboeuf/grpc,sreecha/grpc,muxi/grpc,donnadionne/grpc,nicolasnoble/grpc,grpc/grpc,donnadionne/grpc,jtattermusch/grpc,jboeuf/grpc,ctiller/grpc,ctiller/grpc,firebase/grpc,stanley-cheung/grpc,jboeuf/grpc,pszemus/grpc,muxi/grpc,jboeuf/grpc,grpc/grpc,ctiller/grpc,stanley-cheung/grpc,grpc/grpc,grpc/grpc,ejona86/grpc,sreecha/grpc,nicolasnoble/grpc,muxi/grpc,ejona86/grpc,nicolasnoble/grpc,nicolasnoble/grpc,sreecha/grpc,sreecha/grpc,ctiller/grpc,sreecha/grpc,firebase/grpc,donnadionne/grpc,nicolasnoble/grpc,muxi/grpc,nicolasnoble/grpc,vjpai/grpc,jtattermusch/grpc,vjpai/grpc,jboeuf/grpc,donnadionne/grpc,sreecha/grpc,firebase/grpc,stanley-cheung/grpc,jtattermusch/grpc,ctiller/grpc,jboeuf/grpc,pszemus/grpc,stanley-cheung/grpc,jboeuf/grpc,ejona86/grpc,ctiller/grpc,ejona86/grpc,ejona86/grpc,firebase/grpc,ejona86/grpc,ctiller/grpc,muxi/grpc
src/csharp/Grpc.Core/ForwardedTypes.cs
src/csharp/Grpc.Core/ForwardedTypes.cs
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Runtime.CompilerServices; using Grpc.Core; using Grpc.Core.Internal; using Grpc.Core.Utils; // API types that used to be in Grpc.Core package, but were moved to Grpc.Core.Api // https://docs.microsoft.com/en-us/dotnet/framework/app-domains/type-forwarding-in-the-common-language-runtime [assembly:TypeForwardedToAttribute(typeof(GrpcPreconditions))] [assembly:TypeForwardedToAttribute(typeof(AsyncClientStreamingCall<,>))] [assembly:TypeForwardedToAttribute(typeof(AsyncDuplexStreamingCall<,>))] [assembly:TypeForwardedToAttribute(typeof(AsyncServerStreamingCall<>))] [assembly:TypeForwardedToAttribute(typeof(AsyncUnaryCall<>))] [assembly:TypeForwardedToAttribute(typeof(AuthContext))] [assembly:TypeForwardedToAttribute(typeof(AuthInterceptorContext))] [assembly: TypeForwardedToAttribute(typeof(CallCredentials))] [assembly: TypeForwardedToAttribute(typeof(CallFlags))] [assembly: TypeForwardedToAttribute(typeof(CallInvoker))] [assembly: TypeForwardedToAttribute(typeof(CallOptions))] [assembly:TypeForwardedToAttribute(typeof(ContextPropagationOptions))] [assembly:TypeForwardedToAttribute(typeof(ContextPropagationToken))] [assembly:TypeForwardedToAttribute(typeof(DeserializationContext))] [assembly:TypeForwardedToAttribute(typeof(IAsyncStreamReader<>))] [assembly:TypeForwardedToAttribute(typeof(IAsyncStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(IClientStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(IServerStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(Marshaller<>))] [assembly:TypeForwardedToAttribute(typeof(Marshallers))] [assembly:TypeForwardedToAttribute(typeof(Metadata))] [assembly:TypeForwardedToAttribute(typeof(MethodType))] [assembly:TypeForwardedToAttribute(typeof(IMethod))] [assembly:TypeForwardedToAttribute(typeof(Method<,>))] [assembly:TypeForwardedToAttribute(typeof(RpcException))] [assembly:TypeForwardedToAttribute(typeof(SerializationContext))] [assembly:TypeForwardedToAttribute(typeof(ServerCallContext))] [assembly:TypeForwardedToAttribute(typeof(UnaryServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ClientStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ServerStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(DuplexStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ServerServiceDefinition))] [assembly:TypeForwardedToAttribute(typeof(ServiceBinderBase))] [assembly:TypeForwardedToAttribute(typeof(Status))] [assembly:TypeForwardedToAttribute(typeof(StatusCode))] [assembly:TypeForwardedToAttribute(typeof(VersionInfo))] [assembly:TypeForwardedToAttribute(typeof(WriteOptions))] [assembly:TypeForwardedToAttribute(typeof(WriteFlags))]
#region Copyright notice and license // Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System.Runtime.CompilerServices; using Grpc.Core; using Grpc.Core.Logging; using Grpc.Core.Utils; // API types that used to be in Grpc.Core package, but were moved to Grpc.Core.Api // https://docs.microsoft.com/en-us/dotnet/framework/app-domains/type-forwarding-in-the-common-language-runtime // TODO(jtattermusch): move types needed for implementing a client // TODO: problematic areas: // - CallOptions depends on CallCredentials (publicly) and on CallFlags (internally) & CallOptions is a struct // - internal method CallOptions.Normalize() uses internal method propagationToken.AsImplOrNull() [assembly:TypeForwardedToAttribute(typeof(GrpcPreconditions))] [assembly:TypeForwardedToAttribute(typeof(AsyncClientStreamingCall<,>))] [assembly:TypeForwardedToAttribute(typeof(AsyncDuplexStreamingCall<,>))] [assembly:TypeForwardedToAttribute(typeof(AsyncServerStreamingCall<>))] [assembly:TypeForwardedToAttribute(typeof(AsyncUnaryCall<>))] [assembly:TypeForwardedToAttribute(typeof(AuthContext))] [assembly:TypeForwardedToAttribute(typeof(ContextPropagationOptions))] [assembly:TypeForwardedToAttribute(typeof(ContextPropagationToken))] [assembly:TypeForwardedToAttribute(typeof(DeserializationContext))] [assembly:TypeForwardedToAttribute(typeof(IAsyncStreamReader<>))] [assembly:TypeForwardedToAttribute(typeof(IAsyncStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(IClientStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(IServerStreamWriter<>))] [assembly:TypeForwardedToAttribute(typeof(Marshaller<>))] [assembly:TypeForwardedToAttribute(typeof(Marshallers))] [assembly:TypeForwardedToAttribute(typeof(Metadata))] [assembly:TypeForwardedToAttribute(typeof(MethodType))] [assembly:TypeForwardedToAttribute(typeof(IMethod))] [assembly:TypeForwardedToAttribute(typeof(Method<,>))] [assembly:TypeForwardedToAttribute(typeof(RpcException))] [assembly:TypeForwardedToAttribute(typeof(SerializationContext))] [assembly:TypeForwardedToAttribute(typeof(ServerCallContext))] [assembly:TypeForwardedToAttribute(typeof(UnaryServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ClientStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ServerStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(DuplexStreamingServerMethod<,>))] [assembly:TypeForwardedToAttribute(typeof(ServerServiceDefinition))] [assembly:TypeForwardedToAttribute(typeof(ServiceBinderBase))] [assembly:TypeForwardedToAttribute(typeof(Status))] [assembly:TypeForwardedToAttribute(typeof(StatusCode))] [assembly:TypeForwardedToAttribute(typeof(VersionInfo))] [assembly:TypeForwardedToAttribute(typeof(WriteOptions))] [assembly:TypeForwardedToAttribute(typeof(WriteFlags))]
apache-2.0
C#
f1fc8dda89cbe3af9d7d7bf6798c44452d1c8529
Introduce per-coin-config miner parameters
IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner
MultiMiner.Engine/Configuration/CoinConfiguration.cs
MultiMiner.Engine/Configuration/CoinConfiguration.cs
using MultiMiner.Xgminer; using System.Collections.Generic; namespace MultiMiner.Engine.Configuration { public class CoinConfiguration { public CoinConfiguration() { this.Pools = new List<MiningPool>(); } public CryptoCoin Coin { get; set; } public List<MiningPool> Pools { get; set; } public string MinerFlags { get; set; } } }
using MultiMiner.Xgminer; using System.Collections.Generic; namespace MultiMiner.Engine.Configuration { public class CoinConfiguration { public CoinConfiguration() { this.Pools = new List<MiningPool>(); } public CryptoCoin Coin { get; set; } public List<MiningPool> Pools { get; set; } } }
mit
C#
6110fe9c365304c1358c1752af09e8cfee60632a
add more consul endpoint acceptance tests
Pondidum/OctopusStore,Pondidum/OctopusStore
OctopusStore.Tests/Acceptance/ConsulEndpointTests.cs
OctopusStore.Tests/Acceptance/ConsulEndpointTests.cs
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.Owin.Testing; using Newtonsoft.Json; using OctopusStore.Consul; using Owin; using Shouldly; using Xunit; namespace OctopusStore.Tests { public class ConsulEndpointTests : IDisposable { private readonly TestServer _server; //https://www.consul.io/intro/getting-started/kv.html public ConsulEndpointTests() { _server = TestServer.Create(app => { var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); }); } private HttpResponseMessage Request(HttpMethod method, string url) { return _server .HttpClient .SendAsync(new HttpRequestMessage(method, url)) .Result; } private T BodyOf<T>(HttpResponseMessage response) { var json = response .Content .ReadAsStringAsync() .Result; return JsonConvert.DeserializeObject<T>(json); } [Fact] public void When_there_are_no_keys() { Request(HttpMethod.Get, "v1/kv/?recurse").StatusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] public void When_getting_keys_after_putting() { Request(HttpMethod.Put, "v1/kv/web/key1").StatusCode.ShouldBe(HttpStatusCode.OK); Request(HttpMethod.Put, "v1/kv/web/key2?flags=42").StatusCode.ShouldBe(HttpStatusCode.OK); Request(HttpMethod.Put, "v1/kv/web/sub/key3").StatusCode.ShouldBe(HttpStatusCode.OK); var response = Request(HttpMethod.Get, "v1/kv/?recurse"); var body = BodyOf<IEnumerable<ValueModel>>(response); body.ShouldBe(new[] { new ValueModel(), new ValueModel(), new ValueModel(), }); } [Fact] public void When_getting_a_single_key() { Request(HttpMethod.Put, "v1/kv/web/key1").StatusCode.ShouldBe(HttpStatusCode.OK); var response = Request(HttpMethod.Get, "v1/kv/web/key1"); var body = BodyOf<IEnumerable<ValueModel>>(response); body.ShouldBe(new[] { new ValueModel(), }); } [Fact] public void When_deleting_a_key() { Request(HttpMethod.Delete, "v1/kv/web/key1").StatusCode.ShouldBe(HttpStatusCode.MethodNotAllowed); } public void Dispose() { _server.Dispose(); } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using Microsoft.Owin.Testing; using Newtonsoft.Json; using OctopusStore.Consul; using Owin; using Shouldly; using Xunit; namespace OctopusStore.Tests { public class ConsulEndpointTests : IDisposable { private readonly TestServer _server; //https://www.consul.io/intro/getting-started/kv.html public ConsulEndpointTests() { _server = TestServer.Create(app => { var config = new HttpConfiguration(); WebApiConfig.Register(config); app.UseWebApi(config); }); } private HttpResponseMessage Request(HttpMethod method, string url) { return _server .HttpClient .SendAsync(new HttpRequestMessage(method, url)) .Result; } private T BodyOf<T>(HttpResponseMessage response) { var json = response .Content .ReadAsStringAsync() .Result; return JsonConvert.DeserializeObject<T>(json); } [Fact] public void When_there_are_no_keys() { Request(HttpMethod.Get, "v1/kv/?recurse").StatusCode.ShouldBe(HttpStatusCode.NotFound); } [Fact] public void When_getting_keys_after_putting() { Request(HttpMethod.Put, "v1/kv/web/key1").StatusCode.ShouldBe(HttpStatusCode.OK); Request(HttpMethod.Put, "v1/kv/web/key2?flags=42").StatusCode.ShouldBe(HttpStatusCode.OK); Request(HttpMethod.Put, "v1/kv/web/sub/key3").StatusCode.ShouldBe(HttpStatusCode.OK); var response = Request(HttpMethod.Get, "v1/kv/?recurse"); var body = BodyOf<IEnumerable<ValueModel>>(response); body.ShouldBe(new[] { new ValueModel(), new ValueModel(), new ValueModel(), }); } public void Dispose() { _server.Dispose(); } } }
lgpl-2.1
C#
6b8377ce0acc61174fa72fb988d1971eda7f2436
fix redundant code
eclaus/docs.particular.net,WojcikMike/docs.particular.net
Snippets/Snippets_5/Features/FeatureConfiguration.cs
Snippets/Snippets_5/Features/FeatureConfiguration.cs
// ReSharper disable UnusedParameter.Local namespace Snippets5.Features { using System; using NServiceBus; using NServiceBus.Config; using NServiceBus.Features; using NServiceBus.Pipeline; class SecondLevelRetries : Feature { #region FeatureConfiguration public SecondLevelRetries() { EnableByDefault(); DependsOn<DelayedDeliveryFeature>(); Prerequisite(context => !context.Settings.GetOrDefault<bool>("Endpoint.SendOnly"), "Send only endpoints can't use SLR since it requires receive capabilities"); } #endregion #region FeatureSetup protected override void Setup(FeatureConfigurationContext context) { var retriesConfig = context.Settings.GetConfigSection<SecondLevelRetriesConfig>(); var retryPolicy = new SecondLevelRetryPolicy(retriesConfig.NumberOfRetries, retriesConfig.TimeIncrease); context.Container.RegisterSingleton(typeof(SecondLevelRetryPolicy), retryPolicy); context.Pipeline.Register<SecondLevelRetriesBehavior.Registration>(); } #endregion void EndpointConfiguration() { #region EnableDisableFeatures var configuration = new BusConfiguration(); // enable delayed delivery feature since SLR relies on it configuration.EnableFeature<DelayedDeliveryFeature>(); // this is not required if the feature uses EnableByDefault() configuration.EnableFeature<SecondLevelRetries>(); // we can disable features we won't use configuration.DisableFeature<Sagas>(); var bus = Bus.Create(configuration); #endregion } class SecondLevelRetriesBehavior { public class Registration : RegisterStep { public Registration() : base(string.Empty, typeof(object), null) { } } } class SecondLevelRetryPolicy { public SecondLevelRetryPolicy(int numberOfRetries, TimeSpan timeIncrease) { } } class DelayedDeliveryFeature : Feature { protected override void Setup(FeatureConfigurationContext context) { throw new NotImplementedException(); } } } }
namespace Snippets5.Features { using System; using NServiceBus; using NServiceBus.Config; using NServiceBus.Features; using NServiceBus.Pipeline; class SecondLevelRetries : Feature { #region FeatureConfiguration public SecondLevelRetries() { EnableByDefault(); DependsOn<DelayedDeliveryFeature>(); Prerequisite(context => !context.Settings.GetOrDefault<bool>("Endpoint.SendOnly"), "Send only endpoints can't use SLR since it requires receive capabilities"); } #endregion #region FeatureSetup protected override void Setup(FeatureConfigurationContext context) { var retriesConfig = context.Settings.GetConfigSection<SecondLevelRetriesConfig>(); var retryPolicy = new SecondLevelRetryPolicy(retriesConfig.NumberOfRetries, retriesConfig.TimeIncrease); context.Container.RegisterSingleton(typeof(SecondLevelRetryPolicy), retryPolicy); context.Pipeline.Register<SecondLevelRetriesBehavior.Registration>(); } #endregion void EndpointConfiguration() { #region EnableDisableFeatures var configuration = new BusConfiguration(); // enable delayed delivery feature since SLR relies on it configuration.EnableFeature<DelayedDeliveryFeature>(); // this is not required if the feature uses EnableByDefault() configuration.EnableFeature<SecondLevelRetries>(); // we can disable features we won't use configuration.DisableFeature<Sagas>(); var bus = Bus.Create(configuration); #endregion } class SecondLevelRetriesBehavior { public class Registration : RegisterStep { public Registration() : base(string.Empty, typeof(object), null) { } } } class SecondLevelRetryPolicy { public SecondLevelRetryPolicy(int numberOfRetries, TimeSpan timeIncrease) { } } class DelayedDeliveryFeature : Feature { protected override void Setup(FeatureConfigurationContext context) { throw new NotImplementedException(); } } } }
apache-2.0
C#
92213141e5e306507a4c2979acce4debb88a2b44
add eq
autumn009/TanoCSharpSamples
chap36/PatternMatching/PatternMatching/Program.cs
chap36/PatternMatching/PatternMatching/Program.cs
using System; using System.Linq; class Program { static bool IsLetterOld(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; static bool IsLetterNew(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z'; static void Main() { // and/or sample for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterOld((char)i) ? '1' : '0')}"); Console.WriteLine(); for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterNew((char)i) ? '1' : '0')}"); Console.WriteLine(); // is not null object a1 = null, a2 = ""; bool b1 = a1 is not null; bool b2 = a2 is not null; Console.WriteLine($"{b1},{b2}"); // is int and/or test(1); test(101); test("1"); void test(object p) { if (p is int x and <= 100) Console.WriteLine($"{p}+1 is {x + 1}"); else Console.WriteLine($"{p} is not the condition"); } // property pattern string[] s = { null, "", "Hello" }; foreach (var item in s) Console.WriteLine(item is { Length: > 1 }); // relational pattern int[] ages = { 10, 30, 70 }; foreach (var item in ages) { #if true Console.WriteLine(item switch { < 20 => "CHILD", >= 20 and < 60 => "ADULT", >= 60 => "OLDMAN" }); #else if (item < 20) Console.WriteLine("CHILD"); else if (item >= 20 && item < 60) Console.WriteLine("ADULT"); else if (item >= 60) Console.WriteLine("OLDMAN"); #endif } } }
using System; using System.Linq; class Program { static bool IsLetterOld(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z'; static bool IsLetterNew(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z'; static void Main() { // and/or sample for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterOld((char)i) ? '1' : '0')}"); Console.WriteLine(); for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterNew((char)i) ? '1' : '0')}"); Console.WriteLine(); // is not null object a1 = null, a2 = ""; bool b1 = a1 is not null; bool b2 = a2 is not null; Console.WriteLine($"{b1},{b2}"); // is int and/or test(1); test(101); test("1"); void test(object p) { if (p is int x and <= 100) Console.WriteLine($"{p}+1 is {x + 1}"); else Console.WriteLine($"{p} is not the condition"); } // property pattern string[] s = { null, "", "Hello" }; foreach (var item in s) Console.WriteLine(item is { Length: > 1 }); // relational pattern int[] ages = { 10, 30, 70 }; foreach (var item in ages) { Console.WriteLine(item switch { < 20 => "CHILD", >= 20 and < 60 => "ADULT", >= 60 => "OLDMAN" }); } } }
mit
C#
f258da3a8ba6758d8eb3aadc52fa4547e09a9577
Allow users to provide an implementation of the ILibiMobileDeviceAPI.
libimobiledevice-win32/imobiledevice-net,libimobiledevice-win32/imobiledevice-net
iMobileDevice-net/Utf8Marshal.cs
iMobileDevice-net/Utf8Marshal.cs
using System; using System.Runtime.InteropServices; using System.Text; namespace iMobileDevice { /// <summary> /// Provides marshalling capabilities for UTF-8 strings. /// </summary> public static class Utf8Marshal { /// <summary> /// Converts a pointer to an UTF-8 string. /// </summary> /// <param name="value"> /// The value to marshal. /// </param> /// <returns> /// A <see cref="string"/> which represents the underlying string. /// </returns> public static string PtrToStringUtf8(IntPtr value) { return PtrToStringUtf8(value, LibiMobileDevice.Instance); } /// <summary> /// Converts a pointer to an UTF-8 string. /// </summary> /// <param name="value"> /// The value to marshal. /// </param> /// <param name="api"> /// The libimobiledevice API to use when marshalling. /// </param> /// <returns> /// A <see cref="string"/> which represents the underlying string. /// </returns> public static string PtrToStringUtf8(IntPtr value, ILibiMobileDevice api) { if (value == IntPtr.Zero) { return null; } if (api == null) { throw new ArgumentNullException(nameof(api)); } ulong size = 0; api.Pinvoke.pinvoke_get_string_length(value, out size); byte[] data = new byte[size]; Marshal.Copy(value, data, 0, (int)size); string result = Encoding.UTF8.GetString(data); return result; } /// <summary> /// Converts a value to an UTF-8 string, in native memory. /// </summary> /// <param name="value"> /// The value to encode. /// </param> /// <returns> /// A pointer to the UTF-8 string in unmanaged memory. You must free this pointer /// using <see cref="Marshal.FreeHGlobal(IntPtr)"/>. /// </returns> public static IntPtr StringToHGlobalUtf8(string value) { if (value == null) { return IntPtr.Zero; } byte[] data = Encoding.UTF8.GetBytes(value + '\0'); // Make sure the string is 0-terminated IntPtr handle = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, handle, data.Length); return handle; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace iMobileDevice { public static class Utf8Marshal { public static string PtrToStringUtf8(IntPtr value) { if (value == IntPtr.Zero) { return null; } ulong size = 0; LibiMobileDevice.Instance.Pinvoke.pinvoke_get_string_length(value, out size); byte[] data = new byte[size]; Marshal.Copy(value, data, 0, (int)size); string result = Encoding.UTF8.GetString(data); return result; } public static IntPtr StringToHGlobalUtf8(string value) { if (value == null) { return IntPtr.Zero; } byte[] data = Encoding.UTF8.GetBytes(value + '\0'); // Make sure the string is 0-terminated IntPtr handle = Marshal.AllocHGlobal(data.Length); Marshal.Copy(data, 0, handle, data.Length); return handle; } } }
lgpl-2.1
C#
4baf0b776a01e085040122053c79a6de51e9ab68
comment fix - not to treat field as method
Aprogiena/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode
Stratis.Bitcoin/Builder/Feature/FeatureCollection.cs
Stratis.Bitcoin/Builder/Feature/FeatureCollection.cs
using System; using System.Collections.Generic; using System.Linq; using Stratis.Bitcoin.Utilities; using System.Globalization; namespace Stratis.Bitcoin.Builder.Feature { /// <summary> /// Defines methods for collection of features of the FullNode. /// </summary> public interface IFeatureCollection { /// <summary>List of features already registered in the collection.</summary> List<IFeatureRegistration> FeatureRegistrations { get; } /// <summary>Adds a new feature to the collection provided that the feature of the same type has not been added already.</summary> /// <typeparam name="TImplementation">Type of the feature to be added to the collection.</typeparam> /// <returns>Representation of the registered feature.</returns> IFeatureRegistration AddFeature<TImplementation>() where TImplementation : class, IFullNodeFeature; } /// <summary> /// Collection of features available to and/or used by the FullNode. /// </summary> public class FeatureCollection : IFeatureCollection { /// <summary>List of features already registered in the collection.</summary> private readonly List<IFeatureRegistration> featureRegistrations; /// <summary>Initializes the object instance.</summary> public FeatureCollection() { this.featureRegistrations = new List<IFeatureRegistration>(); } /// <summary>List of features already registered in the collection.</summary> public List<IFeatureRegistration> FeatureRegistrations { get { return this.featureRegistrations; } } /// <summary>Adds a new feature to the collection provided that the feature of the same type has not been added already.</summary> /// <typeparam name="TImplementation">Type of the feature to be added to the collection.</typeparam> /// <returns>Representation of the registered feature.</returns> public IFeatureRegistration AddFeature<TImplementation>() where TImplementation : class, IFullNodeFeature { if (this.featureRegistrations.Any(f => f.FeatureType == typeof(TImplementation))) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Feature of type {0} has already been registered.", typeof(TImplementation).FullName)); var featureRegistration = new FeatureRegistration<TImplementation>(); this.featureRegistrations.Add(featureRegistration); return featureRegistration; } } }
using System; using System.Collections.Generic; using System.Linq; using Stratis.Bitcoin.Utilities; using System.Globalization; namespace Stratis.Bitcoin.Builder.Feature { /// <summary> /// Defines methods for collection of features of the FullNode. /// </summary> public interface IFeatureCollection { /// <summary>Obtains the list of features already registered in the collection.</summary> List<IFeatureRegistration> FeatureRegistrations { get; } /// <summary>Adds a new feature to the collection provided that the feature of the same type has not been added already.</summary> /// <typeparam name="TImplementation">Type of the feature to be added to the collection.</typeparam> /// <returns>Representation of the registered feature.</returns> IFeatureRegistration AddFeature<TImplementation>() where TImplementation : class, IFullNodeFeature; } /// <summary> /// Collection of features available to and/or used by the FullNode. /// </summary> public class FeatureCollection : IFeatureCollection { /// <summary>List of features already registered in the collection.</summary> private readonly List<IFeatureRegistration> featureRegistrations; /// <summary>Initializes the object instance.</summary> public FeatureCollection() { this.featureRegistrations = new List<IFeatureRegistration>(); } /// <summary>Obtains the list of features already registered in the collection.</summary> public List<IFeatureRegistration> FeatureRegistrations { get { return this.featureRegistrations; } } /// <summary>Adds a new feature to the collection provided that the feature of the same type has not been added already.</summary> /// <typeparam name="TImplementation">Type of the feature to be added to the collection.</typeparam> /// <returns>Representation of the registered feature.</returns> public IFeatureRegistration AddFeature<TImplementation>() where TImplementation : class, IFullNodeFeature { if (this.featureRegistrations.Any(f => f.FeatureType == typeof(TImplementation))) throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Feature of type {0} has already been registered.", typeof(TImplementation).FullName)); var featureRegistration = new FeatureRegistration<TImplementation>(); this.featureRegistrations.Add(featureRegistration); return featureRegistration; } } }
mit
C#
ce7e1c699d9d56492690f9ad8bc69ccd4706fe42
Remove Obselete ViewModel Property for SendGrid Password
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
Portal.CMS.Web/Areas/Admin/ViewModels/SettingManager/SetupViewModel.cs
Portal.CMS.Web/Areas/Admin/ViewModels/SettingManager/SetupViewModel.cs
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Portal.CMS.Web.Areas.Admin.ViewModels.SettingManager { public class SetupViewModel { [Required] [DisplayName("Website Name")] public string WebsiteName { get; set; } [Required] [DisplayName("Website Description")] public string WebsiteDescription { get; set; } [DisplayName("Google Tracking Code")] public string GoogleAnalyticsId { get; set; } [DisplayName("Email From Address")] public string EmailFromAddress { get; set; } [DisplayName("SendGrid API Key")] public string SendGridApiKey { get; set; } [DisplayName("SendGrid Password")] public string SendGridPassword { get; set; } [DisplayName("CDN Address")] public string CDNAddress { get; set; } } }
mit
C#
b471e55ce8a7f76b9024da00cecf18d25a58edcb
Bump version to 0.9.11
rpaquay/mtsuite
src/core-filesystem/VersionNumber.cs
src/core-filesystem/VersionNumber.cs
// Copyright 2015 Renaud Paquay All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace mtsuite.CoreFileSystem { public static class VersionNumber { public const string Product = "0.9.11"; public const string File = Product + ".0"; } }
// Copyright 2015 Renaud Paquay All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace mtsuite.CoreFileSystem { public static class VersionNumber { public const string Product = "0.9.10"; public const string File = Product + ".0"; } }
apache-2.0
C#
d3006d320d59cd94e9f3bba46698c8eef7bc3000
Build fix
alexandrnikitin/MPMCQueue.NET,alexandrnikitin/MPMCQueue.NET
sandbox/MPMCQueue.NET.SandboxApp/Program.cs
sandbox/MPMCQueue.NET.SandboxApp/Program.cs
using System; using System.Runtime.CompilerServices; namespace MPMCQueue.NET.SandboxApp { class Program { static void Main(string[] args) { var queue = new MPMCQueue<bool>(65536); Wrapper.Enqueue(queue); Wrapper.Dequeue(queue); Console.ReadKey(); } } public class Wrapper { [MethodImpl(MethodImplOptions.NoInlining)] public static void Enqueue(MPMCQueue<bool> queue) { queue.TryEnqueue(true); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Dequeue(MPMCQueue<bool> queue) { bool ret; queue.TryDequeue(out ret); } } }
using System; using System.Runtime.CompilerServices; namespace MPMCQueue.NET.SandboxApp { class Program { static void Main(string[] args) { var queue = new Sandbox.V2.MPMCQueue<bool>(65536); Wrapper.Enqueue(queue); Wrapper.Dequeue(queue); Console.ReadKey(); } } public class Wrapper { [MethodImpl(MethodImplOptions.NoInlining)] public static void Enqueue(Sandbox.V2.MPMCQueue<bool> queue) { queue.TryEnqueue(true); } [MethodImpl(MethodImplOptions.NoInlining)] public static void Dequeue(Sandbox.V2.MPMCQueue<bool> queue) { bool ret; queue.TryDequeue(out ret); } } }
mit
C#
6f78091580f5dc8b6ff89e803d87428985e8866f
Enable Mongo entity auto-create and auto-ID
jorupp/conference-room,jorupp/conference-room,RightpointLabs/conference-room,RightpointLabs/conference-room,RightpointLabs/conference-room,jorupp/conference-room,jorupp/conference-room,RightpointLabs/conference-room
Infrastructure/Persistence/Collections/EntityCollectionDefinition.cs
Infrastructure/Persistence/Collections/EntityCollectionDefinition.cs
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName, new MongoCollectionSettings() { AssignIdOnInsert = true}); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { if (!Collection.Exists()) { // ReSharper disable once VirtualMemberCallInConstructor Collection.Database.CreateCollection(CollectionName); } try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } }
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.Serialization.IdGenerators; using MongoDB.Bson.Serialization.Serializers; using MongoDB.Driver; using RightpointLabs.ConferenceRoom.Domain.Models; using RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Models; namespace RightpointLabs.ConferenceRoom.Infrastructure.Persistence.Collections { public abstract class EntityCollectionDefinition<T> where T : Entity { protected EntityCollectionDefinition(IMongoConnectionHandler connectionHandler) { if (connectionHandler == null) throw new ArgumentNullException("connectionHandler"); // ReSharper disable once VirtualMemberCallInConstructor Collection = connectionHandler.Database.GetCollection<T>(CollectionName); // setup serialization if (!BsonClassMap.IsClassMapRegistered(typeof(Entity))) { try { BsonClassMap.RegisterClassMap<Entity>( cm => { cm.AutoMap(); cm.SetIdMember(cm.GetMemberMap(i => i.Id)); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); }); } catch (ArgumentException) { // this fails with an argument exception at startup, but otherwise works fine. Probably should try to figure out why, but ignoring it is easier :( } } } public readonly MongoCollection<T> Collection; protected virtual string CollectionName => typeof(T).Name.Replace("Entity", "").ToLower() + "s"; } }
mit
C#
e13a21b8cc3fc5ff93c9d5832180bc75e86fe605
Test case for issue #4
cityindex-attic/CIAPI.CS,cityindex-attic/CIAPI.CS,cityindex-attic/CIAPI.CS
src/CIAPI.IntegrationTests/Rpc/ErrorHandlingFixture.cs
src/CIAPI.IntegrationTests/Rpc/ErrorHandlingFixture.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CIAPI.Rpc; using CityIndex.JsonClient; using NUnit.Framework; using Client = CIAPI.Rpc.Client; namespace CIAPI.IntegrationTests.Rpc { [TestFixture] public class ErrorHandlingFixture { private static Uri RPC_URI = new Uri("http://ciapipreprod.cityindextest9.co.uk/TradingApi"); private const string USERNAME_VALID = "DM904310"; private const string PASSWORD_VALID = "password"; [Test] public void ShouldGiveGuidanceWhenSpecifyingInvalidServerName() { try { var rpcClient = new Client(new Uri("http://invalidservername.asiuhd8h38hsh.wam/TradingApi")); rpcClient.LogIn("username", "password"); } catch (Exception ex) { Assert.That(ex, Is.TypeOf(typeof(ServerConnectionException))); Assert.That(ex.Message, Is.StringContaining("server Url"),"Expecting some info explaining that the server Url is invalid"); } } [Test] public void LogOutShouldInvalidateSession() { var rpcClient = new Client(RPC_URI); rpcClient.LogIn(USERNAME_VALID, PASSWORD_VALID); var headlines = rpcClient.ListNewsHeadlines("UK", 3); Assert.That(headlines.Headlines.Length, Is.GreaterThan(0), "you should have a set of headlines"); rpcClient.LogOut(); try { rpcClient.ListNewsHeadlines("AUS", 4); Assert.Fail("the previous line should have thrown an (401) Unauthorized exception"); } catch (ApiException e) { Assert.That(e.Message, Is.StringContaining("(401) Unauthorized"), "The session token should be invalid after logging out"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CIAPI.Rpc; using CityIndex.JsonClient; using NUnit.Framework; using Client = CIAPI.Rpc.Client; namespace CIAPI.IntegrationTests.Rpc { [TestFixture] public class ErrorHandlingFixture { [Test] public void ShouldGiveGuidanceWhenSpecifyingInvalidServerName() { try { var rpcClient = new Client(new Uri("http://invalidservername.asiuhd8h38hsh.wam/TradingApi")); rpcClient.LogIn("username", "password"); } catch (Exception ex) { Assert.That(ex.Message, Is.StringContaining("DNS"),"Expecting some info explaining that the server name used cannot be found in DNS"); } } } }
apache-2.0
C#
e79b2d0f8bdb4b59bf5d1337ecd09cf84407f373
Update NumberFormatting.cs
keith-hall/Extensions,keith-hall/Extensions
src/NumberFormatting.cs
src/NumberFormatting.cs
namespace HallLibrary.Extensions { public static class NumberFormatting { private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture private const char _defaultThousandsSeparator = ','; private const string _defaultDecimalSeparatorForRegex = @"\."; public static string AddThousandsSeparators (string number, string thousandsSeparator = null) { if (_number.IsMatch(number)) { return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); } else { return number; } } /* // Store integer 182 int decValue = 182; // Convert integer 182 as a hex in a string variable string hexValue = decValue.ToString("X"); // doesn't add 0x prefix // Convert the hex string back to the number int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix */ } }
namespace HallLibrary.Extensions { public static class NumberFormatting { private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture private const char _defaultThousandsSeparator = ','; private const string _defaultDecimalSeparatorForRegex = @"\."; public static string AddThousandsSeparators (string number, string thousandsSeparator = null) { if (_number.IsMatch(number)) { return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); } else { return number; } } } }
apache-2.0
C#
6b51a0d5349fd6b5f75ae2d0beaad9811b811e19
Add using
dotnet/roslyn-analyzers,dotnet/roslyn-analyzers
src/PublicApiAnalyzers/Core/Analyzers/PublicApiFile.cs
src/PublicApiAnalyzers/Core/Analyzers/PublicApiFile.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.IO; namespace Microsoft.CodeAnalysis.PublicApiAnalyzers { public readonly struct PublicApiFile { public PublicApiFile(string path) { var fileName = Path.GetFileName(path); IsShipping = IsFile(fileName, DeclarePublicApiAnalyzer.ShippedFileNamePrefix); var isUnshippedFile = IsFile(fileName, DeclarePublicApiAnalyzer.UnshippedFileNamePrefix); IsApiFile = IsShipping || isUnshippedFile; } public bool IsShipping { get; } public bool IsApiFile { get; } private static bool IsFile(string path, string prefix) => path.StartsWith(prefix, StringComparison.Ordinal) && path.EndsWith(DeclarePublicApiAnalyzer.Extension, StringComparison.Ordinal); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. using System; namespace Microsoft.CodeAnalysis.PublicApiAnalyzers { public readonly struct PublicApiFile { public PublicApiFile(string path) { Path = path; var fileName = System.IO.Path.GetFileName(path); IsShipping = IsFile(fileName, DeclarePublicApiAnalyzer.ShippedFileNamePrefix); var isUnshippedFile = IsFile(fileName, DeclarePublicApiAnalyzer.UnshippedFileNamePrefix); IsApiFile = IsShipping || isUnshippedFile; } public string Path { get; } public bool IsShipping { get; } public bool IsApiFile { get; } private static bool IsFile(string path, string prefix) => path.StartsWith(prefix, StringComparison.Ordinal) && path.EndsWith(DeclarePublicApiAnalyzer.Extension, StringComparison.Ordinal); } }
mit
C#
57094af99630c83e0322ed384c143e8816409cbc
stop installation if one task fails
Sitecore/Sitecore-Instance-Manager
src/SIM.Pipelines/Install/RunSitecoreTasksProcessor.cs
src/SIM.Pipelines/Install/RunSitecoreTasksProcessor.cs
using SIM.Pipelines.Processors; using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SIM.Pipelines.Install { public class RunSitecoreTasksProcessor : ProcessorHive { public override IEnumerable<Processor> CreateProcessors(ProcessorArgs args) { Install9Args arguments = (Install9Args)args; List<Processor> processors = new List<Processor>(); arguments.Tasker.EvaluateGlobalParams(); Processor root = null; foreach (SitecoreTask task in arguments.Tasker.Tasks) { if (!task.ShouldRun) { continue; } Processor proc=null; if (arguments.ScriptsOnly) { proc = new GenerateScriptProcessor(task.Name); } else { proc = new RunSitecoreTaskProcessor(task.Name); } proc.Title = task.Name; if (root == null) { processors.Add(proc); } else { root._NestedProcessors.Add(proc); } root = proc; } return processors; } } }
using SIM.Pipelines.Processors; using SIM.Sitecore9Installer; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SIM.Pipelines.Install { public class RunSitecoreTasksProcessor : ProcessorHive { public override IEnumerable<Processor> CreateProcessors(ProcessorArgs args) { Install9Args arguments = (Install9Args)args; List<Processor> processors = new List<Processor>(); arguments.Tasker.EvaluateGlobalParams(); foreach (SitecoreTask task in arguments.Tasker.Tasks) { if (!task.ShouldRun) { continue; } Processor proc=null; if (arguments.ScriptsOnly) { proc = new GenerateScriptProcessor(task.Name); } else { proc = new RunSitecoreTaskProcessor(task.Name); } proc.Title = task.Name; processors.Add(proc); } return processors; } } }
mit
C#
1983feb356cda3f07da93dcf8c1d9f04b4f18a0f
fix Upgrade_20210414_SimplifyQueryTokenString
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20210414_SimplifyQueryTokenString.cs
Signum.Upgrade/Upgrades/Upgrade_20210414_SimplifyQueryTokenString.cs
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210414_SimplifyQueryTokenString : CodeUpgradeBase { public override string Description => "Simplify QueryTokenString entity().token(a=>a.name) by entity(a=>a.entity.name)"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile("*.tsx,*.ts", "Southwind.React", file => { file.Replace(new Regex(@"token\(\).entity\((\w+) *=> *\1"), @"token($1 => $1.entity"); file.Replace(new Regex(@"t.entity\((\w+) *=> *\1"), @"t.append($1 => $1.entity"); file.Replace(@"token().entity()", @"token(a => a.entity)"); }); } } }
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210414_SimplifyQueryTokenString : CodeUpgradeBase { public override string Description => "Simplify QueryTokenString entity().token(a=>a.name) by entity(a=>a.entity.name)"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile("*.tsx,*.ts", "Southwind.React", file => { file.Replace(new Regex(@"token\(\).entity\((\w) *=> *\1"), @"token($1 => $1.entity"); file.Replace(new Regex(@"t.entity\((\w) *=> *\1"), @"t.append($1 => $1.entity"); file.Replace(new Regex(@"token().entity()"), @"token(a => a.entity)"); }); } } }
mit
C#
8e88d0e35e34f7956a32139f3758fb9f989cbc3c
Fix #465 - Add support for object values to have layouts
sorenhl/Glimpse,Glimpse/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,dudzon/Glimpse,Glimpse/Glimpse,codevlabs/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,sorenhl/Glimpse,dudzon/Glimpse,dudzon/Glimpse,gabrielweyer/Glimpse,gabrielweyer/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,SusanaL/Glimpse,elkingtonmcb/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,flcdrg/Glimpse,flcdrg/Glimpse,rho24/Glimpse
source/Glimpse.Core/Tab/Assist/TabLayout.cs
source/Glimpse.Core/Tab/Assist/TabLayout.cs
using System; using System.Collections.Generic; using System.Linq; namespace Glimpse.Core.Tab.Assist { public class TabLayout : ITabBuild { private readonly List<TabLayoutRow> rows = new List<TabLayoutRow>(); private readonly Dictionary<string, TabLayout> cells = new Dictionary<string, TabLayout>(); private TabLayout() { } public IEnumerable<TabLayoutRow> Rows { get { return rows; } } public static TabLayout Create() { return new TabLayout(); } public static TabLayout Create(Action<TabLayout> layout) { var tabLayout = new TabLayout(); layout.Invoke(tabLayout); return tabLayout; } public TabLayout Row(Action<TabLayoutRow> row) { var layoutRow = new TabLayoutRow(); row.Invoke(layoutRow); rows.Add(layoutRow); return this; } public TabLayout Cell(string target, TabLayout layout) { cells.Add(target, layout); return this; } public object Build() { if (cells.Count > 0) { return cells.ToDictionary(x => x.Key, x => new { Layout = x.Value.Build() }); } return rows.Select(r => r.Build()); } } }
using System; using System.Collections.Generic; using System.Linq; namespace Glimpse.Core.Tab.Assist { public class TabLayout : ITabBuild { private readonly List<TabLayoutRow> rows = new List<TabLayoutRow>(); private TabLayout() { } public IEnumerable<TabLayoutRow> Rows { get { return rows; } } public static TabLayout Create() { return new TabLayout(); } public static TabLayout Create(Action<TabLayout> layout) { var tabLayout = new TabLayout(); layout.Invoke(tabLayout); return tabLayout; } public TabLayout Row(Action<TabLayoutRow> row) { var layoutRow = new TabLayoutRow(); row.Invoke(layoutRow); rows.Add(layoutRow); return this; } public object Build() { return rows.Select(r => r.Build()); } } }
apache-2.0
C#
d6a22d7a1a60c341ece9d7880b8b9419253c16b1
Add damage capabilities to the enemy
allmonty/BrokenShield,allmonty/BrokenShield
Assets/Scripts/Enemy/AttackHandler.cs
Assets/Scripts/Enemy/AttackHandler.cs
using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { other.gameObject.GetComponent<CharacterStatus>().life.decrease(damage); } } }
using UnityEngine; public class AttackHandler : MonoBehaviour { [HideInInspector] public float damage; [HideInInspector] public float duration; [HideInInspector] public BoxCollider hitBox; private float timer = 0f; void Start() { hitBox = gameObject.GetComponent<BoxCollider>(); } void Update() { timer += Time.deltaTime; if(timer >= duration) { timer = 0f; hitBox.enabled = false; } } void OnTriggerEnter(Collider other) { bool isPlayer = other.GetComponent<Collider>().CompareTag("Player"); if(isPlayer) { // Debug.Log("ATTACK"); } } }
apache-2.0
C#
c6873c38ff98b62a501c83f6dc5883f6f5482c6b
increase minimum game/API versions
Pathoschild/StardewMods
ChestsAnywhere/Framework/Constants.cs
ChestsAnywhere/Framework/Constants.cs
using StardewValley; namespace ChestsAnywhere.Framework { /// <summary>Constant mod values.</summary> internal static class Constant { /********* ** Accessors *********/ /// <summary>The minimum supported version of Stardew Valley.</summary> public const string MinimumGameVersion = "1.11"; /// <summary>The minimum supported version of SMAPI.</summary> public const string MinimumApiVersion = "0.40 1.1-3"; /// <summary>The number of rows in an inventory grid.</summary> public const int SlotRows = 3; /// <summary>The number of columns in an inventory grid.</summary> public const int SlotColumns = 12; /// <summary>The maximum number of elements in an inventory.</summary> public const int SlotCount = Constant.SlotRows * Constant.SlotColumns; /// <summary>The inventory slot size for the current zoom level.</summary> public static int SlotSize => Game1.tileSize; } }
using StardewValley; namespace ChestsAnywhere.Framework { /// <summary>Constant mod values.</summary> internal static class Constant { /********* ** Accessors *********/ /// <summary>The minimum supported version of Stardew Valley.</summary> public const string MinimumGameVersion = "1.1"; /// <summary>The minimum supported version of SMAPI.</summary> public const string MinimumApiVersion = "0.40 1.1"; /// <summary>The number of rows in an inventory grid.</summary> public const int SlotRows = 3; /// <summary>The number of columns in an inventory grid.</summary> public const int SlotColumns = 12; /// <summary>The maximum number of elements in an inventory.</summary> public const int SlotCount = Constant.SlotRows * Constant.SlotColumns; /// <summary>The inventory slot size for the current zoom level.</summary> public static int SlotSize => Game1.tileSize; } }
mit
C#
6def7fe471ab59a2dd02d64fb1b2c7642cf72757
Split CheckBox test into two, give better name.
toroso/ruibarbo
tungsten.sampletest/CheckBoxTest.cs
tungsten.sampletest/CheckBoxTest.cs
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void CheckBoxIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } [Test] public void CheckBoxChangeIsChecked() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }
using NUnit.Framework; using tungsten.core.Elements; using tungsten.core.Search; using tungsten.nunit; namespace tungsten.sampletest { [TestFixture] public class CheckBoxTest : TestBase { [Test] public void Hupp() { var window = Desktop.FindFirstChild<WpfWindow>(By.Name("WndMain")); var checkBox = window.FindFirstChild<WpfCheckBox>(By.Name("ShowStuff")); checkBox.AssertThat(x => x.IsChecked(), Is.True); checkBox.Click(); checkBox.AssertThat(x => x.IsChecked(), Is.False); } } }
apache-2.0
C#
8cb0c213134984e769c4caf8ae0d68982f9a86c0
Remove processed by fody
NServiceBusSqlPersistence/NServiceBus.SqlPersistence
src/SqlPersistence.Tests/ConventionTests.cs
src/SqlPersistence.Tests/ConventionTests.cs
using System; using NServiceBus; using NUnit.Framework; [TestFixture] public class ConventionTests { [Test] public void AssertNonPublicTypesHaveNoNamespace() { foreach (var type in typeof(SqlPersistence).Assembly.GetTypes()) { if (type.IsPublic) { continue; } if (type.IsNested) { continue; } if (type.Namespace == null) { continue; } if (type.BaseType != null && type.BaseType == typeof(Exception)) { continue; } if (type.Name == "ProcessedByFody") { continue; } throw new Exception($"Type {type.Name} should have no namespace."); } } }
using System; using NServiceBus; using NUnit.Framework; [TestFixture] public class ConventionTests { [Test] public void AssertNonPublicTypesHaveNoNamespace() { foreach (var type in typeof(SqlPersistence).Assembly.GetTypes()) { if (type.IsPublic) { continue; } if (type.IsNested) { continue; } if (type.Namespace == null) { continue; } if (type.BaseType != null && type.BaseType == typeof(Exception)) { continue; } throw new Exception($"Type {type.Name} should have no namespace."); } } }
mit
C#
11398a0f910f8872aa984003141af912b615d48e
Revert Strip large data values out of events
exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless
src/Exceptionless.Core/Plugins/EventParser/Default/JsonEventParserPlugin.cs
src/Exceptionless.Core/Plugins/EventParser/Default/JsonEventParserPlugin.cs
using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); switch (input.GetJsonType()) { case JsonType.Object: { if (input.TryFromJson(out PersistentEvent ev, _settings)) events.Add(ev); break; } case JsonType.Array: { if (input.TryFromJson(out PersistentEvent[] parsedEvents, _settings)) events.AddRange(parsedEvents); break; } } return events.Count > 0 ? events : null; } } }
using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; using Microsoft.Extensions.Options; using Newtonsoft.Json; using System.IO; using Newtonsoft.Json.Linq; using Microsoft.Extensions.Logging; namespace Exceptionless.Core.Plugins.EventParser { [Priority(0)] public class JsonEventParserPlugin : PluginBase, IEventParserPlugin { private readonly JsonSerializerSettings _settings; private readonly JsonSerializer _serializer; public JsonEventParserPlugin(IOptions<AppOptions> options, JsonSerializerSettings settings) : base(options) { _settings = settings; _serializer = JsonSerializer.CreateDefault(_settings); } public List<PersistentEvent> ParseEvents(string input, int apiVersion, string userAgent) { if (apiVersion < 2) return null; var events = new List<PersistentEvent>(); var reader = new JsonTextReader(new StringReader(input)); reader.DateParseHandling = DateParseHandling.None; while (reader.Read()) { if (reader.TokenType == JsonToken.StartObject) { var ev = JToken.ReadFrom(reader); var data = ev["data"]; if (data != null) { foreach (var property in data.Children<JProperty>()) { // strip out large data entries if (property.Value.ToString().Length > 50000) { property.Value = "(Data Too Large)"; } } } try { events.Add(ev.ToObject<PersistentEvent>(_serializer)); } catch (Exception ex) { _logger.LogError(ex, "Error deserializing event."); } } } return events.Count > 0 ? events : null; } } }
apache-2.0
C#
001fed5efeedc34de9dfa1f8e4ab972c8be5b25a
Remove suppression
mavasani/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,mavasani/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,KevinRansom/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,dotnet/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,weltkante/roslyn,mavasani/roslyn,diryboy/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn
src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/HashFunctions.cs
src/ExpressionEvaluator/Core/Source/ResultProvider/Helpers/HashFunctions.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 Microsoft.CodeAnalysis; namespace Roslyn.Utilities { /// <summary> /// Required by <see cref="CaseInsensitiveComparison"/> /// </summary> internal static class Hash { internal const int FnvOffsetBias = unchecked((int)2166136261); internal const int FnvPrime = 16777619; internal static int CombineFNVHash(int hashCode, char ch) { return unchecked((hashCode ^ ch) * Hash.FnvPrime); } } }
// 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 Microsoft.CodeAnalysis; namespace Roslyn.Utilities { #pragma warning disable CS1574 // XML comment has cref attribute that could not be resolved /// <summary> /// Required by <see cref="CaseInsensitiveComparison"/> /// </summary> internal static class Hash #pragma warning restore CS1574 // XML comment has cref attribute that could not be resolved { internal const int FnvOffsetBias = unchecked((int)2166136261); internal const int FnvPrime = 16777619; internal static int CombineFNVHash(int hashCode, char ch) { return unchecked((hashCode ^ ch) * Hash.FnvPrime); } } }
mit
C#
6346e879c3c083d3ea4c32ce8ad46423b3bcd44f
check playlist count and selection index at background action too
punker76/simple-music-player
SimpleMusicPlayer/SimpleMusicPlayer/Base/BaseListBox.cs
SimpleMusicPlayer/SimpleMusicPlayer/Base/BaseListBox.cs
using System; using System.Diagnostics; using System.Reactive; using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Threading; using ReactiveUI; namespace SimpleMusicPlayer.Base { public class BaseListBox : ListBox { public static readonly DependencyProperty ObserveItemContainerGeneratorProperty = DependencyProperty.Register( "ObserveItemContainerGenerator", typeof(bool), typeof(BaseListBox), new PropertyMetadata(default(bool))); public bool ObserveItemContainerGenerator { get { return (bool)GetValue(ObserveItemContainerGeneratorProperty); } set { SetValue(ObserveItemContainerGeneratorProperty, value); } } public BaseListBox() { this.Loaded += (s, e) => Observable.Zip( this.ObservableForProperty(x => x.ObserveItemContainerGenerator).Where(x => x.Value == true).Select(_ => Unit.Default), this.ItemContainerGenerator.Events().StatusChanged.Throttle(TimeSpan.FromMilliseconds(150), RxApp.MainThreadScheduler).Select(_ => Unit.Default) ).Subscribe(_ => FocusSelectedItem()); } private void FocusSelectedItem() { if (this.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return; this.ObserveItemContainerGenerator = false; Debug.WriteLine(">>>>>>>status changed"); if (this.Items.Count == 0) return; var index = this.SelectedIndex; if (index < 0) return; Action focusAction = () => { if (this.Items.Count == 0) return; index = this.SelectedIndex; if (index < 0) return; this.Focus(); this.ScrollIntoView(this.SelectedItem); var item = this.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem; if (item == null) return; item.Focus(); Debug.WriteLine(">>>>>>>focus selected item"); }; this.Dispatcher.BeginInvoke(DispatcherPriority.Background, focusAction); } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { if (!this.IsTextSearchEnabled && e.Key == Key.Space) { e.Handled = false; } else { base.OnKeyDown(e); } } } }
using System; using System.Diagnostics; using System.Reactive; using System.Reactive.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Threading; using ReactiveUI; namespace SimpleMusicPlayer.Base { public class BaseListBox : ListBox { public static readonly DependencyProperty ObserveItemContainerGeneratorProperty = DependencyProperty.Register( "ObserveItemContainerGenerator", typeof(bool), typeof(BaseListBox), new PropertyMetadata(default(bool))); public bool ObserveItemContainerGenerator { get { return (bool)GetValue(ObserveItemContainerGeneratorProperty); } set { SetValue(ObserveItemContainerGeneratorProperty, value); } } public BaseListBox() { this.Loaded += (s, e) => Observable.Zip( this.ObservableForProperty(x => x.ObserveItemContainerGenerator).Where(x => x.Value == true).Select(_ => Unit.Default), this.ItemContainerGenerator.Events().StatusChanged.Throttle(TimeSpan.FromMilliseconds(150), RxApp.MainThreadScheduler).Select(_ => Unit.Default) ).Subscribe(_ => FocusSelectedItem()); } private void FocusSelectedItem() { if (this.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated) return; this.ObserveItemContainerGenerator = false; Debug.WriteLine(">>>>>>>status changed"); if (this.Items.Count == 0) return; var index = this.SelectedIndex; if (index < 0) return; Action focusAction = () => { this.Focus(); this.ScrollIntoView(this.SelectedItem); var item = this.ItemContainerGenerator.ContainerFromIndex(index) as ListBoxItem; if (item == null) return; item.Focus(); Debug.WriteLine(">>>>>>>focus selected item"); }; this.Dispatcher.BeginInvoke(DispatcherPriority.Background, focusAction); } protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e) { if (!this.IsTextSearchEnabled && e.Key == Key.Space) { e.Handled = false; } else { base.OnKeyDown(e); } } } }
mit
C#
0c192ed3bf50f08a25d6e58e5d56164d82bf3f75
REmove method
jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,eriawan/roslyn,diryboy/roslyn,dotnet/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,KevinRansom/roslyn,wvdd007/roslyn,wvdd007/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,physhi/roslyn,mavasani/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,eriawan/roslyn,sharwell/roslyn,bartdesmet/roslyn,weltkante/roslyn,mavasani/roslyn,dotnet/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,sharwell/roslyn,diryboy/roslyn,sharwell/roslyn,AmadeusW/roslyn
src/Tools/ExternalAccess/OmniSharp/Completion/OmniSharpCompletionService.cs
src/Tools/ExternalAccess/OmniSharp/Completion/OmniSharpCompletionService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Completion { internal static class OmniSharpCompletionService { public static Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsAsync( this CompletionService completionService, Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string>? roles = null, OptionSet? options = null, CancellationToken cancellationToken = default) => completionService.GetCompletionsInternalAsync(document, caretPosition, trigger, roles, options, cancellationToken); public static string GetProviderName(this CompletionItem completionItem) => completionItem.ProviderName; public static PerLanguageOption<bool?> ShowItemsFromUnimportedNamespaces = (PerLanguageOption<bool?>)CompletionOptions.ShowItemsFromUnimportedNamespaces; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Completion { internal static class OmniSharpCompletionService { public static Task<(CompletionList completionList, bool expandItemsAvailable)> GetCompletionsAsync( this CompletionService completionService, Document document, int caretPosition, CompletionTrigger trigger = default, ImmutableHashSet<string>? roles = null, OptionSet? options = null, CancellationToken cancellationToken = default) => completionService.GetCompletionsInternalAsync(document, caretPosition, trigger, roles, options, cancellationToken); public static Task<CompletionChange> GetChangeAsync( this CompletionService completionService, Document document, CompletionItem item, TextSpan completionListSpan, char? commitCharacter = null, bool disallowAddingImports = false, CancellationToken cancellationToken = default) => completionService.GetChangeAsync(document, item, commitCharacter, cancellationToken); public static string GetProviderName(this CompletionItem completionItem) => completionItem.ProviderName; public static PerLanguageOption<bool?> ShowItemsFromUnimportedNamespaces = (PerLanguageOption<bool?>)CompletionOptions.ShowItemsFromUnimportedNamespaces; } }
mit
C#
244b3975b1a5d7938672cfd1a695da25d7aca350
Clean up attributes in InfoModule.cs
portaljacker/portalbot
src/portalbot/Commands/InfoModule.cs
src/portalbot/Commands/InfoModule.cs
using Discord.Commands; using System.Threading.Tasks; namespace Portalbot.Commands { public class InfoModule : ModuleBase { [Command("ping")] [Summary("pong!")] public async Task Ping() { await ReplyAsync("pong!"); } [Command("say")] [Summary("Echos a message.")] public async Task Say([Remainder, Summary("The text to echo")] string echo) { var userInfo = Context.User; await ReplyAsync($"{userInfo.Username} wants me to say, \"{echo}\" frankly I think that's a ridiculous expectation on their part, now don't you?"); } } }
using Discord.Commands; using System.Threading.Tasks; namespace Portalbot.Commands { public class InfoModule : ModuleBase { [Command("ping"), Summary("pong!.")] public async Task Ping() { await ReplyAsync("pong!"); } [Command("say"), Summary("Echos a message.")] public async Task Say([Remainder, Summary("The text to echo")] string echo) { var userInfo = Context.User; await ReplyAsync($"{userInfo.Username} wants me to say, \"{echo}\" frankly I think that's a ridiculous expectation on their part, now don't you?"); } } }
mit
C#
e4ad2092ac01cff2831339333ca8012cfed1e713
Update the mask check in the Bit() extension method
eightlittlebits/elbsms
elbsms_core/Extensions.cs
elbsms_core/Extensions.cs
namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) != 0; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } }
namespace elbsms_core { internal static class Extensions { internal static bool Bit(this byte v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool Bit(this int v, int bit) { int mask = 1 << bit; return (v & mask) == mask; } internal static bool EvenParity(this int v) { v ^= v >> 4; v ^= v >> 2; v ^= v >> 1; return (v & 1) != 1; } } }
mit
C#
6863c0b13b2542a40f4804c3bc3bf54ee8ece9f2
Add .dll suffix to the glue dllimport to make it work on Windows
freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,Forage/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,Forage/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,Forage/gstreamer-sharp,GStreamer/gstreamer-sharp,Forage/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp
gstreamer-sharp/glib-sharp/Thread.cs
gstreamer-sharp/glib-sharp/Thread.cs
// Thread.cs - thread awareness // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace Gst.GLib { using System; using System.Runtime.InteropServices; public class Thread { private Thread () {} [DllImport ("libgthread-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void g_thread_init (IntPtr i); public static void Init () { g_thread_init (IntPtr.Zero); } [DllImport("gstreamersharpglue-0.10.dll")] static extern bool gstglibsharp_g_thread_supported (); public static bool Supported { get { return gstglibsharp_g_thread_supported (); } } } }
// Thread.cs - thread awareness // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. namespace Gst.GLib { using System; using System.Runtime.InteropServices; public class Thread { private Thread () {} [DllImport ("libgthread-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern void g_thread_init (IntPtr i); public static void Init () { g_thread_init (IntPtr.Zero); } [DllImport("gstreamersharpglue-0.10")] static extern bool gstglibsharp_g_thread_supported (); public static bool Supported { get { return gstglibsharp_g_thread_supported (); } } } }
lgpl-2.1
C#
fd119880aae50afd881a8cb0a009e01773f0cc7c
Remove dead wood and tidy up
ceddlyburge/canoe-polo-league-organiser-backend
CanoePoloLeagueOrganiser/OptimalGameOrderWithPragmatisationAndCurtailment.cs
CanoePoloLeagueOrganiser/OptimalGameOrderWithPragmatisationAndCurtailment.cs
using System; using System.Collections.Generic; using static System.Diagnostics.Contracts.Contract; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CanoePoloLeagueOrganiser { public class OptimalGameOrderWithPragmatisationAndCurtailment { IPermutater<Game> Permutater { get; } IPragmatiser Pragmatiser { get; } RunningOptimalGameOrder runningOptimalGameOrder; public OptimalGameOrderWithPragmatisationAndCurtailment( IPragmatiser pragmatiser, IPermutater<Game> permutater) { Requires(pragmatiser != null); Requires(permutater != null); Permutater = permutater; Pragmatiser = pragmatiser; } public GameOrderPossiblyNullCalculation CalculateGameOrder() { Initialise(); Calculate(); return OptimalPermutation(); } void Initialise() => runningOptimalGameOrder = new RunningOptimalGameOrder(); void Calculate() => runningOptimalGameOrder.RunningCalculateOptimalGameOrder(PragmatisedPermutations()); IEnumerable<PlayList> PragmatisedPermutations() { return new PragmatisePermutations( Pragmatiser, Permutater.Permutations(), runningOptimalGameOrder ).PragmatisedPermutations(); } GameOrderPossiblyNullCalculation OptimalPermutation() { return new GameOrderPossiblyNullCalculation( optimisedGameOrder: runningOptimalGameOrder.OptimalGameOrder, pragmatisationLevel: Pragmatiser.Level, optimisationMessage: Pragmatiser.Message); } } }
using System; using System.Collections.Generic; using static System.Diagnostics.Contracts.Contract; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CanoePoloLeagueOrganiser { public class OptimalGameOrderWithPragmatisationAndCurtailment { IPermutater<Game> Permupotater { get; } IPragmatiser Pragmatiser { get; } uint permutationCount; DateTime timeStartedCalculation; RunningOptimalGameOrder runningOptimalGameOrder; public OptimalGameOrderWithPragmatisationAndCurtailment( IPragmatiser pragmatiser, IPermutater<Game> permupotater) { Requires(pragmatiser != null); Requires(permupotater != null); Permupotater = permupotater; Pragmatiser = pragmatiser; runningOptimalGameOrder = new RunningOptimalGameOrder(); } public IEnumerable<PlayList> PragmatisedPermutations() { return new PragmatisePermutations( Pragmatiser, Permupotater.Permutations(), runningOptimalGameOrder ).PragmatisedPermutations(); } public GameOrderPossiblyNullCalculation CalculateGameOrder() { Initialise(); runningOptimalGameOrder.RunningCalculateOptimalGameOrder(PragmatisedPermutations()); return OptimalPermutation(); } void Initialise() { runningOptimalGameOrder = new RunningOptimalGameOrder(); permutationCount = 0; timeStartedCalculation = DateTime.Now; } GameOrderPossiblyNullCalculation OptimalPermutation() { return new GameOrderPossiblyNullCalculation( optimisedGameOrder: runningOptimalGameOrder.OptimalGameOrder, pragmatisationLevel: Pragmatiser.Level, optimisationMessage: Pragmatiser.Message); } } }
mit
C#
fb7b21d75d84a328af1381ab5f0d2f862771dbc0
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.9.1")] [assembly: AssemblyInformationalVersion("0.9.1")] /* * Version 0.9.1 * * Fixes returning a exception command per each test case * * Fixes the using directive 'using Jwc.Experiment', * in the Scenario file of Experiment.AutoFixtureWithExample. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.9.0")] [assembly: AssemblyInformationalVersion("0.9.0")] /* * Version 0.9.0 * * Implemented FirstClassTheoremAttribute which supports providing auto data * using the AutoFixture library. * * Addressed unhandled exception thrown when creating TestCommand instances * in BaseTheoremAttribute.EnumerateTestCommands(IMethodInfo). * * Issue: https://github.com/jwChung/Experimentalism/issues/23 * * Pull request: https://github.com/jwChung/Experimentalism/pull/32 */
mit
C#
f9215bee6bc0a574b53276a9f9747f2edd818c9b
Update InnoSetupProductPackager.cs
vigoo/bari,vigoo/bari,Psychobilly87/bari,Psychobilly87/bari,Psychobilly87/bari,vigoo/bari,vigoo/bari,Psychobilly87/bari
src/innosetup/Bari.Plugins.InnoSetup/cs/Packager/InnoSetupProductPackager.cs
src/innosetup/Bari.Plugins.InnoSetup/cs/Packager/InnoSetupProductPackager.cs
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Bari.Core.Commands.Pack; using Bari.Core.Generic; using Bari.Core.Model; using Bari.Plugins.InnoSetup.Tools; namespace Bari.Plugins.InnoSetup.Packager { public class InnoSetupProductPackager: IProductPackager { private readonly IInnoSetupCompiler compiler; private readonly Suite suite; public InnoSetupProductPackager(IInnoSetupCompiler compiler, Suite suite) { Contract.Requires(compiler != null); Contract.Requires(suite != null); this.compiler = compiler; this.suite = suite; } public void Pack(Product product, ISet<TargetRelativePath> outputs) { var parameters = (InnoSetupPackagerParameters) product.Packager.Parameters; compiler.Compile( parameters.ScriptPath, new TargetRelativePath("", String.Format("{0}-{1}", product.Name, suite.Version)), suite.Version, suite.ActiveGoal); } } }
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using Bari.Core.Commands.Pack; using Bari.Core.Generic; using Bari.Core.Model; using Bari.Plugins.InnoSetup.Tools; namespace Bari.Plugins.InnoSetup.Packager { public class InnoSetupProductPackager: IProductPackager { private readonly IInnoSetupCompiler compiler; private readonly Suite suite; public InnoSetupProductPackager(IInnoSetupCompiler compiler, Suite suite) { Contract.Requires(compiler != null); Contract.Requires(suite != null); this.compiler = compiler; this.suite = suite; } public void Pack(Product product, ISet<TargetRelativePath> outputs) { var parameters = (InnoSetupPackagerParameters) product.Packager.Parameters; compiler.Compile( parameters.ScriptPath, new TargetRelativePath("", String.Format("{0}-{1}.exe", product.Name, suite.Version)), suite.Version, suite.ActiveGoal); } } }
apache-2.0
C#
cd54653977e4486452f3cfbb6d81dc78828a7ad5
Add 'Soft' HoverSampleSet variant
NeoAdonis/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Graphics/UserInterface/HoverSampleSet.cs
osu.Game/Graphics/UserInterface/HoverSampleSet.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Graphics.UserInterface { public enum HoverSampleSet { [Description("default")] Default, [Description("soft")] Soft, [Description("button")] Button, [Description("toolbar")] Toolbar, [Description("tabselect")] TabSelect, [Description("scrolltotop")] ScrollToTop } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Graphics.UserInterface { public enum HoverSampleSet { [Description("default")] Default, [Description("button")] Button, [Description("toolbar")] Toolbar, [Description("tabselect")] TabSelect, [Description("scrolltotop")] ScrollToTop } }
mit
C#
fd11346a289e03b0a5f2f1f2cd5d1da3a578fffe
Update button colours
NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu
osu.Game/Overlays/BeatmapListing/FilterTabItem.cs
osu.Game/Overlays/BeatmapListing/FilterTabItem.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK.Graphics; namespace osu.Game.Overlays.BeatmapListing { public class FilterTabItem<T> : TabItem<T> { [Resolved] private OverlayColourProvider colourProvider { get; set; } private readonly OsuSpriteText text; public FilterTabItem(T value) : base(value) { AutoSizeAxes = Axes.Both; Anchor = Anchor.BottomLeft; Origin = Anchor.BottomLeft; AddRangeInternal(new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(size: 13, weight: FontWeight.Regular), Text = CreateText(value) }, new HoverClickSounds() }); Enabled.Value = true; } protected virtual string CreateText(T value) => (value as Enum)?.GetDescription() ?? value.ToString(); [BackgroundDependencyLoader] private void load() { updateState(); } protected override bool OnHover(HoverEvent e) { base.OnHover(e); updateState(); return true; } protected override void OnHoverLost(HoverLostEvent e) { base.OnHoverLost(e); updateState(); } protected override void OnActivated() => updateState(); protected override void OnDeactivated() => updateState(); private void updateState() { text.FadeColour(IsHovered ? colourProvider.Light1 : getStateColour(), 200, Easing.OutQuint); text.Font = text.Font.With(weight: Active.Value ? FontWeight.SemiBold : FontWeight.Regular); } private Color4 getStateColour() => Active.Value ? colourProvider.Content1 : colourProvider.Light2; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.UserInterface; using osu.Framework.Input.Events; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osuTK.Graphics; namespace osu.Game.Overlays.BeatmapListing { public class FilterTabItem<T> : TabItem<T> { [Resolved] private OverlayColourProvider colourProvider { get; set; } private readonly OsuSpriteText text; public FilterTabItem(T value) : base(value) { AutoSizeAxes = Axes.Both; Anchor = Anchor.BottomLeft; Origin = Anchor.BottomLeft; AddRangeInternal(new Drawable[] { text = new OsuSpriteText { Font = OsuFont.GetFont(size: 13, weight: FontWeight.Regular), Text = CreateText(value) }, new HoverClickSounds() }); Enabled.Value = true; } protected virtual string CreateText(T value) => (value as Enum)?.GetDescription() ?? value.ToString(); [BackgroundDependencyLoader] private void load() { updateState(); } protected override bool OnHover(HoverEvent e) { base.OnHover(e); updateState(); return true; } protected override void OnHoverLost(HoverLostEvent e) { base.OnHoverLost(e); updateState(); } protected override void OnActivated() => updateState(); protected override void OnDeactivated() => updateState(); private void updateState() { text.FadeColour(Active.Value ? Color4.White : getStateColour(), 200, Easing.OutQuint); text.Font = text.Font.With(weight: Active.Value ? FontWeight.SemiBold : FontWeight.Regular); } private Color4 getStateColour() => IsHovered ? colourProvider.Light1 : colourProvider.Light3; } }
mit
C#
07b27fa7e3a89b888303845c40db6e728b7b42b3
Comment everything
andrew-vant/dragalt
src/DraggableNavball.cs
src/DraggableNavball.cs
using IOUtils = KSP.IO.IOUtils; using NavBall = KSP.UI.Screens.Flight.NavBall; using UnityEngine; using UnityEngine.EventSystems; /* Two classes are needed for DraggableNavball. One is the component that * implements the drag behavior. I can't work out how to make it add itself * to the navball, so a second class (NavBallAttacher) is rigged to run at * flight startup solely to add the component. * * I feel like there should be a cleaner way to do this but haven't found it * yet. */ [KSPAddon(KSPAddon.Startup.Flight, false)] public class NavBallAttacher : MonoBehaviour { void Start() { /* When we speak of dragging the navball, what we really want * is to drag the entire SAS/navball/maneuver control cluster. * It has the type "IVAEVACollapseGroup" but I can't figure out * where that's defined so I can't search for it. Taking the * parent of the NavBall works just as well. * * This doesn't drag the (invisible) frame around the navball's * control cluster, but that doesn't seem to hurt anything. */ GameObject navball = FindObjectOfType<NavBall>().gameObject; GameObject cluster = navball.transform.parent.gameObject; cluster.AddComponent<NavBallDrag>(); } } public class NavBallDrag : MonoBehaviour, IBeginDragHandler, IDragHandler { /* This component makes the navball draggable. Movement is restricted * to the x axis, so the ball slides along the bottom edge of the * screen. */ /* I can't figure out how to make ConfigNode.Load do the right thing * with C# properties, so NAVBALL_COORD gets mapped to a private * variable that serves just as a place to keep save-load data. */ [Persistent] private float NAVBALL_XCOORD; private Vector2 dragstart; private Vector3 ballstart; const string cfgfile = "DraggableNavball.cfg"; void Start() { string path = IOUtils.GetFilePathFor(this.GetType(), cfgfile); ConfigNode config = ConfigNode.Load(path); ConfigNode.LoadObjectFromConfig(this, config); xpos = NAVBALL_XCOORD; } public float xpos { /* Assigning to xpos moves the navball. Don't do it any other * way; stuff necessary for consistency happens here. */ get { return transform.position.x; } set { Vector3 newpos = transform.position; newpos.x = value; transform.position = newpos; /* Sometimes outside forces set the navball's * position. They seem to use GameSettings.UI_POS_NAVBALL * to get it, so let's override that. UI_POS_NAVBALL * uses a -1:1 range, while we have a pixel offset * from center, so a conversion is necessary. */ GameSettings.UI_POS_NAVBALL = value * 2 / GameSettings.SCREEN_RESOLUTION_WIDTH; } } public void OnBeginDrag(PointerEventData evtdata) { /* Record the pointer and ball positions when dragging starts. * We'll need them in OnDrag. */ dragstart = evtdata.position; ballstart = transform.position; } public void OnDrag(PointerEventData evtdata) { /* See how far the pointer has dragged and offset the navball * from its original position by that much. * * This might be cleaner with a frame-by-frame delta but I * worry about small errors adding up. */ Vector2 dragdist = evtdata.position - dragstart; xpos = ballstart.x + dragdist.x; } public void OnDestroy() { // I'm not sure when you're "supposed" to save plugin data. // This was the best I could come up with. NAVBALL_XCOORD = xpos; ConfigNode config = ConfigNode.CreateConfigFromObject(this); string path = IOUtils.GetFilePathFor(this.GetType(), cfgfile); config.Save(path); } }
using IOUtils = KSP.IO.IOUtils; using NavBall = KSP.UI.Screens.Flight.NavBall; using UnityEngine; using UnityEngine.EventSystems; [KSPAddon(KSPAddon.Startup.Flight, false)] public class NavBallAttacher : MonoBehaviour { void Start() { /* When we speak of dragging the navball, what we really want * is to drag the entire SAS/navball/maneuver control panel. * It has the type "IVAEVACollapseGroup" but I can't figure out * where that's defined so I can't search for it. Taking the * parent of the NavBall works just as well. * * This doesn't drag the (invisible) frame around the control * cluster, but that doesn't seem to hurt anything. */ GameObject navball = FindObjectOfType<NavBall>().gameObject; GameObject cluster = navball.transform.parent.gameObject; cluster.AddComponent<NavBallDrag>(); } } public class NavBallDrag : MonoBehaviour, IBeginDragHandler, IDragHandler { /* This component makes the navball draggable. It works by recording * the pointer and ball's position when a drag starts, then moving the * ball however far the pointer moved along the X axis. * * Simply setting the ball to the pointer's position doesn't work; the * pointer and ball have different coordinate origins. The pointer's * X:0 is the left edge of the screen; The ball's X:0 is the center. * * Restricting movement to the X axis makes the ball frame slide along * the bottom edge of the screen. */ [Persistent] private float NAVBALL_XCOORD; // used only for load/save private Vector2 dragstart; private Vector3 ballstart; const string modname = "Draggable Navball"; const string cfgfile = "DraggableNavball.cfg"; void Start() { string path = IOUtils.GetFilePathFor(this.GetType(), cfgfile); ConfigNode config = ConfigNode.Load(path); ConfigNode.LoadObjectFromConfig(this, config); xpos = NAVBALL_XCOORD; } public float xpos { get { return transform.position.x; } set { Vector3 newpos = transform.position; newpos.x = value; transform.position = newpos; GameSettings.UI_POS_NAVBALL = value * 2 / GameSettings.SCREEN_RESOLUTION_WIDTH; } } public void OnBeginDrag(PointerEventData evtdata) { dragstart = evtdata.position; ballstart = transform.position; } public void OnDrag(PointerEventData evtdata) { Vector2 dragdist = evtdata.position - dragstart; xpos = ballstart.x + dragdist.x; } public void OnDestroy() { NAVBALL_XCOORD = xpos; ConfigNode config = ConfigNode.CreateConfigFromObject(this); string path = IOUtils.GetFilePathFor(this.GetType(), cfgfile); config.Save(path); } }
mit
C#
fb268211153e209c9f3b8286ca2cc027771c417b
use verbose log
kreuzhofer/AzureLargeFileUploader
Program.cs
Program.cs
using System; using System.IO; namespace AzureLargeFileUploader { class Program { static int Main(string[] args) { if (args.Length != 4) { Help(); return -1; } var fileToUpload = args[0]; if (!File.Exists(fileToUpload)) { Console.WriteLine("File does not exist: "+fileToUpload); Help(); } var containerName = args[1]; var storageAccountName = args[2]; var storageAccountKey = args[3]; var connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}"; LargeFileUploaderUtils.Log = Console.WriteLine; LargeFileUploaderUtils.UploadAsync(fileToUpload, connectionString, containerName, (sender, i) => { }); Console.ReadLine(); return 0; } private static void Help() { Console.WriteLine(); Console.WriteLine("********************************************************************************"); Console.WriteLine("Azure Large File Uploader, (C)2016 by Daniel Kreuzhofer (@dkreuzh), MIT License"); Console.WriteLine("Source code is available at https://github.com/kreuzhofer/AzureLargeFileUploader"); Console.WriteLine("********************************************************************************"); Console.WriteLine("USAGE: AzureLargeFileUploader.exe <FileToUpload> <Container> <StorageAccountName> <StorageAccountKey>"); } } }
using System; using System.IO; namespace AzureLargeFileUploader { class Program { static int Main(string[] args) { if (args.Length != 4) { Help(); return -1; } var fileToUpload = args[0]; if (!File.Exists(fileToUpload)) { Console.WriteLine("File does not exist: "+fileToUpload); Help(); } var containerName = args[1]; var storageAccountName = args[2]; var storageAccountKey = args[3]; var connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}"; LargeFileUploaderUtils.UploadAsync(fileToUpload, connectionString, containerName, (sender, i) => { Console.WriteLine(i); }); Console.ReadLine(); return 0; } private static void Help() { Console.WriteLine(); Console.WriteLine("********************************************************************************"); Console.WriteLine("Azure Large File Uploader, (C)2016 by Daniel Kreuzhofer (@dkreuzh), MIT License"); Console.WriteLine("Source code is available at https://github.com/kreuzhofer/AzureLargeFileUploader"); Console.WriteLine("********************************************************************************"); Console.WriteLine("USAGE: AzureLargeFileUploader.exe <FileToUpload> <Container> <StorageAccountName> <StorageAccountKey>"); } } }
mit
C#
686fef04736ef9b827a5ac0a907521dd19937e52
Change IdleTimeout back to int from uint
Azure/amqpnetlite,ChugR/amqpnetlite
src/Net/AmqpSettings.cs
src/Net/AmqpSettings.cs
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ namespace Amqp { /// <summary> /// Contains the AMQP settings for a <see cref="Connection"/>. /// </summary> public class AmqpSettings { /// <summary> /// Gets or sets the open.max-frame-size field. /// </summary> public int MaxFrameSize { get; set; } /// <summary> /// Gets or sets the open.container-id field. /// </summary> public string ContainerId { get; set; } /// <summary> /// Gets or sets the open.hostname field. /// </summary> public string HostName { get; set; } /// <summary> /// Gets or sets the open.channel-max field (less by one). /// </summary> public ushort MaxSessionsPerConnection { get; set; } /// <summary> /// Gets or sets the begin.handle-max field (less by one). /// </summary> public int MaxLinksPerSession { get; set; } /// <summary> /// Gets or sets the open.idle-time-out field. /// </summary> public int IdleTimeout { get; set; } } }
// ------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR // NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing permissions and // limitations under the License. // ------------------------------------------------------------------------------------ namespace Amqp { /// <summary> /// Contains the AMQP settings for a <see cref="Connection"/>. /// </summary> public class AmqpSettings { /// <summary> /// Gets or sets the open.max-frame-size field. /// </summary> public int MaxFrameSize { get; set; } /// <summary> /// Gets or sets the open.container-id field. /// </summary> public string ContainerId { get; set; } /// <summary> /// Gets or sets the open.hostname field. /// </summary> public string HostName { get; set; } /// <summary> /// Gets or sets the open.channel-max field (less by one). /// </summary> public ushort MaxSessionsPerConnection { get; set; } /// <summary> /// Gets or sets the begin.handle-max field (less by one). /// </summary> public int MaxLinksPerSession { get; set; } /// <summary> /// Gets or sets the open.idle-time-out field. /// </summary> public uint IdleTimeout { get; set; } } }
apache-2.0
C#
2ef5b549ee094c18f2c8c0a5c5001e98b20025cc
Move to .NET Standard - cleanup
prayzzz/SoundCloud.Api
sample/ConsoleApp/Program.cs
sample/ConsoleApp/Program.cs
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using SoundCloud.Api; using SoundCloud.Api.Entities; using SoundCloud.Api.Entities.Enums; using SoundCloud.Api.QueryBuilders; namespace ConsoleApp { internal static class Program { private static async Task Main(string[] args) { var serviceCollection = new ServiceCollection(); serviceCollection.AddSoundCloudClient(string.Empty, args[0]); using (var provider = serviceCollection.BuildServiceProvider()) { var client = provider.GetService<SoundCloudClient>(); var entity = await client.Resolve.GetEntityAsync("https://soundcloud.com/diplo"); if (entity.Kind != Kind.User) { Console.WriteLine("Couldn't resolve account of diplo"); return; } var diplo = entity as User; Console.WriteLine($"Found: {diplo.Username} @ {diplo.PermalinkUrl}"); var tracks = await client.Users.GetTracksAsync(diplo, 10); Console.WriteLine(); Console.WriteLine("Latest 10 Tracks:"); foreach (var track in tracks) { Console.WriteLine(track.Title); } var majorLazerResults = await client.Tracks.GetAllAsync(new TrackQueryBuilder { SearchString = "Major Lazer", Limit = 10 }); Console.WriteLine(); Console.WriteLine("Found Major Lazer Tracks:"); foreach (var track in majorLazerResults) { Console.WriteLine(track.Title); } } } } }
mit
C#
21deb584328d17853455ab194d2b58cfcfe5cc78
remove seo incentives
reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website
input/_Backers.cshtml
input/_Backers.cshtml
@for (var id = 0; id <= 200; id++) { <a href="https://opencollective.com/reactiveui/backer/@id/website" target="_blank" rel="nofollow"> <img src="//opencollective.com/reactiveui/backer/@id/avatar.svg" /> </a> }
@for (var id = 0; id <= 200; id++) { <a href="https://opencollective.com/reactiveui/backer/@id/website" target="_blank"> <img src="//opencollective.com/reactiveui/backer/@id/avatar.svg" /> </a> }
mit
C#
229d893e41b939f2a18846898166250c0a2eccb0
Add ToString override to Renamer.Rule.
CamTechConsultants/CvsntGitImporter
Renamer.cs
Renamer.cs
/* * John Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CTC.CvsntGitImporter { /// <summary> /// Collection of rename rules to rename tags and branches. The rules are processed in the order in which /// they were added and processing stops as soon as a rule matches. /// </summary> class Renamer { private readonly List<Rule> m_rules = new List<Rule>(); /// <summary> /// Adds a renaming rule. /// </summary> public void AddRule(Regex pattern, string replacement) { m_rules.Add(new Rule(pattern, replacement)); } /// <summary> /// Process a name, renaming it if it matches a rule. /// </summary> public string Process(string name) { var match = m_rules.FirstOrDefault(r => r.Pattern.IsMatch(name)); if (match == null) return name; else return match.Pattern.Replace(name, match.Replacement); } private class Rule { public readonly Regex Pattern; public readonly string Replacement; public Rule(Regex pattern, string replacement) { this.Pattern = pattern; this.Replacement = replacement; } public override string ToString() { return string.Format("{0} -> {1}", Pattern.ToString(), Replacement); } } } }
/* * John Hall <john.hall@camtechconsultants.com> * Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved. */ using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace CTC.CvsntGitImporter { /// <summary> /// Collection of rename rules to rename tags and branches. The rules are processed in the order in which /// they were added and processing stops as soon as a rule matches. /// </summary> class Renamer { private readonly List<Rule> m_rules = new List<Rule>(); /// <summary> /// Adds a renaming rule. /// </summary> public void AddRule(Regex pattern, string replacement) { m_rules.Add(new Rule(pattern, replacement)); } /// <summary> /// Process a name, renaming it if it matches a rule. /// </summary> public string Process(string name) { var match = m_rules.FirstOrDefault(r => r.Pattern.IsMatch(name)); if (match == null) return name; else return match.Pattern.Replace(name, match.Replacement); } private class Rule { public readonly Regex Pattern; public readonly string Replacement; public Rule(Regex pattern, string replacement) { this.Pattern = pattern; this.Replacement = replacement; } } } }
mit
C#
7692b650b75addfbb3eb735dbb324804d5c8fa85
Update GenericPersister.cs
guilherme-otran/projeto-integrado-2-sem
projeto-integrado-2-sem/Interactors/GenericPersister.cs
projeto-integrado-2-sem/Interactors/GenericPersister.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using projeto_integrado_2_sem.Repositories; using projeto_integrado_2_sem.Validators; using projeto_integrado_2_sem.Models; namespace projeto_integrado_2_sem.Interactors { class GenericPersister<T> where T : IStorable { private BaseRepository<T> repository; private Validator<T>[] validators; public GenericPersister(BaseRepository<T> repo, Validator<T>[] validators) { this.repository = repo; this.validators = validators; } public bool persist(T record) { var results = validators.Select(v => v.Validate(record)); if (results.All(r => r.Valid())) { repository.persist(record); } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using projeto_integrado_2_sem.Repositories; using projeto_integrado_2_sem.Validators; namespace projeto_integrado_2_sem.Interactors { class GenericPersister<T> where T : IStorable { private BaseRepository<T> repository; private Validator<T>[] validators; public GenericPersister(BaseRepository<T> repo, Validator<T>[] validators) { this.repository = repo; this.validators = validators; } public bool persist(T record) { var results = validators.Select(v => v.Validate(record)); if (results.All(r => r.Valid())) { repository.persist(record); } return false; } } }
mit
C#