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 |
|---|---|---|---|---|---|---|---|---|
c20d2e4938b99b28a72700834d203d4cee40b34d | Update Program.cs | wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp | CefSharp.WinForms.Example/Program.cs | CefSharp.WinForms.Example/Program.cs | // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Forms;
using CefSharp.Example;
using CefSharp.WinForms.Example.Minimal;
namespace CefSharp.WinForms.Example
{
public class Program
{
[STAThread]
public static void Main()
{
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
MessageBox.Show("When running this Example outside of Visual Studio" +
"please make sure you compile in `Release` mode.", "Warning");
}
#endif
const bool multiThreadedMessageLoop = true;
CefExample.Init(false, multiThreadedMessageLoop: multiThreadedMessageLoop);
if(multiThreadedMessageLoop == false)
{
//http://magpcss.org/ceforum/apidocs3/projects/%28default%29/%28_globals%29.html#CefDoMessageLoopWork%28%29
//Perform a single iteration of CEF message loop processing.
//This function is used to integrate the CEF message loop into an existing application message loop.
//Care must be taken to balance performance against excessive CPU usage.
//This function should only be called on the main application thread and only if CefInitialize() is called with a CefSettings.multi_threaded_message_loop value of false.
//This function will not block.
Application.Idle += (s, e) => Cef.DoMessageLoopWork();
}
var browser = new BrowserForm();
//var browser = new SimpleBrowserForm();
//var browser = new TabulationDemoForm();
Application.Run(browser);
}
}
}
| // Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Forms;
using CefSharp.Example;
using CefSharp.WinForms.Example.Minimal;
namespace CefSharp.WinForms.Example
{
public class Program
{
[STAThread]
public static void Main()
{
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
MessageBox.Show("When running this Example outside of Visual Studio" +
"please make sure you compile in `Release` mode.", "Warning");
}
#endif
//坑爹呢 .NET4.5编译的项目啊 让XP怎么办呢?
//自己来编译源码吧 哎 又是C++
const bool multiThreadedMessageLoop = true;
CefExample.Init(false, multiThreadedMessageLoop: multiThreadedMessageLoop);
if(multiThreadedMessageLoop == false)
{
//http://magpcss.org/ceforum/apidocs3/projects/%28default%29/%28_globals%29.html#CefDoMessageLoopWork%28%29
//Perform a single iteration of CEF message loop processing.
//This function is used to integrate the CEF message loop into an existing application message loop.
//Care must be taken to balance performance against excessive CPU usage.
//This function should only be called on the main application thread and only if CefInitialize() is called with a CefSettings.multi_threaded_message_loop value of false.
//This function will not block.
Application.Idle += (s, e) => Cef.DoMessageLoopWork();
}
var browser = new BrowserForm();
//var browser = new SimpleBrowserForm();
//var browser = new TabulationDemoForm();
Application.Run(browser);
}
}
}
| bsd-3-clause | C# |
d0cbed069cc496f0ea741bdad188939144aa5f84 | add country code to company file | MYOB-Technology/AccountRight_Live_API_.Net_SDK,tungripe/AccountRight_Live_API_.Net_SDK,sawilde/AccountRight_Live_API_.Net_SDK | MYOB.API.SDK/SDK/Contracts/CompanyFile.cs | MYOB.API.SDK/SDK/Contracts/CompanyFile.cs | using System;
using System.Runtime.Serialization;
namespace MYOB.AccountRight.SDK.Contracts
{
/// <summary>
/// CompanyFile
/// </summary>
public class CompanyFile
{
/// <summary>
/// The CompanyFile Identifier
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// CompanyFile Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// CompanyFile Library full path (including file name).
/// </summary>
public string LibraryPath { get; set; }
/// <summary>
/// Account Right Live product version compatible with this CompanyFile
/// </summary>
public string ProductVersion { get; set; }
/// <summary>
/// Account Right Live product level of the CompanyFile
/// </summary>
public ProductLevel ProductLevel { get; set; }
/// <summary>
/// Uri of the resource
/// </summary>
public Uri Uri { get; set; }
/// <summary>
/// Launcher Id can be used to open Online Company files from command line
/// </summary>
public Guid? LauncherId { get; set; }
/// <summary>
/// Country code.
/// </summary>
public String Country { get; set; }
}
}
| using System;
using System.Runtime.Serialization;
namespace MYOB.AccountRight.SDK.Contracts
{
/// <summary>
/// CompanyFile
/// </summary>
public class CompanyFile
{
/// <summary>
/// The CompanyFile Identifier
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// CompanyFile Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// CompanyFile Library full path (including file name).
/// </summary>
public string LibraryPath { get; set; }
/// <summary>
/// Account Right Live product version compatible with this CompanyFile
/// </summary>
public string ProductVersion { get; set; }
/// <summary>
/// Account Right Live product level of the CompanyFile
/// </summary>
public ProductLevel ProductLevel { get; set; }
/// <summary>
/// Uri of the resource
/// </summary>
public Uri Uri { get; set; }
/// <summary>
/// Launcher Id can be used to open Online Company files from command line
/// </summary>
public Guid? LauncherId { get; set; }
}
}
| mit | C# |
deac39008fe6e6a86406f192225f36a5ac0df839 | Update EdgeBase.cs to support new ReversePath property. | panthernet/GraphX,slate56/GraphX,edgardozoppi/GraphX,jorgensigvardsson/GraphX,perturbare/GraphX,slate56/GraphX | GraphX.PCL.Common/Models/EdgeBase.cs | GraphX.PCL.Common/Models/EdgeBase.cs | using GraphX.Measure;
using GraphX.PCL.Common.Enums;
using GraphX.PCL.Common.Interfaces;
namespace GraphX.PCL.Common.Models
{
/// <summary>
/// Base class for graph edge
/// </summary>
/// <typeparam name="TVertex">Vertex class</typeparam>
public abstract class EdgeBase<TVertex> : IGraphXEdge<TVertex>
{
/// <summary>
/// Skip edge in algo calc and visualization
/// </summary>
public ProcessingOptionEnum SkipProcessing { get; set; }
protected EdgeBase(TVertex source, TVertex target, double weight = 1)
{
Source = source;
Target = target;
Weight = weight;
ID = -1;
}
/// <summary>
/// Unique edge ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// Returns true if Source vertex equals Target vertex
/// </summary>
public bool IsSelfLoop
{
get { return Source.Equals(Target); }
}
/// <summary>
/// Optional parameter to bind edge to static vertex connection point
/// </summary>
public int? SourceConnectionPointId { get; set; }
/// <summary>
/// Optional parameter to bind edge to static vertex connection point
/// </summary>
public int? TargetConnectionPointId { get; set; }
/// <summary>
/// Routing points collection used to make Path visual object
/// </summary>
public virtual Point[] RoutingPoints { get; set; }
/// <summary>
/// Source vertex
/// </summary>
public TVertex Source { get; set; }
/// <summary>
/// Target vertex
/// </summary>
public TVertex Target { get; set; }
/// <summary>
/// Edge weight that can be used by some weight-related layout algorithms
/// </summary>
public double Weight { get; set; }
/// <summary>
/// Reverse the calculated routing path points.
/// </summary>
public bool ReversePath { get; set; }
}
}
| using GraphX.Measure;
using GraphX.PCL.Common.Enums;
using GraphX.PCL.Common.Interfaces;
namespace GraphX.PCL.Common.Models
{
/// <summary>
/// Base class for graph edge
/// </summary>
/// <typeparam name="TVertex">Vertex class</typeparam>
public abstract class EdgeBase<TVertex> : IGraphXEdge<TVertex>
{
/// <summary>
/// Skip edge in algo calc and visualization
/// </summary>
public ProcessingOptionEnum SkipProcessing { get; set; }
protected EdgeBase(TVertex source, TVertex target, double weight = 1)
{
Source = source;
Target = target;
Weight = weight;
ID = -1;
}
/// <summary>
/// Unique edge ID
/// </summary>
public int ID { get; set; }
/// <summary>
/// Returns true if Source vertex equals Target vertex
/// </summary>
public bool IsSelfLoop
{
get { return Source.Equals(Target); }
}
/// <summary>
/// Optional parameter to bind edge to static vertex connection point
/// </summary>
public int? SourceConnectionPointId { get; set; }
/// <summary>
/// Optional parameter to bind edge to static vertex connection point
/// </summary>
public int? TargetConnectionPointId { get; set; }
/// <summary>
/// Routing points collection used to make Path visual object
/// </summary>
public virtual Point[] RoutingPoints { get; set; }
/// <summary>
/// Source vertex
/// </summary>
public TVertex Source { get; set; }
/// <summary>
/// Target vertex
/// </summary>
public TVertex Target { get; set; }
/// <summary>
/// Edge weight that can be used by some weight-related layout algorithms
/// </summary>
public double Weight { get; set; }
}
}
| apache-2.0 | C# |
4ee05704adf4d448d380f2038232e064e80762d3 | Remove empty OnGet function. | Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net | LearnosityDemo/Pages/Index.cshtml.cs | LearnosityDemo/Pages/Index.cshtml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace LearnosityDemo.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
// public void OnGet()
// {
// }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace LearnosityDemo.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
}
}
}
| apache-2.0 | C# |
ee3cd636282db58a42ed22f80ab6aea99edd58dc | add standard controller/id route | Pondidum/NuCache,Pondidum/NuCache,Pondidum/NuCache | NuCache/App_Start/ConfigureRoutes.cs | NuCache/App_Start/ConfigureRoutes.cs | using System.Web.Http;
using System.Web.Mvc;
namespace NuCache
{
public static class ConfigureRoutes
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Root",
routeTemplate: "api/v2/",
defaults: new { controller = "Packages", action = "Get"}
);
config.Routes.MapHttpRoute(
name: "Metadata",
routeTemplate: "api/v2/$metadata",
defaults: new { controller = "Packages", action = "Metadata" }
);
config.Routes.MapHttpRoute(
name: "Packages",
routeTemplate: "api/v2/packages",
defaults: new { controller = "Packages", action = "List"}
);
config.Routes.MapHttpRoute(
name: "FindByID",
routeTemplate: "api/v2/FindPackagesByID()",
defaults: new { controller = "Packages", action = "FindPackagesByID" }
);
config.Routes.MapHttpRoute(
name: "Search",
routeTemplate: "api/v2/search()/{method}",
defaults: new {controller = "Packages", action = "Search", method = UrlParameter.Optional}
);
config.Routes.MapHttpRoute(
name: "Download",
routeTemplate: "api/v2/package/{name}/{version}",
defaults: new { controller = "Packages", action = "GetPackageByID", name = UrlParameter.Optional, version = UrlParameter.Optional}
);
config.Routes.MapHttpRoute(
name: "package-ids",
routeTemplate: "api/v2/package-ids",
defaults: new { controller = "Packages", action = "GetPackageIDs" }
);
config.Routes.MapHttpRoute(
name: "Home",
routeTemplate: "",
defaults: new {controller = "Home"}
);
config.Routes.MapHttpRoute(
name: "Standard",
routeTemplate: "{controller}/{id}",
defaults: new { id = UrlParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "Error404",
routeTemplate: "{*url}",
defaults: new { controller = "Error", action = "Handle404" }
);
}
}
}
| using System.Web.Http;
using System.Web.Mvc;
namespace NuCache
{
public static class ConfigureRoutes
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Root",
routeTemplate: "api/v2/",
defaults: new { controller = "Packages", action = "Get"}
);
config.Routes.MapHttpRoute(
name: "Metadata",
routeTemplate: "api/v2/$metadata",
defaults: new { controller = "Packages", action = "Metadata" }
);
config.Routes.MapHttpRoute(
name: "Packages",
routeTemplate: "api/v2/packages",
defaults: new { controller = "Packages", action = "List"}
);
config.Routes.MapHttpRoute(
name: "FindByID",
routeTemplate: "api/v2/FindPackagesByID()",
defaults: new { controller = "Packages", action = "FindPackagesByID" }
);
config.Routes.MapHttpRoute(
name: "Search",
routeTemplate: "api/v2/search()/{method}",
defaults: new {controller = "Packages", action = "Search", method = UrlParameter.Optional}
);
config.Routes.MapHttpRoute(
name: "Download",
routeTemplate: "api/v2/package/{name}/{version}",
defaults: new { controller = "Packages", action = "GetPackageByID", name = UrlParameter.Optional, version = UrlParameter.Optional}
);
config.Routes.MapHttpRoute(
name: "package-ids",
routeTemplate: "api/v2/package-ids",
defaults: new { controller = "Packages", action = "GetPackageIDs" }
);
config.Routes.MapHttpRoute(
name: "Home",
routeTemplate: "",
defaults: new {controller = "Home"}
);
config.Routes.MapHttpRoute(
name: "Error404",
routeTemplate: "{*url}",
defaults: new { controller = "Error", action = "Handle404" }
);
}
}
}
| lgpl-2.1 | C# |
a2c95501b2c62c5f613c074671e01f9b3a4d43d3 | optimize StringLengthValidationRule | tibel/Caliburn.Light | src/Caliburn.Core/Validation/StringLengthValidationRule.cs | src/Caliburn.Core/Validation/StringLengthValidationRule.cs | using System.Globalization;
namespace Caliburn.Light
{
/// <summary>
/// Performs a length validation of a <see cref="string"/>.
/// </summary>
public class StringLengthValidationRule : ValidationRule<string>
{
private readonly int _minimumLength;
private readonly int _maximumLength;
private readonly string _errorMessage;
/// <summary>
/// Initializes a new instance of the <see cref="StringLengthValidationRule"/> class.
/// </summary>
/// <param name="minimumLength">The minimum length.</param>
/// <param name="maximumLength">The maximum length.</param>
/// <param name="errorMessage">The error message.</param>
public StringLengthValidationRule(int minimumLength, int maximumLength, string errorMessage)
{
_minimumLength = minimumLength;
_maximumLength = maximumLength;
_errorMessage = errorMessage;
}
/// <summary>
/// Performs validation checks on a value.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>A <see cref="ValidationResult" /> object.</returns>
protected override ValidationResult OnValidate(string value, CultureInfo cultureInfo)
{
var length = 0;
if (!string.IsNullOrEmpty(value))
length = GetTrimmedLength(value);
if (length < _minimumLength || length > _maximumLength)
return ValidationResult.Failure(cultureInfo, _errorMessage, _minimumLength, _maximumLength, length);
return ValidationResult.Success();
}
private static int GetTrimmedLength(string value)
{
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
var end = value.Length - 1;
var start = 0;
for (; start < value.Length; start++)
{
if (!char.IsWhiteSpace(value[start])) break;
}
for (; end >= start; end--)
{
if (!char.IsWhiteSpace(value[end])) break;
}
return end - start + 1;
}
}
}
| using System.Globalization;
namespace Caliburn.Light
{
/// <summary>
/// Performs a length validation of a <see cref="string"/>.
/// </summary>
public class StringLengthValidationRule : ValidationRule<string>
{
private readonly int _minimumLength;
private readonly int _maximumLength;
private readonly string _errorMessage;
/// <summary>
/// Initializes a new instance of the <see cref="StringLengthValidationRule"/> class.
/// </summary>
/// <param name="minimumLength">The minimum length.</param>
/// <param name="maximumLength">The maximum length.</param>
/// <param name="errorMessage">The error message.</param>
public StringLengthValidationRule(int minimumLength, int maximumLength, string errorMessage)
{
_minimumLength = minimumLength;
_maximumLength = maximumLength;
_errorMessage = errorMessage;
}
/// <summary>
/// Performs validation checks on a value.
/// </summary>
/// <param name="value">The value to check.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>A <see cref="ValidationResult" /> object.</returns>
protected override ValidationResult OnValidate(string value, CultureInfo cultureInfo)
{
var length = 0;
if (!string.IsNullOrEmpty(value))
length = value.Trim().Length;
if (length < _minimumLength || length > _maximumLength)
return ValidationResult.Failure(cultureInfo, _errorMessage, _minimumLength, _maximumLength, length);
return ValidationResult.Success();
}
}
}
| mit | C# |
0511100b6b27fdb0dd7e194584451b6a7607d2fd | Remove unused usings. | jrick/Paymetheus,decred/Paymetheus,madferreiro/Paymetheus-Fork,btcsuite/Paymetheus | Paymetheus.Rpc/ConnectTimeoutException.cs | Paymetheus.Rpc/ConnectTimeoutException.cs | // Copyright (c) 2016 The btcsuite developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using System;
namespace Paymetheus.Rpc
{
[Serializable]
public class ConnectTimeoutException : Exception
{
public ConnectTimeoutException() : base() { }
}
}
| // Copyright (c) 2016 The btcsuite developers
// Licensed under the ISC license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Paymetheus.Rpc
{
[Serializable]
public class ConnectTimeoutException : Exception
{
public ConnectTimeoutException() : base() { }
}
}
| isc | C# |
361c65ef19caa4040fa1ddd26245537b4cd5b284 | Update anchor within help link (follow-up to r3671). Closes #3647. | dokipen/trac,moreati/trac-gitsvn,dafrito/trac-mirror,exocad/exotrac,dokipen/trac,dokipen/trac,dafrito/trac-mirror,dafrito/trac-mirror,moreati/trac-gitsvn,exocad/exotrac,moreati/trac-gitsvn,exocad/exotrac,exocad/exotrac,dafrito/trac-mirror,moreati/trac-gitsvn | templates/anydiff.cs | templates/anydiff.cs | <?cs include "header.cs"?>
<div id="ctxtnav" class="nav"></div>
<div id="content" class="changeset">
<div id="title">
<h1>Select Base and Target for Diff:</h1>
</div>
<div id="anydiff">
<form action="<?cs var:anydiff.changeset_href ?>" method="get">
<table>
<tr>
<th><label for="old_path">From:</label></th>
<td>
<input type="text" id="old_path" name="old_path" value="<?cs
var:anydiff.old_path ?>" size="44" />
<label for="old_rev">at Revision:</label>
<input type="text" id="old_rev" name="old" value="<?cs
var:anydiff.old_rev ?>" size="4" />
</td>
</tr>
<tr>
<th><label for="new_path">To:</label></th>
<td>
<input type="text" id="new_path" name="new_path" value="<?cs
var:anydiff.new_path ?>" size="44" />
<label for="new_rev">at Revision:</label>
<input type="text" id="new_rev" name="new" value="<?cs
var:anydiff.new_rev ?>" size="4" />
</td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="View changes" />
</div>
</form>
</div>
<div id="help">
<strong>Note:</strong> See <a href="<?cs var:trac.href.wiki
?>/TracChangeset#ExaminingDifferencesBetweenBranches">TracChangeset</a> for help on using the arbitrary diff feature.
</div>
</div>
<?cs include "footer.cs"?>
| <?cs include "header.cs"?>
<div id="ctxtnav" class="nav"></div>
<div id="content" class="changeset">
<div id="title">
<h1>Select Base and Target for Diff:</h1>
</div>
<div id="anydiff">
<form action="<?cs var:anydiff.changeset_href ?>" method="get">
<table>
<tr>
<th><label for="old_path">From:</label></th>
<td>
<input type="text" id="old_path" name="old_path" value="<?cs
var:anydiff.old_path ?>" size="44" />
<label for="old_rev">at Revision:</label>
<input type="text" id="old_rev" name="old" value="<?cs
var:anydiff.old_rev ?>" size="4" />
</td>
</tr>
<tr>
<th><label for="new_path">To:</label></th>
<td>
<input type="text" id="new_path" name="new_path" value="<?cs
var:anydiff.new_path ?>" size="44" />
<label for="new_rev">at Revision:</label>
<input type="text" id="new_rev" name="new" value="<?cs
var:anydiff.new_rev ?>" size="4" />
</td>
</tr>
</table>
<div class="buttons">
<input type="submit" value="View changes" />
</div>
</form>
</div>
<div id="help">
<strong>Note:</strong> See <a href="<?cs var:trac.href.wiki
?>/TracChangeset#ExaminingArbitraryDifferences">TracChangeset</a> for help on using the arbitrary diff feature.
</div>
</div>
<?cs include "footer.cs"?>
| bsd-3-clause | C# |
50ce4a5225e1f62c622001a02c9f66e2e86012a3 | Fix to not use a test filter in NUnit when no filters has been declared in Giles. This was causing NUnit to not run the tests | michaelsync/Giles,codereflection/Giles,codereflection/Giles,codereflection/Giles,michaelsync/Giles,michaelsync/Giles,michaelsync/Giles | src/Runners/Giles.Runner.NUnit/NUnitRunner.cs | src/Runners/Giles.Runner.NUnit/NUnitRunner.cs | using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
if (filters.Count() == 0)
remoteTestRunner.Run(listener);
else
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Giles.Core.Runners;
using Giles.Core.Utility;
using NUnit.Core;
using NUnit.Core.Filters;
namespace Giles.Runner.NUnit
{
public class NUnitRunner : IFrameworkRunner
{
IEnumerable<string> filters;
public SessionResults RunAssembly(Assembly assembly, IEnumerable<string> filters)
{
this.filters = filters;
var remoteTestRunner = new RemoteTestRunner(0);
var package = SetupTestPackager(assembly);
remoteTestRunner.Load(package);
var listener = new GilesNUnitEventListener();
remoteTestRunner.Run(listener, GetFilters());
return listener.SessionResults;
}
ITestFilter GetFilters()
{
var simpleNameFilter = new SimpleNameFilter(filters.ToArray());
return simpleNameFilter;
}
public IEnumerable<string> RequiredAssemblies()
{
return new[]
{
Assembly.GetAssembly(typeof(NUnitRunner)).Location,
"nunit.core.dll", "nunit.core.interfaces.dll"
};
}
private static TestPackage SetupTestPackager(Assembly assembly)
{
return new TestPackage(assembly.FullName, new[] { assembly.Location });
}
}
} | mit | C# |
1fa570f1238302ba0af2749fc69d66978f66fb7b | Update copyright. | FantasticFiasco/teamcity-backup | src/TeamCityBackup/Properties/AssemblyInfo.cs | src/TeamCityBackup/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TeamCity Backup")]
[assembly: AssemblyDescription("Console application capable of creating TeamCity backups.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("FantasticFiasco")]
[assembly: AssemblyProduct("TeamCity Backup")]
[assembly: AssemblyCopyright("Copyright © FantasticFiasco 2014-2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("046f3afa-643e-40aa-aa66-4116659266ed")]
// 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.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("TeamCity Backup")]
[assembly: AssemblyDescription("Console application capable of creating TeamCity backups.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("FantasticFiasco")]
[assembly: AssemblyProduct("TeamCity Backup")]
[assembly: AssemblyCopyright("Copyright © FantasticFiasco 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("046f3afa-643e-40aa-aa66-4116659266ed")]
// 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")] | apache-2.0 | C# |
86e4187032094c108eadaebed0251104bb46c67c | Update help responder with new commands | prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15,prinzo/Attack-Of-The-Fines-TA15 | FineBot/FineBot.BotRunner/Responders/HelpResponder.cs | FineBot/FineBot.BotRunner/Responders/HelpResponder.cs | using System;
using System.Text;
using FineBot.BotRunner.Extensions;
using FineBot.BotRunner.Responders.Interfaces;
using FineBot.Enums;
using MargieBot.Models;
namespace FineBot.BotRunner.Responders
{
public class HelpResponder : IFineBotResponder
{
public bool CanRespond(ResponseContext context)
{
var command = context.GetCommandMentioningBot("help");
return context.Message.MentionsBot
&& !context.BotHasResponded
&& context.Message.Text.ToLower().Contains(command.ToLower());
}
public BotMessage GetResponse(ResponseContext context)
{
var builder = new StringBuilder();
builder.AppendLine("@finesbot fine @<slack user> for <reason>: Award a fine to a slack user, you can fine multiple people at once.");
builder.AppendLine();
builder.AppendLine("seconded!: Second the oldest awarded fine that was not seconded.");
builder.AppendLine();
builder.AppendLine("@finesbot pay <number of fines> fine(s) for @<slack user>: Pay the specified number of fines for the specified user. Note: You must include an image of the fine payment and may not pay your own fines!");
builder.AppendLine();
builder.AppendLine("@finesbot leaderboard <today|week|month|year>: Leaderboard of the top five users with the most fines for the current day/week/month/year. If no time period is specified, the all time leaderboard is displayed");
builder.AppendLine();
builder.AppendLine("@finesbot fine count <all|users>: Counts the number of fines successfully issued (i.e. seconded) by the specified users. If \"all\" is specified the count for all fines will be displayed. If no users are specified, the fine count of the requester will be displayed.");
builder.AppendLine();
builder.AppendLine("@finesbot seconded count <users>: Counts the number of fines seconded by the specified users. If no user is specified, the number of fines seconded by the requester will be displayed.");
builder.AppendLine();
builder.AppendLine(String.Format("@FinesBot support <support type: {0}> <message>: Creates a support ticket with the status selected. If no status is specified it is created as a general issue.", String.Join("|", Enum.GetNames(typeof(SupportType)))));
return new BotMessage{Text = builder.ToString()};
}
}
} | using System;
using System.Text;
using FineBot.BotRunner.Extensions;
using FineBot.BotRunner.Responders.Interfaces;
using FineBot.Enums;
using MargieBot.Models;
namespace FineBot.BotRunner.Responders
{
public class HelpResponder : IFineBotResponder
{
public bool CanRespond(ResponseContext context)
{
var command = context.GetCommandMentioningBot("help");
return context.Message.MentionsBot
&& !context.BotHasResponded
&& context.Message.Text.ToLower().Contains(command.ToLower());
}
public BotMessage GetResponse(ResponseContext context)
{
var builder = new StringBuilder();
builder.AppendLine("@finesbot fine @<slack user> for <reason>: Award a fine to a slack user, you can fine multiple people at once.");
builder.AppendLine();
builder.AppendLine("seconded!: Second the oldest awarded fine that was not seconded.");
builder.AppendLine();
builder.AppendLine("@finesbot pay <number of fines> fine(s) for @<slack user>: Pay the specified number of fines for the specified user. Note: You must include an image of the fine payment and may not pay your own fines!");
builder.AppendLine();
builder.AppendLine("@finesbot leaderboard <today|week|month|year>: Leaderboard of the top five users with the most fines for the current day/week/month/year. If no time period is specified, the all time leaderboard is displayed");
builder.AppendLine();
builder.AppendLine("@finesbot count all: Counts the number of fines successfully issued (i.e. seconded) by all users.");
builder.AppendLine();
builder.AppendLine(String.Format("@FinesBot support <support type: {0}> <message>: Creates a support ticket with the status selected. If no status is specified it is created as a general issue.", String.Join("|", Enum.GetNames(typeof(SupportType)))));
return new BotMessage{Text = builder.ToString()};
}
}
} | mit | C# |
e604e17df7ea0a7481cf3a94a5e3ea1d533b2b22 | Fix the rat for now. | tgiphil/Cosmos,zarlo/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,trivalik/Cosmos,trivalik/Cosmos,CosmosOS/Cosmos,zarlo/Cosmos,tgiphil/Cosmos,CosmosOS/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,tgiphil/Cosmos,trivalik/Cosmos,jp2masa/Cosmos,fanoI/Cosmos,zarlo/Cosmos,jp2masa/Cosmos,CosmosOS/Cosmos,fanoI/Cosmos | source/Cosmos.Core.Memory/HeapSmall.cs | source/Cosmos.Core.Memory/HeapSmall.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Native = System.UInt32;
namespace Cosmos.Core.Memory {
//TODO Remove empty pages as necessary
unsafe static public class HeapSmall {
public const Native PrefixBytes = 4 * sizeof(Native);
public static Native mMaxItemSize;
private static void** mSMT;
static public void Init() {
// Size map table
// Smaller sizes point to bigger one
// Each Page then is linked forward to next for each size.
// //TODO Adjust for new page and header sizes
InitSMT(1016);
// TODO Change these sizes after further stufy and also when page size
// changes. Also can adjust and create new ones dynamicaly as it runs.
// SMT can be grown as needed.
CreatePage(16);
CreatePage(24);
CreatePage(48);
CreatePage(64);
CreatePage(128);
CreatePage(256);
CreatePage(512);
CreatePage(mMaxItemSize);
}
static void InitSMT(Native aMaxItemSize) {
mMaxItemSize = aMaxItemSize;
Native xPageCount = mMaxItemSize * (Native)sizeof(void*) / RAT.PageSize;
mSMT = (void**)RAT.Alloc(RAT.PageType.HeapSmall, xPageCount);
}
static void CreatePage(Native aItemSize) {
if (aItemSize == 0) {
throw new Exception("ItemSize cannot be 0.");
} else if (aItemSize % sizeof(Native) != 0) {
throw new Exception("Item size must be word aligned.");
} else if (mMaxItemSize == 0) {
throw new Exception("SMT is not initialized.");
} else if (aItemSize > mMaxItemSize) {
throw new Exception("Cannot allocate more than MaxItemSize in SmallHeap.");
}
var xPtr = (Native*)RAT.Alloc(RAT.PageType.HeapSmall);
*xPtr = 0;
//for (void** p = mSMT + aItemSize; ; p--) {
//// TODO - Make a free list, put a ptr in item header and first page header - how to keep compact?
//}
// Header
// Ptr to next page of same size
// Each Item
//xPtr[0] = aSize; // Actual data size
//xPtr[1] = 0; // Ref count
//xPtr[2] = 0; // Ptr to first
}
static public byte* Alloc(Native aSize) {
return HeapLarge.Alloc(aSize);
}
static public void Free(void* aPtr) {
HeapLarge.Free(aPtr);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Native = System.UInt32;
namespace Cosmos.Core.Memory {
//TODO Remove empty pages as necessary
unsafe static public class HeapSmall {
public const Native PrefixBytes = 4 * sizeof(Native);
public static Native mMaxItemSize;
private static void** mSMT;
static public void Init() {
// Size map table
// Smaller sizes point to bigger one
// Each Page then is linked forward to next for each size.
// //TODO Adjust for new page and header sizes
InitSMT(1016);
// TODO Change these sizes after further stufy and also when page size
// changes. Also can adjust and create new ones dynamicaly as it runs.
// SMT can be grown as needed.
CreatePage(16);
CreatePage(24);
CreatePage(48);
CreatePage(64);
CreatePage(128);
CreatePage(256);
CreatePage(512);
CreatePage(mMaxItemSize);
}
static void InitSMT(Native aMaxItemSize) {
mMaxItemSize = aMaxItemSize;
Native xPageCount = mMaxItemSize * (Native)sizeof(void*) / RAT.PageSize;
mSMT = (void**)RAT.Alloc(RAT.PageType.HeapSmall, xPageCount);
}
static void CreatePage(Native aItemSize) {
if (aItemSize == 0) {
throw new Exception("ItemSize cannot be 0.");
} else if (aItemSize % sizeof(Native) != 0) {
throw new Exception("Item size must be word aligned.");
} else if (mMaxItemSize == 0) {
throw new Exception("SMT is not initialized.");
} else if (aItemSize > mMaxItemSize) {
throw new Exception("Cannot allocate more than MaxItemSize in SmallHeap.");
}
var xPtr = (Native*)RAT.Alloc(RAT.PageType.HeapSmall);
*xPtr = 0;
for (void** p = mSMT + aItemSize; ; p--) {
// TODO - Make a free list, put a ptr in item header and first page header - how to keep compact?
}
// Header
// Ptr to next page of same size
// Each Item
//xPtr[0] = aSize; // Actual data size
//xPtr[1] = 0; // Ref count
//xPtr[2] = 0; // Ptr to first
}
static public byte* Alloc(Native aSize) {
return HeapLarge.Alloc(aSize);
}
static public void Free(void* aPtr) {
HeapLarge.Free(aPtr);
}
}
}
| bsd-3-clause | C# |
b6378c7ae22ef88365a604a34289f574d6decae1 | fix speed | smoogipooo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,EVAST9919/osu | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.Enabled = false;
spinner.OnUpdate += autoSpin;
}
}
}
private void autoSpin(Drawable drawable)
{
if (drawable is DrawableSpinner spinner)
{
if (spinner.Disc.Valid)
spinner.Disc.Rotate(180 / MathF.PI * (float)spinner.Clock.ElapsedFrameTime * 0.03f);
if (!spinner.SpmCounter.IsPresent)
spinner.SpmCounter.FadeIn(spinner.HitObject.TimeFadeIn);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.Enabled = false;
spinner.OnUpdate += autoSpin;
}
}
}
private void autoSpin(Drawable drawable)
{
if (drawable is DrawableSpinner spinner)
{
if (spinner.Disc.Valid)
spinner.Disc.Rotate(180 / MathF.PI * (float)spinner.Clock.ElapsedFrameTime / 40);
if (!spinner.SpmCounter.IsPresent)
spinner.SpmCounter.FadeIn(spinner.HitObject.TimeFadeIn);
}
}
}
}
| mit | C# |
50985d1b1d952b7d922c0a4ccd3936218061cc26 | Fix disposal logic | peppy/osu,UselessToucan/osu,ppy/osu,2yangk23/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,ppy/osu,smoogipoo/osu,EVAST9919/osu,2yangk23/osu,peppy/osu,EVAST9919/osu,ZLima12/osu,johnneijzen/osu,ZLima12/osu,peppy/osu-new,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu | osu.Game/Rulesets/UI/FallbackSampleStore.cs | osu.Game/Rulesets/UI/FallbackSampleStore.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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.UI
{
public class FallbackSampleStore : ISampleStore
{
private readonly ISampleStore primary;
private readonly ISampleStore secondary;
public FallbackSampleStore(ISampleStore primary, ISampleStore secondary)
{
this.primary = primary;
this.secondary = secondary;
}
public SampleChannel Get(string name) => primary.Get(name) ?? secondary.Get(name);
public Task<SampleChannel> GetAsync(string name) => primary.GetAsync(name) ?? secondary.GetAsync(name);
public Stream GetStream(string name) => primary.GetStream(name) ?? secondary.GetStream(name);
public IEnumerable<string> GetAvailableResources() => primary.GetAvailableResources().Concat(secondary.GetAvailableResources());
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.AddAdjustment(type, adjustBindable);
secondary.AddAdjustment(type, adjustBindable);
}
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.RemoveAdjustment(type, adjustBindable);
secondary.RemoveAdjustment(type, adjustBindable);
}
public BindableDouble Volume => primary.Volume;
public BindableDouble Balance => primary.Balance;
public BindableDouble Frequency => primary.Frequency;
public int PlaybackConcurrency
{
get => primary.PlaybackConcurrency;
set
{
primary.PlaybackConcurrency = value;
secondary.PlaybackConcurrency = value;
}
}
public void Dispose()
{
}
}
}
| // 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.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio.Track;
using osu.Framework.Bindables;
namespace osu.Game.Rulesets.UI
{
public class FallbackSampleStore : ISampleStore
{
private readonly ISampleStore primary;
private readonly ISampleStore secondary;
public FallbackSampleStore(ISampleStore primary, ISampleStore secondary)
{
this.primary = primary;
this.secondary = secondary;
}
public void Dispose()
{
primary.Dispose();
secondary.Dispose();
}
public SampleChannel Get(string name) => primary.Get(name) ?? secondary.Get(name);
public Task<SampleChannel> GetAsync(string name) => primary.GetAsync(name) ?? secondary.GetAsync(name);
public Stream GetStream(string name) => primary.GetStream(name) ?? secondary.GetStream(name);
public IEnumerable<string> GetAvailableResources() => primary.GetAvailableResources().Concat(secondary.GetAvailableResources());
public void AddAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.AddAdjustment(type, adjustBindable);
secondary.AddAdjustment(type, adjustBindable);
}
public void RemoveAdjustment(AdjustableProperty type, BindableDouble adjustBindable)
{
primary.RemoveAdjustment(type, adjustBindable);
secondary.RemoveAdjustment(type, adjustBindable);
}
public BindableDouble Volume => primary.Volume;
public BindableDouble Balance => primary.Balance;
public BindableDouble Frequency => primary.Frequency;
public int PlaybackConcurrency
{
get => primary.PlaybackConcurrency;
set => primary.PlaybackConcurrency = value;
}
}
}
| mit | C# |
30c6011c6fe1b68a90fe8fd0bf4b28be1dd21b45 | add benchmarks | kaosborn/KaosCollections | Bench/BtreeBench03/BtreeBench03.cs | Bench/BtreeBench03/BtreeBench03.cs | //
// Program: BtreeBench03.cs
// Purpose: Benchmark BtreeDictionary fill percent.
//
// Usage notes:
// • Run in Debug build for diagnostics.
//
using System;
using System.Reflection;
using Kaos.Collections;
[assembly: AssemblyVersion ("0.1.0.0")]
namespace BenchApp
{
public class BtreeBench03
{
static BtreeDictionary<Guid,int> tree;
static void Main (string[] args)
{
foreach (var reps in new int[] { 100, 1000, 10000, 100000, 1000000, 10000000, 20000000, 40000000 })
{
tree = new BtreeDictionary<Guid,int> (128);
for (int ii = 0; ii < reps; ++ii)
tree.Add (Guid.NewGuid(), ii);
Console.WriteLine (reps);
#if DEBUG
Console.WriteLine (tree.GetTreeStatsText());
#endif
}
}
}
}
| //
// Program: BtreeBench03.cs
// Purpose: Benchmark BtreeDictionary fill percent.
//
// Usage notes:
// • Run in Debug build for diagnostics.
//
using System;
using System.Reflection;
using Kaos.Collections;
[assembly: AssemblyVersion ("0.1.0.0")]
namespace BenchApp
{
public class BtreeBench03
{
static int reps = 50000000;
static BtreeDictionary<Guid,int> tree = new BtreeDictionary<Guid,int> (128);
static void Main (string[] args)
{
for (int ii = 0; ii < reps; ++ii)
tree.Add (Guid.NewGuid(), ii);
Console.WriteLine (reps);
Console.WriteLine (tree.GetTreeStatsText());
}
}
}
| mit | C# |
b74b745651ad325819d8182b2d0fcbee06997379 | remove \t in favour of spaces | Senthilvera/google-api-dotnet-client,line21c/google-api-dotnet-client,amnsinghl/google-api-dotnet-client,eshangin/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,chenneo/google-api-dotnet-client,DJJam/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,rburgstaler/google-api-dotnet-client,initaldk/google-api-dotnet-client,googleapis/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,shumaojie/google-api-dotnet-client,luantn2/google-api-dotnet-client,maha-khedr/google-api-dotnet-client,hivie7510/google-api-dotnet-client,neil-119/google-api-dotnet-client,hurcane/google-api-dotnet-client,smarly-net/google-api-dotnet-client,bacm/google-api-dotnet-client,duckhamqng/google-api-dotnet-client,shumaojie/google-api-dotnet-client,lli-klick/google-api-dotnet-client,ajmal744/google-api-dotnet-client,SimonAntony/google-api-dotnet-client,arjunRanosys/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,peleyal/google-api-dotnet-client,ephraimncory/google-api-dotnet-client,peleyal/google-api-dotnet-client,aoisensi/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,chrisdunelm/google-api-dotnet-client,abujehad139/google-api-dotnet-client,jskeet/google-api-dotnet-client,amitla/google-api-dotnet-client,amit-learning/google-api-dotnet-client,kekewong/google-api-dotnet-client,hurcane/google-api-dotnet-client,olofd/google-api-dotnet-client,milkmeat/google-api-dotnet-client,asifshaon/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,kapil-chauhan-ngi/google-api-dotnet-client,aoisensi/google-api-dotnet-client,googleapis/google-api-dotnet-client,nicolasdavel/google-api-dotnet-client,kelvinRosa/google-api-dotnet-client,RavindraPatidar/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,ssett/google-api-dotnet-client,initaldk/google-api-dotnet-client,jesusog/google-api-dotnet-client,jtattermusch/google-api-dotnet-client,jskeet/google-api-dotnet-client,ErAmySharma/google-api-dotnet-client,hurcane/google-api-dotnet-client,pgallastegui/google-api-dotnet-client,ivannaranjo/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,Duikmeester/google-api-dotnet-client,inetdream/google-api-dotnet-client,eshivakant/google-api-dotnet-client,googleapis/google-api-dotnet-client,liuqiaosz/google-api-dotnet-client,joesoc/google-api-dotnet-client,jskeet/google-api-dotnet-client,duongnhyt/google-api-dotnet-client,MyOwnClone/google-api-dotnet-client,MesutGULECYUZ/google-api-dotnet-client,cdanielm58/google-api-dotnet-client,LPAMNijoel/google-api-dotnet-client,neil-119/google-api-dotnet-client,sqt-android/google-api-dotnet-client,hurcane/google-api-dotnet-client,amitla/google-api-dotnet-client,PiRSquared17/google-api-dotnet-client,karishmal/google-api-dotnet-client,ajaypradeep/google-api-dotnet-client,sawanmishra/google-api-dotnet-client,mylemans/google-api-dotnet-client,eydjey/google-api-dotnet-client,hoangduit/google-api-dotnet-client,peleyal/google-api-dotnet-client,mjacobsen4DFM/google-api-dotnet-client,initaldk/google-api-dotnet-client | Src/GoogleApis/Apis/Discovery/IService.cs | Src/GoogleApis/Apis/Discovery/IService.cs | /*
Copyright 2010 Google 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 System.Collections.Generic;
using Google.Apis.Requests;
using Google.Apis.Discovery.Schema;
namespace Google.Apis.Discovery
{
/// <summary>
/// Represent a specific version of a service as defined in Google Api Discovery Document.
/// Has a collection of IResources and ISchemas
/// </summary>
/// <seealso cref="IResource"/>
/// <seealso cref="ISchema"/>
public interface IService : IResourceContainer
{
/// <summary> The version of this service </summary>
string Version {get;}
Uri BaseUri {get;}
Uri RpcUri {get;}
/// <summary>The version of the discovery that defined this service. </summary>
DiscoveryVersion DiscoveryVersion{get;}
/// <summary>A dictionary containing all the schemas defined in this Service </summary>
IDictionary<string, ISchema> Schemas{get;}
/// <summary>
/// Creates a Request Object based on the HTTP Method Type.
/// </summary>
IRequest CreateRequest (string resource, string methodName);
}
}
| /*
Copyright 2010 Google 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 System.Collections.Generic;
using Google.Apis.Requests;
using Google.Apis.Discovery.Schema;
namespace Google.Apis.Discovery
{
/// <summary>
/// Represent a specific version of a service as defined in Google Api Discovery Document.
/// Has a collection of IResources and ISchemas
/// </summary>
/// <seealso cref="IResource"/>
/// <seealso cref="ISchema"/>
public interface IService : IResourceContainer
{
/// <summary> The version of this service </summary>
string Version {get;}
Uri BaseUri {get;}
Uri RpcUri {get;}
/// <summary>The version of the discovery that defined this service. </summary>
DiscoveryVersion DiscoveryVersion{get;}
/// <summary>A dictionary containing all the schemas defined in this Service </summary>
IDictionary<string, ISchema> Schemas{get;}
/// <summary>
/// Creates a Request Object based on the HTTP Method Type.
/// </summary>
IRequest CreateRequest (string resource, string methodName);
}
}
| apache-2.0 | C# |
e2379c1d3eae8de652142b9bc420bff12e04498e | Format GlacierJobTier | carbon/Amazon | src/Amazon.S3/Models/GlacierJobTier.cs | src/Amazon.S3/Models/GlacierJobTier.cs | namespace Amazon.S3
{
public enum GlacierJobTier : byte
{
Standard = 0, // $0.01 per GB + $0.05 per 1,000 requests [3-5 hours]
Expedited = 1, // $0.03 per GP + $10.00 per 1000 requests [1-5 minutes]
Bulk = 2 // $0.0025 per GB + $0.025 per 1,000 requests [5-12 hours]
}
} | namespace Amazon.S3
{
public enum GlacierJobTier
{
Standard = 0,
Expedited = 1,
Bulk = 2
}
}
/*
POST /ObjectName?restore&versionId=VersionID HTTP/1.1
Host: BucketName.s3.amazonaws.com
Date: date
Authorization: authorization string (see Authenticating Requests (AWS Signature Version 4))
Content-MD5: MD5
<RestoreRequest xmlns="http://s3.amazonaws.com/doc/2006-3-01">
<Days>NumberOfDays</Days>
</RestoreRequest>
*/
| mit | C# |
83af477416c1b08a9a44d4a78f0ef275c6bc73c2 | Remove unmatched variables | mstevenson/SeudoBuild | UnityBuildServer/TextReplacements.cs | UnityBuildServer/TextReplacements.cs | using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace UnityBuildServer
{
/// <summary>
/// Register in-line variables to replace in strings and their replacement values.
/// Variables begin and end with the % character.
/// Example: %project_name% variable could be replaced with the string MyProject.
/// </summary>
public class TextReplacements : Dictionary<string, string>
{
public string ReplaceVariablesInText(string source)
{
// Replace all variables that are known by TextReplacements
foreach (var kvp in this)
{
source = source.Replace($"%{kvp.Key}%", kvp.Value);
}
// Remove any variables that were not matched
source = Regex.Replace(source, "%.*?%", string.Empty, RegexOptions.Multiline);
return source;
}
}
}
| using System.Collections.Generic;
namespace UnityBuildServer
{
/// <summary>
/// Register in-line variables to replace in strings and their replacement values.
/// Variables begin and end with the % character.
/// Example: %project_name% variable could be replaced with the string MyProject.
/// </summary>
public class TextReplacements : Dictionary<string, string>
{
public string ReplaceVariablesInText(string source)
{
foreach (var kvp in this)
{
source = source.Replace($"%{kvp.Key}%", kvp.Value);
}
return source;
}
}
}
| mit | C# |
cfc4b118c8fb90a938c33990508f8507d97dadc8 | Return null if invalid offset and seek to the offset | 0xd4d/dnlib,kiootic/dnlib,modulexcite/dnlib,ZixiangBoy/dnlib,picrap/dnlib,Arthur2e5/dnlib,yck1509/dnlib,ilkerhalil/dnlib,jorik041/dnlib | dot10/dotNET/StringsStream.cs | dot10/dotNET/StringsStream.cs | using System.Text;
using dot10.IO;
namespace dot10.dotNET {
/// <summary>
/// Represents the #Strings stream
/// </summary>
public class StringsStream : DotNetStream {
/// <inheritdoc/>
public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <summary>
/// Read a <see cref="string"/>
/// </summary>
/// <param name="offset">Offset of string</param>
/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
public string Read(uint offset) {
if (offset >= imageStream.Length)
return null;
imageStream.Position = offset;
var data = imageStream.ReadBytesUntilByte(0);
if (data == null)
return null;
return Encoding.UTF8.GetString(data);
}
}
}
| using System.Text;
using dot10.IO;
namespace dot10.dotNET {
/// <summary>
/// Represents the #Strings stream
/// </summary>
public class StringsStream : DotNetStream {
/// <inheritdoc/>
public StringsStream(IImageStream imageStream, StreamHeader streamHeader)
: base(imageStream, streamHeader) {
}
/// <summary>
/// Read a <see cref="string"/>
/// </summary>
/// <param name="offset">Offset of string</param>
/// <returns>The UTF-8 decoded string or null if invalid offset</returns>
public string Read(uint offset) {
var data = imageStream.ReadBytesUntilByte(0);
if (data == null)
return null;
return Encoding.UTF8.GetString(data);
}
}
}
| mit | C# |
c1c0b9a9db1c9a35114fd0535fc49ed3b5671e9d | Add realtime to room categories | peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu | osu.Game/Online/Multiplayer/RoomCategory.cs | osu.Game/Online/Multiplayer/RoomCategory.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.
namespace osu.Game.Online.Multiplayer
{
public enum RoomCategory
{
Normal,
Spotlight,
Realtime,
}
}
| // 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.
namespace osu.Game.Online.Multiplayer
{
public enum RoomCategory
{
Normal,
Spotlight
}
}
| mit | C# |
c57d1de4267f61c89e4245955145b6e56184a212 | Fix tests | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.SystemConfig/Metadata/MetadataUniqueName.cs | InfinniPlatform.SystemConfig/Metadata/MetadataUniqueName.cs | using System;
using System.Linq;
namespace InfinniPlatform.Core.Metadata
{
public class MetadataUniqueName : IEquatable<MetadataUniqueName>
{
private const char NamespaceSeparator = '.';
public MetadataUniqueName(string ns, string name)
{
Namespace = ns;
Name = name;
}
public MetadataUniqueName(string fullQuelifiedName)
{
Namespace = fullQuelifiedName.Remove(fullQuelifiedName.LastIndexOf(NamespaceSeparator));
Name = fullQuelifiedName.Split(NamespaceSeparator).Last();
}
public string Namespace { get; }
public string Name { get; }
public bool Equals(MetadataUniqueName other)
{
return string.Equals(Namespace, other.Namespace, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return ToString().ToLower().GetHashCode();
}
public override string ToString()
{
return (string.IsNullOrEmpty(Namespace)) ? Name : $"{Namespace}{NamespaceSeparator}{Name}";
}
}
} | using System;
using System.Linq;
namespace InfinniPlatform.Core.Metadata
{
public class MetadataUniqueName : IEquatable<MetadataUniqueName>
{
private const char NamespaceSeparator = '.';
public MetadataUniqueName(string ns, string name)
{
Namespace = ns;
Name = name;
}
public MetadataUniqueName(string fullQuelifiedName)
{
Namespace = fullQuelifiedName.Remove(fullQuelifiedName.LastIndexOf(NamespaceSeparator));
Name = fullQuelifiedName.Split(NamespaceSeparator).Last();
}
public string Namespace { get; }
public string Name { get; }
public bool Equals(MetadataUniqueName other)
{
return string.Equals(Namespace, other.Namespace, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase);
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override string ToString()
{
return (string.IsNullOrEmpty(Namespace)) ? Name : $"{Namespace}{NamespaceSeparator}{Name}";
}
}
} | agpl-3.0 | C# |
fb07b49b71366d8fba0bd656a7c9471bf587217e | Fix issue where ratio was always returning "1" | janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent,janjonas/OpenContent | Components/TemplateHelpers/Images/Ratio.cs | Components/TemplateHelpers/Images/Ratio.cs | using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height; }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
} | using System;
namespace Satrabel.OpenContent.Components.TemplateHelpers
{
public class Ratio
{
private readonly float _ratio;
public int Width { get; private set; }
public int Height { get; private set; }
public float AsFloat
{
get { return (float)Width / (float)Height); }
}
public Ratio(string ratioString)
{
Width = 1;
Height = 1;
var elements = ratioString.ToLowerInvariant().Split('x');
if (elements.Length == 2)
{
int leftPart;
int rightPart;
if (int.TryParse(elements[0], out leftPart) && int.TryParse(elements[1], out rightPart))
{
Width = leftPart;
Height = rightPart;
}
}
_ratio = AsFloat;
}
public Ratio(int width, int height)
{
if (width < 1) throw new ArgumentOutOfRangeException("width", width, "should be 1 or larger");
if (height < 1) throw new ArgumentOutOfRangeException("height", height, "should be 1 or larger");
Width = width;
Height = height;
_ratio = AsFloat;
}
public void SetWidth(int newWidth)
{
Width = newWidth;
Height = Convert.ToInt32(newWidth / _ratio);
}
public void SetHeight(int newHeight)
{
Width = Convert.ToInt32(newHeight * _ratio);
Height = newHeight;
}
}
} | mit | C# |
51d051760cf889c6613f679df0697e45dcd7369e | Fix absence of extension in snippet URL when no language type was specified on the code block | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix/Utilities/FormatUtilities.cs | Modix/Utilities/FormatUtilities.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
namespace Modix.Utilities
{
public static class FormatUtilities
{
private static Regex _buildContentRegex = new Regex(@"```([^\s]+|)");
/// <summary>
/// Prepares a piece of input code for use in HTTP operations
/// </summary>
/// <param name="code">The code to prepare</param>
/// <returns>The resulting StringContent for HTTP operations</returns>
public static StringContent BuildContent(string code)
{
string cleanCode = _buildContentRegex.Replace(code.Trim(), string.Empty); //strip out the ` characters and code block markers
cleanCode = cleanCode.Replace("\t", " "); //spaces > tabs
cleanCode = FixIndentation(cleanCode);
return new StringContent(cleanCode, Encoding.UTF8, "text/plain");
}
/// <summary>
/// Attempts to get the language of the code piece
/// </summary>
/// <param name="code">The code</param>
/// <returns>The code language if a match is found, null of none are found</returns>
public static string GetCodeLanguage(string message)
{
var match = _buildContentRegex.Match(message);
if (match.Success)
{
string codeLanguage = match.Groups[1].Value;
return string.IsNullOrEmpty(codeLanguage) ? null : codeLanguage;
}
else
{
return null;
}
}
/// <summary>
/// Attempts to fix the indentation of a piece of code by aligning the left sidie.
/// </summary>
/// <param name="code">The code to align</param>
/// <returns>The newly aligned code</returns>
public static string FixIndentation(string code)
{
var lines = code.Split('\n');
string indentLine = lines.SkipWhile(d => d.FirstOrDefault() != ' ').FirstOrDefault();
if (indentLine != null)
{
int indent = indentLine.LastIndexOf(' ') + 1;
string pattern = $@"^[^\S\n]{{{indent}}}";
return Regex.Replace(code, pattern, "", RegexOptions.Multiline);
}
return code;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
namespace Modix.Utilities
{
public static class FormatUtilities
{
private static Regex _buildContentRegex = new Regex(@"```([^\s]+|)");
/// <summary>
/// Prepares a piece of input code for use in HTTP operations
/// </summary>
/// <param name="code">The code to prepare</param>
/// <returns>The resulting StringContent for HTTP operations</returns>
public static StringContent BuildContent(string code)
{
string cleanCode = _buildContentRegex.Replace(code.Trim(), string.Empty); //strip out the ` characters and code block markers
cleanCode = cleanCode.Replace("\t", " "); //spaces > tabs
cleanCode = FixIndentation(cleanCode);
return new StringContent(cleanCode, Encoding.UTF8, "text/plain");
}
/// <summary>
/// Attempts to get the language of the code piece
/// </summary>
/// <param name="code">The code</param>
/// <returns>The code language if a match is found, null of none are found</returns>
public static string GetCodeLanguage(string message)
{
var match = _buildContentRegex.Match(message);
return match.Success ? match.Groups[1].Value : null;
}
/// <summary>
/// Attempts to fix the indentation of a piece of code by aligning the left sidie.
/// </summary>
/// <param name="code">The code to align</param>
/// <returns>The newly aligned code</returns>
public static string FixIndentation(string code)
{
var lines = code.Split('\n');
string indentLine = lines.SkipWhile(d => d.FirstOrDefault() != ' ').FirstOrDefault();
if (indentLine != null)
{
int indent = indentLine.LastIndexOf(' ') + 1;
string pattern = $@"^[^\S\n]{{{indent}}}";
return Regex.Replace(code, pattern, "", RegexOptions.Multiline);
}
return code;
}
}
}
| mit | C# |
0f7912dc50a40b8cca9a7ea2b6f50abd7ed338cb | Comment FiberResult | spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit,spicypixel/cs-concurrency-kit | Source/SpicyPixel.Threading/FiberResult.cs | Source/SpicyPixel.Threading/FiberResult.cs | using System;
namespace SpicyPixel.Threading
{
/// <summary>
/// An instruction to stop fiber execution and set a result on the fiber.
/// </summary>
public sealed class FiberResult : FiberInstruction
{
object result;
/// <summary>
/// Gets the result of the fiber execution.
/// </summary>
/// <value>The result of the fiber execution.</value>
public object Result {
get { return result; }
}
/// <summary>
/// Initializes a new instance of the <see cref="SpicyPixel.Threading.FiberResult"/> class.
/// </summary>
/// <param name="result">Result of the fiber execution.</param>
public FiberResult(object result)
{
this.result = result;
}
}
}
| using System;
namespace SpicyPixel.Threading
{
public sealed class FiberResult : FiberInstruction
{
object result;
public object Result {
get { return result; }
}
public FiberResult(object result)
{
this.result = result;
}
}
}
| mit | C# |
9a7ef5cea13402ca632c4cc0b2621906273ca4fd | Make FeeParser throw if the fee parsed is not low, medium or high (previously defaulted to medium0 | mikedennis/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,Aprogiena/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode | Stratis.Bitcoin/Features/Wallet/FeeType.cs | Stratis.Bitcoin/Features/Wallet/FeeType.cs | using System;
namespace Stratis.Bitcoin.Features.Wallet
{
/// <summary>
/// An indicator of how fast a transaction will be accepted in a block.
/// </summary>
public enum FeeType
{
/// <summary>
/// Slow.
/// </summary>
Low = 0,
/// <summary>
/// Avarage.
/// </summary>
Medium = 1,
/// <summary>
/// Fast.
/// </summary>
High = 105
}
public static class FeeParser
{
public static FeeType Parse(string value)
{
bool isParsed = Enum.TryParse<FeeType>(value, true, out var result);
if (!isParsed)
{
throw new FormatException($"FeeType {value} is not a valid FeeType");
}
return result;
}
/// <summary>
/// Map a fee type to the number of confirmations
/// </summary>
public static int ToConfirmations(this FeeType fee)
{
switch (fee)
{
case FeeType.Low:
return 50;
case FeeType.Medium:
return 20;
case FeeType.High:
return 5;
}
throw new WalletException("Invalid fee");
}
}
}
| using System;
namespace Stratis.Bitcoin.Features.Wallet
{
/// <summary>
/// An indicator on how fast a transaction will be accepted in a block
/// </summary>
public enum FeeType
{
/// <summary>
/// Slow.
/// </summary>
Low = 0,
/// <summary>
/// Avarage.
/// </summary>
Medium = 1,
/// <summary>
/// Fast.
/// </summary>
High = 105
}
public static class FeeParser
{
public static FeeType Parse(string value)
{
if (Enum.TryParse<FeeType>(value, true, out var ret))
return ret;
return FeeType.Medium;
}
/// <summary>
/// Map a fee type to the number of confirmations
/// </summary>
public static int ToConfirmations(this FeeType fee)
{
switch (fee)
{
case FeeType.Low:
return 50;
case FeeType.Medium:
return 20;
case FeeType.High:
return 5;
}
throw new WalletException("Invalid fee");
}
}
}
| mit | C# |
28674c33d2b4ee235a4d5e4dd291253bbbeccc72 | Tag version 0.3.0.0. | m5219/POGOLib,AeonLucid/POGOLib | POGOLib/Properties/AssemblyInfo.cs | POGOLib/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("POGOLib.Official")]
[assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AeonLucid")]
[assembly: AssemblyProduct("POGOLib.Official")]
[assembly: AssemblyCopyright("Copyright © AeonLucid 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3ba89dfb-a162-420a-9ded-daa211e52ad2")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("POGOLib.Official")]
[assembly: AssemblyDescription("A community driven PokémonGo API Library written in C#.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AeonLucid")]
[assembly: AssemblyProduct("POGOLib.Official")]
[assembly: AssemblyCopyright("Copyright © AeonLucid 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3ba89dfb-a162-420a-9ded-daa211e52ad2")]
// 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.0")]
[assembly: AssemblyFileVersion("0.2.0.0")] | mit | C# |
664cfe80166be3f0ce355ac47f11c6a8c1d85f6a | Update InputStateTester.cs to compile with updated App framework. | eylvisaker/AgateLib | Tests/Input/InputState/InputStateTester.cs | Tests/Input/InputState/InputStateTester.cs | // The contents of this file are public domain.
// You may use them as you wish.
//
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.InputLib;
namespace Tests.InputStateTester
{
class InputStateTester : AgateApplication
{
#region IAgateTest Members
public string Name { get { return "Input State Tester"; } }
public string Category { get { return "Input"; } }
#endregion
public void Main(string[] args)
{
Run(args);
}
protected override void Update(double time_ms)
{
base.Update(time_ms);
}
protected override void Render()
{
base.Render();
}
}
} | // The contents of this file are public domain.
// You may use them as you wish.
//
using System;
using System.Collections.Generic;
using AgateLib;
using AgateLib.DisplayLib;
using AgateLib.InputLib;
namespace Tests.InputStateTester
{
class InputStateTester : AgateApplication
{
#region IAgateTest Members
public string Name { get { return "Input State Tester"; } }
public string Category { get { return "Input"; } }
#endregion
public void Main(string[] args)
{
Run(args);
}
protected override void Render(double time_ms)
{
base.Render(time_ms);
}
}
} | mit | C# |
6594992252292890adf37883f4971d8d53f0a903 | Update version | GAnatoliy/ViewModelLoader | ViewModelLoader/Properties/AssemblyInfo.cs | ViewModelLoader/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("ViewModelLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ViewModelLoader")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26173ffd-2a06-4dee-941d-fd3164cf4054")]
// 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.1.*")]
[assembly: AssemblyFileVersion("1.0.1.*")]
| 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("ViewModelLoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ViewModelLoader")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("26173ffd-2a06-4dee-941d-fd3164cf4054")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
c18ed3365d7209daad99a4adfd331cead792fe38 | Add comments | sakapon/Samples-2015 | WpfSample/ResolutionWpf/MainWindow.xaml.cs | WpfSample/ResolutionWpf/MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ResolutionWpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty MouseOnWindowProperty =
DependencyProperty.Register("MouseOnWindow", typeof(Point), typeof(MainWindow), new PropertyMetadata(new Point()));
public static readonly DependencyProperty MouseOnScreenProperty =
DependencyProperty.Register("MouseOnScreen", typeof(Point), typeof(MainWindow), new PropertyMetadata(new Point()));
public Point MouseOnWindow
{
get { return (Point)GetValue(MouseOnWindowProperty); }
private set { SetValue(MouseOnWindowProperty, value); }
}
public Point MouseOnScreen
{
get { return (Point)GetValue(MouseOnScreenProperty); }
private set { SetValue(MouseOnScreenProperty, value); }
}
public MainWindow()
{
InitializeComponent();
// WindowStyle="None" のときにウィンドウを最大化すると、左上のスクリーン座標は (-8, -8) となります (枠の幅が 8)。
// さらに AllowsTransparency="True" の場合、(-8, -8) からウィンドウが描画されます。
MouseMove += (o, e) =>
{
MouseOnWindow = e.GetPosition(this);
MouseOnScreen = PointToScreen(MouseOnWindow);
};
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace ResolutionWpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty MouseOnWindowProperty =
DependencyProperty.Register("MouseOnWindow", typeof(Point), typeof(MainWindow), new PropertyMetadata(new Point()));
public static readonly DependencyProperty MouseOnScreenProperty =
DependencyProperty.Register("MouseOnScreen", typeof(Point), typeof(MainWindow), new PropertyMetadata(new Point()));
public Point MouseOnWindow
{
get { return (Point)GetValue(MouseOnWindowProperty); }
private set { SetValue(MouseOnWindowProperty, value); }
}
public Point MouseOnScreen
{
get { return (Point)GetValue(MouseOnScreenProperty); }
private set { SetValue(MouseOnScreenProperty, value); }
}
public MainWindow()
{
InitializeComponent();
MouseMove += (o, e) =>
{
MouseOnWindow = e.GetPosition(this);
MouseOnScreen = PointToScreen(MouseOnWindow);
};
}
}
}
| mit | C# |
2f92875b970478b5d1d0b0b10a86624e20f65f67 | Fix contacts initializing bug | DevelopersGuild/famine-games | Assets/Scripts/Hub.cs | Assets/Scripts/Hub.cs | using UnityEngine;
using System.Collections;
using System;
public class Hub : MonoBehaviour {
static public int maxContact = 6;
static public int minContact = 2;
private System.Random rnd;
public int contacts;
// Use this for initialization
void Awake () {
rnd = new System.Random(System.Guid.NewGuid().GetHashCode());
contacts = rnd.Next(2, 7);
}
public int returnContacts()
{ return contacts; }
// Update is called once per frame
void Update () {
}
};
| using UnityEngine;
using System.Collections;
using System;
public class Hub : MonoBehaviour {
static public int maxContact = 6;
static public int minContact = 2;
private System.Random rnd;
public int contacts;
// Use this for initialization
void Start () {
rnd = new System.Random(System.Guid.NewGuid().GetHashCode());
contacts = rnd.Next(2, 7);
}
public int returnContacts()
{ return contacts; }
// Update is called once per frame
void Update () {
}
};
| mit | C# |
1060a2a9bab4561c70a977d6ed08e4194338a808 | Make ListFilter default constructor protected | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Filters/ListFilter.cs | ShopifySharp/Filters/ListFilter.cs | using Newtonsoft.Json;
using System.Collections.Generic;
namespace ShopifySharp.Filters
{
/// <summary>
/// A generic class for filtering the results of a .ListAsync command.
/// </summary>
public class ListFilter<T> : Parameterizable
{
/// <summary>
/// A unique ID used to access a page of results. Must be present to list more than the first page of results.
/// </summary>
[JsonProperty("page_info")]
public string PageInfo { get; }
/// <summary>
/// The number of items which should be returned. Default is 50, maximum is 250.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
/// <summary>
/// Comma-separated list of which fields to show in the results. This parameter only works for some endpoints.
/// </summary>
[JsonProperty("fields")]
public string Fields { get; set; }
/// <remarks>
/// This constructor is protected to prevent developers from using `new ListFilter()`, but to make creating your
/// own ListFilter easier.
/// https://github.com/nozzlegear/shopifysharp/issues/515
/// </remarks>
protected ListFilter()
{
}
public ListFilter(string pageInfo, int? limit, string fields = null)
{
PageInfo = pageInfo;
Limit = limit;
Fields = fields;
}
public ListFilter<T> AsListFilter() => this;
}
}
| using Newtonsoft.Json;
using System.Collections.Generic;
namespace ShopifySharp.Filters
{
/// <summary>
/// A generic class for filtering the results of a .ListAsync command.
/// </summary>
public class ListFilter<T> : Parameterizable
{
/// <summary>
/// A unique ID used to access a page of results. Must be present to list more than the first page of results.
/// </summary>
[JsonProperty("page_info")]
public string PageInfo { get; }
/// <summary>
/// The number of items which should be returned. Default is 50, maximum is 250.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
/// <summary>
/// Comma-separated list of which fields to show in the results. This parameter only works for some endpoints.
/// </summary>
[JsonProperty("fields")]
public string Fields { get; set; }
internal ListFilter()
{
}
public ListFilter(string pageInfo, int? limit, string fields = null)
{
PageInfo = pageInfo;
Limit = limit;
Fields = fields;
}
public ListFilter<T> AsListFilter() => this;
}
}
| mit | C# |
8f1f3d12b49fc174294187b793dfc078ebc0d17a | bump version | Fody/Janitor | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.5.1")]
[assembly: AssemblyFileVersion("1.5.1")]
| using System.Reflection;
[assembly: AssemblyVersion("1.5.0")]
[assembly: AssemblyFileVersion("1.5.0")]
| mit | C# |
53cdce74d18b57dbc85dc9e03e053cc6409d51a9 | bump version 2.2.1 | Fody/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.1")] | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("2.2.0")] | mit | C# |
9b8fa89c2d340c46ea1079213f6e66020b40ace2 | patch working directory | brthor/Dockerize.NET,brthor/Dockerize.NET | DockerfileTemplate.cs | DockerfileTemplate.cs | namespace Brthor.Dockerize
{
public static class DockerfileTemplate
{
public static string Generate(DockerizeConfiguration config, string outputBinaryName)
{
var addUser = config.Username == null
? ""
: $@"RUN groupadd -r {config.Username} && useradd --no-log-init -r -g {config.Username} {config.Username}
RUN chown {config.Username}:{config.Username} /projectBinaries
USER {config.Username}:{config.Username}";
var chownOnAdd = config.Username == null
? ""
: $"--chown={config.Username}:{config.Username} ";
var dockerfileContent = $@"
FROM {config.BaseImage}
RUN mkdir /projectBinaries
{addUser}
ADD {chownOnAdd}./publish/ /projectBinaries/
WORKDIR /projectBinaries/
CMD /projectBinaries/{outputBinaryName}
";
return dockerfileContent;
}
}
} | namespace Brthor.Dockerize
{
public static class DockerfileTemplate
{
public static string Generate(DockerizeConfiguration config, string outputBinaryName)
{
var addUser = config.Username == null
? ""
: $@"RUN groupadd -r {config.Username} && useradd --no-log-init -r -g {config.Username} {config.Username}
RUN chown {config.Username}:{config.Username} /projectBinaries
USER {config.Username}:{config.Username}";
var chownOnAdd = config.Username == null
? ""
: $"--chown={config.Username}:{config.Username} ";
var dockerfileContent = $@"
FROM {config.BaseImage}
RUN mkdir /projectBinaries
{addUser}
ADD {chownOnAdd}./publish/ /projectBinaries/
CMD /projectBinaries/{outputBinaryName}
";
return dockerfileContent;
}
}
} | mit | C# |
d4e9a787cbd9ca0b0c974b0bfae2dc86327a6660 | Update SmallAppliances.cs | jkanchelov/Telerik-OOP-Team-StarFruit | TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs | TeamworkStarFruit/CatalogueLib/Products/SmallAppliances.cs | namespace CatalogueLib
{
using System.Text;
using CatalogueLib.Products.Enumerations;
public abstract class SmallAppliances : Product
{
public SmallAppliances()
{
}
public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes)
: base(ID, price, isAvailable, brand)
{
this.Capacity = Capacity;
this.CableLength = CableLength;
this.Affixes = Affixes;
}
public double Capacity { get; private set; }
public double CableLength { get; private set; }
public int Affixes { get; private set; }
public override string ToString()
{
StringBuilder result = new StringBuilder();
result = result.Append(string.Format("{0}", base.ToString()));
result = result.Append(string.Format(" Capacity: {0}",this.Capacity));
result = result.AppendLine();
result = result.Append(string.Format(" Cable length: {0}",this.CableLength));
result = result.AppendLine();
result = result.Append(string.Format(" Affixes: {0}", this.Affixes));
return result.AppendLine().ToString();
}
}
}
| namespace CatalogueLib
{
using System.Text;
using CatalogueLib.Products.Enumerations;
public abstract class SmallAppliances : Product
{
public SmallAppliances()
{
}
public SmallAppliances(int ID, decimal price, bool isAvailable, Brand brand, double Capacity, double CableLength, int Affixes)
: base(ID, price, isAvailable, brand)
{
this.Capacity = Capacity;
this.CableLength = CableLength;
this.Affixes = Affixes;
}
public double Capacity { get; private set; }
public double CableLength { get; private set; }
public int Affixes { get; private set; }
public override string ToString()
{
StringBuilder stroitel = new StringBuilder();
stroitel = stroitel.Append(string.Format("{0}", base.ToString()));
stroitel = stroitel.Append(string.Format(" Capacity: {0}\n Cable length: {1}\n Affixes: {2}", this.Capacity, this.CableLength, this.Affixes));
return stroitel.AppendLine().ToString();
}
}
}
| mit | C# |
4148d355474dc1d099e504585ed6e800e09d4b5b | Change logger to singleton | wgraham17/Foundatio,exceptionless/Foundatio,Bartmax/Foundatio,FoundatioFx/Foundatio | src/JobSample/Program.cs | src/JobSample/Program.cs | using System;
using System.Threading.Tasks;
using Foundatio.Jobs;
using Foundatio.JobSample.Jobs;
using Foundatio.Logging;
using Foundatio.Logging.NLog;
using SimpleInjector;
namespace Foundatio.JobSample {
public class Program {
public static int Main() {
var loggerFactory = new LoggerFactory();
loggerFactory.AddNLog();
return new JobRunner(loggerFactory).RunInConsole<PingQueueJob>(serviceProvider => {
var container = serviceProvider as Container;
if (container == null)
return;
container.RegisterSingleton<ILoggerFactory>(loggerFactory);
container.RegisterSingleton(typeof(ILogger<>), typeof(Logger<>));
container.AddStartupAction<EnqueuePings>();
Task.Run(() => container.RunStartupActionsAsync().GetAwaiter().GetResult());
});
}
}
}
| using System;
using System.Threading.Tasks;
using Foundatio.Jobs;
using Foundatio.JobSample.Jobs;
using Foundatio.Logging;
using Foundatio.Logging.NLog;
using SimpleInjector;
namespace Foundatio.JobSample {
public class Program {
public static int Main() {
var loggerFactory = new LoggerFactory();
loggerFactory.AddNLog();
return new JobRunner(loggerFactory).RunInConsole<PingQueueJob>(serviceProvider => {
var container = serviceProvider as Container;
if (container == null)
return;
container.RegisterSingleton<ILoggerFactory>(loggerFactory);
container.Register(typeof(ILogger<>), typeof(Logger<>));
container.AddStartupAction<EnqueuePings>();
Task.Run(() => container.RunStartupActionsAsync().GetAwaiter().GetResult());
});
}
}
}
| apache-2.0 | C# |
705335cf7854b4d9857d1640cbe9ca702ab7b55f | Fix handling peer exchange message when it's not completed. | amacal/leak | sources/Leak.Core/Extensions/PeerExchange/PeerExchangeHandler.cs | sources/Leak.Core/Extensions/PeerExchange/PeerExchangeHandler.cs | using Leak.Core.Bencoding;
using Leak.Core.Common;
using Leak.Core.Messages;
using System;
using System.Collections.Generic;
using System.Text;
namespace Leak.Core.Extensions.PeerExchange
{
public class PeerExchangeHandler : ExtenderHandler
{
private readonly PeerExchangeConfiguration configuration;
public PeerExchangeHandler(Action<PeerExchangeConfiguration> configurer)
{
configuration = configurer.Configure(with =>
{
with.Callback = new PeerExchangeCallbackNothing();
});
}
public bool CanHandle(string name)
{
return name == "ut_pex";
}
public void Handle(PeerHash peer, ExtendedIncomingMessage message)
{
BencodedValue value = Bencoder.Decode(message.ToBytes());
byte[] added = value.Find("added", x => x?.Data?.GetBytes());
List<PeerAddress> peers = new List<PeerAddress>();
if (added != null)
{
for (int i = 0; i < added.Length; i += 6)
{
string host = GetHost(added, i);
int port = GetPort(added, i);
peers.Add(new PeerAddress(host, port));
}
}
configuration.Callback.OnMessage(peer, new PeerExchangeMessage(peers.ToArray()));
}
private static string GetHost(byte[] data, int offset)
{
StringBuilder builder = new StringBuilder();
builder.Append(data[0 + offset]);
builder.Append('.');
builder.Append(data[1 + offset]);
builder.Append('.');
builder.Append(data[2 + offset]);
builder.Append('.');
builder.Append(data[3 + offset]);
return builder.ToString();
}
private static int GetPort(byte[] data, int offset)
{
return data[4 + offset] * 256 + data[5 + offset];
}
}
} | using Leak.Core.Bencoding;
using Leak.Core.Common;
using Leak.Core.Messages;
using System;
using System.Collections.Generic;
using System.Text;
namespace Leak.Core.Extensions.PeerExchange
{
public class PeerExchangeHandler : ExtenderHandler
{
private readonly PeerExchangeConfiguration configuration;
public PeerExchangeHandler(Action<PeerExchangeConfiguration> configurer)
{
configuration = configurer.Configure(with =>
{
with.Callback = new PeerExchangeCallbackNothing();
});
}
public bool CanHandle(string name)
{
return name == "ut_pex";
}
public void Handle(PeerHash peer, ExtendedIncomingMessage message)
{
BencodedValue value = Bencoder.Decode(message.ToBytes());
byte[] added = value.Find("added", x => x.Data.GetBytes());
List<PeerAddress> peers = new List<PeerAddress>();
if (added != null)
{
for (int i = 0; i < added.Length; i += 6)
{
string host = GetHost(added, i);
int port = GetPort(added, i);
peers.Add(new PeerAddress(host, port));
}
}
configuration.Callback.OnMessage(peer, new PeerExchangeMessage(peers.ToArray()));
}
private static string GetHost(byte[] data, int offset)
{
StringBuilder builder = new StringBuilder();
builder.Append(data[0 + offset]);
builder.Append('.');
builder.Append(data[1 + offset]);
builder.Append('.');
builder.Append(data[2 + offset]);
builder.Append('.');
builder.Append(data[3 + offset]);
return builder.ToString();
}
private static int GetPort(byte[] data, int offset)
{
return data[4 + offset] * 256 + data[5 + offset];
}
}
} | mit | C# |
3c43967993aaf3c2fa286e739dc975e32910e1ee | Rename db param to descriptorBuilder | CSGOpenSource/elasticsearch-net,robrich/elasticsearch-net,elastic/elasticsearch-net,joehmchan/elasticsearch-net,starckgates/elasticsearch-net,abibell/elasticsearch-net,tkirill/elasticsearch-net,UdiBen/elasticsearch-net,wawrzyn/elasticsearch-net,geofeedia/elasticsearch-net,TheFireCookie/elasticsearch-net,starckgates/elasticsearch-net,Grastveit/NEST,abibell/elasticsearch-net,RossLieberman/NEST,elastic/elasticsearch-net,gayancc/elasticsearch-net,tkirill/elasticsearch-net,jonyadamit/elasticsearch-net,LeoYao/elasticsearch-net,amyzheng424/elasticsearch-net,adam-mccoy/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,gayancc/elasticsearch-net,robrich/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,faisal00813/elasticsearch-net,KodrAus/elasticsearch-net,ststeiger/elasticsearch-net,wawrzyn/elasticsearch-net,joehmchan/elasticsearch-net,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,LeoYao/elasticsearch-net,jonyadamit/elasticsearch-net,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,LeoYao/elasticsearch-net,junlapong/elasticsearch-net,Grastveit/NEST,ststeiger/elasticsearch-net,CSGOpenSource/elasticsearch-net,amyzheng424/elasticsearch-net,starckgates/elasticsearch-net,abibell/elasticsearch-net,geofeedia/elasticsearch-net,gayancc/elasticsearch-net,mac2000/elasticsearch-net,UdiBen/elasticsearch-net,geofeedia/elasticsearch-net,robertlyson/elasticsearch-net,azubanov/elasticsearch-net,ststeiger/elasticsearch-net,Grastveit/NEST,SeanKilleen/elasticsearch-net,azubanov/elasticsearch-net,joehmchan/elasticsearch-net,amyzheng424/elasticsearch-net,mac2000/elasticsearch-net,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,mac2000/elasticsearch-net,TheFireCookie/elasticsearch-net,faisal00813/elasticsearch-net,cstlaurent/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,DavidSSL/elasticsearch-net,KodrAus/elasticsearch-net,faisal00813/elasticsearch-net,tkirill/elasticsearch-net,azubanov/elasticsearch-net,wawrzyn/elasticsearch-net,DavidSSL/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net | src/Nest/DSL/Query/Functions/FunctionScoreFunctionsDescriptor.cs | src/Nest/DSL/Query/Functions/FunctionScoreFunctionsDescriptor.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Nest
{
public class FunctionScoreFunctionsDescriptor<T> : IEnumerable<FunctionScoreFunction<T>> where T : class
{
internal List<FunctionScoreFunction<T>> _Functions { get; set; }
public FunctionScoreFunctionsDescriptor()
{
this._Functions = new List<FunctionScoreFunction<T>>();
}
public FunctionScoreFunction<T> Gauss(string field, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new GaussFunction<T>(field, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Gauss(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new GaussFunction<T>(objectPath, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Linear(string field, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new LinearFunction<T>(field, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Linear(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new LinearFunction<T>(objectPath, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Exp(string field, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new ExpFunction<T>(field, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Exp(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> descriptorBuilder)
{
var fn = new ExpFunction<T>(objectPath, descriptorBuilder);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> BoostFactor(double value)
{
var fn = new BoostFactorFunction<T>(value);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> ScriptScore(Action<ScriptFilterDescriptor> scriptSelector)
{
var fn = new ScriptScoreFunction<T>(scriptSelector);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> FieldValueFactor(Action<FieldValueFactorDescriptor<T>> db)
{
var fn = new FieldValueFactor<T>(db);
this._Functions.Add(fn);
return fn;
}
public IEnumerator<FunctionScoreFunction<T>> GetEnumerator()
{
return _Functions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _Functions.GetEnumerator();
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Nest
{
public class FunctionScoreFunctionsDescriptor<T> : IEnumerable<FunctionScoreFunction<T>> where T : class
{
internal List<FunctionScoreFunction<T>> _Functions { get; set; }
public FunctionScoreFunctionsDescriptor()
{
this._Functions = new List<FunctionScoreFunction<T>>();
}
public FunctionScoreFunction<T> Gauss(string field, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new GaussFunction<T>(field, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Gauss(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new GaussFunction<T>(objectPath, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Linear(string field, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new LinearFunction<T>(field, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Linear(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new LinearFunction<T>(objectPath, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Exp(string field, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new ExpFunction<T>(field, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> Exp(Expression<Func<T, object>> objectPath, Action<FunctionScoreDecayFieldDescriptor> db)
{
var fn = new ExpFunction<T>(objectPath, db);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> BoostFactor(double value)
{
var fn = new BoostFactorFunction<T>(value);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> ScriptScore(Action<ScriptFilterDescriptor> scriptSelector)
{
var fn = new ScriptScoreFunction<T>(scriptSelector);
this._Functions.Add(fn);
return fn;
}
public FunctionScoreFunction<T> FieldValueFactor(Action<FieldValueFactorDescriptor<T>> db)
{
var fn = new FieldValueFactor<T>(db);
this._Functions.Add(fn);
return fn;
}
public IEnumerator<FunctionScoreFunction<T>> GetEnumerator()
{
return _Functions.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return _Functions.GetEnumerator();
}
}
} | apache-2.0 | C# |
75c12289cb6ab620ec075b51dcad2b65e1b16275 | Add TODO | OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania,OvidiuCaba/StatisticsRomania | src/WebClient/Program.cs | src/WebClient/Program.cs | using Microsoft.AspNetCore.Hosting;
using System.IO;
// TODO: numarul de locuinte autorizate in fiecare luna/semestru (Beniamin Petrovai)
// Ar merge si o piramida a varstelor implementata. (review Google Play 21.03.2019)
namespace WebClient
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| using Microsoft.AspNetCore.Hosting;
using System.IO;
// TODO: numarul de locuinte autorizate in fiecare luna/semestru (Beniamin Petrovai)
namespace WebClient
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseApplicationInsights()
.Build();
host.Run();
}
}
}
| mit | C# |
85bf4e81a789b274a043ed11a2954c9a496ec70d | Insert missing function calls | jlucansky/Camunda.Api.Client | Camunda.Api.Client/UserTask/UserTaskService.cs | Camunda.Api.Client/UserTask/UserTaskService.cs | using System.Collections.Generic;
using System.Threading.Tasks;
namespace Camunda.Api.Client.UserTask
{
public class UserTaskService
{
private IUserTaskRestService _api;
internal UserTaskService(IUserTaskRestService api)
{
_api = api;
}
public TaskResource this[string taskId] => new TaskResource(_api, taskId);
/// <summary>
/// Retrieves the number of tasks for each candidate group.
/// </summary>
public Task<List<TaskCountByCandidateGroupResult>> GetTaskCountByCandidateGroup() => _api.GetTaskCountByCandidateGroup();
public QueryResource<TaskQuery, UserTaskInfo> Query(TaskQuery query = null)
=> new QueryResource<TaskQuery, UserTaskInfo>(_api, query);
/// <summary>
/// Creates a new (user) task.
/// </summary>
public Task Create(UserTask task) => _api.CreateTask(task);
/// <summary>
/// Retrieves a task by id.
/// </summary>
public Task<UserTaskInfo> Get(string id) => _api.Get(id);
/// <summary>
/// Claims a task for a specific user.
/// Note: The difference with the Set Assignee method is that here a check is performed to see if the task already has a user assigned to it.
/// </summary>
public Task Claim(string id, UserInfo userinfo) => _api.ClaimTask(id, userinfo);
/// <summary>
/// Resets a task’s assignee. If successful, the task is not assigned to a user.
/// </summary>
public Task Unclaim(string id) => _api.UnclaimTask(id);
/// <summary>
/// Completes a task and updates process variables.
/// </summary>
public Task Complete(string id, CompleteTask completeTask) => _api.CompleteTask(id, completeTask);
/// <summary>
/// Completes a task and updates process variables using a form submit. There are two difference between this method and the complete method:
/// - If the task is in state PENDING - i.e., has been delegated before, it is not completed but resolved.Otherwise it will be completed.
/// - If the task has Form Field Metadata defined, the process engine will perform backend validation for any form fields which have validators defined.See the Generated Task Forms section of the User Guide for more information.
/// </summary>
public Task SubmitForm(string id, CompleteTask completeTask) => _api.SubmitFormTask(id, completeTask);
/// <summary>
/// Resolves a task and updates execution variables.
/// </summary>
public Task ResolveTask(string id, CompleteTask completeTask) => _api.ResolveTask(id, completeTask);
/// <summary>
/// Changes the assignee of a task to a specific user.
/// Note: The difference with the Claim Task method is that this method does not check if the task already has a user assigned to it.
/// </summary>
public Task SetAssignee(string id, UserInfo user) => _api.SetAssignee(id, user);
/// <summary>
/// Delegates a task to another user.
/// </summary>
public Task Delegate(string id, UserInfo user) => _api.DelegateTask(id, user);
/// <summary>
/// Retrieves the rendered form for a task. This method can be used to get the HTML rendering of a Generated Task Form.
/// </summary>
public Task<string> GetRenderedForm(string id) => _api.GetRenderedForm(id);
/// <summary>
/// Retrieves the form variables for a task. The form variables take form data specified on the task into account. If form fields are defined, the variable types and default values of the form fields are taken into account.
/// </summary>
public Task<Dictionary<string, VariableValue>> GetFormVariables(string id, string variableNames, bool deserializeValues = true) => _api.GetFormVariables(id, variableNames, deserializeValues);
/// <summary>
/// Updates a task.
/// </summary>
public Task Update(string id, UserTask task) => _api.UpdateTask(id, task);
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
namespace Camunda.Api.Client.UserTask
{
public class UserTaskService
{
private IUserTaskRestService _api;
internal UserTaskService(IUserTaskRestService api)
{
_api = api;
}
public TaskResource this[string taskId] => new TaskResource(_api, taskId);
/// <summary>
/// Retrieves the number of tasks for each candidate group.
/// </summary>
public Task<List<TaskCountByCandidateGroupResult>> GetTaskCountByCandidateGroup() => _api.GetTaskCountByCandidateGroup();
public QueryResource<TaskQuery, UserTaskInfo> Query(TaskQuery query = null)
=> new QueryResource<TaskQuery, UserTaskInfo>(_api, query);
public Task Create(UserTask task) => _api.CreateTask(task);
// Retrieve a single task
public Task<UserTaskInfo> Get(string id) => _api.Get(id);
}
}
| mit | C# |
62e72aa2008e4cbe2c62817e1d5e835150e6e74d | Set current directory for initial script. | uoinfusion/Infusion | Infusion.EngineScripts/Scripts/ScriptEngine.cs | Infusion.EngineScripts/Scripts/ScriptEngine.cs | using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace Infusion.EngineScripts
{
public sealed class ScriptEngine
{
private readonly IScriptEngine[] engines;
private string scriptRootPath;
public ScriptEngine(params IScriptEngine[] engines)
{
this.engines = engines;
}
public string ScriptRootPath
{
get => scriptRootPath;
set
{
scriptRootPath = value;
ForeachEngine(engine => engine.ScriptRootPath = value);
}
}
public Task ExecuteInitialScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
var currentRoot = Path.GetDirectoryName(scriptPath);
Directory.SetCurrentDirectory(currentRoot);
ScriptRootPath = currentRoot;
return ExecuteScript(scriptPath, cancellationTokenSource);
}
public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
if (!File.Exists(scriptPath))
throw new FileNotFoundException($"Script file not found: {scriptPath}", scriptPath);
await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
}
public void Reset() => ForeachEngine(engine => engine.Reset());
private void ForeachEngine(Action<IScriptEngine> engineAction)
{
foreach (var engine in engines)
engineAction(engine);
}
private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
{
foreach (var engine in engines)
await engineAction(engine);
}
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Infusion.EngineScripts
{
public sealed class ScriptEngine
{
private readonly IScriptEngine[] engines;
private string scriptRootPath;
public ScriptEngine(params IScriptEngine[] engines)
{
this.engines = engines;
}
public string ScriptRootPath
{
get => scriptRootPath;
set
{
scriptRootPath = value;
ForeachEngine(engine => engine.ScriptRootPath = value);
}
}
public async Task ExecuteScript(string scriptPath, CancellationTokenSource cancellationTokenSource)
{
await ForeachEngineAsync(engine => engine.ExecuteScript(scriptPath, cancellationTokenSource));
}
public void Reset() => ForeachEngine(engine => engine.Reset());
private void ForeachEngine(Action<IScriptEngine> engineAction)
{
foreach (var engine in engines)
engineAction(engine);
}
private async Task ForeachEngineAsync(Func<IScriptEngine, Task> engineAction)
{
foreach (var engine in engines)
await engineAction(engine);
}
}
}
| mit | C# |
0f5f9cd581221b6330441da045f6324b32d9fa65 | make DbContextExtensions public | JSONAPIdotNET/JSONAPI.NET,SphtKr/JSONAPI.NET,SathishN/JSONAPI.NET,DefactoSoftware/JSONAPI.NET,danshapir/JSONAPI.NET | JSONAPI.EntityFramework/DbContextExtensions.cs | JSONAPI.EntityFramework/DbContextExtensions.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
namespace JSONAPI.EntityFramework
{
/// <summary>
/// Extensions on DbContext useful for JSONAPI.NET
/// </summary>
public static class DbContextExtensions
{
/// <summary>
/// Gets the ID key names for an entity type
/// </summary>
/// <param name="dbContext"></param>
/// <param name="type"></param>
/// <returns></returns>
public static IEnumerable<string> GetKeyNames(this DbContext dbContext, Type type)
{
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.NonPublic | BindingFlags.Static);
var method = openMethod.MakeGenericMethod(type);
try
{
return (IEnumerable<string>)method.Invoke(null, new object[] { dbContext });
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
// ReSharper disable once UnusedMember.Local
private static IEnumerable<string> GetKeyNamesFromGeneric<T>(this DbContext dbContext) where T : class
{
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<T> objectSet;
try
{
objectSet = objectContext.CreateObjectSet<T>();
}
catch (InvalidOperationException e)
{
throw new ArgumentException(
String.Format("The Type {0} was not found in the DbContext with Type {1}", typeof(T).Name, dbContext.GetType().Name),
e
);
}
return objectSet.EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}
}
}
| using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Reflection;
namespace JSONAPI.EntityFramework
{
internal static class DbContextExtensions
{
internal static IEnumerable<string> GetKeyNames(this DbContext dbContext, Type type)
{
var openMethod = typeof(DbContextExtensions).GetMethod("GetKeyNamesFromGeneric", BindingFlags.NonPublic | BindingFlags.Static);
var method = openMethod.MakeGenericMethod(type);
try
{
return (IEnumerable<string>)method.Invoke(null, new object[] { dbContext });
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
// ReSharper disable once UnusedMember.Local
private static IEnumerable<string> GetKeyNamesFromGeneric<T>(this DbContext dbContext) where T : class
{
var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
ObjectSet<T> objectSet;
try
{
objectSet = objectContext.CreateObjectSet<T>();
}
catch (InvalidOperationException e)
{
throw new ArgumentException(
String.Format("The Type {0} was not found in the DbContext with Type {1}", typeof(T).Name, dbContext.GetType().Name),
e
);
}
return objectSet.EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray();
}
}
}
| mit | C# |
3faffa87bb4895a82fb7325e15b5abc5b22af8f2 | add ILoginService method | ProjectBlueMonkey/BlueMonkey,ProjectBlueMonkey/BlueMonkey | client/BlueMonkey/BlueMonkey.LoginService/ILoginService.cs | client/BlueMonkey/BlueMonkey.LoginService/ILoginService.cs | using BlueMonkey.Business;
using System.Threading.Tasks;
namespace BlueMonkey.LoginService
{
public interface ILoginService
{
Task<AuthUser> LoginAsync();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BlueMonkey.LoginService
{
public class Class1
{
}
}
| mit | C# |
56578d797aa35b96ee1fe72400b52a9374e7871c | Check for objects existing using their equals operation rather than Ids | TheEadie/LazyStorage,TheEadie/LazyStorage,TheEadie/LazyLibrary | LazyLibrary/Storage/Memory/MemoryRepository.cs | LazyLibrary/Storage/Memory/MemoryRepository.cs | using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LazyLibrary.Storage.Memory
{
internal class MemoryRepository<T> : IRepository<T> where T : IStorable
{
private List<T> repository = new List<T>();
public T GetById(int id)
{
return this.repository.SingleOrDefault(x => x.Id == id);
}
public IQueryable<T> Get(System.Func<T, bool> exp = null)
{
return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
}
public void Upsert(T item)
{
if (repository.Contains(item))
{
// Update
var obj = repository.Single(x => x.Equals(item));
this.repository.Remove(obj);
this.repository.Add(item);
}
else
{
// Insert
var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
item.Id = nextId;
this.repository.Add(item);
}
}
public void Delete(T item)
{
var obj = GetById(item.Id);
this.repository.Remove(obj);
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace LazyLibrary.Storage.Memory
{
internal class MemoryRepository<T> : IRepository<T> where T : IStorable
{
private List<T> repository = new List<T>();
public T GetById(int id)
{
return this.repository.Where(x => x.Id == id).SingleOrDefault();
}
public IQueryable<T> Get(System.Func<T, bool> exp = null)
{
return exp != null ? repository.Where(exp).AsQueryable<T>() : repository.AsQueryable<T>();
}
public void Upsert(T item)
{
var obj = GetById(item.Id);
if (obj != null)
{
// Update
this.repository.Remove(obj);
this.repository.Add(item);
}
else
{
// Insert
var nextId = this.repository.Any() ? this.repository.Max(x => x.Id) + 1 : 1;
item.Id = nextId;
this.repository.Add(item);
}
}
public void Delete(T item)
{
var obj = GetById(item.Id);
this.repository.Remove(obj);
}
}
} | mit | C# |
6248f6da55730e7e20bac601ddb0fb5a7217f2fe | Change how indexes are built to fix field selection errors. | SilkStack/Silk.Data.SQL.ORM | Silk.Data.SQL.ORM/Schema/SchemaIndexBuilder.cs | Silk.Data.SQL.ORM/Schema/SchemaIndexBuilder.cs | using Silk.Data.Modelling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Silk.Data.SQL.ORM.Schema
{
public interface ISchemaIndexBuilder
{
SchemaIndex Build(Table table, ISchemaField[] entityFields);
}
public class SchemaIndexBuilder<T> : ISchemaIndexBuilder
where T : class
{
private readonly TypeModel<T> _entityTypeModel = TypeModel.GetModelOf<T>();
private readonly List<string[]> _indexFields = new List<string[]>();
public string IndexName { get; }
public bool HasUniqueConstraint { get; set; }
public SchemaIndexBuilder(string indexName)
{
IndexName = indexName;
}
public SchemaIndex Build(Table table, ISchemaField[] entityFields)
{
return new SchemaIndex(IndexName, HasUniqueConstraint,
entityFields.Where(q => _indexFields.Any(q2 => q2.SequenceEqual(q.ModelPath))).ToArray(),
table);
}
public void AddFields(params Expression<Func<T, object>>[] indexFields)
{
foreach (var indexField in indexFields)
{
AddField(indexField);
}
}
private void AddField(Expression indexField)
{
if (indexField is LambdaExpression lambdaExpression)
{
if (lambdaExpression.Body is UnaryExpression unaryExpression)
{
AddField(unaryExpression.Operand);
}
else if (lambdaExpression.Body is MemberExpression memberExpression)
{
AddField(memberExpression);
}
}
else
{
var path = new List<string>();
PopulatePath(indexField, path);
var field = GetField(path);
if (field == null)
throw new ArgumentException("Field selector expression doesn't specify a valid member.", nameof(indexField));
if (!_indexFields.Any(q => q.SequenceEqual(path)))
_indexFields.Add(path.ToArray());
}
}
private IPropertyField GetField(IEnumerable<string> path)
{
var fields = _entityTypeModel.Fields;
var field = default(IPropertyField);
foreach (var segment in path)
{
field = fields.FirstOrDefault(q => q.FieldName == segment);
fields = field.FieldTypeModel?.Fields;
}
return field;
}
private void PopulatePath(Expression expression, List<string> path)
{
if (expression is MemberExpression memberExpression)
{
var parentExpr = memberExpression.Expression;
PopulatePath(parentExpr, path);
path.Add(memberExpression.Member.Name);
}
}
}
}
| using Silk.Data.Modelling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Silk.Data.SQL.ORM.Schema
{
public interface ISchemaIndexBuilder
{
SchemaIndex Build(Table table, ISchemaField[] entityFields);
}
public class SchemaIndexBuilder<T> : ISchemaIndexBuilder
where T : class
{
private readonly TypeModel<T> _entityTypeModel = TypeModel.GetModelOf<T>();
private readonly List<IPropertyField> _indexFields = new List<IPropertyField>();
public string IndexName { get; }
public bool HasUniqueConstraint { get; set; }
public SchemaIndexBuilder(string indexName)
{
IndexName = indexName;
}
public SchemaIndex Build(Table table, ISchemaField[] entityFields)
{
return new SchemaIndex(IndexName, HasUniqueConstraint,
entityFields.Where(q => _indexFields.Any(q2 => q.FieldName == q2.FieldName)).ToArray(),
table);
}
public void AddFields(params Expression<Func<T, object>>[] indexFields)
{
foreach (var indexField in indexFields)
{
AddField(indexField);
}
}
private void AddField(Expression indexField)
{
if (indexField is LambdaExpression lambdaExpression)
{
if (lambdaExpression.Body is UnaryExpression unaryExpression)
{
AddField(unaryExpression.Operand);
}
else if (lambdaExpression.Body is MemberExpression memberExpression)
{
AddField(memberExpression);
}
}
else
{
var path = new List<string>();
PopulatePath(indexField, path);
var field = GetField(path);
if (field == null)
throw new ArgumentException("Field selector expression doesn't specify a valid member.", nameof(indexField));
if (!_indexFields.Contains(field))
_indexFields.Add(field);
}
}
private IPropertyField GetField(IEnumerable<string> path)
{
var fields = _entityTypeModel.Fields;
var field = default(IPropertyField);
foreach (var segment in path)
{
field = fields.FirstOrDefault(q => q.FieldName == segment);
fields = field.FieldTypeModel?.Fields;
}
return field;
}
private void PopulatePath(Expression expression, List<string> path)
{
if (expression is MemberExpression memberExpression)
{
var parentExpr = memberExpression.Expression;
PopulatePath(parentExpr, path);
path.Add(memberExpression.Member.Name);
}
}
}
}
| mit | C# |
7d107e726bce4abe72923291350f054a2e04f21a | Put the scratch and warehouse directories up on WASB in the Shark test service. This gets CTAS to work. | mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee,mooso/BlueCoffee | TestServices/ElectricBlobs/Shark/WorkerRole.cs | TestServices/ElectricBlobs/Shark/WorkerRole.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;
namespace Shark
{
public class WorkerRole : SharkNodeBase
{
protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
{
var rootFs = String.Format("wasb://shark@{0}.blob.core.windows.net",
WasbConfiguration.ReadWasbAccountsFile().First());
return WasbConfiguration.GetWasbConfigKeys()
.Add("hive.exec.scratchdir", rootFs + "/scratch")
.Add("hive.metastore.warehouse.dir", rootFs + "/warehouse");
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.Experimental.Azure.Spark;
using System.Collections.Immutable;
using System.IO;
using Microsoft.Experimental.Azure.CommonTestUtilities;
namespace Shark
{
public class WorkerRole : SharkNodeBase
{
protected override ImmutableDictionary<string, string> GetHadoopConfigProperties()
{
return WasbConfiguration.GetWasbConfigKeys();
}
}
}
| mit | C# |
6a10ff93af584050988f69b5e069839474639e3e | Fix sonarqube markup that sub has lhs and rhs identical | steven-r/Oberon0Compiler | oberon0/Expressions/Arithmetic/SubExpression.cs | oberon0/Expressions/Arithmetic/SubExpression.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;
namespace Oberon0.Compiler.Expressions.Arithmetic
{
[Export(typeof(ICalculatable))]
class SubExpression: BinaryExpression, ICalculatable
{
public SubExpression()
{
Operator = TokenType.Sub;
}
public override Expression Calc(Block block)
{
if (this.BinaryConstChecker(block) == null)
{
return null;
}
// 1. Easy as int
var leftHandSide = (ConstantExpression)LeftHandSide;
var rightHandSide = (ConstantExpression)RightHandSide;
if (rightHandSide.BaseType == leftHandSide.BaseType && leftHandSide.BaseType == BaseType.IntType)
{
return new ConstantIntExpression(leftHandSide.ToInt32() - rightHandSide.ToInt32());
}
// at least one of them is double
return new ConstantDoubleExpression(leftHandSide.ToDouble() - rightHandSide.ToDouble());
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oberon0.Compiler.Definitions;
using Oberon0.Compiler.Solver;
namespace Oberon0.Compiler.Expressions.Arithmetic
{
[Export(typeof(ICalculatable))]
class SubExpression: BinaryExpression, ICalculatable
{
public SubExpression()
{
Operator = TokenType.Sub;
}
public override Expression Calc(Block block)
{
if (this.BinaryConstChecker(block) == null)
{
return null;
}
// 1. Easy as int
var lhi = (ConstantExpression)LeftHandSide;
var rhi = (ConstantExpression)RightHandSide;
if (rhi.BaseType == lhi.BaseType && lhi.BaseType == BaseType.IntType)
{
return new ConstantIntExpression(lhi.ToInt32() - rhi.ToInt32());
}
// at least one of them is double
return new ConstantDoubleExpression(lhi.ToDouble() - lhi.ToDouble());
}
}
}
| mit | C# |
8285ce28ae0ad1507d4bf5eed886d61ba22fc6a5 | Make GetMatchedType virtual | appharbor/appharbor-cli | src/AppHarbor/TypeNameMatcher.cs | src/AppHarbor/TypeNameMatcher.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace AppHarbor
{
public class TypeNameMatcher<T>
{
private readonly IEnumerable<Type> _candidateTypes;
public TypeNameMatcher(IEnumerable<Type> candidateTypes)
{
if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x)))
{
throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes");
}
_candidateTypes = candidateTypes;
}
public virtual Type GetMatchedType(string commandName, string scope)
{
var typeNameSuffix = "Command";
var scopedTypes = _candidateTypes
.Where(x => x.Name.ToLower().EndsWith(string.Concat(scope, typeNameSuffix).ToLower()));
Type command;
try
{
return _candidateTypes.Single(x => x.Name.ToLower() == string.Concat(commandName, typeNameSuffix).ToLower());
}
catch (InvalidOperationException)
{
}
try
{
command = scopedTypes.SingleOrDefault(x => x.Name.ToLower().StartsWith(commandName.ToLower()));
if (command != null)
{
return command;
}
}
catch (InvalidOperationException)
{
throw new ArgumentException(string.Format("More than one command matches \"{0}\".", commandName));
}
throw new ArgumentException(string.Format("No commands matches \"{0}\".", commandName));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace AppHarbor
{
public class TypeNameMatcher<T>
{
private readonly IEnumerable<Type> _candidateTypes;
public TypeNameMatcher(IEnumerable<Type> candidateTypes)
{
if (candidateTypes.Any(x => !typeof(T).IsAssignableFrom(x)))
{
throw new ArgumentException(string.Format("{0} must be assignable from all injected types", typeof(T).FullName), "candidateTypes");
}
_candidateTypes = candidateTypes;
}
public Type GetMatchedType(string commandName, string scope)
{
var typeNameSuffix = "Command";
var scopedTypes = _candidateTypes
.Where(x => x.Name.ToLower().EndsWith(string.Concat(scope, typeNameSuffix).ToLower()));
Type command;
try
{
return _candidateTypes.Single(x => x.Name.ToLower() == string.Concat(commandName, typeNameSuffix).ToLower());
}
catch (InvalidOperationException)
{
}
try
{
command = scopedTypes.SingleOrDefault(x => x.Name.ToLower().StartsWith(commandName.ToLower()));
if (command != null)
{
return command;
}
}
catch (InvalidOperationException)
{
throw new ArgumentException(string.Format("More than one command matches \"{0}\".", commandName));
}
throw new ArgumentException(string.Format("No commands matches \"{0}\".", commandName));
}
}
}
| mit | C# |
e8a72793588b4827e12955e18f17ed7ca15a1c26 | update version again | agileharbor/shipStationAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.61.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.60.0" ) ] | bsd-3-clause | C# |
a49ac9edcf157ce185dfe2ac52005e2ffb6ae7dd | Add comments | Abc-Arbitrage/Zebus | src/Abc.Zebus/Directory/PeerUpdateAction.cs | src/Abc.Zebus/Directory/PeerUpdateAction.cs | namespace Abc.Zebus.Directory
{
public enum PeerUpdateAction
{
Stopped,
Started,
/// <summary> Peer subscriptions are updated </summary>
Updated,
Decommissioned,
}
}
| namespace Abc.Zebus.Directory
{
public enum PeerUpdateAction
{
Stopped,
Started,
Updated,
Decommissioned,
}
} | mit | C# |
4a9b59d22c4869b32784bd134a26f367aa80bd64 | Add FederatedAmazonCredentials#GetSessionCredentials | appharbor/appharbor-cli | src/AppHarbor/FederatedAmazonCredentials.cs | src/AppHarbor/FederatedAmazonCredentials.cs | using Amazon.Runtime;
namespace AppHarbor
{
public class FederatedAmazonCredentials
{
public string AccessKeyId { get; set; }
public string SecretAccessKey { get; set; }
public string SessionToken { get; set; }
public SessionAWSCredentials GetSessionCredentials()
{
return new SessionAWSCredentials(AccessKeyId, SecretAccessKey, SessionToken);
}
}
}
| namespace AppHarbor
{
public class FederatedAmazonCredentials
{
public string AccessKeyId { get; set; }
public string SecretAccessKey { get; set; }
public string SessionToken { get; set; }
}
}
| mit | C# |
368c894f9b7afae08e46673e9ff47899be01992e | Update GeoffreyHuntley.cs (#160) | MabroukENG/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin | src/Firehose.Web/Authors/GeoffreyHuntley.cs | src/Firehose.Web/Authors/GeoffreyHuntley.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP, IAmAXamarinMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string ShortBioOrTagLine => "has been involved in the Xamarin community since the early monotouch/monodroid days";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://ghuntley.com/atom.xml"); }
}
public string GravatarHash => "";
public string GitHubHandle => "ghuntley";
public GeoPosition Position => new GeoPosition(-33.8641859, 151.2143821);
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string ShortBioOrTagLine => "has been involved in the Xamarin community since the early monotouch/monodroid days";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://ghuntley.com/atom.xml"); }
}
public string GravatarHash => "";
public string GitHubHandle => "ghuntley";
public GeoPosition Position => new GeoPosition(-33.8641859, 151.2143821);
}
} | mit | C# |
c5c012e900647c3381fd2bf4bf6f0b3535fe2ff2 | Set nuget version to 1.0.0-beta1 | kevinkuszyk/FluentAssertions.Ioc.Ninject,kevinkuszyk/FluentAssertions.Ioc.Ninject | src/FluentAssertions.Ioc.Ninject/Properties/AssemblyInfo.cs | src/FluentAssertions.Ioc.Ninject/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Kuszyk")]
[assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyCopyright("Copyright © Kevin Kuszyk 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
06787b5389cdf53242492ac5f8263fd252807126 | include score in results | AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us | src/Maw.Domain/Search/MultimediaCategory.cs | src/Maw.Domain/Search/MultimediaCategory.cs | using SolrNet.Attributes;
namespace Maw.Domain.Search
{
public class MultimediaCategory {
[SolrUniqueKey("solr_id")]
public string SolrId { get; set; }
[SolrField("id")]
public int Id { get; set; }
[SolrField("year")]
public int Year { get; set; }
[SolrField("name")]
public string Name { get; set; }
[SolrField("type")]
public string MultimediaType { get; set; }
[SolrField("teaser_photo_height")]
public int TeaserPhotoHeight { get; set; }
[SolrField("teaser_photo_width")]
public int TeaserPhotoWidth { get; set; }
[SolrField("teaser_photo_path")]
public string TeaserPhotoPath { get; set; }
[SolrField("teaser_photo_sq_height")]
public int TeaserPhotoSqHeight { get; set; }
[SolrField("teaser_photo_sq_width")]
public int TeaserPhotoSqWidth { get; set; }
[SolrField("teaser_photo_sq_path")]
public string TeaserPhotoSqPath { get; set; }
[SolrField("score")]
public double Score { get; set; }
}
}
| using SolrNet.Attributes;
namespace Maw.Domain.Search
{
public class MultimediaCategory {
[SolrUniqueKey("solr_id")]
public string SolrId { get; set; }
[SolrField("id")]
public int Id { get; set; }
[SolrField("year")]
public int Year { get; set; }
[SolrField("name")]
public string Name { get; set; }
[SolrField("type")]
public string MultimediaType { get; set; }
[SolrField("teaser_photo_height")]
public int TeaserPhotoHeight { get; set; }
[SolrField("teaser_photo_width")]
public int TeaserPhotoWidth { get; set; }
[SolrField("teaser_photo_path")]
public string TeaserPhotoPath { get; set; }
[SolrField("teaser_photo_sq_height")]
public int TeaserPhotoSqHeight { get; set; }
[SolrField("teaser_photo_sq_width")]
public int TeaserPhotoSqWidth { get; set; }
[SolrField("teaser_photo_sq_path")]
public string TeaserPhotoSqPath { get; set; }
}
}
| mit | C# |
0fc762cb449c9f7e78e77cb784cdccc11b828199 | Implement new 'CanCreate' methods. Fixes #838 | mysql-net/MySqlConnector,mysql-net/MySqlConnector | src/MySqlConnector/MySqlConnectorFactory.cs | src/MySqlConnector/MySqlConnectorFactory.cs | using System.Data.Common;
namespace MySqlConnector
{
public sealed class MySqlConnectorFactory : DbProviderFactory
{
public static readonly MySqlConnectorFactory Instance = new();
public override DbCommand CreateCommand() => new MySqlCommand();
public override DbConnection CreateConnection() => new MySqlConnection();
public override DbConnectionStringBuilder CreateConnectionStringBuilder() => new MySqlConnectionStringBuilder();
public override DbParameter CreateParameter() => new MySqlParameter();
#if !NETSTANDARD1_3
public override DbCommandBuilder CreateCommandBuilder() => new MySqlCommandBuilder();
public override DbDataAdapter CreateDataAdapter() => new MySqlDataAdapter();
#if !NET45 && !NET461 && !NET471 && !NETSTANDARD2_0 && !NETCOREAPP2_1
public override bool CanCreateCommandBuilder => true;
public override bool CanCreateDataAdapter => true;
public override bool CanCreateDataSourceEnumerator => false;
#endif
#endif
public MySqlBatch CreateBatch() => new MySqlBatch();
public MySqlBatchCommand CreateBatchCommand() => new MySqlBatchCommand();
public bool CanCreateBatch => true;
private MySqlConnectorFactory()
{
}
}
}
| using System.Data.Common;
namespace MySqlConnector
{
public sealed class MySqlConnectorFactory : DbProviderFactory
{
public static readonly MySqlConnectorFactory Instance = new();
public override DbCommand CreateCommand() => new MySqlCommand();
public override DbConnection CreateConnection() => new MySqlConnection();
public override DbConnectionStringBuilder CreateConnectionStringBuilder() => new MySqlConnectionStringBuilder();
public override DbParameter CreateParameter() => new MySqlParameter();
#if !NETSTANDARD1_3
public override DbCommandBuilder CreateCommandBuilder() => new MySqlCommandBuilder();
public override DbDataAdapter CreateDataAdapter() => new MySqlDataAdapter();
#endif
public MySqlBatch CreateBatch() => new MySqlBatch();
public MySqlBatchCommand CreateBatchCommand() => new MySqlBatchCommand();
public bool CanCreateBatch => true;
private MySqlConnectorFactory()
{
}
}
}
| mit | C# |
c5dd11c9534b632bf3524589d2a36e521b44c771 | Fix spaces for tabs | gregsochanik/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper | src/SevenDigital.Api.Schema/Tracks/Track.cs | src/SevenDigital.Api.Schema/Tracks/Track.cs | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Artists;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.Media;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
using SevenDigital.Api.Schema.Releases;
namespace SevenDigital.Api.Schema.Tracks
{
[XmlRoot("track")]
[ApiEndpoint("track/details")]
[Serializable]
public class Track : HasTrackIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
/// <summary>
/// Track number or in cases where disc number is greater than 1, it is the discNumber + trackNumber (ie 203)
/// </summary>
/// <remarks>Will soon de decommisioned</remarks>
[XmlElement("trackNumber")]
public int TrackNumber { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("isrc")]
public string Isrc { get; set; }
[XmlElement("release")]
public Release Release { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("price")]
public Price Price { get; set; }
[XmlElement("type")]
public TrackType Type { get; set; }
[XmlElement(ElementName = "streamingReleaseDate", IsNullable = true)]
public DateTime? StreamingReleaseDate { get; set; }
[XmlElement("discNumber")]
public int DiscNumber { get; set; }
[XmlElement("formats")]
public FormatList Formats { get; set; }
/// <summary>
/// Track Number. Should be used instead of "TrackNumber"
/// </summary>
[XmlElement("number")]
public int Number { get; set; }
}
} | using System;
using System.Xml.Serialization;
using SevenDigital.Api.Schema.Artists;
using SevenDigital.Api.Schema.Attributes;
using SevenDigital.Api.Schema.Media;
using SevenDigital.Api.Schema.ParameterDefinitions.Get;
using SevenDigital.Api.Schema.Pricing;
using SevenDigital.Api.Schema.Releases;
namespace SevenDigital.Api.Schema.Tracks
{
[XmlRoot("track")]
[ApiEndpoint("track/details")]
[Serializable]
public class Track : HasTrackIdParameter
{
[XmlAttribute("id")]
public int Id { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("artist")]
public Artist Artist { get; set; }
/// <summary>
/// Track number or in cases where disc number is greater than 1, it is the discNumber + trackNumber (ie 203)
/// </summary>
/// <remarks>Will soon de decommisioned</remarks>
[XmlElement("trackNumber")]
public int TrackNumber { get; set; }
[XmlElement("duration")]
public int Duration { get; set; }
[XmlElement("explicitContent")]
public bool ExplicitContent { get; set; }
[XmlElement("isrc")]
public string Isrc { get; set; }
[XmlElement("release")]
public Release Release { get; set; }
[XmlElement("url")]
public string Url { get; set; }
[XmlElement("image")]
public string Image { get; set; }
[XmlElement("price")]
public Price Price { get; set; }
[XmlElement("type")]
public TrackType Type { get; set; }
[XmlElement(ElementName = "streamingReleaseDate", IsNullable = true)]
public DateTime? StreamingReleaseDate { get; set; }
[XmlElement("discNumber")]
public int DiscNumber { get; set; }
[XmlElement("formats")]
public FormatList Formats { get; set; }
/// <summary>
/// Track Number. Should be used instead of "TrackNumber"
/// </summary>
[XmlElement("number")]
public int Number { get; set; }
}
} | mit | C# |
e23b52d59ff6323e7aae7a1948c05bb57f425c2a | Add basic bindable instantiation benchmark | ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework | osu.Framework.Benchmarks/BenchmarkBindableInstantiation.cs | osu.Framework.Benchmarks/BenchmarkBindableInstantiation.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 BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkBindableInstantiation
{
[Benchmark]
public Bindable<int> Instantiate() => new Bindable<int>();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using BenchmarkDotNet.Attributes;
using osu.Framework.Bindables;
namespace osu.Framework.Benchmarks
{
public class BenchmarkBindableInstantiation
{
[Benchmark(Baseline = true)]
public Bindable<int> GetBoundCopyOld() => new BindableOld<int>().GetBoundCopy();
[Benchmark]
public Bindable<int> GetBoundCopy() => new Bindable<int>().GetBoundCopy();
private class BindableOld<T> : Bindable<T>
{
public BindableOld(T defaultValue = default)
: base(defaultValue)
{
}
protected override Bindable<T> CreateInstance() => (BindableOld<T>)Activator.CreateInstance(GetType(), Value);
}
}
}
| mit | C# |
eda22e29ba99c0dd421a45414ab1923cc6bd6c74 | Fix wrong dimensions when iterating over feature footprint | MHeasell/Mappy,MHeasell/Mappy | Mappy/Data/Feature.cs | Mappy/Data/Feature.cs | namespace Mappy.Data
{
using System;
using System.Drawing;
using Mappy.Collections;
/// <summary>
/// Represents the "blueprint" for a feature.
/// Contains metadata about the feature.
/// </summary>
public class Feature
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public Size Footprint { get; set; }
public Point Offset { get; set; }
public Bitmap Image { get; set; }
public Rectangle GetDrawBounds(IGrid<int> heightmap, int xPos, int yPos)
{
int accum = 0;
for (int y = 0; y <= this.Footprint.Height; y++)
{
for (int x = 0; x <= this.Footprint.Width; x++)
{
int accX = xPos + x;
int accY = yPos + y;
// avoid crashing if we try to draw a feature too close to the map edge
if (accX < 0 || accY < 0 || accX >= heightmap.Width || accY >= heightmap.Height)
{
continue;
}
accum += heightmap.Get(xPos + x, yPos + y);
}
}
int avg = accum / ((this.Footprint.Width + 1) * (this.Footprint.Height + 1));
float posX = ((float)xPos + (this.Footprint.Width / 2.0f)) * 16;
float posY = (((float)yPos + (this.Footprint.Height / 2.0f)) * 16) - (avg / 2);
Point pos = new Point((int)Math.Round(posX) - this.Offset.X, (int)Math.Round(posY) - this.Offset.Y);
return new Rectangle(pos, this.Image.Size);
}
}
}
| namespace Mappy.Data
{
using System;
using System.Drawing;
using Mappy.Collections;
/// <summary>
/// Represents the "blueprint" for a feature.
/// Contains metadata about the feature.
/// </summary>
public class Feature
{
public string Name { get; set; }
public string World { get; set; }
public string Category { get; set; }
public Size Footprint { get; set; }
public Point Offset { get; set; }
public Bitmap Image { get; set; }
public Rectangle GetDrawBounds(IGrid<int> heightmap, int xPos, int yPos)
{
int accum = 0;
for (int y = 0; y <= this.Footprint.Width; y++)
{
for (int x = 0; x <= this.Footprint.Height; x++)
{
int accX = xPos + x;
int accY = yPos + y;
// avoid crashing if we try to draw a feature too close to the map edge
if (accX < 0 || accY < 0 || accX >= heightmap.Width || accY >= heightmap.Height)
{
continue;
}
accum += heightmap.Get(xPos + x, yPos + y);
}
}
int avg = accum / ((this.Footprint.Width + 1) * (this.Footprint.Height + 1));
float posX = ((float)xPos + (this.Footprint.Width / 2.0f)) * 16;
float posY = (((float)yPos + (this.Footprint.Height / 2.0f)) * 16) - (avg / 2);
Point pos = new Point((int)Math.Round(posX) - this.Offset.X, (int)Math.Round(posY) - this.Offset.Y);
return new Rectangle(pos, this.Image.Size);
}
}
}
| mit | C# |
c7cf8a55b8964d2671d8e84a9474142bd247625f | Add DOTNET_HOST_PATH for dotnet nuget commands | dasMulli/cli,livarcocc/cli-1,johnbeisner/cli,dasMulli/cli,johnbeisner/cli,dasMulli/cli,johnbeisner/cli,livarcocc/cli-1,livarcocc/cli-1 | src/dotnet/commands/dotnet-nuget/Program.cs | src/dotnet/commands/dotnet-nuget/Program.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;
namespace Microsoft.DotNet.Tools.NuGet
{
public class NuGetCommand
{
public static int Run(string[] args)
{
return Run(args, new NuGetCommandRunner());
}
public static int Run(string[] args, ICommandRunner nugetCommandRunner)
{
DebugHelper.HandleDebugSwitch(ref args);
if (nugetCommandRunner == null)
{
throw new ArgumentNullException(nameof(nugetCommandRunner));
}
return nugetCommandRunner.Run(args);
}
private class NuGetCommandRunner : ICommandRunner
{
public int Run(string[] args)
{
var nugetApp = new NuGetForwardingApp(args);
nugetApp.WithEnvironmentVariable("DOTNET_HOST_PATH", GetDotnetPath());
return nugetApp.Execute();
}
}
private static string GetDotnetPath()
{
return new Muxer().MuxerPath;
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.InternalAbstractions;
using Microsoft.DotNet.Tools;
namespace Microsoft.DotNet.Tools.NuGet
{
public class NuGetCommand
{
public static int Run(string[] args)
{
return Run(args, new NuGetCommandRunner());
}
public static int Run(string[] args, ICommandRunner nugetCommandRunner)
{
DebugHelper.HandleDebugSwitch(ref args);
if (nugetCommandRunner == null)
{
throw new ArgumentNullException(nameof(nugetCommandRunner));
}
return nugetCommandRunner.Run(args);
}
private class NuGetCommandRunner : ICommandRunner
{
public int Run(string[] args)
{
var nugetApp = new NuGetForwardingApp(args);
return nugetApp.Execute();
}
}
}
}
| mit | C# |
762f6ec3cd06d33ba6ed3dc4dc83b7b28c174d74 | Make tests runnable on mono | rflechner/FAKE,haithemaraissia/FAKE,hitesh97/FAKE,MichalDepta/FAKE,daniel-chambers/FAKE,mat-mcloughlin/FAKE,RMCKirby/FAKE,darrelmiller/FAKE,xavierzwirtz/FAKE,brianary/FAKE,xavierzwirtz/FAKE,darrelmiller/FAKE,jayp33/FAKE,mfalda/FAKE,xavierzwirtz/FAKE,ovu/FAKE,xavierzwirtz/FAKE,beeker/FAKE,leflings/FAKE,NaseUkolyCZ/FAKE,tpetricek/FAKE,MiloszKrajewski/FAKE,dmorgan3405/FAKE,haithemaraissia/FAKE,dmorgan3405/FAKE,jayp33/FAKE,rflechner/FAKE,warnergodfrey/FAKE,neoeinstein/FAKE,ArturDorochowicz/FAKE,JonCanning/FAKE,haithemaraissia/FAKE,ArturDorochowicz/FAKE,yonglehou/FAKE,neoeinstein/FAKE,hitesh97/FAKE,JonCanning/FAKE,modulexcite/FAKE,satsuper/FAKE,pmcvtm/FAKE,ilkerde/FAKE,molinch/FAKE,gareth-evans/FAKE,MiloszKrajewski/FAKE,mfalda/FAKE,dmorgan3405/FAKE,ArturDorochowicz/FAKE,mglodack/FAKE,NaseUkolyCZ/FAKE,modulexcite/FAKE,mglodack/FAKE,naveensrinivasan/FAKE,brianary/FAKE,ilkerde/FAKE,tpetricek/FAKE,gareth-evans/FAKE,pmcvtm/FAKE,pmcvtm/FAKE,hitesh97/FAKE,neoeinstein/FAKE,MiloszKrajewski/FAKE,wooga/FAKE,MichalDepta/FAKE,MiloszKrajewski/FAKE,dlsteuer/FAKE,brianary/FAKE,yonglehou/FAKE,NaseUkolyCZ/FAKE,MichalDepta/FAKE,pacificIT/FAKE,naveensrinivasan/FAKE,jayp33/FAKE,ilkerde/FAKE,rflechner/FAKE,haithemaraissia/FAKE,RMCKirby/FAKE,rflechner/FAKE,darrelmiller/FAKE,warnergodfrey/FAKE,mglodack/FAKE,featuresnap/FAKE,naveensrinivasan/FAKE,ctaggart/FAKE,daniel-chambers/FAKE,Kazark/FAKE,philipcpresley/FAKE,gareth-evans/FAKE,pmcvtm/FAKE,pacificIT/FAKE,tpetricek/FAKE,Kazark/FAKE,brianary/FAKE,modulexcite/FAKE,gareth-evans/FAKE,philipcpresley/FAKE,wooga/FAKE,daniel-chambers/FAKE,jayp33/FAKE,yonglehou/FAKE,wooga/FAKE,daniel-chambers/FAKE,ctaggart/FAKE,mat-mcloughlin/FAKE,satsuper/FAKE,ctaggart/FAKE,molinch/FAKE,darrelmiller/FAKE,ArturDorochowicz/FAKE,mfalda/FAKE,Kazark/FAKE,satsuper/FAKE,dmorgan3405/FAKE,philipcpresley/FAKE,NaseUkolyCZ/FAKE,JonCanning/FAKE,JonCanning/FAKE,featuresnap/FAKE,wooga/FAKE,modulexcite/FAKE,ctaggart/FAKE,warnergodfrey/FAKE,satsuper/FAKE,RMCKirby/FAKE,featuresnap/FAKE,mfalda/FAKE,ilkerde/FAKE,mat-mcloughlin/FAKE,hitesh97/FAKE,ovu/FAKE,pacificIT/FAKE,dlsteuer/FAKE,neoeinstein/FAKE,yonglehou/FAKE,beeker/FAKE,beeker/FAKE,featuresnap/FAKE,dlsteuer/FAKE,naveensrinivasan/FAKE,mglodack/FAKE,ovu/FAKE,beeker/FAKE,MichalDepta/FAKE,tpetricek/FAKE,leflings/FAKE,pacificIT/FAKE,leflings/FAKE,philipcpresley/FAKE,warnergodfrey/FAKE,mat-mcloughlin/FAKE,ovu/FAKE,molinch/FAKE,Kazark/FAKE,leflings/FAKE,RMCKirby/FAKE,molinch/FAKE,dlsteuer/FAKE | src/test/Test.FAKECore/AssemblyInfoSpecs.cs | src/test/Test.FAKECore/AssemblyInfoSpecs.cs | using System;
using System.Collections.Generic;
using System.IO;
using Fake;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_accessing_internals
{
It should_have_access_to_FAKE_internals =
() => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>());
}
public class when_using_fsharp_task_with_default_config
{
It should_use_system_namespace_and_emit_a_verison_module = () =>
{
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes);
const string expected = "namespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] Version = \"1.0.0.0\"\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
public class when_using_fsharp_task_with_custom_config
{
It should_use_custom_namespace_and_not_emit_a_version_module = () =>
{
var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false, "Custom");
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig);
const string expected = "namespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
} | using System;
using System.Collections.Generic;
using System.IO;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_accessing_internals
{
It should_have_access_to_FAKE_internals =
() => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>());
}
public class when_using_fsharp_task_with_default_config
{
It should_use_system_namespace_and_emit_a_verison_module = () =>
{
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes);
string expected =
"namespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] Version = \"1.0.0.0\"\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
public class when_using_fsharp_task_with_custom_config
{
It should_use_custom_namespace_and_not_emit_a_version_module = () =>
{
var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false, "Custom");
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig);
string expected =
"namespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
} | apache-2.0 | C# |
50ecea74338f7a358b2655b2a6c3b526017a7fb5 | update CommanderTest for the newline | haruair/csharp-command | test/Haruair.Command.Tests/CommanderTest.cs | test/Haruair.Command.Tests/CommanderTest.cs | using NUnit.Framework;
using System;
using System.IO;
namespace Haruair.Command.Tests
{
[TestFixture ()]
public class CommanderTest
{
Commander commander;
TextWriter originalSw;
StringWriter sw;
[SetUp()]
public void Init ()
{
this.commander = new Commander ();
this.commander.Add (typeof(HelloCommand));
this.commander.Add (typeof(TimeCommand));
this.originalSw = Console.Out;
this.sw = new StringWriter ();
Console.SetOut (sw);
}
[TearDown()]
public void Dispose()
{
this.commander = null;
this.sw = null;
Console.SetOut (this.originalSw);
}
[Test ()]
public void NoInputTestCase ()
{
var mockArgs = new string[0];
this.commander.Run (mockArgs);
var expected = @"Example:
hello, h Hello Command. Nothing Special.
time, t Check the system time.
";
expected = expected.Replace ("\n", Environment.NewLine);
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void HelloTestCase()
{
var mockArgs = new string[] { "hello" };
this.commander.Run (mockArgs);
var expected = @"Example of hello:
say, s When you want to say something, you can use it.
";
expected = expected.Replace ("\n", Environment.NewLine);
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void HelloSayTestCase()
{
var mockArgs = new string[] { "hello", "say" };
this.commander.Run (mockArgs);
var expected = String.Format ("Yo. You called me.{0}", Environment.NewLine);
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void TimeTestCase()
{
var mockArgs = new string[] { "t" };
this.commander.Run (mockArgs);
var expected = @"Example of t:
now
";
expected = expected.Replace ("\n", Environment.NewLine);
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void TimeNowTestCase()
{
var mockArgs = new string[] { "t", "now" };
this.commander.Run (mockArgs);
var expected = String.Format("{0}{1}", DateTime.Now.ToString(), Environment.NewLine);
Assert.AreEqual (expected, sw.ToString());
}
}
[Command("hello", "h")]
[Usage("Hello Command. Nothing Special.")]
public class HelloCommand
{
[Command("say", "s")]
[Usage("When you want to say something, you can use it.")]
public void Say() {
Console.WriteLine ("Yo. You called me.");
}
}
[Command("time", "t")]
[Usage("Check the system time.")]
public class TimeCommand
{
[Command("now")]
public void Now() {
Console.WriteLine ("{0}", DateTime.Now);
}
}
}
| using NUnit.Framework;
using System;
using System.IO;
namespace Haruair.Command.Tests
{
[TestFixture ()]
public class CommanderTest
{
Commander commander;
TextWriter originalSw;
StringWriter sw;
[SetUp()]
public void Init ()
{
this.commander = new Commander ();
this.commander.Add (typeof(HelloCommand));
this.commander.Add (typeof(TimeCommand));
this.originalSw = Console.Out;
this.sw = new StringWriter ();
Console.SetOut (sw);
}
[TearDown()]
public void Dispose()
{
this.commander = null;
this.sw = null;
Console.SetOut (this.originalSw);
}
[Test ()]
public void NoInputTestCase ()
{
var mockArgs = new string[0];
this.commander.Run (mockArgs);
var expected = @"Example:
hello, h Hello Command. Nothing Special.
time, t Check the system time.
";
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void HelloTestCase()
{
var mockArgs = new string[] { "hello" };
this.commander.Run (mockArgs);
var expected = @"Example of hello:
say, s When you want to say something, you can use it.
";
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void HelloSayTestCase()
{
var mockArgs = new string[] { "hello", "say" };
this.commander.Run (mockArgs);
var expected = String.Format ("Yo. You called me.{0}", Environment.NewLine);
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void TimeTestCase()
{
var mockArgs = new string[] { "t" };
this.commander.Run (mockArgs);
var expected = @"Example of t:
now
";
Assert.AreEqual (expected, sw.ToString ());
}
[Test ()]
public void TimeNowTestCase()
{
var mockArgs = new string[] { "t", "now" };
this.commander.Run (mockArgs);
var expected = String.Format("{0}{1}", DateTime.Now.ToString(), Environment.NewLine);
Assert.AreEqual (expected, sw.ToString());
}
}
[Command("hello", "h")]
[Usage("Hello Command. Nothing Special.")]
public class HelloCommand
{
[Command("say", "s")]
[Usage("When you want to say something, you can use it.")]
public void Say() {
Console.WriteLine ("Yo. You called me.");
}
}
[Command("time", "t")]
[Usage("Check the system time.")]
public class TimeCommand
{
[Command("now")]
public void Now() {
Console.WriteLine ("{0}", DateTime.Now);
}
}
}
| mit | C# |
709304d4b01d62bf3692b9762ce4e8b876017219 | Add instructions | mdileep/NFugue | src/NFugue/Staccato/IInstruction.cs | src/NFugue/Staccato/IInstruction.cs | using NFugue.Patterns;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NFugue.Staccato
{
public interface IInstruction
{
string OnIstructionReceived(IEnumerable<string> instructions);
}
public class Choice : IInstruction
{
public List<string> Choices { get; } = new List<string>();
public Choice(params string[] choices)
{
Choices.AddRange(choices);
}
public Choice(params int[] choices)
{
Choices.AddRange(choices.Select(c => c.ToString()));
}
public Choice(params IPatternProducer[] choices)
{
Choices.AddRange(choices.Select(c => c.GetPattern().ToString()));
}
public string OnIstructionReceived(IEnumerable<string> instructions)
{
int choice = int.Parse(instructions.Last());
return Choices[choice];
}
}
public class Switch : IInstruction
{
public const char ReplaceChar = '$';
private readonly string instruction;
private readonly string offValue;
private readonly string onValue;
public Switch(string instruction, string offValue, string onValue)
{
this.instruction = instruction;
this.offValue = offValue;
this.onValue = onValue;
}
public Switch(string instruction, int offValue, int onValue)
: this(instruction, offValue.ToString(), onValue.ToString())
{
}
public Switch(string instruction, Pattern offValue, Pattern onValue)
: this(instruction, offValue.ToString(), onValue.ToString())
{
}
public string OnIstructionReceived(IEnumerable<string> instructions)
{
var sb = new StringBuilder();
int posDollar = instruction.IndexOf(ReplaceChar);
sb.Append(instruction.Substring(0, posDollar));
string lastInstruction = instructions.Last();
if (lastInstruction.Equals("ON", StringComparison.OrdinalIgnoreCase))
{
sb.Append(onValue);
}
else if (lastInstruction.Equals("OFF", StringComparison.OrdinalIgnoreCase))
{
sb.Append(offValue);
}
else
{
sb.Append(ReplaceChar);
}
sb.Append(instruction.Substring(posDollar + 1, instruction.Length - posDollar - 1));
return sb.ToString();
}
}
public class LastIsValue : IInstruction
{
public const char ReplaceChar = '$';
private readonly string instruction;
public LastIsValue(string instruction)
{
this.instruction = instruction;
}
public string OnIstructionReceived(IEnumerable<string> instructions)
{
var sb = new StringBuilder();
int posDollar = instruction.IndexOf(ReplaceChar);
sb.Append(instruction.Substring(0, posDollar));
sb.Append(instructions.Last());
sb.Append(instruction.Substring(posDollar + 1, instruction.Length - posDollar - 1);
return sb.ToString();
}
}
public class LastIsValueToSplit : IInstruction
{
private string instruction;
private readonly Func<string, IDictionary<string, string>> splitter;
public LastIsValueToSplit(string instruction, Func<string, IDictionary<string, string>> splitter)
{
this.instruction = instruction;
this.splitter = splitter;
}
public string OnIstructionReceived(IEnumerable<string> instructions)
{
IDictionary<string, string> map = splitter(instructions.Last());
foreach (string key in map.Keys)
{
instruction = instruction.Replace(key, map[key]);
}
return instruction;
}
}
} | namespace NFugue.Staccato
{
public interface IInstruction
{
string OnIstructionReceived(string[] instructions);
}
} | apache-2.0 | C# |
bf8dce0ee32b71d73d9de7d2814ddadd43a7c52e | Fix return statement | DaveSenn/Extend | PortableExtensions/System.DateTime/DateTime.LastDayOfWeek.cs | PortableExtensions/System.DateTime/DateTime.LastDayOfWeek.cs | #region Usings
using System;
#endregion
namespace PortableExtensions
{
/// <summary>
/// Class containing some extension methods for <see cref="DateTime" />.
/// </summary>
public static partial class DateTimeEx
{
/// <summary>
/// Returns the last day of the given week.
/// </summary>
/// <param name="week">The week to get the last day of.</param>
/// <returns>Returns the last day of the given week.</returns>
public static DateTime LastDayOfWeek ( this DateTime week )
{
return week.DayOfWeek == DayOfWeek.Sunday
? new DateTime( week.Year, week.Month, week.Day )
: new DateTime( week.Year, week.Month, week.Day ).AddDays( 7 - (Int32) week.DayOfWeek );
}
}
} | #region Usings
using System;
#endregion
namespace PortableExtensions
{
/// <summary>
/// Class containing some extension methods for <see cref="DateTime" />.
/// </summary>
public static partial class DateTimeEx
{
/// <summary>
/// Returns the last day of the given week.
/// </summary>
/// <param name="week">The week to get the last day of.</param>
/// <returns>Returns the last day of the given week.</returns>
public static DateTime LastDayOfWeek ( this DateTime week )
{
if ( week.DayOfWeek == DayOfWeek.Sunday )
return new DateTime( week.Year, week.Month, week.Day );
return new DateTime( week.Year, week.Month, week.Day ).AddDays( 7 - (Int32) week.DayOfWeek );
}
}
} | mit | C# |
4f1647e0a16edad1283e2685df71832e895b3033 | change keyHeader to name (#10877) | hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,markcowl/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,stankovski/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,hyonholee/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,stankovski/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net | sdk/core/Azure.Core/src/Shared/AzureKeyCredentialPolicy.cs | sdk/core/Azure.Core/src/Shared/AzureKeyCredentialPolicy.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core.Pipeline;
namespace Azure.Core
{
internal class AzureKeyCredentialPolicy : HttpPipelineSynchronousPolicy
{
private readonly string _name;
private readonly AzureKeyCredential _credential;
/// <summary>
/// Initializes a new instance of the <see cref="AzureKeyCredentialPolicy"/> class.
/// </summary>
/// <param name="credential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param>
/// <param name="name">The name of the key header used for the credential.</param>
public AzureKeyCredentialPolicy(AzureKeyCredential credential, string name)
{
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNullOrEmpty(name, nameof(name));
_credential = credential;
_name = name;
}
/// <inheritdoc/>
public override void OnSendingRequest(HttpMessage message)
{
base.OnSendingRequest(message);
message.Request.Headers.SetValue(_name, _credential.Key);
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Azure.Core.Pipeline;
namespace Azure.Core
{
internal class AzureKeyCredentialPolicy : HttpPipelineSynchronousPolicy
{
private readonly string _keyHeader;
private readonly AzureKeyCredential _credential;
/// <summary>
/// Initializes a new instance of the <see cref="AzureKeyCredentialPolicy"/> class.
/// </summary>
/// <param name="credential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param>
/// <param name="keyHeader">The name of the API key header used for signing requests.</param>
public AzureKeyCredentialPolicy(AzureKeyCredential credential, string keyHeader)
{
Argument.AssertNotNull(credential, nameof(credential));
Argument.AssertNotNullOrEmpty(keyHeader, nameof(keyHeader));
_credential = credential;
_keyHeader = keyHeader;
}
/// <inheritdoc/>
public override void OnSendingRequest(HttpMessage message)
{
base.OnSendingRequest(message);
message.Request.Headers.SetValue(_keyHeader, _credential.Key);
}
}
}
| mit | C# |
1a25c742e1ea8b22804d0ccbe3bf1ce4d8d55747 | test 3re | emksaz/testgit2,emksaz/testgit2,emksaz/testgit2 | testgit23/testgit23/Views/Home/Index.cshtml | testgit23/testgit23/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="jumbotron">
<h1>ASP.NET -david.z 1655 34234 test2-brah1 q</h1>
<h1>ASP.NET -david.z 1655 34234 test2-brah1</h1>
<h1>ASP.NET -david.z 1655 34234 test3-brah2 3re</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="jumbotron">
<h1>ASP.NET -david.z 1655 34234 test2-brah1 q</h1>
<h1>ASP.NET -david.z 1655 34234 test2-brah1</h1>
<h1>ASP.NET -david.z 1655 34234 test3-brah2</h1>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | apache-2.0 | C# |
5327b6b781f4be1e60ac6451806db0b61185e208 | Use KnockoutBindingGroup.AddValue in HierarchyRepeaterLevel | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/Framework/Framework/Controls/HierarchyRepeaterLevel.cs | src/Framework/Framework/Controls/HierarchyRepeaterLevel.cs | using System;
using System.Collections.Generic;
using System.Text;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Hosting;
using DotVVM.Framework.Utils;
namespace DotVVM.Framework.Controls
{
/// <summary>
/// A container for a level of the <see cref="HierarchyRepeater"/>.
/// </summary>
public class HierarchyRepeaterLevel : DotvvmControl
{
public string? ItemTemplateId { get; set; }
public string? ForeachExpression { get; set; }
public bool IsRoot { get; set; } = false;
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context)
{
if (ForeachExpression is null)
{
base.RenderControl(writer, context);
return;
}
if (!RenderOnServer)
{
var koGroup = new KnockoutBindingGroup {
{ "foreach", ForeachExpression }
};
koGroup.AddValue("name", ItemTemplateId.NotNull());
koGroup.AddValue("hierarchyRole", IsRoot ? "Root" : "Child");
writer.WriteKnockoutDataBindComment("template", koGroup.ToString());
}
else
{
writer.WriteKnockoutDataBindComment("dotvvm-SSR-foreach", new KnockoutBindingGroup {
{ "data", ForeachExpression}
}.ToString());
}
base.RenderControl(writer, context);
writer.WriteKnockoutDataBindEndComment();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using DotVVM.Framework.Binding;
using DotVVM.Framework.Binding.Expressions;
using DotVVM.Framework.Hosting;
namespace DotVVM.Framework.Controls
{
/// <summary>
/// A container for a level of the <see cref="HierarchyRepeater"/>.
/// </summary>
public class HierarchyRepeaterLevel : DotvvmControl
{
public string? ItemTemplateId { get; set; }
public string? ForeachExpression { get; set; }
public bool IsRoot { get; set; } = false;
protected override void RenderControl(IHtmlWriter writer, IDotvvmRequestContext context)
{
if (ForeachExpression is null)
{
base.RenderControl(writer, context);
return;
}
if (!RenderOnServer)
{
writer.WriteKnockoutDataBindComment("template", new KnockoutBindingGroup {
{ "foreach", ForeachExpression },
{ "name", ItemTemplateId ?? string.Empty },
{ "hierarchyRole", IsRoot ? "Root" : "Child" }
}.ToString());
}
else
{
writer.WriteKnockoutDataBindComment("dotvvm-SSR-foreach", new KnockoutBindingGroup {
{ "data", ForeachExpression}
}.ToString());
}
base.RenderControl(writer, context);
writer.WriteKnockoutDataBindEndComment();
}
}
}
| apache-2.0 | C# |
4087dbc23ce30f252900efb40c976460a9bc957f | Update version to 1.3.0 | TheOtherTimDuncan/TOTD-Mailer | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| using System.Reflection;
// 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: AssemblyConfiguration("")]
[assembly: AssemblyCompany("The Other Tim Duncan")]
[assembly: AssemblyProduct("TOTD Mailer")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
// 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.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| mit | C# |
b2be35afd09ca57050b27cb523935dff878394dc | Correct function instance output blob. | brendankowitz/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,Azure/azure-webjobs-sdk,Azure/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,brendankowitz/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,oliver-feng/azure-webjobs-sdk,oaastest/azure-webjobs-sdk,gibwar/azure-webjobs-sdk,shrishrirang/azure-webjobs-sdk,vasanthangel4/azure-webjobs-sdk,oaastest/azure-webjobs-sdk | src/Microsoft.Azure.Jobs.Host/Loggers/FunctionOutputLog.cs | src/Microsoft.Azure.Jobs.Host/Loggers/FunctionOutputLog.cs | using System;
using System.IO;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.Azure.Jobs
{
// Wrap facilities for logging a function's output.
// This means capturing console out, redirecting to a textwriter that is available at a blob.
// Handle incremental updates to get real-time updates for long running functions.
internal class FunctionOutputLog
{
static Action empty = () => { };
public FunctionOutputLog()
{
this.Output = Console.Out;
this.CloseOutput = empty;
}
public TextWriter Output { get; set; }
public Action CloseOutput { get; set; }
public string Uri { get; set; } // Uri to refer to output
// Separate channel for logging structured (and updating) information about parameters
public CloudBlobDescriptor ParameterLogBlob { get; set; }
// Get a default instance of
public static FunctionOutputLog GetLogStream(FunctionInvokeRequest f, string accountConnectionString, string containerName)
{
string name = f.Id.ToString("N") + ".txt";
var c = BlobClient.GetContainer(accountConnectionString, containerName);
if (c.CreateIfNotExists())
{
c.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Off });
}
CloudBlockBlob blob = c.GetBlockBlobReference(name);
var period = TimeSpan.FromMinutes(1); // frequency to refresh
var x = new BlobIncrementalTextWriter(blob, period);
TextWriter tw = x.Writer;
return new FunctionOutputLog
{
CloseOutput = () =>
{
x.Close();
},
Uri = blob.Uri.ToString(),
Output = tw,
ParameterLogBlob = new CloudBlobDescriptor
{
AccountConnectionString = accountConnectionString,
ContainerName = containerName,
BlobName = f.ToString() + ".params.txt"
}
};
}
}
}
| using System;
using System.IO;
using Microsoft.WindowsAzure.Storage.Blob;
namespace Microsoft.Azure.Jobs
{
// Wrap facilities for logging a function's output.
// This means capturing console out, redirecting to a textwriter that is available at a blob.
// Handle incremental updates to get real-time updates for long running functions.
internal class FunctionOutputLog
{
static Action empty = () => { };
public FunctionOutputLog()
{
this.Output = Console.Out;
this.CloseOutput = empty;
}
public TextWriter Output { get; set; }
public Action CloseOutput { get; set; }
public string Uri { get; set; } // Uri to refer to output
// Separate channel for logging structured (and updating) information about parameters
public CloudBlobDescriptor ParameterLogBlob { get; set; }
// Get a default instance of
public static FunctionOutputLog GetLogStream(FunctionInvokeRequest f, string accountConnectionString, string containerName)
{
string name = f.ToString() + ".txt";
var c = BlobClient.GetContainer(accountConnectionString, containerName);
if (c.CreateIfNotExists())
{
c.SetPermissions(new BlobContainerPermissions() { PublicAccess = BlobContainerPublicAccessType.Off });
}
CloudBlockBlob blob = c.GetBlockBlobReference(name);
var period = TimeSpan.FromMinutes(1); // frequency to refresh
var x = new BlobIncrementalTextWriter(blob, period);
TextWriter tw = x.Writer;
return new FunctionOutputLog
{
CloseOutput = () =>
{
x.Close();
},
Uri = blob.Uri.ToString(),
Output = tw,
ParameterLogBlob = new CloudBlobDescriptor
{
AccountConnectionString = accountConnectionString,
ContainerName = containerName,
BlobName = f.ToString() + ".params.txt"
}
};
}
}
}
| mit | C# |
15b54533d12eba28b275f306b2c2c80c3276ebc9 | Convert comma to underline in enum names, closes https://github.com/RSuter/NSwag/issues/2009 | RSuter/NJsonSchema,NJsonSchema/NJsonSchema | src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs | src/NJsonSchema.CodeGeneration/DefaultEnumNameGenerator.cs | //-----------------------------------------------------------------------
// <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NJsonSchema.CodeGeneration
{
/// <summary>The default enumeration name generator.</summary>
public class DefaultEnumNameGenerator : IEnumNameGenerator
{
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary>
/// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param>
/// <param name="name">The name/key.</param>
/// <param name="value">The value.</param>
/// <param name="schema">The schema.</param>
/// <returns>The enumeration name.</returns>
public string Generate(int index, string name, object value, JsonSchema4 schema)
{
if (name.StartsWith("_-"))
{
name = "__" + name.Substring(2);
}
return ConversionUtilities.ConvertToUpperCamelCase(name
.Replace(":", "-").Replace(@"""", @""), true)
.Replace(".", "_")
.Replace(",", "_")
.Replace("#", "_")
.Replace("-", "_")
.Replace("\\", "_");
}
}
}
| //-----------------------------------------------------------------------
// <copyright file="DefaultEnumNameGenerator.cs" company="NJsonSchema">
// Copyright (c) Rico Suter. All rights reserved.
// </copyright>
// <license>https://github.com/rsuter/NJsonSchema/blob/master/LICENSE.md</license>
// <author>Rico Suter, mail@rsuter.com</author>
//-----------------------------------------------------------------------
namespace NJsonSchema.CodeGeneration
{
/// <summary>The default enumeration name generator.</summary>
public class DefaultEnumNameGenerator : IEnumNameGenerator
{
/// <summary>Generates the enumeration name/key of the given enumeration entry.</summary>
/// <param name="index">The index of the enumeration value (check <see cref="JsonSchema4.Enumeration" /> and <see cref="JsonSchema4.EnumerationNames" />).</param>
/// <param name="name">The name/key.</param>
/// <param name="value">The value.</param>
/// <param name="schema">The schema.</param>
/// <returns>The enumeration name.</returns>
public string Generate(int index, string name, object value, JsonSchema4 schema)
{
if (name.StartsWith("_-"))
{
name = "__" + name.Substring(2);
}
return ConversionUtilities.ConvertToUpperCamelCase(name
.Replace(":", "-").Replace(@"""", @""), true)
.Replace(".", "_")
.Replace("#", "_")
.Replace("-", "_")
.Replace("\\", "_");
}
}
}
| mit | C# |
c9b58dcf65e781e1f0bb4e1cd497aec315ee296f | Add benchmarks for Instant/unix time conversions (#573) | jskeet/nodatime,jskeet/nodatime,malcolmr/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,nodatime/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,nodatime/nodatime,malcolmr/nodatime | src/NodaTime.Benchmarks/NodaTimeTests/InstantBenchmarks.cs | src/NodaTime.Benchmarks/NodaTimeTests/InstantBenchmarks.cs | // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Globalization;
using BenchmarkDotNet.Attributes;
namespace NodaTime.Benchmarks.NodaTimeTests
{
public class InstantBenchmarks
{
private static readonly Instant Sample = Instant.FromUtc(2011, 8, 24, 12, 29, 30);
private static readonly long SampleUnixTimeSeconds = Sample.ToUnixTimeSeconds();
private static readonly long SampleUnixTimeMilliseconds = Sample.ToUnixTimeMilliseconds();
private static readonly long SampleUnixTimeTicks = Sample.ToUnixTimeTicks();
private static readonly Offset SmallOffset = Offset.FromHours(1);
private static readonly Offset LargePositiveOffset = Offset.FromHours(12);
private static readonly Offset LargeNegativeOffset = Offset.FromHours(-13);
private static readonly DateTimeZone London = DateTimeZoneProviders.Tzdb["Europe/London"];
[Benchmark]
public string ToStringIso() => Sample.ToString("g", CultureInfo.InvariantCulture);
[Benchmark]
public Instant PlusDuration() => Sample.Plus(Duration.Epsilon);
[Benchmark]
public ZonedDateTime InUtc() => Sample.InUtc();
[Benchmark]
public ZonedDateTime InZoneLondon() => Sample.InZone(London);
#if !V1
[Benchmark]
public Instant FromUnixTimeSeconds() => Instant.FromUnixTimeSeconds(SampleUnixTimeSeconds);
[Benchmark]
public Instant FromUnixTimeMilliseconds() => Instant.FromUnixTimeMilliseconds(SampleUnixTimeMilliseconds);
[Benchmark]
public Instant FromUnixTimeTicks() => Instant.FromUnixTimeTicks(SampleUnixTimeTicks);
[Benchmark]
public long ToUnixTimeSeconds() => Sample.ToUnixTimeSeconds();
[Benchmark]
public long ToUnixTimeMilliseconds() => Sample.ToUnixTimeMilliseconds();
[Benchmark]
public long ToUnixTimeTicks() => Sample.ToUnixTimeTicks();
#endif
#if !V1_0 && !V1_1
[Benchmark]
public OffsetDateTime WithOffset_SameUtcDay() => Sample.WithOffset(SmallOffset);
[Benchmark]
public OffsetDateTime WithOffset_NextUtcDay() => Sample.WithOffset(LargePositiveOffset);
[Benchmark]
public OffsetDateTime WithOffset_PreviousUtcDay() => Sample.WithOffset(LargeNegativeOffset);
#endif
}
}
| // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Globalization;
using BenchmarkDotNet.Attributes;
namespace NodaTime.Benchmarks.NodaTimeTests
{
public class InstantBenchmarks
{
private static readonly Instant Sample = Instant.FromUtc(2011, 8, 24, 12, 29, 30);
private static readonly Offset SmallOffset = Offset.FromHours(1);
private static readonly Offset LargePositiveOffset = Offset.FromHours(12);
private static readonly Offset LargeNegativeOffset = Offset.FromHours(-13);
private static readonly DateTimeZone London = DateTimeZoneProviders.Tzdb["Europe/London"];
[Benchmark]
public string ToStringIso() => Sample.ToString("g", CultureInfo.InvariantCulture);
[Benchmark]
public Instant PlusDuration() => Sample.Plus(Duration.Epsilon);
[Benchmark]
public ZonedDateTime InUtc() => Sample.InUtc();
[Benchmark]
public ZonedDateTime InZoneLondon() => Sample.InZone(London);
#if !V1_0 && !V1_1
[Benchmark]
public OffsetDateTime WithOffset_SameUtcDay() => Sample.WithOffset(SmallOffset);
[Benchmark]
public OffsetDateTime WithOffset_NextUtcDay() => Sample.WithOffset(LargePositiveOffset);
[Benchmark]
public OffsetDateTime WithOffset_PreviousUtcDay() => Sample.WithOffset(LargeNegativeOffset);
#endif
}
}
| apache-2.0 | C# |
f941d3938cc957cf1f5c5993b5f93c201a3696cb | Add appropriate tag styling | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Support.Web/Views/Account/SubHeader.cshtml | src/SFA.DAS.EAS.Support.Web/Views/Account/SubHeader.cshtml | @model SFA.DAS.EAS.Support.Core.Models.Account
@{
Layout = null;
}
<div class="grid-row">
<div class="column-full">
<h5 class="heading-small">
<a href="/" class="govuk-back-link">
Home
</a>
</h5>
<h1 class="heading-large">
@(Model?.DasAccountName)
@if (!string.IsNullOrEmpty(Model?.PublicHashedAccountId))
{
<span class="heading-secondary"> Account ID @(Model?.PublicHashedAccountId), created @Model.DateRegistered.ToString("dd/MM/yyyy")</span>
}
<span class="heading-secondary">
Levy Status <strong class="govuk-tag govuk-tag--blue">
@Model.ApprenticeshipEmployerType
</strong>
</span>
</h1>
</div>
</div>
| @model SFA.DAS.EAS.Support.Core.Models.Account
@{
Layout = null;
}
<div class="grid-row">
<div class="column-full">
<h5 class="heading-small">
<a href="/" class="govuk-back-link">
Home
</a>
</h5>
<h1 class="heading-large">
@(Model?.DasAccountName)
@if (!string.IsNullOrEmpty(Model?.PublicHashedAccountId))
{
<span class="heading-secondary"> Account ID @(Model?.PublicHashedAccountId), created @Model.DateRegistered.ToString("dd/MM/yyyy")</span>
}
<span class="heading-secondary"> Levy Status @Model.ApprenticeshipEmployerType</span>
</h1>
</div>
</div>
| mit | C# |
be6499ba67d9d5e3e18638876665e32fe803e66a | Add test coverage for generic method definition handle roundtripping (#17754) | seanshpark/corefx,ViktorHofer/corefx,the-dwyer/corefx,tijoytom/corefx,cydhaselton/corefx,ericstj/corefx,gkhanna79/corefx,mmitche/corefx,fgreinacher/corefx,richlander/corefx,Ermiar/corefx,Jiayili1/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,richlander/corefx,MaggieTsang/corefx,tijoytom/corefx,BrennanConroy/corefx,rubo/corefx,rjxby/corefx,zhenlan/corefx,the-dwyer/corefx,parjong/corefx,shimingsg/corefx,rahku/corefx,twsouthwick/corefx,the-dwyer/corefx,MaggieTsang/corefx,MaggieTsang/corefx,nbarbettini/corefx,alexperovich/corefx,billwert/corefx,seanshpark/corefx,twsouthwick/corefx,elijah6/corefx,gkhanna79/corefx,Ermiar/corefx,rjxby/corefx,ravimeda/corefx,stone-li/corefx,twsouthwick/corefx,the-dwyer/corefx,axelheer/corefx,nbarbettini/corefx,elijah6/corefx,rjxby/corefx,ptoonen/corefx,alexperovich/corefx,stone-li/corefx,Petermarcu/corefx,the-dwyer/corefx,twsouthwick/corefx,Jiayili1/corefx,shimingsg/corefx,stone-li/corefx,yizhang82/corefx,rjxby/corefx,billwert/corefx,parjong/corefx,zhenlan/corefx,seanshpark/corefx,cydhaselton/corefx,tijoytom/corefx,weltkante/corefx,jlin177/corefx,cydhaselton/corefx,weltkante/corefx,wtgodbe/corefx,nchikanov/corefx,weltkante/corefx,wtgodbe/corefx,ravimeda/corefx,stephenmichaelf/corefx,wtgodbe/corefx,ptoonen/corefx,billwert/corefx,Jiayili1/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,nbarbettini/corefx,billwert/corefx,Petermarcu/corefx,stone-li/corefx,alexperovich/corefx,krytarowski/corefx,weltkante/corefx,axelheer/corefx,dhoehna/corefx,krytarowski/corefx,weltkante/corefx,mmitche/corefx,MaggieTsang/corefx,elijah6/corefx,axelheer/corefx,nchikanov/corefx,Jiayili1/corefx,dhoehna/corefx,mmitche/corefx,krytarowski/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,BrennanConroy/corefx,DnlHarvey/corefx,nchikanov/corefx,jlin177/corefx,krk/corefx,wtgodbe/corefx,nchikanov/corefx,ptoonen/corefx,elijah6/corefx,gkhanna79/corefx,mmitche/corefx,stephenmichaelf/corefx,seanshpark/corefx,richlander/corefx,ravimeda/corefx,yizhang82/corefx,Petermarcu/corefx,rjxby/corefx,nbarbettini/corefx,yizhang82/corefx,billwert/corefx,seanshpark/corefx,richlander/corefx,mmitche/corefx,elijah6/corefx,zhenlan/corefx,MaggieTsang/corefx,dotnet-bot/corefx,jlin177/corefx,ravimeda/corefx,mazong1123/corefx,zhenlan/corefx,DnlHarvey/corefx,Petermarcu/corefx,weltkante/corefx,jlin177/corefx,parjong/corefx,ViktorHofer/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,YoupHulsebos/corefx,alexperovich/corefx,rubo/corefx,ericstj/corefx,rubo/corefx,nbarbettini/corefx,DnlHarvey/corefx,parjong/corefx,axelheer/corefx,ericstj/corefx,dotnet-bot/corefx,shimingsg/corefx,the-dwyer/corefx,Ermiar/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,MaggieTsang/corefx,nbarbettini/corefx,krk/corefx,Jiayili1/corefx,rahku/corefx,ptoonen/corefx,YoupHulsebos/corefx,Petermarcu/corefx,stephenmichaelf/corefx,fgreinacher/corefx,weltkante/corefx,ptoonen/corefx,YoupHulsebos/corefx,cydhaselton/corefx,seanshpark/corefx,tijoytom/corefx,yizhang82/corefx,krk/corefx,Petermarcu/corefx,alexperovich/corefx,rahku/corefx,shimingsg/corefx,elijah6/corefx,rubo/corefx,twsouthwick/corefx,rahku/corefx,ericstj/corefx,the-dwyer/corefx,twsouthwick/corefx,ericstj/corefx,dotnet-bot/corefx,ViktorHofer/corefx,twsouthwick/corefx,ericstj/corefx,seanshpark/corefx,mmitche/corefx,krytarowski/corefx,rubo/corefx,ravimeda/corefx,stone-li/corefx,krytarowski/corefx,dotnet-bot/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,yizhang82/corefx,stephenmichaelf/corefx,YoupHulsebos/corefx,richlander/corefx,cydhaselton/corefx,parjong/corefx,gkhanna79/corefx,gkhanna79/corefx,Ermiar/corefx,tijoytom/corefx,krk/corefx,JosephTremoulet/corefx,cydhaselton/corefx,stephenmichaelf/corefx,MaggieTsang/corefx,mazong1123/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,yizhang82/corefx,ViktorHofer/corefx,parjong/corefx,yizhang82/corefx,alexperovich/corefx,dhoehna/corefx,jlin177/corefx,Ermiar/corefx,nchikanov/corefx,mazong1123/corefx,zhenlan/corefx,ptoonen/corefx,jlin177/corefx,Jiayili1/corefx,shimingsg/corefx,elijah6/corefx,parjong/corefx,ViktorHofer/corefx,rahku/corefx,mazong1123/corefx,wtgodbe/corefx,Jiayili1/corefx,fgreinacher/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,axelheer/corefx,zhenlan/corefx,dhoehna/corefx,shimingsg/corefx,cydhaselton/corefx,krk/corefx,richlander/corefx,rjxby/corefx,nchikanov/corefx,Petermarcu/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,wtgodbe/corefx,JosephTremoulet/corefx,fgreinacher/corefx,DnlHarvey/corefx,richlander/corefx,wtgodbe/corefx,billwert/corefx,tijoytom/corefx,nbarbettini/corefx,Ermiar/corefx,DnlHarvey/corefx,rahku/corefx,stone-li/corefx,zhenlan/corefx,axelheer/corefx,mazong1123/corefx,mazong1123/corefx,dhoehna/corefx,krk/corefx,stone-li/corefx,billwert/corefx,krk/corefx,mazong1123/corefx,nchikanov/corefx,gkhanna79/corefx,ravimeda/corefx,Ermiar/corefx,dhoehna/corefx,gkhanna79/corefx,tijoytom/corefx,krytarowski/corefx,krytarowski/corefx,rahku/corefx,ravimeda/corefx,jlin177/corefx,alexperovich/corefx,dhoehna/corefx,YoupHulsebos/corefx,rjxby/corefx,shimingsg/corefx,DnlHarvey/corefx | src/System.Runtime/tests/System/HandleTests.cs | src/System.Runtime/tests/System/HandleTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Reflection;
using Xunit;
public static class HandleTests
{
[Fact]
public static void RuntimeFieldHandleTest()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
RuntimeFieldHandle h = f.FieldHandle;
Assert.True(h.Value != null);
}
[Fact]
public static void RuntimeMethodHandleTest()
{
MethodInfo minfo = typeof( Co6006LateBoundDelegate).GetMethod( "Method1" );
RuntimeMethodHandle rmh = minfo.MethodHandle;
Assert.True(rmh.Value != null);
Assert.True(rmh.GetFunctionPointer() != null);
Object [] args = new Object[] { null, rmh.GetFunctionPointer() };
MyDelegate dg = (MyDelegate)Activator.CreateInstance( typeof( MyDelegate ), args );
dg();
Assert.True(Co6006LateBoundDelegate.iInvokeCount == 1);
}
[Fact]
public static void GenericMethodRuntimeMethodHandleTest()
{
// Make sure uninstantiated generic method has a valid handle
MethodInfo mi1 = typeof(Base).GetMethod("GenericMethod");
MethodInfo mi2 = (MethodInfo)MethodBase.GetMethodFromHandle(mi1.MethodHandle);
Assert.Equal(mi1, mi2);
}
[Fact]
public static void RuntimeTypeHandleTest()
{
RuntimeTypeHandle r1 = typeof(int).TypeHandle;
RuntimeTypeHandle r2 = typeof(uint).TypeHandle;
Assert.NotEqual(r1, r2);
}
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
public static void GenericMethod<T>() { }
}
private class Derived : Base
{
}
delegate void MyDelegate();
public class Co6006LateBoundDelegate
{
public static int iInvokeCount = 0;
public static void Method1()
{
iInvokeCount++;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime;
using System.Reflection;
using Xunit;
public static class HandleTests
{
public static void RuntimeFieldHandleTest()
{
Type t = typeof(Derived);
FieldInfo f = t.GetField(nameof(Base.MyField));
RuntimeFieldHandle h = f.FieldHandle;
Assert.True(h.Value != null);
}
public static void RuntimeMethodHandleTest()
{
MethodInfo minfo = typeof( Co6006LateBoundDelegate).GetMethod( "Method1" );
RuntimeMethodHandle rmh = minfo.MethodHandle;
Assert.True(rmh.Value != null);
Assert.True(rmh.GetFunctionPointer() != null);
Object [] args = new Object[] { null, rmh.GetFunctionPointer() };
MyDelegate dg = (MyDelegate)Activator.CreateInstance( typeof( MyDelegate ), args );
dg();
Assert.True(Co6006LateBoundDelegate.iInvokeCount == 1);
}
public static void RuntimeTypeHandleTest()
{
RuntimeTypeHandle r1 = typeof(int).TypeHandle;
Assert.True(r1 != null);
}
private class Base
{
public event Action MyEvent { add { } remove { } }
#pragma warning disable 0649
public int MyField;
#pragma warning restore 0649
public int MyProperty { get; set; }
public int MyProperty1 { get; private set; }
public int MyProperty2 { private get; set; }
}
private class Derived : Base
{
}
delegate void MyDelegate();
public class Co6006LateBoundDelegate
{
public static int iInvokeCount = 0;
public static void Method1()
{
iInvokeCount++;
}
}
}
| mit | C# |
617596cba468e035652f979961c92dec10f0bcf8 | Fix some newline issues | umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,madsoulswe/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,lars-erik/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,WebCentrum/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,tompipe/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS | src/Umbraco.Core/Strings/Css/StylesheetRule.cs | src/Umbraco.Core/Strings/Css/StylesheetRule.cs | using System;
using System.Linq;
using System.Text;
namespace Umbraco.Core.Strings.Css
{
internal class StylesheetRule
{
public string Name { get; set; }
public string Selector { get; set; }
public string Styles { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("/**");
sb.AppendFormat("umb_name:{0}", Name);
sb.Append("*/");
sb.Append(Environment.NewLine);
sb.Append(Selector);
sb.Append(" {");
sb.Append(Environment.NewLine);
// append nicely formatted style rules
// - using tabs because the back office code editor uses tabs
if (Styles.IsNullOrWhiteSpace() == false)
{
// since we already have a string builder in play here, we'll append to it the "hard" way
// instead of using string interpolation (for increased performance)
foreach (var style in Styles.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
sb.Append("\t").Append(style.StripNewLines().Trim()).Append(";").Append(Environment.NewLine);
}
}
sb.Append("}");
return sb.ToString();
}
}
}
| using System;
using System.Linq;
using System.Text;
namespace Umbraco.Core.Strings.Css
{
internal class StylesheetRule
{
public string Name { get; set; }
public string Selector { get; set; }
public string Styles { get; set; }
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("/**");
sb.AppendFormat("umb_name:{0}", Name);
sb.Append("*/");
sb.Append(Environment.NewLine);
sb.Append(Selector);
sb.Append(" {");
sb.Append(Environment.NewLine);
// append nicely formatted style rules
// - using tabs because the back office code editor uses tabs
if (Styles.IsNullOrWhiteSpace() == false)
{
// since we already have a string builder in play here, we'll append to it the "hard" way
// instead of using string interpolation (for increased performance)
foreach (var style in Styles.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
{
sb.Append("\t").Append(style).Append(";").Append(Environment.NewLine);
}
}
sb.Append("}");
return sb.ToString();
}
}
}
| mit | C# |
75fb45cbd6fee6aeae7092000e1360becc93a014 | Remove unnecessary using directive | ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate | src/Abp/Reflection/ProxyHelper.cs | src/Abp/Reflection/ProxyHelper.cs | using Castle.DynamicProxy;
using System;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
return ProxyUtil.GetUnproxiedInstance(obj);
}
/// <summary>
/// Returns the type of the dynamic proxy target object if this is a proxied object, otherwise returns the type of the given object.
/// </summary>
public static Type GetUnproxiedType(object obj)
{
return ProxyUtil.GetUnproxiedType(obj);
}
}
}
| using Abp.Extensions;
using Castle.DynamicProxy;
using System;
namespace Abp.Reflection
{
public static class ProxyHelper
{
/// <summary>
/// Returns dynamic proxy target object if this is a proxied object, otherwise returns the given object.
/// </summary>
public static object UnProxy(object obj)
{
return ProxyUtil.GetUnproxiedInstance(obj);
}
/// <summary>
/// Returns the type of the dynamic proxy target object if this is a proxied object, otherwise returns the type of the given object.
/// </summary>
public static Type GetUnproxiedType(object obj)
{
return ProxyUtil.GetUnproxiedType(obj);
}
}
}
| mit | C# |
51ffe29f5c17e651b548403953b4d248f8705eed | Make changes per review | mdavid/nuget,mdavid/nuget | src/VsExtension/FontAndColorsRegistrationAttribute.cs | src/VsExtension/FontAndColorsRegistrationAttribute.cs | using Microsoft.VisualStudio.Shell;
namespace NuGet.Tools {
/// <summary>
/// This class is used to create a registry key for the FontAndColors category
/// </summary>
public class FontAndColorsRegistrationAttribute : RegistrationAttribute {
// this GUID is used by all VSPackages that use the default font and color configurations.
// http://msdn.microsoft.com/en-us/library/bb165737.aspx
private const string PackageGuid = "{F5E7E71D-1401-11D1-883B-0000F87579D2}";
// this ID is set in VSPackage.resx
private const int CategoryNameResourceID = 200;
public string CategoryGuid { get; private set; }
public string ToolWindowPackageGuid { get; private set; }
public string CategoryKey { get; private set; }
public FontAndColorsRegistrationAttribute(string categoryKeyName, string categoryGuid, string toolWindowPackageGuid) {
CategoryGuid = categoryGuid;
ToolWindowPackageGuid = toolWindowPackageGuid;
CategoryKey = "FontAndColors\\" + categoryKeyName;
}
public override void Register(RegistrationContext context) {
using (var key = context.CreateKey(CategoryKey)) {
key.SetValue("Category", CategoryGuid);
key.SetValue("Package", PackageGuid);
key.SetValue("NameID", CategoryNameResourceID);
key.SetValue("ToolWindowPackage", ToolWindowPackageGuid);
// IMPORTANT: without calling Close() the values won't be persisted to registry.
key.Close();
}
}
public override void Unregister(RegistrationContext context) {
context.RemoveKey(CategoryKey);
}
}
} | using Microsoft.VisualStudio.Shell;
namespace NuGet.Tools {
/// <summary>
/// This class is used to create a registry key for the FontAndColors category
/// </summary>
public class FontAndColorsRegistrationAttribute : RegistrationAttribute {
// this GUID is used by all VSPackages that use the default font and color configurations.
// http://msdn.microsoft.com/en-us/library/bb165737.aspx
private const string PackageGuid = "{F5E7E71D-1401-11D1-883B-0000F87579D2}";
// this ID is set in VSPackage.resx
private const int CategoryNameResourceID = 200;
public string CategoryGuid { get; private set; }
public string ToolWindowPackageGuid { get; private set; }
public string CategoryKey { get; private set; }
public FontAndColorsRegistrationAttribute(string categoryKeyName, string categoryGuid, string toolWindowPackageGuid) {
CategoryGuid = categoryGuid;
ToolWindowPackageGuid = toolWindowPackageGuid;
CategoryKey = "FontAndColors\\" + categoryKeyName;
}
public override void Register(RegistrationContext context) {
var key = context.CreateKey(CategoryKey);
key.SetValue("Category", CategoryGuid);
key.SetValue("Package", PackageGuid);
key.SetValue("NameID", CategoryNameResourceID);
key.SetValue("ToolWindowPackage", ToolWindowPackageGuid);
// IMPORTANT: without calling Close() the values won't be persisted to registry.
key.Close();
}
public override void Unregister(RegistrationContext context) {
context.RemoveKey(CategoryKey);
}
}
} | apache-2.0 | C# |
185c56b0e9b2aafed67e28fee21a215f1dc091b7 | Add Cli basic tests | codetasy/cli | src/Codetasy.Cli.Tests/CliTest.cs | src/Codetasy.Cli.Tests/CliTest.cs | using System;
using Xunit;
using Codetasy.Cli;
using System.Collections.Generic;
using System.IO;
namespace Codetasy.Cli.Tests
{
public class CliTest
{
[Fact]
public void CanExecuteCommand()
{
var executed = false;
var arguments = new [] {"hello"};
var commands = new Dictionary<string, Action<CliDictionary<string, string>>>();
commands.Add("hello", args =>
{
executed = true;
});
new Cli(arguments).Execute(commands);
Assert.True(executed);
}
[Fact]
public void CanParseSingleArgument()
{
var message = string.Empty;
var arguments = new [] {"hello", "name=Frodo"};
var commands = new Dictionary<string, Action<CliDictionary<string, string>>>();
commands.Add("hello", args =>
{
message = $"Hello {args["name"]}";
});
new Cli(arguments).Execute(commands);
Assert.Equal("Hello Frodo", message);
}
[Fact]
public void CanParseMultipleArguments()
{
var message = string.Empty;
var arguments = new [] {"hello", "--name=\"Frodo Baggins\"", "--region=\"The Shire\""};
var commands = new Dictionary<string, Action<CliDictionary<string, string>>>();
commands.Add("hello", args =>
{
message = $"Hello {args["name"]} from {args["region"]}";
});
new Cli(arguments).Execute(commands);
Assert.Equal("Hello \"Frodo Baggins\" from \"The Shire\"", message);
}
}
}
| using System;
using Xunit;
using Codetasy.Cli;
namespace Codetasy.Cli.Tests
{
public class CliTest
{
[Fact]
public void CanInstantiate()
{
var args = new string[0];
var cli = new Cli(args);
Assert.IsType<Cli>(cli);
}
}
}
| mit | C# |
72f8347ea3e4ada80fb6b592678e146db0c98a77 | Refactor code. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Views/Home/Index.cshtml | src/CompetitionPlatform/Views/Home/Index.cshtml | @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<div class="projects-filter-buttons">
<div class="col-md-12">
<a asp-area="" asp-controller="Home" asp-action="Index" class="btn btn-primary btn-sm">All Projects</a>
<a asp-area="" asp-controller="Home" asp-action="FilterMyProjects" class="btn btn-info btn-sm">My Projects</a>
<button type="button" class="btn btn-info btn-sm">Following</button>
</div>
</div>
<div class="col-md-12">
<div class="row col-md-3 project-filter">
<select id="projectStatusFilter" name="projectStatusFilter" class="form-control" value="Create">
<option value="">Status : All</option>
@foreach (var status in Enum.GetValues(typeof(Status)))
{
<option value=@status>@status</option>
}
</select>
</div>
<div class="row col-md-3 project-filter">
<select id="projectCategoryFilter" name="projectCategoryFilter" class="form-control" value="Create">
<option value="">Category: All</option>
@foreach (var category in Model.ProjectCategories)
{
<option value="@category">@category</option>
}
</select>
</div>
</div>
<div>
<div id="projectListResults">
@await Html.PartialAsync("ProjectListPartial", Model)
</div>
</div>
| @model CompetitionPlatform.Models.ProjectViewModels.ProjectListIndexViewModel
@{
ViewData["Title"] = "Projects";
}
<div class="projects-filter-buttons">
<div class="col-md-12">
<a asp-area="" asp-controller="Home" asp-action="Index" class="btn btn-primary btn-sm">All Projects</a>
<a asp-area="" asp-controller="Home" asp-action="FilterMyProjects" class="btn btn-info btn-sm">My Projects</a>
<button type="button" class="btn btn-info btn-sm">Following</button>
</div>
</div>
<div class="col-md-12">
<div class="row col-md-3 project-filter">
<select id="projectStatusFilter" name="projectStatusFilter" class="form-control" value="Create">
<option value="">Status : All</option>
@foreach (var status in Enum.GetValues(typeof(Status)))
{
<option value=@status>@status</option>
}
</select>
</div>
<div class="row col-md-3 project-filter">
<select id="projectCategoryFilter" name="projectCategoryFilter" class="form-control" value="Create">
<option value="">Category: All</option>
@foreach (var category in Model.ProjectCategories)
{
<option value="@category">@category</option>
}
</select>
</div>
</div>
<div class="">
<div id="projectListResults">
@await Html.PartialAsync("ProjectListPartial", Model)
</div>
</div>
| mit | C# |
38cdb6690dc8bfa70bda3ba19b092ad58d449cb3 | Add a dropdown for selecting organizations | github-for-unity/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,mpOzelot/Unity | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/PublishWindow.cs | using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private int selectedOrg = 0;
private bool togglePrivate = false;
private string[] orgs = { "donokuda", "github", "donokudallc", "another-org" };
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
selectedOrg = EditorGUILayout.Popup("Organization", 0, orgs);
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.Button("Create");
}
GUILayout.EndHorizontal();
}
}
}
| using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
public class PublishWindow : EditorWindow
{
private const string PublishTitle = "Publish this repository to GitHub";
private string repoName = "";
private string repoDescription = "";
private bool togglePrivate = false;
static void Init()
{
PublishWindow window = (PublishWindow)EditorWindow.GetWindow(typeof(PublishWindow));
window.Show();
}
void OnGUI()
{
GUILayout.Label(PublishTitle, EditorStyles.boldLabel);
GUILayout.Space(5);
repoName = EditorGUILayout.TextField("Name", repoName);
repoDescription = EditorGUILayout.TextField("Description", repoDescription);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
togglePrivate = GUILayout.Toggle(togglePrivate, "Keep my code private");
}
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
{
GUILayout.FlexibleSpace();
GUILayout.Button("Create");
}
GUILayout.EndHorizontal();
}
}
}
| mit | C# |
52c6b56a41cb262811030e91beeaaea86565e2bf | Fix for account type dropdown in edit vs new mode. | grae22/BoozeHoundCloud,grae22/BoozeHoundCloud,grae22/BoozeHoundCloud | BoozeHoundCloud/Areas/Core/Views/Account/AccountForm.cshtml | BoozeHoundCloud/Areas/Core/Views/Account/AccountForm.cshtml | @model BoozeHoundCloud.Areas.Core.ViewModels.AccountFormViewModel
@{
bool isNewAccount = (Model.Id == 0);
var formTitle = "";
if (isNewAccount)
{
formTitle = "Create Account";
}
else
{
formTitle = "Edit Account";
}
ViewBag.Title = formTitle;
}
<h2>@formTitle</h2>
@using (Html.BeginForm("Save", "Account"))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { @class="form-control" })
@Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => m.AccountTypeId)
@if (isNewAccount)
{
@Html.DropDownListFor(
m => m.AccountTypeId,
new SelectList(
Model.AccountTypes,
"Id",
"Name"),
"Select one...",
new { @class = "form-control" })
@Html.ValidationMessageFor(m => m.AccountTypeId)
}
else
{
@Html.TextBoxFor(
m => m.AccountTypes.First(x => x.Id == Model.AccountTypeId).Name,
new { @class = "form-control", @readonly = "true" } )
}
</div>
@Html.HiddenFor(m => m.Id);
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" onclick="history.go(-1);">Cancel</button>
}
@section scripts
{
@Scripts.Render( "~/bundles/jqueryval" )
} | @model BoozeHoundCloud.Areas.Core.ViewModels.AccountFormViewModel
@{
bool isNewAccount = (Model.Id == 0);
var formTitle = "";
if (isNewAccount)
{
formTitle = "Create Account";
}
else
{
formTitle = "Edit Account";
}
ViewBag.Title = formTitle;
}
<h2>@formTitle</h2>
@using (Html.BeginForm("Save", "Account"))
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name, new { @class="form-control" })
@Html.ValidationMessageFor(m => m.Name)
</div>
<div class="form-group">
@Html.LabelFor(m => m.AccountTypeId)
@Html.DropDownListFor(
m => m.AccountTypeId,
new SelectList(
Model.AccountTypes,
"Id",
"Name"),
"Select one...",
new {@class = "form-control", @readonly = "true" })
@Html.ValidationMessageFor(m => m.AccountTypeId)
</div>
@Html.HiddenFor(m => m.Id);
@Html.AntiForgeryToken()
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" onclick="history.go(-1);">Cancel</button>
}
@section scripts
{
@Scripts.Render( "~/bundles/jqueryval" )
} | mit | C# |
cacbc6a0f37e6b5c83fde638a8fc26a520eea120 | Update namespace for InputHints | yakumo/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,msft-shahins/BotBuilder,stevengum97/BotBuilder,msft-shahins/BotBuilder,msft-shahins/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder,yakumo/BotBuilder,stevengum97/BotBuilder | CSharp/Library/Microsoft.Bot.Connector.Shared/InputHints.cs | CSharp/Library/Microsoft.Bot.Connector.Shared/InputHints.cs | using System;
using System.Linq;
namespace Microsoft.Bot.Connector
{
/// <summary>
/// Indicates whether the bot is accepting, expecting, or ignoring input
/// </summary>
public static class InputHints
{
/// <summary>
/// The sender is passively ready for input but is not waiting on a response.
/// </summary>
public const string AcceptingInput = "acceptingInput";
/// <summary>
/// The sender is ignoring input. Bots may send this hint if they are actively processing a request and will ignore input
/// from users until the request is complete.
/// </summary>
public const string IgnoringInput = "ignoringInput";
/// <summary>
/// The sender is actively expecting a response from the user.
/// </summary>
public const string ExpectingInput = "expectingInput";
}
}
| using System;
using System.Linq;
namespace Microsoft.Bot.Schema
{
/// <summary>
/// Indicates whether the bot is accepting, expecting, or ignoring input
/// </summary>
public static class InputHints
{
/// <summary>
/// The sender is passively ready for input but is not waiting on a response.
/// </summary>
public const string AcceptingInput = "acceptingInput";
/// <summary>
/// The sender is ignoring input. Bots may send this hint if they are actively processing a request and will ignore input
/// from users until the request is complete.
/// </summary>
public const string IgnoringInput = "ignoringInput";
/// <summary>
/// The sender is actively expecting a response from the user.
/// </summary>
public const string ExpectingInput = "expectingInput";
}
}
| mit | C# |
7fbeb9ecc7a78fed1ef88d45b42eed54d13a19d7 | Add failing test coverage for tournament startup states | smoogipoo/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipoo/osu | osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.cs | osu.Game.Tournament.Tests/Screens/TestSceneGameplayScreen.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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.IPC;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
[Test]
public void TestStartupState([Values] TourneyState state)
{
AddStep("set state", () => IPCInfo.State.Value = state);
createScreen();
}
[Test]
public void TestWarmup()
{
createScreen();
checkScoreVisibility(false);
toggleWarmup();
checkScoreVisibility(true);
toggleWarmup();
checkScoreVisibility(false);
}
private void createScreen()
{
AddStep("setup screen", () =>
{
Remove(chat);
Children = new Drawable[]
{
new GameplayScreen(),
chat,
};
});
}
private void checkScoreVisibility(bool visible)
=> AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
() => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));
private void toggleWarmup()
=> AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
}
}
| // 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.Linq;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Testing;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Gameplay.Components;
namespace osu.Game.Tournament.Tests.Screens
{
public class TestSceneGameplayScreen : TournamentTestScene
{
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay { Width = 0.5f };
[BackgroundDependencyLoader]
private void load()
{
Add(new GameplayScreen());
Add(chat);
}
[Test]
public void TestWarmup()
{
checkScoreVisibility(false);
toggleWarmup();
checkScoreVisibility(true);
toggleWarmup();
checkScoreVisibility(false);
}
private void checkScoreVisibility(bool visible)
=> AddUntilStep($"scores {(visible ? "shown" : "hidden")}",
() => this.ChildrenOfType<TeamScore>().All(score => score.Alpha == (visible ? 1 : 0)));
private void toggleWarmup()
=> AddStep("toggle warmup", () => this.ChildrenOfType<TourneyButton>().First().TriggerClick());
}
}
| mit | C# |
7e781501443b62d2b3dc4102b2375c35252c7f42 | add basic content wiki sidebar | smoogipoo/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu | osu.Game/Overlays/Wiki/WikiSidebar.cs | osu.Game/Overlays/Wiki/WikiSidebar.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
namespace osu.Game.Overlays.Wiki
{
public class WikiSidebar : OverlaySidebar
{
private FillFlowContainer tableOfContents;
protected override Drawable CreateContent() => new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new OsuSpriteText
{
Text = "CONTENTS",
Font = OsuFont.GetFont(size: 12, weight: FontWeight.Bold),
},
tableOfContents = new FillFlowContainer
{
Direction = FillDirection.Vertical,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
}
},
};
}
}
| // 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.
namespace osu.Game.Overlays.Wiki
{
public class WikiSidebar : OverlaySidebar
{
}
}
| mit | C# |
fe5202b3d2ad7dbd0606b6e83e9e11fd80c1b251 | Fix test. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/Microsoft.AspNet.PipelineCore.Tests/HeaderDictionaryTests.cs | test/Microsoft.AspNet.PipelineCore.Tests/HeaderDictionaryTests.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.PipelineCore.Collections;
using Xunit;
namespace Microsoft.AspNet.PipelineCore.Tests
{
public class HeaderDictionaryTests
{
[Fact]
public void PropertiesAreAccessible()
{
var headers = new HeaderDictionary(
new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
{
{ "Header1", new[] { "Value1" } }
});
Assert.Equal(1, headers.Count);
Assert.Equal(new[] { "Header1" }, headers.Keys);
Assert.True(headers.ContainsKey("header1"));
Assert.False(headers.ContainsKey("header2"));
Assert.Equal("Value1", headers["header1"]);
Assert.Equal("Value1", headers.Get("header1"));
Assert.Equal(new[] { "Value1" }, headers.GetValues("header1"));
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using Microsoft.AspNet.PipelineCore.Collections;
using Xunit;
namespace Microsoft.AspNet.PipelineCore.Tests
{
public class HeaderDictionaryTests
{
[Fact]
public void PropertiesAreAccessible()
{
var headers = new HeaderDictionary(
new Dictionary<string, string[]>(StringComparer.OrdinalIgnoreCase)
{
{ "Header1", new[] { "Value1" } }
});
Assert.Equal(1, headers.Count);
Assert.Equal(new[] { "Headers1" }, headers.Keys);
Assert.True(headers.ContainsKey("headers1"));
Assert.False(headers.ContainsKey("headers2"));
Assert.Equal("Value1", headers["header1"]);
Assert.Equal("Value1", headers.Get("header1"));
Assert.Equal(new[] { "Value1" }, headers.GetValues("header1"));
}
}
} | apache-2.0 | C# |
93a23a68eea8b067692aaa41fff6a2858ca4abbd | fix test case name | NCTUGDC/HearthStone | HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs | HearthStone/HearthStone.Library.Test/CardManagerUnitTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
class CardManagerUnitTest
{
[TestMethod]
public void CardManagerInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance);
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards);
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card);
Assert.IsFalse(IDs.Contains(card.CardID));
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects);
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect);
Assert.IsFalse(IDs.Contains(effect.EffectID));
IDs.Add(effect.EffectID);
}
}
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HearthStone.Library.Test
{
[TestClass]
class CardManagerUnitTest
{
[TestMethod]
public void StaticInstanceTestMethod1()
{
CardManager instance = CardManager.Instance;
Assert.IsNotNull(instance);
}
[TestMethod]
public void CardsEnumerableTestMethod1()
{
IEnumerable<Card> cards = CardManager.Instance.Cards;
Assert.IsNotNull(cards);
}
[TestMethod]
public void CardsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Card card in CardManager.Instance.Cards)
{
Assert.IsNotNull(card);
Assert.IsFalse(IDs.Contains(card.CardID));
IDs.Add(card.CardID);
}
}
[TestMethod]
public void EffectsEnumerableTestMethod1()
{
IEnumerable<Effect> effects = CardManager.Instance.Effects;
Assert.IsNotNull(effects);
}
[TestMethod]
public void EffectsEnumerableTestMethod2()
{
HashSet<int> IDs = new HashSet<int>();
foreach (Effect effect in CardManager.Instance.Effects)
{
Assert.IsNotNull(effect);
Assert.IsFalse(IDs.Contains(effect.EffectID));
IDs.Add(effect.EffectID);
}
}
}
}
| apache-2.0 | C# |
ee58e9bafca9fedcd34993566716da14bb018c5b | Add RemoveReport Test with AdminController [#136389281] | revaturelabs/revashare-svc-webapi | revashare-svc-webapi/revashare-svc-webapi.Tests/FlagTests.cs | revashare-svc-webapi/revashare-svc-webapi.Tests/FlagTests.cs | using Moq;
using NSubstitute;
using revashare_svc_webapi.Client.Controllers;
using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.AdminLogic;
using revashare_svc_webapi.Logic.Interfaces;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using revashare_svc_webapi.Logic.ServiceClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
ServiceClient sc = new ServiceClient();
AdminLogic admLogic = new AdminLogic(sc);
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
[Fact]
public void test_RemoveReport_AdminController()
{
var mock = new Mock<IAdmin>();
mock.Setup(a => a.RemoveReport(new FlagDTO())).Returns(true);
var ctrl = new AdminController(mock.Object);
ctrl.Request = Substitute.For<HttpRequestMessage>();
ctrl.Configuration = Substitute.For<HttpConfiguration>();
HttpResponseMessage res = ctrl.RemoveReport(new FlagDTO());
Assert.Equal(res.StatusCode, HttpStatusCode.OK);
}
}
}
| using revashare_svc_webapi.Logic;
using revashare_svc_webapi.Logic.AdminLogic;
using revashare_svc_webapi.Logic.Models;
using revashare_svc_webapi.Logic.RevaShareServiceReference;
using revashare_svc_webapi.Logic.ServiceClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace revashare_svc_webapi.Tests
{
public class FlagTests
{
[Fact]
public void test_GetFlags()
{
RevaShareDataServiceClient dataClient = new RevaShareDataServiceClient();
List<FlagDAO> getflags = dataClient.GetAllFlags().ToList();
Assert.NotNull(getflags);
}
[Fact]
public void test_GetFlags_AdminLogic()
{
ServiceClient sc = new ServiceClient();
AdminLogic admLogic = new AdminLogic(sc);
var a = admLogic.GetUserReports();
Assert.NotEmpty(a);
}
//[Fact]
//public void test_RemoveReport_AdminLogic()
//{
// ServiceClient sc = new ServiceClient();
// AdminLogic admLogic = new AdminLogic(sc);
// FlagDTO reportNumber = new FlagDTO { FlagId = 22 };
// bool actual = admLogic.RemoveReport(reportNumber);
// Assert.True(actual);
//}
}
}
| mit | C# |
2f87a6135ad2b2a119725585755560fcfb408b8f | Add support for the "payments" and “profile” properties in the "_links" object of the SubscriptionResponseLinks class | Viincenttt/MollieApi,Viincenttt/MollieApi | Mollie.Api/Models/Subscription/SubscriptionResponseLinks.cs | Mollie.Api/Models/Subscription/SubscriptionResponseLinks.cs | using Mollie.Api.Models.Customer;
using Mollie.Api.Models.List;
using Mollie.Api.Models.Payment.Response;
using Mollie.Api.Models.Profile.Response;
using Mollie.Api.Models.Url;
namespace Mollie.Api.Models.Subscription {
public class SubscriptionResponseLinks {
/// <summary>
/// The API resource URL of the subscription itself.
/// </summary>
public UrlObjectLink<SubscriptionResponse> Self { get; set; }
/// <summary>
/// The API resource URL of the customer the subscription is for.
/// </summary>
public UrlObjectLink<CustomerResponse> Customer { get; set; }
/// <summary>
/// The API resource URL of the payments that are created by this subscription. Not present
/// if no payments yet created.
/// </summary>
public UrlObjectLink<ListResponse<PaymentResponse>> Payments { get; set; }
/// <summary>
/// The API resource URL of the website profile on which this subscription was created.
/// </summary>
public UrlObjectLink<ProfileResponse> Profile { get; set; }
/// <summary>
/// The URL to the subscription retrieval endpoint documentation.
/// </summary>
public UrlLink Documentation { get; set; }
}
} | using Mollie.Api.Models.Customer;
using Mollie.Api.Models.Url;
namespace Mollie.Api.Models.Subscription {
public class SubscriptionResponseLinks {
/// <summary>
/// The API resource URL of the subscription itself.
/// </summary>
public UrlObjectLink<SubscriptionResponse> Self { get; set; }
/// <summary>
/// The API resource URL of the customer the subscription is for.
/// </summary>
public UrlObjectLink<CustomerResponse> Customer { get; set; }
/// <summary>
/// The URL to the subscription retrieval endpoint documentation.
/// </summary>
public UrlLink Documentation { get; set; }
}
} | mit | C# |
e2f4eea7bbb941d3c912ed54900d4432e0bcfb96 | update loader to correctly load genes instead of nets | jobeland/GeneticAlgorithm | NeuralNetwork.GeneticAlgorithm/Utils/NeuralNetworkLoader.cs | NeuralNetwork.GeneticAlgorithm/Utils/NeuralNetworkLoader.cs | using ArtificialNeuralNetwork;
using Newtonsoft.Json;
using System.IO;
using ArtificialNeuralNetwork.Factories;
using ArtificialNeuralNetwork.Genes;
namespace NeuralNetwork.GeneticAlgorithm.Utils
{
public class NeuralNetworkLoader : INeuralNetworkLoader
{
private readonly string _directory;
public NeuralNetworkLoader(string directory)
{
_directory = directory;
}
public INeuralNetwork LoadNeuralNetwork(string filename)
{
var jsonGenes = File.ReadAllText(_directory + filename);
var networkGene = JsonConvert.DeserializeObject<NeuralNetworkGene>(jsonGenes);
var network = NeuralNetworkFactory.GetInstance().Create(networkGene);
return network;
}
}
}
| using ArtificialNeuralNetwork;
using Newtonsoft.Json;
using System.IO;
namespace NeuralNetwork.GeneticAlgorithm.Utils
{
public class NeuralNetworkLoader : INeuralNetworkLoader
{
private readonly string _directory;
public NeuralNetworkLoader(string directory)
{
_directory = directory;
}
public INeuralNetwork LoadNeuralNetwork(string filename)
{
var jsonNet = File.ReadAllText(_directory + filename);
INeuralNetwork network = JsonConvert.DeserializeObject<INeuralNetwork>(jsonNet);
return network;
}
}
}
| mit | C# |
541512b26445bcf02ecc04b57b1886ddf4bffb6d | Use existing file encoding if provided override is invalid | allansson/Calamari,allansson/Calamari | source/Calamari/Integration/Substitutions/FileSubstituter.cs | source/Calamari/Integration/Substitutions/FileSubstituter.cs | using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;
namespace Calamari.Integration.Substitutions
{
public class FileSubstituter : IFileSubstituter
{
readonly ICalamariFileSystem fileSystem;
public FileSubstituter(ICalamariFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables)
{
PerformSubstitution(sourceFile, variables, sourceFile);
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
{
var source = fileSystem.ReadFile(sourceFile);
var encoding = GetEncoding(sourceFile, variables);
var result = variables.Evaluate(source);
fileSystem.OverwriteFile(targetFile, result, encoding);
}
private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
{
var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
if (requestedEncoding == null)
{
return fileSystem.GetFileEncoding(sourceFile);
}
try
{
return Encoding.GetEncoding(requestedEncoding);
}
catch (ArgumentException)
{
return fileSystem.GetFileEncoding(sourceFile);
}
}
}
}
| using System;
using System.IO;
using System.Text;
using Calamari.Deployment;
using Calamari.Integration.FileSystem;
using Octostache;
namespace Calamari.Integration.Substitutions
{
public class FileSubstituter : IFileSubstituter
{
readonly ICalamariFileSystem fileSystem;
public FileSubstituter(ICalamariFileSystem fileSystem)
{
this.fileSystem = fileSystem;
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables)
{
PerformSubstitution(sourceFile, variables, sourceFile);
}
public void PerformSubstitution(string sourceFile, VariableDictionary variables, string targetFile)
{
var source = fileSystem.ReadFile(sourceFile);
var encoding = GetEncoding(sourceFile, variables);
var result = variables.Evaluate(source);
fileSystem.OverwriteFile(targetFile, result, encoding);
}
private Encoding GetEncoding(string sourceFile, VariableDictionary variables)
{
var requestedEncoding = variables.Get(SpecialVariables.Package.SubstituteInFilesOutputEncoding);
if (requestedEncoding == null)
{
return fileSystem.GetFileEncoding(sourceFile);
}
try
{
return Encoding.GetEncoding(requestedEncoding);
}
catch (ArgumentException)
{
return Encoding.GetEncoding(sourceFile);
}
}
}
}
| apache-2.0 | C# |
5a14a8cce0dc670e89144abcd006db56b68fd5d5 | add ActiveDirectoryController | signumsoftware/framework,signumsoftware/extensions,signumsoftware/framework,signumsoftware/extensions | Signum.React.Extensions/Authorization/ActiveDirectoryController.cs | Signum.React.Extensions/Authorization/ActiveDirectoryController.cs | using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Signum.Engine;
using Signum.Engine.Authorization;
using Signum.Engine.Mailing;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.React.Filters;
using Signum.Services;
using Signum.Utilities;
using Signum.Engine.Basics;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
namespace Signum.React.Authorization
{
[ValidateModelFilter]
public class ActiveDirectoryController : ControllerBase
{
[HttpGet("api/findADUsers")]
public Task<List<ActiveDirectoryUser>> FindADUsers(string subString, int count, CancellationToken token)
{
var config = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer!).GetConfig();
if (config.Azure_ApplicationID.HasText())
return MicrosoftGraphLogic.FindActiveDirectoryUsers(subString, count, token);
if (config.DomainName.HasText())
return ActiveDirectoryLogic.SearchUser(subString);
throw new InvalidOperationException($"Neither {nameof(config.Azure_ApplicationID)} or {nameof(config.DomainName)} are set in {config.GetType().Name}");
}
[HttpPost("api/createADUser")]
public Lite<UserEntity> CreateADUser([FromBody][Required] ActiveDirectoryUser user)
{
return MicrosoftGraphLogic.CreateUserFromAD(user).ToLite();
}
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Signum.Engine;
using Signum.Engine.Authorization;
using Signum.Engine.Mailing;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.React.Filters;
using Signum.Services;
using Signum.Utilities;
using Signum.Engine.Basics;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
namespace Signum.React.Authorization
{
[ValidateModelFilter]
public class ActiveDirectoryController : ControllerBase
{
[HttpGet("api/findADUsers")]
public Task<List<ActiveDirectoryUser>> FindADUsers(string subString, int count, CancellationToken token)
{
var config = ((ActiveDirectoryAuthorizer)AuthLogic.Authorizer!).GetConfig();
if (config.Azure_ApplicationID.HasText())
return MicrosoftGraphLogic.FindActiveDirectoryUsers(subString, count, token);
if (config.DomainName.HasText())
return ActiveDirectoryLogic.SearchUser(subString);
throw new InvalidOperationException($"Neither {nameof(ActiveDirectoryConfigurationEmbedded.Azure_ApplicationID)} or {nameof(ActiveDirectoryConfigurationEmbedded.DomainName)} are set in {nameof(ActiveDirectoryConfigurationEmbedded)}")
}
[HttpPost("api/createADUser")]
public Lite<UserEntity> CreateADUser([FromBody][Required] ActiveDirectoryUser user)
{
return MicrosoftGraphLogic.CreateUserFromAD(user).ToLite();
}
}
}
| mit | C# |
58e61280a3d47561a0df98f7667a88ecc8dbc563 | Fix null annotation of SyntaxFactory.UsingStatement (#51984) | eriawan/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,weltkante/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,wvdd007/roslyn,dotnet/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,physhi/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,wvdd007/roslyn,mavasani/roslyn,weltkante/roslyn,KevinRansom/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,bartdesmet/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,AmadeusW/roslyn,sharwell/roslyn,diryboy/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,diryboy/roslyn | src/Compilers/CSharp/Portable/Syntax/UsingStatementSyntax.cs | src/Compilers/CSharp/Portable/Syntax/UsingStatementSyntax.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.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class UsingStatementSyntax
{
public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AwaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public UsingStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static UsingStatementSyntax UsingStatement(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> UsingStatement(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public static UsingStatementSyntax UsingStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> UsingStatement(attributeLists: default, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public static UsingStatementSyntax UsingStatement(VariableDeclarationSyntax? declaration, ExpressionSyntax? expression, StatementSyntax statement)
=> UsingStatement(attributeLists: default, declaration, expression, statement);
}
}
| // 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.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.Syntax
{
public partial class UsingStatementSyntax
{
public UsingStatementSyntax Update(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AwaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public UsingStatementSyntax Update(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> Update(AttributeLists, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
}
}
namespace Microsoft.CodeAnalysis.CSharp
{
public partial class SyntaxFactory
{
public static UsingStatementSyntax UsingStatement(SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> UsingStatement(awaitKeyword: default, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public static UsingStatementSyntax UsingStatement(SyntaxToken awaitKeyword, SyntaxToken usingKeyword, SyntaxToken openParenToken, VariableDeclarationSyntax declaration, ExpressionSyntax expression, SyntaxToken closeParenToken, StatementSyntax statement)
=> UsingStatement(attributeLists: default, awaitKeyword, usingKeyword, openParenToken, declaration, expression, closeParenToken, statement);
public static UsingStatementSyntax UsingStatement(VariableDeclarationSyntax declaration, ExpressionSyntax expression, StatementSyntax statement)
=> UsingStatement(attributeLists: default, declaration, expression, statement);
}
}
| mit | C# |
00c09e0b832e8ad222262fced8a3ab62ae5ccb30 | add comment for clarity to defensive blueprints | Construktion/Construktion,Construktion/Construktion | Construktion/Blueprints/DefaultBlueprints.cs | Construktion/Blueprints/DefaultBlueprints.cs | namespace Construktion.Blueprints
{
using System;
using System.Collections;
using System.Collections.Generic;
using Recursive;
using Simple;
public class DefaultBlueprints : IEnumerable<Blueprint>
{
private readonly IEnumerable<Blueprint> _defaultBlueprints;
public DefaultBlueprints() : this(new Dictionary<Type, Type>()) { }
public DefaultBlueprints(IDictionary<Type, Type> typeMap)
{
_defaultBlueprints = new List<Blueprint>
{
new StringBlueprint(),
new NumericBlueprint(),
new CharBlueprint(),
new GuidBlueprint(),
new BoolBlueprint(),
new TimespanBlueprint(),
new DictionaryBlueprint(),
new EnumerableBlueprint(),
new ArrayBlueprint(),
new EnumBlueprint(),
new DateTimeBlueprint(),
new NullableTypeBlueprint(),
new EmptyCtorBlueprint(),
new NonEmptyCtorBlueprint(),
new InterfaceBlueprint(typeMap),
//always last
new DefensiveBlueprint()
};
}
public IEnumerator<Blueprint> GetEnumerator() => _defaultBlueprints.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
} | namespace Construktion.Blueprints
{
using System;
using System.Collections;
using System.Collections.Generic;
using Recursive;
using Simple;
public class DefaultBlueprints : IEnumerable<Blueprint>
{
private readonly IEnumerable<Blueprint> _defaultBlueprints;
public DefaultBlueprints() : this(new Dictionary<Type, Type>()) { }
public DefaultBlueprints(IDictionary<Type, Type> typeMap)
{
_defaultBlueprints = new List<Blueprint>
{
new StringBlueprint(),
new NumericBlueprint(),
new CharBlueprint(),
new GuidBlueprint(),
new BoolBlueprint(),
new TimespanBlueprint(),
new DictionaryBlueprint(),
new EnumerableBlueprint(),
new ArrayBlueprint(),
new EnumBlueprint(),
new DateTimeBlueprint(),
new NullableTypeBlueprint(),
new EmptyCtorBlueprint(),
new NonEmptyCtorBlueprint(),
new InterfaceBlueprint(typeMap),
new DefensiveBlueprint()
};
}
public IEnumerator<Blueprint> GetEnumerator() => _defaultBlueprints.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
} | mit | C# |
f86800844a1611177fc1228406d168441b2d3d56 | Update IIndex.cs | tamasflamich/nmemory | Main/Source/NMemory.Shared/Indexes/IIndex.cs | Main/Source/NMemory.Shared/Indexes/IIndex.cs | // ----------------------------------------------------------------------------------
// <copyright file="IIndex.cs" company="NMemory Team">
// Copyright (C) NMemory Team
//
// 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.
// </copyright>
// ----------------------------------------------------------------------------------
namespace NMemory.Indexes
{
using NMemory.Tables;
public interface IIndex
{
ITable Table { get; }
IKeyInfo KeyInfo { get; }
bool SupportsIntervalSearch { get; }
long Count { get; }
void Clear();
void Rebuild();
}
}
| // ----------------------------------------------------------------------------------
// <copyright file="IIndex.cs" company="NMemory Team">
// Copyright (C) NMemory Team
//
// 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.
// </copyright>
// ----------------------------------------------------------------------------------
namespace NMemory.Indexes
{
using NMemory.Tables;
public interface IIndex
{
ITable Table { get; }
IKeyInfo KeyInfo { get; }
bool SupportsIntervalSearch { get; }
long Count { get; }
////void Clear();
void Rebuild();
}
}
| mit | C# |
0e52f29f4fa348480ec08c49b1aca51cfd190b8c | Add app.Map("/sub" | vlko/DevDays2015-MVC6 | devdays/Startup.cs | devdays/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
namespace devdays
{
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
// Add the platform handler to the request pipeline.
app.UseIISPlatformHandler();
app.Map("/sub", appSub =>
{
appSub.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World from sub!");
});
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;
namespace devdays
{
public class Startup
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app)
{
// Add the platform handler to the request pipeline.
app.UseIISPlatformHandler();
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
}
}
| mit | C# |
d1c1c8ada308acb837e291a1d776300072e6bcd1 | Fix canDisarm datafield (#11963) | space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14 | Content.Shared/CombatMode/SharedCombatModeComponent.cs | Content.Shared/CombatMode/SharedCombatModeComponent.cs | using Content.Shared.Actions;
using Content.Shared.Actions.ActionTypes;
using Content.Shared.Targeting;
using Content.Shared.Verbs;
using Robust.Shared.Audio;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Utility;
namespace Content.Shared.CombatMode
{
[NetworkedComponent()]
public abstract class SharedCombatModeComponent : Component
{
#region Disarm
/// <summary>
/// Whether we are able to disarm. This requires our active hand to be free.
/// False if it's toggled off for whatever reason, null if it's not possible.
/// </summary>
[ViewVariables(VVAccess.ReadWrite), DataField("canDisarm")]
public bool? CanDisarm;
[DataField("disarmSuccessSound")]
public readonly SoundSpecifier DisarmSuccessSound = new SoundPathSpecifier("/Audio/Effects/thudswoosh.ogg");
[DataField("disarmFailChance")]
public readonly float BaseDisarmFailChance = 0.75f;
#endregion
private bool _isInCombatMode;
private TargetingZone _activeZone;
[DataField("combatToggleActionId", customTypeSerializer: typeof(PrototypeIdSerializer<InstantActionPrototype>))]
public readonly string CombatToggleActionId = "CombatModeToggle";
[DataField("combatToggleAction")]
public InstantAction? CombatToggleAction;
[ViewVariables(VVAccess.ReadWrite)]
public virtual bool IsInCombatMode
{
get => _isInCombatMode;
set
{
if (_isInCombatMode == value) return;
_isInCombatMode = value;
if (CombatToggleAction != null)
EntitySystem.Get<SharedActionsSystem>().SetToggled(CombatToggleAction, _isInCombatMode);
Dirty();
}
}
[ViewVariables(VVAccess.ReadWrite)]
public virtual TargetingZone ActiveZone
{
get => _activeZone;
set
{
if (_activeZone == value) return;
_activeZone = value;
Dirty();
}
}
}
}
| using Content.Shared.Actions;
using Content.Shared.Actions.ActionTypes;
using Content.Shared.Targeting;
using Content.Shared.Verbs;
using Robust.Shared.Audio;
using Robust.Shared.GameStates;
using Robust.Shared.Serialization;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype;
using Robust.Shared.Utility;
namespace Content.Shared.CombatMode
{
[NetworkedComponent()]
public abstract class SharedCombatModeComponent : Component
{
#region Disarm
/// <summary>
/// Whether we are able to disarm. This requires our active hand to be free.
/// False if it's toggled off for whatever reason, null if it's not possible.
/// </summary>
[ViewVariables(VVAccess.ReadWrite), DataField("disarm")]
public bool? CanDisarm;
[DataField("disarmSuccessSound")]
public readonly SoundSpecifier DisarmSuccessSound = new SoundPathSpecifier("/Audio/Effects/thudswoosh.ogg");
[DataField("disarmFailChance")]
public readonly float BaseDisarmFailChance = 0.75f;
#endregion
private bool _isInCombatMode;
private TargetingZone _activeZone;
[DataField("combatToggleActionId", customTypeSerializer: typeof(PrototypeIdSerializer<InstantActionPrototype>))]
public readonly string CombatToggleActionId = "CombatModeToggle";
[DataField("combatToggleAction")]
public InstantAction? CombatToggleAction;
[ViewVariables(VVAccess.ReadWrite)]
public virtual bool IsInCombatMode
{
get => _isInCombatMode;
set
{
if (_isInCombatMode == value) return;
_isInCombatMode = value;
if (CombatToggleAction != null)
EntitySystem.Get<SharedActionsSystem>().SetToggled(CombatToggleAction, _isInCombatMode);
Dirty();
}
}
[ViewVariables(VVAccess.ReadWrite)]
public virtual TargetingZone ActiveZone
{
get => _activeZone;
set
{
if (_activeZone == value) return;
_activeZone = value;
Dirty();
}
}
}
}
| mit | C# |
c046f4503f119071fd49e4409ff4e1a1b02b2673 | Add Football-API's testing key complete. | tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer,tlaothong/dailysoccer | DailySoccer2015/ApiApp/Repositories/FootballService.cs | DailySoccer2015/ApiApp/Repositories/FootballService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApiApp.Models;
using System.Net;
using RestSharp;
namespace ApiApp.Repositories
{
/// <summary>
/// ตัวเชื่อมต่อกับฟุตบอลเซอร์วิส
/// </summary>
public class FootballService : IFootballService
{
#region IFootballService members
/// <summary>
/// ดึงข้อมูลแมช์การแข่งขันจากรหัสลีก
/// </summary>
/// <param name="leagueId">รหัสลีก</param>
/// <param name="fromDate">เริ่มดึงจากวันที่</param>
/// <param name="toDate">ดึงถึงวันที่</param>
public IEnumerable<MatchAPIInformation> GetMatchesByLeagueId(string leagueId, DateTime fromDate, DateTime toDate)
{
const string dateFormat = "dd.MM.yyyy";
//const string APIKey = "d7946ce1-b897-975e-d462b1899cd6"; // miolynet fot Joker azure
const string APIKey = "fb8e4d95-d176-b433-7a10ecb4ebe7"; // perawatt fot localhost
const string urlFormat = "/api/?Action=fixtures&APIKey={0}&comp_id={1}&from_date={2}&to_date={3}";
var url = string.Format(urlFormat, APIKey, leagueId, fromDate.ToString(dateFormat), toDate.ToString(dateFormat));
const string ClientBaseURL = "http://football-api.com";
var client = new RestClient(ClientBaseURL);
var request = new RestRequest(url);
var respond = client.Execute<MatchAPIRespond>(request);
var error = respond.Data == null || respond.Data.matches == null;
if (error) return Enumerable.Empty<MatchAPIInformation>();
return respond.Data.matches;
}
#endregion IFootballService members
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ApiApp.Models;
using System.Net;
using RestSharp;
namespace ApiApp.Repositories
{
/// <summary>
/// ตัวเชื่อมต่อกับฟุตบอลเซอร์วิส
/// </summary>
public class FootballService : IFootballService
{
#region IFootballService members
/// <summary>
/// ดึงข้อมูลแมช์การแข่งขันจากรหัสลีก
/// </summary>
/// <param name="leagueId">รหัสลีก</param>
/// <param name="fromDate">เริ่มดึงจากวันที่</param>
/// <param name="toDate">ดึงถึงวันที่</param>
public IEnumerable<MatchAPIInformation> GetMatchesByLeagueId(string leagueId, DateTime fromDate, DateTime toDate)
{
const string dateFormat = "dd.MM.yyyy";
const string APIKey = "d7946ce1-b897-975e-d462b1899cd6";
const string urlFormat = "/api/?Action=fixtures&APIKey={0}&comp_id={1}&from_date={2}&to_date={3}";
var url = string.Format(urlFormat, APIKey, leagueId, fromDate.ToString(dateFormat), toDate.ToString(dateFormat));
const string ClientBaseURL = "http://football-api.com";
var client = new RestClient(ClientBaseURL);
var request = new RestRequest(url);
var respond = client.Execute<MatchAPIRespond>(request);
var error = respond.Data == null || respond.Data.matches == null;
if (error) return Enumerable.Empty<MatchAPIInformation>();
return respond.Data.matches;
}
#endregion IFootballService members
}
}
| mit | C# |
fe744b26a37e9bb093a3e370b1a1b33f97bd93d7 | Remove more references | Xenoleth/Reverb-MVC,Xenoleth/Reverb-MVC,Xenoleth/Reverb-MVC | Reverb/Reverb.Data/UnitOfWork/SaveContext.cs | Reverb/Reverb.Data/UnitOfWork/SaveContext.cs | using Reverb.Data.Contracts;
namespace Reverb.Data.SaveChanges
{
public class SaveContext : ISaveContext
{
private readonly IReverbDbContext context;
public SaveContext(IReverbDbContext context)
{
//Guard.WhenArgument(context, "context").IsNull().Throw();
this.context = context;
}
public void SaveChanges()
{
this.context.SaveChanges();
}
}
}
| using Bytes2you.Validation;
using Reverb.Data.Contracts;
namespace Reverb.Data.SaveChanges
{
public class SaveContext : ISaveContext
{
private readonly IReverbDbContext context;
public SaveContext(IReverbDbContext context)
{
Guard.WhenArgument(context, "context").IsNull().Throw();
this.context = context;
}
public void SaveChanges()
{
this.context.SaveChanges();
}
}
}
| mit | C# |
4777b221e251b4adf94aeff11970d9f00f84df51 | Fix a bug where RequiredFieldChecker skipped fields of a value type if those were not marked with the RequiredAttribute. | lukyad/Eco | Eco/SettingsVisitors/RequiredFieldChecker.cs | Eco/SettingsVisitors/RequiredFieldChecker.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Eco.Extensions;
namespace Eco.SettingsVisitors
{
public class RequiredFieldChecker : TwinSettingsVisitorBase
{
readonly HashSet<Tuple<object, FieldInfo>> _defaultedAndOverridenFields;
public RequiredFieldChecker(HashSet<Tuple<object, FieldInfo>> defaultedAndOverridenFields)
{
_defaultedAndOverridenFields = defaultedAndOverridenFields;
}
public override void Visit(string settingsNamesapce, string fieldPath, FieldInfo refinedSettingsField, object refinedSettings, FieldInfo rawSettingsField, object rawSettings)
{
if (!rawSettingsField.IsDefined<RequiredAttribute>()) return;
bool fieldInitialized =
rawSettingsField != null && rawSettingsField.GetValue(rawSettings) != null ||
// Some refined fields could be initialized through applyDefaults or applyOverrides.
_defaultedAndOverridenFields.Contains(Tuple.Create(refinedSettings, refinedSettingsField));
if (!fieldInitialized)
throw new ConfigurationException("Missing required field '{0}'.", fieldPath);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Eco.Extensions;
namespace Eco.SettingsVisitors
{
public class RequiredFieldChecker : TwinSettingsVisitorBase
{
readonly HashSet<Tuple<object, FieldInfo>> _defaultedAndOverridenFields;
public RequiredFieldChecker(HashSet<Tuple<object, FieldInfo>> defaultedAndOverridenFields)
{
_defaultedAndOverridenFields = defaultedAndOverridenFields;
}
public override void Visit(string settingsNamesapce, string fieldPath, FieldInfo refinedSettingsField, object refinedSettings, FieldInfo rawSettingsField, object rawSettings)
{
if (!refinedSettingsField.IsDefined<RequiredAttribute>()) return;
bool fieldInitialized =
rawSettingsField != null && rawSettingsField.GetValue(rawSettings) != null ||
// Some refined fields could be initialized through applyDefaults or applyOverrides.
_defaultedAndOverridenFields.Contains(Tuple.Create(refinedSettings, refinedSettingsField));
if (!fieldInitialized)
throw new ConfigurationException("Missing required field '{0}'.", fieldPath);
}
}
}
| apache-2.0 | C# |
33ae9f8bd285b7ae85bac39b81bc957dcafe2147 | Handle nullable types. | JohanLarsson/Gu.ChangeTracking,JohanLarsson/Gu.State,JohanLarsson/Gu.State | Gu.State/EqualBy/Comparers/EquatableEqualByComparer.cs | Gu.State/EqualBy/Comparers/EquatableEqualByComparer.cs | namespace Gu.State
{
using System;
using System.Collections.Generic;
using System.Reflection;
internal static class EquatableEqualByComparer
{
internal static bool TryGet(Type type, MemberSettings settings, out EqualByComparer comparer)
{
if (settings.IsEquatable(type) &&
type.Name != "ImmutableArray`1")
{
if (type.IsNullable())
{
comparer = (EqualByComparer)typeof(NullableComparer<>).MakeGenericType(type.GenericTypeArguments)
.GetField(nameof(NullableComparer<int>.Default), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
else
{
comparer = (EqualByComparer)typeof(Comparer<>).MakeGenericType(type)
.GetField(nameof(Comparer<int>.Default), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
}
return true;
}
comparer = null;
return false;
}
private class Comparer<T> : EqualByComparer
{
public static Comparer<T> Default = new Comparer<T>(EqualityComparer<T>.Default);
private readonly EqualityComparer<T> comparer;
private Comparer(EqualityComparer<T> comparer)
{
this.comparer = comparer;
}
public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
{
return this.comparer.Equals((T)x, (T)y);
}
}
private class NullableComparer<T> : EqualByComparer
where T : struct
{
public static NullableComparer<T> Default = new NullableComparer<T>();
private NullableComparer()
{
}
public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
{
return Nullable.Equals((T?)x, (T?)y);
}
}
}
}
| namespace Gu.State
{
using System;
using System.Collections.Generic;
using System.Reflection;
internal static class EquatableEqualByComparer
{
internal static bool TryGet(Type type, MemberSettings settings, out EqualByComparer comparer)
{
if (settings.IsEquatable(type) &&
type.Name != "ImmutableArray`1")
{
comparer = (EqualByComparer)typeof(Comparer<>).MakeGenericType(type)
.GetField(nameof(Comparer<int>.Default), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
.GetValue(null);
return true;
}
comparer = null;
return false;
}
private class Comparer<T> : EqualByComparer
where T : IEquatable<T>
{
public static Comparer<T> Default = new Comparer<T>(EqualityComparer<T>.Default);
private readonly EqualityComparer<T> comparer;
private Comparer(EqualityComparer<T> comparer)
{
this.comparer = comparer;
}
public override bool Equals(object x, object y, MemberSettings settings, ReferencePairCollection referencePairs)
{
return this.comparer.Equals((T)x, (T)y);
}
}
}
}
| mit | C# |
7ad8f083fe5b3d68e1c21cb9f11c64c0bd3e4393 | Update SettingsServiceTests.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core.Tests/Settings/SettingsServiceTests.cs | TIKSN.Framework.Core.Tests/Settings/SettingsServiceTests.cs | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.DependencyInjection;
using TIKSN.FileSystem;
namespace TIKSN.Settings.Tests
{
public partial class SettingsServiceTests
{
partial void SetupDenepdencies()
{
services.AddFrameworkPlatform();
services.AddSingleton<ISettingsService, FileSettingsService>();
services.AddSingleton(new KnownFoldersConfiguration(GetType().Assembly, KnownFolderVersionConsideration.None));
var configurationRoot = new ConfigurationBuilder()
.AddInMemoryCollection()
.Build();
configurationRoot["RelativePath"] = "settings.db";
services.ConfigurePartial<FileSettingsServiceOptions, FileSettingsServiceOptionsValidator>(configurationRoot);
}
}
} | using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TIKSN.DependencyInjection;
using TIKSN.FileSystem;
namespace TIKSN.Settings.Tests
{
public partial class SettingsServiceTests
{
partial void SetupDenepdencies()
{
PlatformDependencyRegistration.Register(services);
services.AddSingleton<ISettingsService, FileSettingsService>();
services.AddSingleton(new KnownFoldersConfiguration(GetType().Assembly, KnownFolderVersionConsideration.None));
var configurationRoot = new ConfigurationBuilder()
.AddInMemoryCollection()
.Build();
configurationRoot["RelativePath"] = "settings.db";
services.ConfigurePartial<FileSettingsServiceOptions, FileSettingsServiceOptionsValidator>(configurationRoot);
}
}
} | mit | C# |
4e7e471cf788486d9f26f99ad267676b115645f2 | Add entities while enumerating | EasyPeasyLemonSqueezy/MadCat | MadCat/NutEngine/Components/EntityManager.cs | MadCat/NutEngine/Components/EntityManager.cs | using System;
using System.Collections.Generic;
namespace NutEngine
{
public class EntityManager
{
public List<Entity> Entities { get; } = new List<Entity>();
private static Dictionary<Type, Type[]> Dependencies = new Dictionary<Type, Type[]>();
private List<Entity> toBeAdded = new List<Entity>();
public void Update(float deltaTime)
{
foreach (var entity in toBeAdded) {
entity.Manager = this;
Entities.Add(entity);
}
toBeAdded.Clear();
foreach (var entity in Entities) {
entity.Update(deltaTime);
}
Entities.RemoveAll(
entity => {
if (entity.Invalid) {
entity.Dispose();
return true;
}
return false;
});
}
public void Add(Entity entity)
{
toBeAdded.Add(entity);
}
public static void AddDependency<T>(params Type[] types)
where T : Component
{
Dependencies.Add(typeof(T), types);
}
public static Type[] GetDependency(Type type)
{
if (!Dependencies.ContainsKey(type)) {
Dependencies.Add(type, new Type[0]);
}
return Dependencies[type];
}
}
}
| using System;
using System.Collections.Generic;
namespace NutEngine
{
public class EntityManager
{
public List<Entity> Entities { get; } = new List<Entity>();
private static Dictionary<Type, Type[]> Dependencies = new Dictionary<Type, Type[]>();
public void Update(float deltaTime)
{
foreach (var entity in Entities) {
entity.Update(deltaTime);
}
Entities.RemoveAll(
entity => {
if (entity.Invalid) {
entity.Dispose();
return true;
}
return false;
});
}
public void Add(Entity entity)
{
entity.Manager = this;
Entities.Add(entity);
}
public static void AddDependency<T>(params Type[] types)
where T : Component
{
Dependencies.Add(typeof(T), types);
}
public static Type[] GetDependency(Type type)
{
if (!Dependencies.ContainsKey(type)) {
Dependencies.Add(type, new Type[0]);
}
return Dependencies[type];
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.