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 |
|---|---|---|---|---|---|---|---|---|
7b5f1c89e26035d862f9541562f5ee712627c507 | Support to tween colors | alvivar/Hasten | Experimental/loop/loop.cs | Experimental/loop/loop.cs | // Tween library API prototype using DOTween in the meantime.
// Andrés Villalobos | twitter.com/matnesis | andresalvivar@gmail.com
// 2017/08/13 11:15 pm
using System;
using DG.Tweening;
using DG.Tweening.Core;
using UnityEngine;
public class loop {
private Sequence dotween = DOTween.Sequence();
public static loop create() {
return new loop();
}
public loop then(DOGetter<float> getter, DOSetter<float> setter, float endvalue, float time) {
dotween.Append(DOTween.To(getter, setter, endvalue, time));
return this;
}
public loop then(DOGetter<Color> getter, DOSetter<Color> setter, Color endvalue, float time) {
dotween.Append(DOTween.To(getter, setter, endvalue, time));
return this;
}
public loop then(Tweener tweener) {
dotween.Append(tweener);
return this;
}
public loop then(TweenCallback callback) {
dotween.AppendCallback(callback);
return this;
}
public loop wait(float time) {
dotween.AppendInterval(time);
return this;
}
public loop wait(Func<float> callback) {
dotween.AppendCallback(() => {
loop.create()
.then(() => dotween.Pause())
.wait(callback())
.then(() => dotween.Play());
});
return this;
}
public YieldInstruction WaitForCompletion() {
return dotween.WaitForCompletion();
}
public loop repeat() {
dotween.SetLoops(-1);
return this;
}
} |
// Tween library API prototype using DOTween in the meantime.
// Andrés Villalobos | twitter.com/matnesis | andresalvivar@gmail.com
// 2017/08/13 11:15 pm
using System;
using UnityEngine;
using DG.Tweening;
using DG.Tweening.Core;
public class loop
{
private Sequence dotween = DOTween.Sequence();
public static loop create()
{
return new loop();
}
public loop then(DOGetter<float> getter, DOSetter<float> setter, float endvalue, float time)
{
dotween.Append(DOTween.To(getter, setter, endvalue, time));
return this;
}
public loop then(Tweener tweener)
{
dotween.Append(tweener);
return this;
}
public loop then(TweenCallback callback)
{
dotween.AppendCallback(callback);
return this;
}
public loop wait(float time)
{
dotween.AppendInterval(time);
return this;
}
public loop wait(Func<float> callback)
{
dotween.AppendCallback(() =>
{
loop.create()
.then(() => dotween.Pause())
.wait(callback())
.then(() => dotween.Play());
});
return this;
}
public YieldInstruction WaitForCompletion()
{
return dotween.WaitForCompletion();
}
public loop repeat()
{
dotween.SetLoops(-1);
return this;
}
}
| mit | C# |
c1284cf62472598eda3e06c785d15895ccca6220 | Change `TfsWorkItemRegex` to allow any whitespace between the item id and the action. Fixes #234. | modulexcite/git-tfs,TheoAndersen/git-tfs,modulexcite/git-tfs,TheoAndersen/git-tfs,bleissem/git-tfs,spraints/git-tfs,adbre/git-tfs,pmiossec/git-tfs,hazzik/git-tfs,irontoby/git-tfs,jeremy-sylvis-tmg/git-tfs,spraints/git-tfs,codemerlin/git-tfs,adbre/git-tfs,guyboltonking/git-tfs,spraints/git-tfs,codemerlin/git-tfs,hazzik/git-tfs,irontoby/git-tfs,WolfVR/git-tfs,allansson/git-tfs,WolfVR/git-tfs,NathanLBCooper/git-tfs,modulexcite/git-tfs,allansson/git-tfs,PKRoma/git-tfs,TheoAndersen/git-tfs,git-tfs/git-tfs,steveandpeggyb/Public,hazzik/git-tfs,NathanLBCooper/git-tfs,jeremy-sylvis-tmg/git-tfs,vzabavnov/git-tfs,hazzik/git-tfs,guyboltonking/git-tfs,kgybels/git-tfs,allansson/git-tfs,WolfVR/git-tfs,andyrooger/git-tfs,jeremy-sylvis-tmg/git-tfs,steveandpeggyb/Public,guyboltonking/git-tfs,codemerlin/git-tfs,NathanLBCooper/git-tfs,steveandpeggyb/Public,bleissem/git-tfs,bleissem/git-tfs,allansson/git-tfs,irontoby/git-tfs,adbre/git-tfs,kgybels/git-tfs,TheoAndersen/git-tfs,kgybels/git-tfs | GitTfs/GitTfsConstants.cs | GitTfs/GitTfsConstants.cs | using System.Text.RegularExpressions;
using System;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
// e.g. git-tfs-work-item: 24 associate
public static readonly Regex TfsWorkItemRegex =
new Regex(GitTfsPrefix + @"-work-item:\s+(?<item_id>\d+)\s+(?<action>.+)");
// e.g. git-tfs-force: override reason
public static readonly Regex TfsForceRegex =
new Regex(GitTfsPrefix + @"-force:\s+(?<reason>.+)\s*$");
}
}
| using System.Text.RegularExpressions;
using System;
namespace Sep.Git.Tfs
{
public static class GitTfsConstants
{
public static readonly Regex Sha1 = new Regex("[a-f\\d]{40}", RegexOptions.IgnoreCase);
public static readonly Regex Sha1Short = new Regex("[a-f\\d]{4,40}", RegexOptions.IgnoreCase);
public static readonly Regex CommitRegex = new Regex("^commit (" + Sha1 + ")\\s*$");
public const string DefaultRepositoryId = "default";
public const string GitTfsPrefix = "git-tfs";
// e.g. git-tfs-id: [http://team:8080/]$/sandbox;C123
public const string TfsCommitInfoFormat = "git-tfs-id: [{0}]{1};C{2}";
public static readonly Regex TfsCommitInfoRegex =
new Regex("^\\s*" +
GitTfsPrefix +
"-id:\\s+" +
"\\[(?<url>.+)\\]" +
"(?<repository>.+);" +
"C(?<changeset>\\d+)" +
"\\s*$");
// e.g. git-tfs-work-item: 24 associate
public static readonly Regex TfsWorkItemRegex =
new Regex(GitTfsPrefix + @"-work-item:\s+(?<item_id>\d+)\s(?<action>.+)");
// e.g. git-tfs-force: override reason
public static readonly Regex TfsForceRegex =
new Regex(GitTfsPrefix + @"-force:\s+(?<reason>.+)\s*$");
}
}
| apache-2.0 | C# |
ad0acefd4eac536143371e02a4488a18bb016382 | Add missing attribute. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Core/ParameterAttribute.cs | source/Nuke.Core/ParameterAttribute.cs | // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Execution;
using Nuke.Core.Injection;
namespace Nuke.Core
{
/// <inheritdoc/>
/// <summary>
/// <inheritdoc/><para/>
/// Parameters are resolved case-insensitively in the following order:
/// <ul>
/// <li>From command-line arguments (e.g., <c>-arg value</c>)</li>
/// <li>From environment variables (e.g., <c>Arg=value</c>)</li>
/// </ul>
/// <para/>
/// For value-types, there is a distinction between pure value-types, and their <em>nullable</em>
/// counterparts. For instance, <c>int</c> will have its default value <c>0</c> even when it's not
/// supplied via command-line or environment variable, and therefore also can't be used as requirements.
/// Declaring the field as <c>int?</c> however, will enable validation and setting the requirement.
/// </summary>
/// <example>
/// <code>
/// [Parameter("MyGet API key for private feed."] string MyGetApiKey;
/// Target Push => _ => _
/// .Requires(() => MyGetApiKey)
/// .Executes() => { /* ... */ });
/// </code>
/// </example>
[PublicAPI]
[UsedImplicitly(ImplicitUseKindFlags.Assign)]
public class ParameterAttribute : InjectionAttributeBase
{
private static readonly ParameterService s_parameterService = new ParameterService();
public ParameterAttribute (string description = null)
{
Description = description;
}
[CanBeNull]
public string Description { get; }
public string Name { get; set; }
public string Separator { get; set; }
public override Type InjectionType => null;
[CanBeNull]
public override object GetValue (string memberName, Type memberType)
{
memberType = Nullable.GetUnderlyingType(memberType) == null
&& memberType != typeof(string)
&& !memberType.IsArray
? typeof(Nullable<>).MakeGenericType(memberType)
: memberType;
return s_parameterService.GetParameter(Name ?? memberName, memberType, (Separator ?? string.Empty).SingleOrDefault());
}
}
}
| // Copyright Matthias Koch 2017.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Linq;
using JetBrains.Annotations;
using Nuke.Core.Execution;
using Nuke.Core.Injection;
namespace Nuke.Core
{
/// <inheritdoc/>
/// <summary>
/// <inheritdoc/><para/>
/// Parameters are resolved case-insensitively in the following order:
/// <ul>
/// <li>From command-line arguments (e.g., <c>-arg value</c>)</li>
/// <li>From environment variables (e.g., <c>Arg=value</c>)</li>
/// </ul>
/// <para/>
/// For value-types, there is a distinction between pure value-types, and their <em>nullable</em>
/// counterparts. For instance, <c>int</c> will have its default value <c>0</c> even when it's not
/// supplied via command-line or environment variable, and therefore also can't be used as requirements.
/// Declaring the field as <c>int?</c> however, will enable validation and setting the requirement.
/// </summary>
/// <example>
/// <code>
/// [Parameter("MyGet API key for private feed."] string MyGetApiKey;
/// Target Push => _ => _
/// .Requires(() => MyGetApiKey)
/// .Executes() => { /* ... */ });
/// </code>
/// </example>
[PublicAPI]
[UsedImplicitly(ImplicitUseKindFlags.Assign)]
public class ParameterAttribute : InjectionAttributeBase
{
private static readonly ParameterService s_parameterService = new ParameterService();
public ParameterAttribute (string description = null)
{
Description = description;
}
public string Description { get; }
public string Name { get; set; }
public string Separator { get; set; }
public override Type InjectionType => null;
[CanBeNull]
public override object GetValue (string memberName, Type memberType)
{
memberType = Nullable.GetUnderlyingType(memberType) == null
&& memberType != typeof(string)
&& !memberType.IsArray
? typeof(Nullable<>).MakeGenericType(memberType)
: memberType;
return s_parameterService.GetParameter(Name ?? memberName, memberType, (Separator ?? string.Empty).SingleOrDefault());
}
}
}
| mit | C# |
802b7c7b42607fcd7228dbac99db90d0b85b6200 | Change version to 1.0.4 | dbraillon/Roggle | src/Roggle.Core/Properties/AssemblyInfo.cs | src/Roggle.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Roggle.Core")]
[assembly: AssemblyDescription("Core library for Roggle solution.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Davy Braillon")]
[assembly: AssemblyProduct("Roggle.Core")]
[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("de43fcfe-19a2-4d0c-8f4a-3d3c28b152d7")]
// 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.4.0")]
[assembly: AssemblyFileVersion("1.0.4.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Roggle.Core")]
[assembly: AssemblyDescription("Core library for Roggle solution.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Davy Braillon")]
[assembly: AssemblyProduct("Roggle.Core")]
[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("de43fcfe-19a2-4d0c-8f4a-3d3c28b152d7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.3.0")]
[assembly: AssemblyFileVersion("1.0.3.0")]
| mit | C# |
330f904d19fd8e922d47d3f2e51c207e0851e579 | add capture startup errors | OdeToCode/aspcoreclass,OdeToCode/aspcoreclass | Program.cs | Program.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using aspcoreclass.Services;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace aspcoreclass
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
MigrateDatabase(host);
host.Run();
}
private static void MigrateDatabase(IWebHost host)
{
using(var scope = host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<TeamDbContext>();
db.Database.Migrate();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.CaptureStartupErrors(true)
.UseStartup<Startup>();
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using aspcoreclass.Services;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace aspcoreclass
{
public class Program
{
public static void Main(string[] args)
{
var host = CreateWebHostBuilder(args).Build();
MigrateDatabase(host);
host.Run();
}
private static void MigrateDatabase(IWebHost host)
{
using(var scope = host.Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<TeamDbContext>();
db.Database.Migrate();
}
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
| mit | C# |
a5aa3bae549df0960af34d7a36da09223494a5fe | change test | walkingriver/scoutcheers,walkingriver/scoutcheers | ScoutCheersWeb/Controllers/HomeController.cs | ScoutCheersWeb/Controllers/HomeController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ScoutCheersWeb.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
//hello
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace ScoutCheersWeb.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
| mit | C# |
4395d77667afd7a9106a7a37d08531bcc14d3a5b | Add the MitternachtBot instance and its services to the ASP.NET services. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | MitternachtWeb/Startup.cs | MitternachtWeb/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting;
using System.Linq;
namespace MitternachtWeb {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
services.Add(ServiceDescriptor.Singleton(Program.MitternachtBot));
services.Add(Program.MitternachtBot.Services.Services.Select(s => ServiceDescriptor.Singleton(s.Key, s.Value)));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace MitternachtWeb {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services) {
services.AddControllersWithViews();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if(env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
} else {
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| mit | C# |
152a782cc3dcbec3c015c5046da112d9762a53c1 | Add warning on delete from source | rgregg/photo-organizer | PhotoOrganizer/Program.cs | PhotoOrganizer/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using CommandLine.Text;
namespace PhotoOrganizer
{
class Program
{
static void Main(string[] args)
{
var opts = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, opts))
{
Console.WriteLine(HelpText.AutoBuild(opts));
return;
}
if (string.IsNullOrEmpty(opts.SourceFolder))
opts.SourceFolder = System.Environment.CurrentDirectory;
DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder);
if (!destination.Exists)
{
Console.WriteLine("Error: Destination folder doesn't exist.");
return;
}
DirectoryInfo source = new DirectoryInfo(opts.SourceFolder);
if (!source.Exists)
{
Console.WriteLine("Error: Source folder doesn't exist. Nothing to do.");
return;
}
if (opts.DeleteSourceOnExistingFile)
{
Console.Write("Delete source files on existing files in destination is enabled.\nTHIS MAY CAUSE DATA LOSS, are you sure? [Y/N]: ");
var key = Console.ReadKey();
if (!(key.KeyChar == 'y' || key.KeyChar == 'Y'))
return;
Console.WriteLine();
}
FileOrganizer organizer = new FileOrganizer(destination, opts);
organizer.ProcessSourceFolder(source);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using CommandLine.Text;
namespace PhotoOrganizer
{
class Program
{
static void Main(string[] args)
{
var opts = new CommandLineOptions();
if (!CommandLine.Parser.Default.ParseArguments(args, opts))
{
Console.WriteLine(HelpText.AutoBuild(opts));
return;
}
if (string.IsNullOrEmpty(opts.SourceFolder))
opts.SourceFolder = System.Environment.CurrentDirectory;
DirectoryInfo destination = new DirectoryInfo(opts.DestinationFolder);
if (!destination.Exists)
{
Console.WriteLine("Error: Destination folder doesn't exist.");
return;
}
DirectoryInfo source = new DirectoryInfo(opts.SourceFolder);
if (!source.Exists)
{
Console.WriteLine("Error: Source folder doesn't exist. Nothing to do.");
return;
}
FileOrganizer organizer = new FileOrganizer(destination, opts);
organizer.ProcessSourceFolder(source);
}
}
}
| mit | C# |
0027eb0b5fefb374714247ad21db182af88eed6f | Use interface | gibachan/XmlDict | XmlDict/XmlDictNodeList.cs | XmlDict/XmlDictNodeList.cs | using System;
using System.Collections.Generic;
namespace XmlDict
{
public class XmlDictNodeList : IXmlDict
{
private List<XmlDictNode> _dictionaries = new List<XmlDictNode>();
#region IXMLDict
public string Text { get { return FirstNode.Text; } }
public bool Exists { get { return _dictionaries.Count > 0 ? true : false; } }
public XmlAttributeList Attributes { get { return FirstNode.Attributes; } }
public IEnumerator<IXmlDict> GetEnumerator()
{
foreach (var child in _dictionaries)
yield return child;
}
public string Name { get { return FirstNode.Name; } }
public IXmlDict this[string name]
{
get
{
foreach (var node in FirstNode)
{
if (node.Name == name)
return node;
}
return new XmlDictNode();
}
}
public IXmlDict this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException();
return _dictionaries[index];
}
}
public int Count { get { return _dictionaries.Count; } }
#endregion
public void Add(XmlDictNode dict)
{
_dictionaries.Add(dict);
}
public void Remove(int index)
{
if (index < 0 || index >= _dictionaries.Count)
{
throw new ArgumentOutOfRangeException();
}
_dictionaries.RemoveAt(index);
}
private IXmlDict FirstNode
{
get
{
if (_dictionaries.Count > 0)
return _dictionaries[0];
else
return new XmlDictNode();
}
}
}
}
| using System;
using System.Collections.Generic;
namespace XmlDict
{
public class XmlDictNodeList : IXmlDict
{
private List<XmlDictNode> _dictionaries = new List<XmlDictNode>();
#region IXMLDict
public string Text { get { return FirstNode.Text; } }
public bool Exists { get { return _dictionaries.Count > 0 ? true : false; } }
public XmlAttributeList Attributes { get { return FirstNode.Attributes; } }
public IEnumerator<IXmlDict> GetEnumerator()
{
foreach (var child in _dictionaries)
yield return child;
}
public string Name { get { return FirstNode.Name; } }
public IXmlDict this[string name]
{
get
{
foreach (var node in FirstNode)
{
if (node.Name == name)
return node;
}
return new XmlDictNode();
}
}
public IXmlDict this[int index]
{
get
{
if (index < 0 || index >= Count)
throw new ArgumentOutOfRangeException();
return _dictionaries[index];
}
}
public int Count { get { return _dictionaries.Count; } }
#endregion
public void Add(XmlDictNode dict)
{
_dictionaries.Add(dict);
}
public void Remove(int index)
{
if (index < 0 || index >= _dictionaries.Count)
{
throw new ArgumentOutOfRangeException();
}
_dictionaries.RemoveAt(index);
}
private XmlDictNode FirstNode
{
get
{
if (_dictionaries.Count > 0)
return _dictionaries[0];
else
return new XmlDictNode();
}
}
}
}
| mit | C# |
36cfed75946398201dd1ab2019f3e126f38382ae | Fix converter | tobyclh/UnityCNTK,tobyclh/UnityCNTK | Assets/UnityCNTK/Convert.cs | Assets/UnityCNTK/Convert.cs | using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System;
namespace UnityCNTK
{
public static class Convert
{
public static CNTK.Value ToValue(Texture2D texture, bool useAlpha = false)
{
//Non-copying way to create a value
var shape = NDShape.CreateNDShape(new int[] { useAlpha ? 4 : 3 * texture.width * texture.height });
var pixels = texture.GetPixels();
var channelPixelCount = texture.width * texture.height;
var pixelArray = new float[channelPixelCount * (useAlpha ? 4 : 3)];
Array.Copy(Array.ConvertAll(pixels, p => (float)p.r), 0, pixelArray, 0, channelPixelCount);
Array.Copy(Array.ConvertAll(pixels, p => (float)p.g), 0, pixelArray, channelPixelCount, channelPixelCount);
Array.Copy(Array.ConvertAll(pixels, p => (float)p.b), 0, pixelArray, channelPixelCount*2, channelPixelCount);
if (useAlpha) Array.Copy(Array.ConvertAll(pixels, p => (float)p.a), 0, pixelArray, channelPixelCount*3, channelPixelCount);
List<float[]> list = new List<float[]>(){pixelArray};
// var array = new float[useAlpha ? 4 : 3, texture.width * texture.height];
// NDArrayView arrayView = new NDArrayView()
var inputVal = CNTK.Value.Create(shape, list, new bool[]{true}, DeviceDescriptor.CPUDevice, false);
return inputVal;
}
public static CNTK.Value ToValue(Material mat)
{
return Convert.ToValue(mat.mainTexture as Texture2D);
}
}
}
| using UnityEngine;
using CNTK;
using System;
using System.Linq;
using System.Collections.Generic;
using System;
namespace UnityCNTK
{
public static class Convert
{
public static CNTK.Value ToValue(Texture2D texture, bool useAlpha = false)
{
var shape = NDShape.CreateNDShape(new int[] { useAlpha ? 4 : 3, texture.width, texture.height });
var pixels = texture.GetRawTextureData();
NDArrayView arrayView;
//Non-copying way to create a value
pixels.AsFloatArray(x => arrayView = new NDArrayView(shape, x, DeviceDescriptor.CPUDevice, false) );
// var array = new float[useAlpha ? 4 : 3, texture.width * texture.height];
NDArrayViewPtrVector pVec = new NDArrayViewPtrVector(pixels);
// NDArrayView arrayView = new NDArrayView()
var inputVal = CNTK.Value.Create(shape, pVec, new BoolVector() { true }, DeviceDescriptor.CPUDevice, false, false);
return inputVal;
}
public static CNTK.Value ToValue(Material mat)
{
return Convert.ToValue(mat.mainTexture as Texture2D);
}
}
}
| mit | C# |
f02d1f9013720196f4613d0307a729c5e7aabfb0 | move the 250 appear disance to a const var. | smoogipoo/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,EVAST9919/osu,peppy/osu,naoey/osu,smoogipooo/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,naoey/osu,2yangk23/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,ZLima12/osu,naoey/osu,DrabWeb/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,peppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModArrange.cs | osu.Game.Rulesets.Osu/Mods/OsuModArrange.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING";
public override double ScoreMultiplier => 1.05;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
// repeat points get their position data from the slider.
if (hitObject is RepeatPoint)
return;
Vector2 originalPosition = drawable.Position;
// avoiding that the player can see the abroupt move.
const int pre_time_offset = 1000;
const float appearDistance = 250;
using (drawable.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimeFadeIn - pre_time_offset, true))
{
drawable
.MoveTo(originalPosition, hitObject.TimeFadeIn + pre_time_offset, Easing.InOutSine);
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * appearDistance)
}
// That way slider ticks come all from the same direction.
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.Fun;
public override string Description => "Everything rotates. EVERYTHING";
public override double ScoreMultiplier => 1.05;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
// repeat points get their position data from the slider.
if (hitObject is RepeatPoint)
return;
Vector2 originalPosition = drawable.Position;
// avoiding that the player can see the abroupt move.
const int pre_time_offset = 1000;
using (drawable.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimeFadeIn - pre_time_offset, true))
{
drawable
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * 250)
.MoveTo(originalPosition, hitObject.TimeFadeIn + pre_time_offset, Easing.InOutSine);
}
// That way slider ticks come all from the same direction.
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| mit | C# |
5871b9af2368a2473a8e8c6620cbeb95682ef01c | Revert "make command line host non blocking" | xkproject/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2,alexbocharov/Orchard2,lukaskabrt/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,jtkech/Orchard2,alexbocharov/Orchard2,yiji/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,yiji/Orchard2,lukaskabrt/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,jtkech/Orchard2,OrchardCMS/Brochard,lukaskabrt/Orchard2,petedavis/Orchard2,jtkech/Orchard2,alexbocharov/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,yiji/Orchard2 | src/Orchard.Web/Program.cs | src/Orchard.Web/Program.cs | using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Run();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
} | using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Start();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
} | bsd-3-clause | C# |
9b07e6170949cae08ceb247f4981bb7c9df0d721 | Update ValuesOut.cs | EricZimmerman/RegistryPlugins | RegistryPlugin.VolumeInfoCache/ValuesOut.cs | RegistryPlugin.VolumeInfoCache/ValuesOut.cs | using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.VolumeInfoCache
{
public class ValuesOut : IValueOut
{
public ValuesOut(string drivename, string volumelabel, DateTimeOffset? timestamp)
{
DriveName = drivename;
VolumeLabel = volumelabel;
Timestamp = timestamp;
}
public DateTimeOffset? Timestamp { get; }
public string DriveName { get; }
public string VolumeLabel { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"DriveName: {DriveName} VolumeLabel: {VolumeLabel}";
public string BatchValueData2 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}";
public string BatchValueData3 => string.Empty;
}
}
| using System;
using RegistryPluginBase.Interfaces;
namespace RegistryPlugin.VolumeInfoCache
{
public class ValuesOut : IValueOut
{
public ValuesOut(string drivename, string volumelabel, DateTimeOffset? timestamp)
{
DriveName = drivename;
VolumeLabel = volumelabel;
Timestamp = timestamp;
}
public DateTimeOffset? Timestamp { get; }
public string DriveName { get; }
public string VolumeLabel { get; }
public string BatchKeyPath { get; set; }
public string BatchValueName { get; set; }
public string BatchValueData1 => $"DriveName: {DriveName} VolumeLabel: {VolumeLabel}";
public string BatchValueData2 => $"Timestamp: {Timestamp?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff} ";
public string BatchValueData3 => string.Empty;
}
}
| mit | C# |
15d33d4a03eab711d3312719af12d63198da94dd | Refactor the arrange part of the test | GoodSoil/cqrs-starter-kit,GoodSoil/cqrs-starter-kit | sample-app/CafeTests/AddingEventHandlers.cs | sample-app/CafeTests/AddingEventHandlers.cs | using Cafe.Tab;
using Edument.CQRS;
using Events.Cafe;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebFrontend;
namespace CafeTests
{
[TestFixture]
public class AddingEventHandlers
{
private static void Arrange(out OpenTab command, out TabOpened expectedEvent, out ISubscribeTo<TabOpened> handler)
{
// Arrange
Guid testId = Guid.NewGuid();
command = new OpenTab()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
expectedEvent = new TabOpened()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
handler = new EventHandler();
}
[Test]
public void ShouldAddEventHandlers()
{
ISubscribeTo<TabOpened> handler;
OpenTab command;
TabOpened expectedEvent;
Arrange(out command, out expectedEvent, out handler);
// Act
Domain.Setup();
Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler);
Domain.Dispatcher.SendCommand(command);
// Assert
Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id);
}
public class EventHandler : ISubscribeTo<TabOpened>
{
public TabOpened Actual { get; private set; }
public void Handle(TabOpened e)
{
Actual = e;
}
}
}
}
| using Cafe.Tab;
using Edument.CQRS;
using Events.Cafe;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebFrontend;
namespace CafeTests
{
[TestFixture]
public class AddingEventHandlers
{
[Test]
public void ShouldAddEventHandlers()
{
// Arrange
Guid testId = Guid.NewGuid();
var command = new OpenTab()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
var expectedEvent = new TabOpened()
{
Id = testId,
TableNumber = 5,
Waiter = "Bob"
};
ISubscribeTo<TabOpened> handler = new EventHandler();
// Act
Domain.Setup();
Domain.Dispatcher.AddSubscriberFor<TabOpened>(handler);
Domain.Dispatcher.SendCommand(command);
// Assert
Assert.AreEqual(expectedEvent.Id, (handler as EventHandler).Actual.Id);
}
public class EventHandler : ISubscribeTo<TabOpened>
{
public TabOpened Actual { get; private set; }
public void Handle(TabOpened e)
{
Actual = e;
}
}
}
}
| bsd-3-clause | C# |
9f353507afdafb767241f50e6b4b5d3bc5055090 | Create negative test for getting values from nested environments | escamilla/squirrel | test/test-library/EnvironmentTests.cs | test/test-library/EnvironmentTests.cs | using Xunit;
using Squirrel;
using Squirrel.Nodes;
namespace Tests
{
public class EnvironmentTests
{
private static readonly string TestVariableName = "x";
private static readonly INode TestVariableValue = new IntegerNode(1);
[Fact]
public void TestCanGetValueFromCurrentEnvironment() {
var environment = new Environment();
environment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, environment.Get(TestVariableName));
}
[Fact]
public void TestCanGetValueFromParentEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
parentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestCanGetValueFromGrandparentEnvironment() {
var grandparentEnvironment = new Environment();
var parentEnvironment = new Environment(grandparentEnvironment);
var childEnvironment = new Environment(parentEnvironment);
grandparentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestCannotGetValueFromChildEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
childEnvironment.Put(TestVariableName, TestVariableValue);
Assert.NotEqual(TestVariableValue, parentEnvironment.Get(TestVariableName));
}
}
}
| using Xunit;
using Squirrel;
using Squirrel.Nodes;
namespace Tests
{
public class EnvironmentTests
{
private static readonly string TestVariableName = "x";
private static readonly INode TestVariableValue = new IntegerNode(1);
[Fact]
public void TestGetValueFromCurrentEnvironment() {
var environment = new Environment();
environment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, environment.Get(TestVariableName));
}
[Fact]
public void TestGetValueFromParentEnvironment() {
var parentEnvironment = new Environment();
var childEnvironment = new Environment(parentEnvironment);
parentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
[Fact]
public void TestGetValueFromGrandparentEnvironment() {
var grandparentEnvironment = new Environment();
var parentEnvironment = new Environment(grandparentEnvironment);
var childEnvironment = new Environment(parentEnvironment);
grandparentEnvironment.Put(TestVariableName, TestVariableValue);
Assert.Equal(TestVariableValue, childEnvironment.Get(TestVariableName));
}
}
}
| mit | C# |
527a5f51d0238399d9f611a5a2f7ee369d792458 | Remove loglevel wrong example. This options isn't available for over half a year now. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/CommandLine/MixerCommand.cs | WalletWasabi.Gui/CommandLine/MixerCommand.cs | using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.CommandLine
{
internal class MixerCommand : Command
{
public string WalletName { get; set; }
public bool MixAll { get; set; }
public bool KeepMixAlive { get; set; }
public bool ShowHelp { get; set; }
public Daemon Daemon { get; }
public MixerCommand(Daemon daemon)
: base("mix", "Start mixing without the GUI with the specified wallet.")
{
Daemon = daemon;
Options = new OptionSet()
{
"usage: mix --wallet:WalletName --mixall --keepalive",
"",
"Start mixing without the GUI with the specified wallet.",
"eg: ./wassabee mix --wallet:MyWalletName --mixall --keepalive",
{ "h|help", "Displays help page and exit.", x => ShowHelp = x != null },
{ "w|wallet=", "The name of the wallet file.", x => WalletName = x },
{ "mixall", "Mix once even if the coin reached the target anonymity set specified in the config file.", x => MixAll = x != null },
{ "keepalive", "Do not exit the software after mixing has been finished, rather keep mixing when new money arrives.", x => KeepMixAlive = x != null }
};
}
public override async Task<int> InvokeAsync(IEnumerable<string> args)
{
var error = false;
try
{
var extra = Options.Parse(args);
if (ShowHelp)
{
Options.WriteOptionDescriptions(CommandSet.Out);
}
if (!error && !ShowHelp)
{
await Daemon.RunAsync(WalletName, MixAll, KeepMixAlive);
}
}
catch (Exception ex)
{
Console.WriteLine($"commands: There was a problem interpreting the command, please review it.");
Logger.LogDebug(ex);
error = true;
}
Environment.Exit(error ? 1 : 0);
return 0;
}
}
}
| using Mono.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.CommandLine
{
internal class MixerCommand : Command
{
public string WalletName { get; set; }
public bool MixAll { get; set; }
public bool KeepMixAlive { get; set; }
public bool ShowHelp { get; set; }
public Daemon Daemon { get; }
public MixerCommand(Daemon daemon)
: base("mix", "Start mixing without the GUI with the specified wallet.")
{
Daemon = daemon;
Options = new OptionSet()
{
"usage: mix --wallet:WalletName --mixall --keepalive",
"",
"Start mixing without the GUI with the specified wallet.",
"eg: ./wassabee mix --wallet:MyWalletName --mixall --keepalive --loglevel:info",
{ "h|help", "Displays help page and exit.", x => ShowHelp = x != null },
{ "w|wallet=", "The name of the wallet file.", x => WalletName = x },
{ "mixall", "Mix once even if the coin reached the target anonymity set specified in the config file.", x => MixAll = x != null },
{ "keepalive", "Do not exit the software after mixing has been finished, rather keep mixing when new money arrives.", x => KeepMixAlive = x != null }
};
}
public override async Task<int> InvokeAsync(IEnumerable<string> args)
{
var error = false;
try
{
var extra = Options.Parse(args);
if (ShowHelp)
{
Options.WriteOptionDescriptions(CommandSet.Out);
}
if (!error && !ShowHelp)
{
await Daemon.RunAsync(WalletName, MixAll, KeepMixAlive);
}
}
catch (Exception ex)
{
Console.WriteLine($"commands: There was a problem interpreting the command, please review it.");
Logger.LogDebug(ex);
error = true;
}
Environment.Exit(error ? 1 : 0);
return 0;
}
}
}
| mit | C# |
cfbd5c65aaacda482e5fc9efe47fc72dbd9415bb | fix inconsistent access modifier | Babblesort/GameOfLife | UI/GameForm.cs | UI/GameForm.cs | using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Engine;
using System.Threading;
namespace UI
{
public partial class GameForm : Form
{
private TaskScheduler _scheduler;
private Grid _grid;
public GameForm()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void GameForm_Load(object sender, EventArgs e)
{
_scheduler = TaskScheduler.FromCurrentSynchronizationContext();
_grid = new Grid(35, 35);
gamePanel.Grid = _grid;
}
private void btnRun_Click(object sender, EventArgs e)
{
var gaea = new Gaea(_grid, new Rules());
gaea.Run(UpdateGameVisualization);
}
private void UpdateGameVisualization(int generationNumber, Generation cells)
{
Task.Factory.StartNew(() => UpdateVisualization(generationNumber, cells),
CancellationToken.None,
TaskCreationOptions.None,
_scheduler);
}
private void UpdateVisualization(int generation, Generation cells)
{
lblGeneration.Text = generation.ToString();
gamePanel.Cells = cells;
}
}
}
| using System;
using System.Threading.Tasks;
using System.Windows.Forms;
using Engine;
using System.Threading;
namespace UI
{
public partial class GameForm : Form
{
TaskScheduler _scheduler;
private Grid _grid;
public GameForm()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
Environment.Exit(0);
}
private void GameForm_Load(object sender, EventArgs e)
{
_scheduler = TaskScheduler.FromCurrentSynchronizationContext();
_grid = new Grid(35, 35);
gamePanel.Grid = _grid;
}
private void btnRun_Click(object sender, EventArgs e)
{
var gaea = new Gaea(_grid, new Rules());
gaea.Run(UpdateGameVisualization);
}
private void UpdateGameVisualization(int generationNumber, Generation cells)
{
Task.Factory.StartNew(() => UpdateVisualization(generationNumber, cells),
CancellationToken.None,
TaskCreationOptions.None,
_scheduler);
}
private void UpdateVisualization(int generation, Generation cells)
{
lblGeneration.Text = generation.ToString();
gamePanel.Cells = cells;
}
}
}
| mit | C# |
98812f36143f2a8317e5961d85717a10594e1214 | Fix bug | warpzone81/ColouredCoins,warpzone81/ColouredCoins,warpzone81/ColouredCoins | WebApplication/Views/Shared/_Property.cshtml | WebApplication/Views/Shared/_Property.cshtml | @model IEnumerable<WebApplication.Models.PropertyViewModel>
@foreach (var item in Model) {
<div class="col-sm-6 col-md-3">
<div class="thumbnail text-default">
<div class="overlay-container">
<img src="assets/img/item-large.jpg">
<div class="overlay-content">
<h3 class="h4 headline">@Html.DisplayFor(modelItem => item.Name)</h3>
<p>@Html.DisplayFor(modelItem => item.Description)</p>
</div><!-- /.overlay-content -->
</div><!-- /.overlay-container -->
<div class="thumbnail-meta">
<p><i class="fa fa-fw fa-home"></i> 1199 Pacific Hwy #110</p>
<p><i class="fa fa-fw fa-map-marker"></i> San Diego, CA 92101</p>
</div>
<div class="thumbnail-meta">
<i class="fa fa-fw fa-info-circle"></i> @Html.DisplayFor(modelItem => item.FeatureSummary)
</div>
<div class="thumbnail-meta">
<i class="fa fa-fw fa-dollar"></i> <span class="h3 heading-default">@Html.DisplayFor(modelItem => item.Value)</span> @Html.ActionLink("Details", "Details", new { id = item.ID }) <a href="#link" class="btn btn-link pull-right">View <i class="fa fa-arrow-right"></i></a>
</div>
</div><!-- /.thumbnail -->
</div><!-- /.col -->
}
| @model IEnumerable<WebApplication.Models.PropertyViewModel>
@foreach (var item in Model) {
<div class="col-sm-6 col-md-3">
<div class="thumbnail text-default">
<div class="overlay-container">
<img src="assets/img/item-large.jpg">
<div class="overlay-content">
<h3 class="h4 headline">@Html.DisplayFor(modelItem => item.Name)</h3>
<p>@Html.DisplayFor(modelItem => item.Description)</p>
</div><!-- /.overlay-content -->
</div><!-- /.overlay-container -->
<div class="thumbnail-meta">
<p><i class="fa fa-fw fa-home"></i> 1199 Pacific Hwy #110</p>
<p><i class="fa fa-fw fa-map-marker"></i> San Diego, CA 92101</p>
</div>
<div class="thumbnail-meta">
<i class="fa fa-fw fa-info-circle"></i> @Html.DisplayFor(modelItem => modelItem.FeatureSummary)
</div>
<div class="thumbnail-meta">
<i class="fa fa-fw fa-dollar"></i> <span class="h3 heading-default">@Html.DisplayFor(modelItem => item.Value)</span> @Html.ActionLink("Details", "Details", new { id = item.ID }) <a href="#link" class="btn btn-link pull-right">View <i class="fa fa-arrow-right"></i></a>
</div>
</div><!-- /.thumbnail -->
</div><!-- /.col -->
}
| mit | C# |
093ec74551e225865e0ddcdf4728f2f99b339678 | rename variable | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.UI/Converters/BranchNameConverter.cs | src/GitHub.UI/Converters/BranchNameConverter.cs | using GitHub.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace GitHub.UI.Converters
{
public class BranchNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var branch = (IBranch)values[0];
var repo = (IRemoteRepositoryModel)branch.Repository;
var activeRepo = (IRepositoryModel)values[1];
if (repo.Parent == null && activeRepo.Owner != repo.Owner)
{
return repo.Owner + ":" + branch.Name;
}
return branch.DisplayName;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
}
| using GitHub.Models;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace GitHub.UI.Converters
{
public class BranchNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var branch = (IBranch)values[0];
var remoteRepo = (IRemoteRepositoryModel)branch.Repository;
var activeRepo = (IRepositoryModel)values[1];
if (remoteRepo.Parent == null && !String.Equals(activeRepo.Owner, remoteRepo.Owner))
{
return remoteRepo.Owner + ":" + branch.Name;
}
return branch.DisplayName;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
return null;
}
}
}
| mit | C# |
ea616e46209d3ec6f860873f75e5686bafab096d | Add AnyUnix to PlatformID enum. | schaabs/buildtools,ianhays/buildtools,tarekgh/buildtools,MattGal/buildtools,joperezr/buildtools,naamunds/buildtools,weshaggard/buildtools,MattGal/buildtools,jthelin/dotnet-buildtools,chcosta/buildtools,JeremyKuhne/buildtools,karajas/buildtools,roncain/buildtools,MattGal/buildtools,dotnet/buildtools,roncain/buildtools,venkat-raman251/buildtools,crummel/dotnet_buildtools,crummel/dotnet_buildtools,ericstj/buildtools,jthelin/dotnet-buildtools,naamunds/buildtools,alexperovich/buildtools,mmitche/buildtools,stephentoub/buildtools,nguerrera/buildtools,joperezr/buildtools,ianhays/buildtools,ChadNedzlek/buildtools,maririos/buildtools,schaabs/buildtools,venkat-raman251/buildtools,ChadNedzlek/buildtools,tarekgh/buildtools,FiveTimesTheFun/buildtools,naamunds/buildtools,mmitche/buildtools,pgavlin/buildtools,dotnet/buildtools,dotnet/buildtools,stephentoub/buildtools,mmitche/buildtools,weshaggard/buildtools,jhendrixMSFT/buildtools,weshaggard/buildtools,jthelin/dotnet-buildtools,AlexGhiondea/buildtools,tarekgh/buildtools,JeremyKuhne/buildtools,naamunds/buildtools,crummel/dotnet_buildtools,alexperovich/buildtools,MattGal/buildtools,nguerrera/buildtools,ericstj/buildtools,Priya91/buildtools,AlexGhiondea/buildtools,nguerrera/buildtools,crummel/dotnet_buildtools,ChadNedzlek/buildtools,AlexGhiondea/buildtools,eatdrinksleepcode/buildtools,chcosta/buildtools,AlexGhiondea/buildtools,ianhays/buildtools,joperezr/buildtools,karajas/buildtools,karajas/buildtools,chcosta/buildtools,tarekgh/buildtools,jhendrixMSFT/buildtools,maririos/buildtools,JeremyKuhne/buildtools,tarekgh/buildtools,MattGal/buildtools,joperezr/buildtools,jhendrixMSFT/buildtools,joperezr/buildtools,dotnet/buildtools,karajas/buildtools,mmitche/buildtools,stephentoub/buildtools,ianhays/buildtools,alexperovich/buildtools,schaabs/buildtools,maririos/buildtools,jhendrixMSFT/buildtools,nguerrera/buildtools,stephentoub/buildtools,mmitche/buildtools,schaabs/buildtools,ChadNedzlek/buildtools,chcosta/buildtools,ericstj/buildtools,JeremyKuhne/buildtools,roncain/buildtools,alexperovich/buildtools,ericstj/buildtools,mellinoe/buildtools,alexperovich/buildtools,jthelin/dotnet-buildtools,weshaggard/buildtools,maririos/buildtools,roncain/buildtools | src/xunit.netcore.extensions/PlatformID.cs | src/xunit.netcore.extensions/PlatformID.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit.Sdk;
namespace Xunit
{
[Flags]
public enum PlatformID
{
Windows = 1,
Linux = 2,
OSX = 4,
AnyUnix = Linux | OSX,
Any = Windows | Linux | OSX
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit.Sdk;
namespace Xunit
{
[Flags]
public enum PlatformID
{
Windows = 1,
Linux = 2,
OSX = 4,
Any = Windows | Linux | OSX
}
}
| mit | C# |
225a2ca5e6c4b483048466da5f5df7ac2f89e6c3 | Update build.cake | xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents | iOS/SwiftRuntimeSupport/build.cake | iOS/SwiftRuntimeSupport/build.cake |
#load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "ci"));
var SWIFT_RUNTIME_SUPPORT_VERSION = "0.2.1";
var SWIFT_RUNTIME_SUPPORT_NUGET_VERSION = SWIFT_RUNTIME_SUPPORT_VERSION;
Task ("externals")
.Does (() =>
{
// Update .csproj nuget versions
XmlPoke("./source/SwiftRuntimeSupport.csproj", "/Project/PropertyGroup/PackageVersion", SWIFT_RUNTIME_SUPPORT_NUGET_VERSION);
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
MSBuild("./SwiftRuntimeSupport.sln", c => {
c.Configuration = "Release";
c.Restore = true;
c.MaxCpuCount = 0;
});
});
Task("nuget")
.IsDependentOn("libs")
.Does(() =>
{
MSBuild ("./SwiftRuntimeSupport.sln", c => {
c.Configuration = "Release";
c.MaxCpuCount = 0;
c.Targets.Clear();
c.Targets.Add("Pack");
c.Properties.Add("PackageOutputPath", new [] { MakeAbsolute(new FilePath("./output")).FullPath });
c.Properties.Add("PackageRequireLicenseAcceptance", new [] { "true" });
c.Properties.Add("IncludeBuildOutput", new [] { "false" });
});
});
Task("samples")
.IsDependentOn("nuget");
Task("ci")
.IsDependentOn("externals")
.IsDependentOn("libs")
.IsDependentOn("nuget")
.IsDependentOn("samples");
RunTarget (TARGET);
|
#load "../../common.cake"
var TARGET = Argument ("t", Argument ("target", "Default"));
var SWIFT_RUNTIME_SUPPORT_VERSION = "0.2.1";
var SWIFT_RUNTIME_SUPPORT_NUGET_VERSION = SWIFT_RUNTIME_SUPPORT_VERSION;
Task ("externals")
.Does (() =>
{
// Update .csproj nuget versions
XmlPoke("./source/SwiftRuntimeSupport.csproj", "/Project/PropertyGroup/PackageVersion", SWIFT_RUNTIME_SUPPORT_NUGET_VERSION);
});
Task("libs")
.IsDependentOn("externals")
.Does(() =>
{
MSBuild("./SwiftRuntimeSupport.sln", c => {
c.Configuration = "Release";
c.Restore = true;
c.MaxCpuCount = 0;
});
});
Task("nuget")
.IsDependentOn("libs")
.Does(() =>
{
MSBuild ("./SwiftRuntimeSupport.sln", c => {
c.Configuration = "Release";
c.MaxCpuCount = 0;
c.Targets.Clear();
c.Targets.Add("Pack");
c.Properties.Add("PackageOutputPath", new [] { MakeAbsolute(new FilePath("./output")).FullPath });
c.Properties.Add("PackageRequireLicenseAcceptance", new [] { "true" });
c.Properties.Add("IncludeBuildOutput", new [] { "false" });
});
});
Task("samples")
.IsDependentOn("nuget");
RunTarget (TARGET);
| mit | C# |
2bd1737505b54849b373d114ee523d267d6dc8b7 | Remove unneeded code in the StorageEngineExtensions class | openchain/openchain | src/Openchain.Ledger/StorageEngineExtensions.cs | src/Openchain.Ledger/StorageEngineExtensions.cs | // Copyright 2015 Coinprism, 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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Openchain.Ledger
{
public static class StorageEngineExtensions
{
public static async Task<Record> GetRecord(this IStorageEngine store, RecordKey key)
{
IList<Record> result = await store.GetRecords(new[] { key.ToBinary() });
return result[0];
}
public static async Task<IReadOnlyDictionary<AccountKey, AccountStatus>> GetAccounts(this IStorageEngine store, IEnumerable<AccountKey> accounts)
{
IList<Record> records = await store.GetRecords(accounts.Select(account => account.Key.ToBinary()));
return records.Select(record => AccountStatus.FromRecord(RecordKey.Parse(record.Key), record)).ToDictionary(account => account.AccountKey, account => account);
}
}
}
| // Copyright 2015 Coinprism, 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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Openchain.Ledger
{
public static class StorageEngineExtensions
{
public static async Task<Record> GetRecord(this IStorageEngine store, RecordKey key)
{
IList<Record> result = await store.GetRecords(new[] { key.ToBinary() });
return result[0];
}
public static async Task<IReadOnlyDictionary<AccountKey, AccountStatus>> GetAccounts(this IStorageEngine store, IEnumerable<AccountKey> accounts)
{
IList<Record> records = await store.GetRecords(accounts.Select(account => account.Key.ToBinary()));
return records.Select(record => AccountStatus.FromRecord(RecordKey.Parse(record.Key), record)).ToDictionary(account => account.AccountKey, account => account);
}
public static async Task<AccountStatus> GetAccount(this IStorageEngine store, AccountKey account)
{
return (await store.GetAccounts(new[] { account })).First().Value;
}
}
}
| apache-2.0 | C# |
f4b970b2f9d0f176eea67fe6cbeb5f23aa54428d | Refactor rainbow example | OpenStreamDeck/StreamDeckSharp | src/StreamDeckSharp.Examples.Rainbow/Program.cs | src/StreamDeckSharp.Examples.Rainbow/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StreamDeckSharp.Examples.Rainbow
{
class Program
{
private static readonly Random rnd = new Random();
private static readonly ManualResetEvent exitSignal = new ManualResetEvent(false);
private static byte[] rgbBuffer = new byte[3];
static void Main(string[] args)
{
Console.CancelKeyPress += Console_CancelKeyPress;
using (var deck = StreamDeck.FromHID())
{
deck.SetBrightness(100);
Console.WriteLine("Connected. Now press some keys on the Stream Deck.");
deck.ClearKeys();
deck.KeyPressed += Deck_KeyPressed;
Console.WriteLine("To close the console app press Ctrl + C");
exitSignal.WaitOne();
}
}
private static void Deck_KeyPressed(object sender, StreamDeckKeyEventArgs e)
{
var d = sender as IStreamDeck;
if (d == null) return;
if (e.IsDown)
d.SetKeyBitmap(e.Key, GetRandomColorImage());
}
private static StreamDeckKeyBitmap GetRandomColorImage()
{
rnd.NextBytes(rgbBuffer);
return StreamDeckKeyBitmap.FromRGBColor(rgbBuffer[0], rgbBuffer[1], rgbBuffer[2]);
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
exitSignal.Set();
e.Cancel = true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace StreamDeckSharp.Examples.Rainbow
{
class Program
{
private static readonly Random rnd = new Random();
private static readonly ManualResetEvent exitSignal = new ManualResetEvent(false);
private static byte[] rgbBuffer = new byte[3];
static void Main(string[] args)
{
Console.CancelKeyPress += Console_CancelKeyPress;
using (var deck = StreamDeck.FromHID())
{
deck.SetBrightness(100);
Console.WriteLine("Connected. Now press some keys on the Stream Deck.");
deck.ClearKeys();
deck.KeyPressed += Deck_KeyPressed;
Console.WriteLine("To close the console app press Ctrl + C");
exitSignal.WaitOne();
}
}
private static void Deck_KeyPressed(object sender, StreamDeckKeyEventArgs e)
{
var d = sender as IStreamDeck;
if (d == null) return;
if (e.IsDown)
{
rnd.NextBytes(rgbBuffer);
var randomColor = StreamDeckKeyBitmap.FromRGBColor(rgbBuffer[0], rgbBuffer[1], rgbBuffer[2]);
d.SetKeyBitmap(e.Key, randomColor);
}
}
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
exitSignal.Set();
e.Cancel = true;
}
}
}
| mit | C# |
daa2517ce3f1e20d90805ba11709bb81e1cfaed5 | Build script corrections | nefarius/AirBender,nefarius/AirBender,nefarius/AirBender,nefarius/AirBender | build/Build.cs | build/Build.cs | using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;
class Build : NukeBuild
{
// Console application entry. Also defines the default target.
public static int Main () => Execute<Build>(x => x.Compile);
// Auto-injection fields:
// [GitVersion] readonly GitVersion GitVersion;
// - Semantic versioning. Must have 'GitVersion.CommandLine' referenced.
// [GitRepository] readonly GitRepository GitRepository;
// - Parses origin, branch name and head from git config.
// [Parameter] readonly string MyGetApiKey;
// - Returns command-line arguments and environment variables.
Target Clean => _ => _
.OnlyWhen(() => false) // Disabled for safety.
.Executes(() =>
{
DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj"));
EnsureCleanDirectory(OutputDirectory);
});
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
MSBuild(s => DefaultMSBuildRestore.SetTargetPlatform(MSBuildTargetPlatform.x64));
MSBuild(s => DefaultMSBuildRestore.SetTargetPlatform(MSBuildTargetPlatform.x86));
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
MSBuild(s => DefaultMSBuildCompile.SetTargetPlatform(MSBuildTargetPlatform.x64));
MSBuild(s => DefaultMSBuildCompile.SetTargetPlatform(MSBuildTargetPlatform.x86));
});
}
| using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;
class Build : NukeBuild
{
// Console application entry. Also defines the default target.
public static int Main () => Execute<Build>(x => x.Compile);
// Auto-injection fields:
// [GitVersion] readonly GitVersion GitVersion;
// - Semantic versioning. Must have 'GitVersion.CommandLine' referenced.
// [GitRepository] readonly GitRepository GitRepository;
// - Parses origin, branch name and head from git config.
// [Parameter] readonly string MyGetApiKey;
// - Returns command-line arguments and environment variables.
Target Clean => _ => _
.OnlyWhen(() => false) // Disabled for safety.
.Executes(() =>
{
DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj"));
EnsureCleanDirectory(OutputDirectory);
});
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
MSBuild(s => DefaultMSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() =>
{
MSBuild(s => DefaultMSBuildCompile.SetTargetPlatform(MSBuildTargetPlatform.x64));
MSBuild(s => DefaultMSBuildCompile.SetTargetPlatform(MSBuildTargetPlatform.x86));
});
}
| mit | C# |
aede24535ce51841460d334d57cbecf5d61a1ed3 | Add regions to CommitListExtensionsTest. | CamTechConsultants/CvsntGitImporter | CvsGitTest/CommitListExtensionsTest.cs | CvsGitTest/CommitListExtensionsTest.cs | /*
* John Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CvsGitConverter;
namespace CvsGitTest
{
/// <summary>
/// Unit tests for the CommitListExtensions class.
/// </summary>
[TestClass]
public class CommitListExtensionsTest
{
#region Move
[TestMethod]
public void Move_FirstItem()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(0, 3);
Assert.IsTrue(list.SequenceEqual(new[] { 2, 3, 4, 1, 5 }));
}
[TestMethod]
public void Move_ToEnd()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(2, 4);
Assert.IsTrue(list.SequenceEqual(new[] { 1, 2, 4, 5, 3 }));
}
[TestMethod]
public void Move_ToSelf()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(2, 2);
Assert.IsTrue(list.SequenceEqual(new[] { 1, 2, 3, 4, 5 }));
}
#endregion Move
#region IndexOfFromEnd
[TestMethod]
public void IndexOfFromEnd_NotFound()
{
var list = new List<int>() { 1, 2, 3 };
var result = list.IndexOfFromEnd(3, 1);
Assert.AreEqual(result, -1);
}
[TestMethod]
public void IndexOfFromEnd_Found()
{
var list = new List<int>() { 1, 2, 3, 4 };
var result = list.IndexOfFromEnd(2, 3);
Assert.AreEqual(result, 1);
}
#endregion IndexOfFromEnd
#region ToListIfNeeded
[TestMethod]
public void ToListIfNeeded_NotAList()
{
var list = Enumerable.Repeat(1, 5);
var ilist = list.ToListIfNeeded();
Assert.AreNotSame(list, ilist);
}
[TestMethod]
public void ToListIfNeeded_IsAList()
{
var list = Enumerable.Repeat(1, 5).ToList();
var ilist = list.ToListIfNeeded();
Assert.AreSame(list, ilist);
}
#endregion ToListIfNeeded
}
} | /*
* John Hall <john.hall@camtechconsultants.com>
* Copyright (c) Cambridge Technology Consultants Ltd. All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CvsGitConverter;
namespace CvsGitTest
{
/// <summary>
/// Unit tests for the CommitListExtensions class.
/// </summary>
[TestClass]
public class CommitListExtensionsTest
{
[TestMethod]
public void Move_FirstItem()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(0, 3);
Assert.IsTrue(list.SequenceEqual(new[] { 2, 3, 4, 1, 5 }));
}
[TestMethod]
public void Move_ToEnd()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(2, 4);
Assert.IsTrue(list.SequenceEqual(new[] { 1, 2, 4, 5, 3 }));
}
[TestMethod]
public void Move_ToSelf()
{
var list = new List<int>() { 1, 2, 3, 4, 5 };
list.Move(2, 2);
Assert.IsTrue(list.SequenceEqual(new[] { 1, 2, 3, 4, 5 }));
}
[TestMethod]
public void IndexOfFromEnd_NotFound()
{
var list = new List<int>() { 1, 2, 3 };
var result = list.IndexOfFromEnd(3, 1);
Assert.AreEqual(result, -1);
}
[TestMethod]
public void IndexOfFromEnd_Found()
{
var list = new List<int>() { 1, 2, 3, 4 };
var result = list.IndexOfFromEnd(2, 3);
Assert.AreEqual(result, 1);
}
[TestMethod]
public void ToListIfNeeded_NotAList()
{
var list = Enumerable.Repeat(1, 5);
var ilist = list.ToListIfNeeded();
Assert.AreNotSame(list, ilist);
}
[TestMethod]
public void ToListIfNeeded_IsAList()
{
var list = Enumerable.Repeat(1, 5).ToList();
var ilist = list.ToListIfNeeded();
Assert.AreSame(list, ilist);
}
}
} | mit | C# |
7ce1c1bd4222d4b2bca360acf5169eed011e3fed | Fix DatabaseHelperFactory | lecaillon/Evolve | src/Evolve/Dialect/DatabaseHelperFactory.cs | src/Evolve/Dialect/DatabaseHelperFactory.cs | using System;
using System.Collections.Generic;
using Evolve.Connection;
using Evolve.Dialect.PostgreSQL;
using Evolve.Dialect.SQLite;
using Evolve.Utilities;
namespace Evolve.Dialect
{
public static class DatabaseHelperFactory
{
private const string UnknownDBMS = "Unknown DBMS {0}.";
private static Dictionary<DBMS, Func<WrappedConnection, DatabaseHelper>> _dbmsMap = new Dictionary<DBMS, Func<WrappedConnection, DatabaseHelper>>
{
[DBMS.SQLite] = wcnn => new SQLiteDatabase(wcnn),
[DBMS.PostgreSQL] = wcnn => new PostgreSQLDatabase(wcnn),
};
public static DatabaseHelper GetDatabaseHelper(DBMS dbmsType, WrappedConnection connection)
{
Check.NotNull(connection, nameof(connection));
_dbmsMap.TryGetValue(dbmsType, out Func<WrappedConnection, DatabaseHelper> dbHelperCreationDelegate);
if(dbHelperCreationDelegate == null)
{
throw new EvolveException(string.Format(UnknownDBMS, dbmsType));
}
return dbHelperCreationDelegate(connection);
}
}
}
| using System;
using System.Collections.Generic;
using Evolve.Connection;
using Evolve.Dialect.PostgreSQL;
using Evolve.Dialect.SQLite;
namespace Evolve.Dialect
{
public static class DatabaseHelperFactory
{
private static Dictionary<DBMS, Func<WrappedConnection, DatabaseHelper>> _dbmsMap = new Dictionary<DBMS, Func<WrappedConnection, DatabaseHelper>>
{
[DBMS.SQLite] = wcnn => new SQLiteDatabase(wcnn),
[DBMS.PostgreSQL] = wcnn => new PostgreSQLDatabase(wcnn),
};
public static DatabaseHelper GetDatabaseHelper(DBMS dbmsType, WrappedConnection connection)
{
_dbmsMap.TryGetValue(dbmsType, out Func<WrappedConnection, DatabaseHelper> dbHelperCreationDelegate);
if(dbHelperCreationDelegate == null)
{
}
return dbHelperCreationDelegate(connection);
}
}
}
| mit | C# |
17f832a33fc4602b7204c3394ce7f365a8555483 | Add some more chain command tests | InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET | src/InEngine.Core.Test/Commands/ChainTest.cs | src/InEngine.Core.Test/Commands/ChainTest.cs | using System.Collections.Generic;
using BeekmanLabs.UnitTesting;
using InEngine.Commands;
using InEngine.Core.Commands;
using InEngine.Core.Exceptions;
using Moq;
using NUnit.Framework;
using Quartz;
namespace InEngine.Core.Test.Commands
{
[TestFixture]
public class ChainTest : TestBase<Chain>
{
[SetUp]
public void Setup()
{
}
[Test]
public void ShouldRunChainOfCommands()
{
var mockCommand1 = new Mock<AbstractCommand>();
var mockCommand2 = new Mock<AbstractCommand>();
var commands = new[] {
mockCommand1.Object,
mockCommand2.Object,
};
Subject.Commands = commands;
Subject.Run();
mockCommand1.Verify(x => x.Run(), Times.Once());
mockCommand2.Verify(x => x.Run(), Times.Once());
}
[Test]
public void ShouldRunChainOfCommandsAndFail()
{
var mockCommand1 = new Mock<AlwaysFail>();
var mockCommand2 = new Mock<AlwaysFail>();
var alwaysFail = new AlwaysFail();
var commands = new[] {
mockCommand1.Object,
new AlwaysFail(),
mockCommand2.Object,
};
Subject.Commands = commands;
Assert.That(Subject.Run, Throws.TypeOf<CommandChainFailedException>());
mockCommand1.Verify(x => x.Run(), Times.Once());
mockCommand2.Verify(x => x.Run(), Times.Never());
}
[Test]
public void ShouldRunChainOfDifferentCommands()
{
Subject.Commands = new List<AbstractCommand>() {
new AlwaysSucceed(),
new Echo() { VerbatimText = "Hello, world!"},
};
Subject.Run();
}
[Test]
public void ShouldRunChainOfDifferentCommandsAsAbstractCommand()
{
Subject.Commands = new[] {
new AlwaysSucceed() as AbstractCommand,
new Echo() { VerbatimText = "Hello, world!"} as AbstractCommand,
};
Subject.Run();
}
}
}
| using BeekmanLabs.UnitTesting;
using InEngine.Commands;
using InEngine.Core.Commands;
using InEngine.Core.Exceptions;
using Moq;
using NUnit.Framework;
using Quartz;
namespace InEngine.Core.Test.Commands
{
[TestFixture]
public class ChainTest : TestBase<Chain>
{
[SetUp]
public void Setup()
{
}
[Test]
public void ShouldRunChainOfCommands()
{
var mockCommand1 = new Mock<AbstractCommand>();
var mockCommand2 = new Mock<AbstractCommand>();
var commands = new[] {
mockCommand1.Object,
mockCommand2.Object,
};
Subject.Commands = commands;
Subject.Run();
mockCommand1.Verify(x => x.Run(), Times.Once());
mockCommand2.Verify(x => x.Run(), Times.Once());
}
[Test]
public void ShouldRunChainOfCommandsAndFail()
{
var mockCommand1 = new Mock<AlwaysFail>();
var mockCommand2 = new Mock<AlwaysFail>();
var alwaysFail = new AlwaysFail();
var commands = new[] {
mockCommand1.Object,
new AlwaysFail(),
mockCommand2.Object,
};
Subject.Commands = commands;
Assert.That(Subject.Run, Throws.TypeOf<CommandChainFailedException>());
mockCommand1.Verify(x => x.Run(), Times.Once());
mockCommand2.Verify(x => x.Run(), Times.Never());
}
}
}
| mit | C# |
b8c6547139b803b2ccfa60fa5702da47ee0c6ea1 | Use CORS (#25) | RikkiGibson/Corvallis-Bus-Server,RikkiGibson/Corvallis-Bus-Server | CorvallisBus.Web/Startup.cs | CorvallisBus.Web/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CorvallisBus.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(builder => builder.AllowAnyOrigin());
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace CorvallisBus.Web
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
}
}
| mit | C# |
26e0f45a1cf0b856acfd4218956d0f0b77a748ba | Fix benchmark to really have an invalid value. | BenJenkinson/nodatime,malcolmr/nodatime,jskeet/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,nodatime/nodatime,zaccharles/nodatime,nodatime/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,jskeet/nodatime,zaccharles/nodatime | src/NodaTime.Benchmarks/OffsetBenchmarks.cs | src/NodaTime.Benchmarks/OffsetBenchmarks.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using NodaTime.Benchmarks.Timing;
using NodaTime.Format;
using NodaTime.Globalization;
using System.Globalization;
namespace NodaTime.Benchmarks
{
internal class OffsetBenchmarks
{
private static readonly NodaFormatInfo InvariantFormatInfo = NodaFormatInfo.GetFormatInfo(CultureInfo.InvariantCulture);
[Benchmark]
public void TryParseExact_Valid()
{
Offset result;
Offset.TryParseExact("12:34", "HH:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
[Benchmark]
public void TryParseExact_InvalidFormat()
{
Offset result;
Offset.TryParseExact("12:34", "bb:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
[Benchmark]
public void TryParseExact_InvalidValue()
{
Offset result;
Offset.TryParseExact("123:45", "HH:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
}
}
| #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2011 Jon Skeet
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using NodaTime.Benchmarks.Timing;
using NodaTime.Format;
using NodaTime.Globalization;
using System.Globalization;
namespace NodaTime.Benchmarks
{
internal class OffsetBenchmarks
{
private static readonly NodaFormatInfo InvariantFormatInfo = NodaFormatInfo.GetFormatInfo(CultureInfo.InvariantCulture);
[Benchmark]
public void TryParseExact_Valid()
{
Offset result;
Offset.TryParseExact("12:34", "HH:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
[Benchmark]
public void TryParseExact_InvalidFormat()
{
Offset result;
Offset.TryParseExact("12:34", "bb:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
[Benchmark]
public void TryParseExact_InvalidValue()
{
Offset result;
Offset.TryParseExact("35:34", "HH:mm", InvariantFormatInfo, DateTimeParseStyles.None, out result);
}
}
}
| apache-2.0 | C# |
b88ccde71ebee073126c760273572960b12157ed | Add `Delta` property to `DragStartEvent`s | peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Input/Events/DragStartEvent.cs | osu.Framework/Input/Events/DragStartEvent.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.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.Events
{
/// <summary>
/// An event representing the start of a mouse drag.
/// </summary>
public class DragStartEvent : MouseButtonEvent
{
/// <summary>
/// The difference from mouse down position to current position in local space.
/// </summary>
public Vector2 Delta => MousePosition - MouseDownPosition;
public DragStartEvent(InputState state, MouseButton button, Vector2? screenSpaceMouseDownPosition = null)
: base(state, button, screenSpaceMouseDownPosition)
{
}
}
}
| // 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.Input.States;
using osuTK;
using osuTK.Input;
namespace osu.Framework.Input.Events
{
/// <summary>
/// An event representing the start of a mouse drag.
/// </summary>
public class DragStartEvent : MouseButtonEvent
{
public DragStartEvent(InputState state, MouseButton button, Vector2? screenSpaceMouseDownPosition = null)
: base(state, button, screenSpaceMouseDownPosition)
{
}
}
}
| mit | C# |
a8dfa5e2a9b09e07893c83fb410b0c669e6868a5 | Rename typo'd method | UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu | osu.Game/Online/Rooms/BeatmapAvailability.cs | osu.Game/Online/Rooms/BeatmapAvailability.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 Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly double? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, double? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(double progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Downloaded() => new BeatmapAvailability(DownloadState.Downloaded);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
| // 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 Newtonsoft.Json;
namespace osu.Game.Online.Rooms
{
/// <summary>
/// The local availability information about a certain beatmap for the client.
/// </summary>
public class BeatmapAvailability : IEquatable<BeatmapAvailability>
{
/// <summary>
/// The beatmap's availability state.
/// </summary>
public readonly DownloadState State;
/// <summary>
/// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state.
/// </summary>
public readonly double? DownloadProgress;
[JsonConstructor]
private BeatmapAvailability(DownloadState state, double? downloadProgress = null)
{
State = state;
DownloadProgress = downloadProgress;
}
public static BeatmapAvailability NotDownload() => new BeatmapAvailability(DownloadState.NotDownloaded);
public static BeatmapAvailability Downloading(double progress) => new BeatmapAvailability(DownloadState.Downloading, progress);
public static BeatmapAvailability Downloaded() => new BeatmapAvailability(DownloadState.Downloaded);
public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable);
public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress;
public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}";
}
}
| mit | C# |
5a2c8b29151d186570f36323835c8c0c2618fec2 | Reset stopwatch on Start instead of Pause | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/Models/Variant960/Clock.cs | src/ChessVariantsTraining/Models/Variant960/Clock.cs | using MongoDB.Bson.Serialization.Attributes;
using System.Diagnostics;
namespace ChessVariantsTraining.Models.Variant960
{
public class Clock
{
Stopwatch stopwatch;
[BsonElement("secondsLeftAfterLatestMove")]
public double SecondsLeftAfterLatestMove
{
get;
set;
}
[BsonElement("increment")]
public int Increment
{
get;
set;
}
public Clock()
{
stopwatch = new Stopwatch();
}
public Clock(TimeControl tc) : this()
{
Increment = tc.Increment;
SecondsLeftAfterLatestMove = tc.InitialSeconds;
}
public void Start()
{
stopwatch.Reset();
stopwatch.Start();
}
public void Pause()
{
stopwatch.Stop();
}
public void AddIncrement()
{
SecondsLeftAfterLatestMove += Increment;
}
public void MoveMade()
{
Pause();
AddIncrement();
SecondsLeftAfterLatestMove = GetSecondsLeft();
}
public double GetSecondsLeft()
{
return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds;
}
}
}
| using MongoDB.Bson.Serialization.Attributes;
using System.Diagnostics;
namespace ChessVariantsTraining.Models.Variant960
{
public class Clock
{
Stopwatch stopwatch;
[BsonElement("secondsLeftAfterLatestMove")]
public double SecondsLeftAfterLatestMove
{
get;
set;
}
[BsonElement("increment")]
public int Increment
{
get;
set;
}
public Clock()
{
stopwatch = new Stopwatch();
}
public Clock(TimeControl tc) : this()
{
Increment = tc.Increment;
SecondsLeftAfterLatestMove = tc.InitialSeconds;
}
public void Start()
{
stopwatch.Start();
}
public void Pause()
{
stopwatch.Stop();
stopwatch.Reset();
}
public void AddIncrement()
{
SecondsLeftAfterLatestMove += Increment;
}
public void MoveMade()
{
Pause();
AddIncrement();
SecondsLeftAfterLatestMove = GetSecondsLeft();
}
public double GetSecondsLeft()
{
return SecondsLeftAfterLatestMove - stopwatch.Elapsed.TotalSeconds;
}
}
}
| agpl-3.0 | C# |
98a3bac23d4dd1a95429ba95ec1132dc476055ad | remove array | Appleseed/base,Appleseed/base | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string code_info { get; set; }
public string[] reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string[] recall_number { get; set; }
public string recalling_firm { get; set; }
public string[] voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string[] status { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Appleseed.Base.Alerts.Model
{
class SolrResponseItem
{
public string id { get; set; }
public string item_type { get; set; }
public string address_1 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string classification { get; set; }
public string country { get; set; }
public string postal_code { get; set; }
public string product_description { get; set; }
public string product_quantity { get; set; }
public string product_type { get; set; }
public string[] code_info { get; set; }
public string[] reason_for_recall { get; set; }
public DateTime recall_initiation_date { get; set; }
public string[] recall_number { get; set; }
public string recalling_firm { get; set; }
public string[] voluntary_mandated { get; set; }
public DateTime report_date { get; set; }
public string[] status { get; set; }
}
}
| apache-2.0 | C# |
fbf3c0130bc9776f30e1044222e47a4b568f17b0 | Add VariableParser to the main parser | Seddryck/NBi,Seddryck/NBi | NBi.genbiL/Parser/Action.cs | NBi.genbiL/Parser/Action.cs | using NBi.GenbiL.Action;
using Sprache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.GenbiL.Parser
{
class Action
{
public readonly static Parser<IAction> Parser =
(
from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser.Or(Variable.Parser))))
from terminator in Grammar.Terminator.AtLeastOnce()
select sentence
);
}
}
| using NBi.GenbiL.Action;
using Sprache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.GenbiL.Parser
{
class Action
{
public readonly static Parser<IAction> Parser =
(
from sentence in Case.Parser.Or(Setting.Parser.Or(Suite.Parser.Or(Template.Parser)))
from terminator in Grammar.Terminator.AtLeastOnce()
select sentence
);
}
}
| apache-2.0 | C# |
655c037c17e7bf65c2f6e587c557ae7ff633bf0d | Update InputHandler.cs | dabbertorres/ObjRenderer | ObjRenderer/InputHandler.cs | ObjRenderer/InputHandler.cs | using System;
using System.Collections.Generic;
using OpenTK;
using System.Windows.Forms;
namespace ObjRenderer
{
public class InputHandler
{
public delegate void KeyPressed(Enum flags);
public delegate void MousePressed(int x, int y);
public delegate void MouseWheelMoved(int delta);
public delegate void MouseMoved(int x, int y);
public delegate void FileDropped(string file);
public readonly Dictionary<Keys, KeyPressed> keyDownListeners;
public readonly Dictionary<Keys, KeyPressed> keyUpListeners;
public readonly Dictionary<MouseButtons, MousePressed> mouseDownListeners;
public readonly Dictionary<MouseButtons, MousePressed> mouseUpListeners;
public event MouseWheelMoved mouseWheelMoved;
public event MouseMoved mouseMoved;
public event FileDropped fileDropped;
public InputHandler(GLControl glControl)
{
glControl.KeyDown += KeyDown;
glControl.KeyUp += KeyUp;
glControl.MouseDown += MouseDown;
glControl.MouseUp += MouseUp;
glControl.MouseWheel += MouseWheel;
glControl.MouseMove += MouseMove;
glControl.DragDrop += DragDrop;
keyDownListeners = new Dictionary<Keys, KeyPressed>();
keyUpListeners = new Dictionary<Keys, KeyPressed>();
mouseDownListeners = new Dictionary<MouseButtons, MousePressed>();
mouseUpListeners = new Dictionary<MouseButtons, MousePressed>();
}
private void KeyDown(object sender, KeyEventArgs e)
{
if (keyDownListeners.ContainsKey(e.KeyCode))
{
keyDownListeners[e.KeyCode].Invoke(e.Modifiers);
}
e.Handled = true;
}
private void KeyUp(object sender, KeyEventArgs e)
{
if (keyUpListeners.ContainsKey(e.KeyCode))
{
keyUpListeners[e.KeyCode].Invoke(e.Modifiers);
}
e.Handled = true;
}
private void MouseDown(object sender, MouseEventArgs e)
{
if (mouseDownListeners.ContainsKey(e.Button))
{
mouseDownListeners[e.Button].Invoke(e.X, e.Y);
}
}
private void MouseUp(object sender, MouseEventArgs e)
{
if (mouseUpListeners.ContainsKey(e.Button))
{
mouseUpListeners[e.Button].Invoke(e.X, e.Y);
}
}
private void MouseWheel(object sender, MouseEventArgs e)
{
if (mouseWheelMoved.GetInvocationList().Length != 0)
{
mouseWheelMoved.Invoke(e.Delta);
}
}
private void MouseMove(object sender, MouseEventArgs e)
{
if(mouseMoved.GetInvocationList().Length != 0)
{
mouseMoved.Invoke(e.X, e.Y);
}
}
private void DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
fileDropped.Invoke((string)e.Data.GetData(DataFormats.FileDrop));
}
}
}
}
| using System;
using System.Collections.Generic;
using OpenTK;
using System.Windows.Forms;
namespace ObjRenderer
{
public class InputHandler
{
public delegate void KeyPressed(Enum flags);
public delegate void MousePressed(int x, int y);
public delegate void MouseWheelMoved(int delta);
public delegate void MouseMoved(int x, int y);
public delegate void FileDropped(string file);
public readonly Dictionary<Keys, KeyPressed> keyDownListeners;
public readonly Dictionary<Keys, KeyPressed> keyUpListeners;
public readonly Dictionary<MouseButtons, MousePressed> mouseDownListeners;
public readonly Dictionary<MouseButtons, MousePressed> mouseUpListeners;
public event MouseWheelMoved mouseWheelMoved;
public event MouseMoved mouseMoved;
public event FileDropped fileDropped;
public InputHandler(GLControl glControl)
{
glControl.KeyDown += KeyDown;
glControl.KeyUp += KeyUp;
glControl.MouseDown += MouseDown;
glControl.MouseUp += MouseUp;
glControl.MouseWheel += MouseWheel;
glControl.MouseMove += MouseMove;
glControl.DragDrop += DragDrop;
keyDownListeners = new Dictionary<Keys, KeyPressed>();
keyUpListeners = new Dictionary<Keys, KeyPressed>();
mouseDownListeners = new Dictionary<MouseButtons, MousePressed>();
mouseUpListeners = new Dictionary<MouseButtons, MousePressed>();
}
private void KeyDown(object sender, KeyEventArgs e)
{
if (keyDownListeners.ContainsKey(e.KeyCode))
{
keyDownListeners[e.KeyCode].Invoke(e.Modifiers);
}
e.Handled = true;
}
private void KeyUp(object sender, KeyEventArgs e)
{
if (keyUpListeners.ContainsKey(e.KeyCode))
{
keyUpListeners[e.KeyCode].Invoke(e.Modifiers);
}
e.Handled = true;
}
private void MouseDown(object sender, MouseEventArgs e)
{
if (mouseDownListeners.ContainsKey(e.Button))
{
mouseDownListeners[e.Button].Invoke(e.X, e.Y);
}
}
private void MouseUp(object sender, MouseEventArgs e)
{
if (mouseUpListeners.ContainsKey(e.Button))
{
mouseUpListeners[e.Button].Invoke(e.X, e.Y);
}
}
private void MouseWheel(object sender, MouseEventArgs e)
{
if (mouseWheelMoved.GetInvocationList().Length != 0)
{
mouseWheelMoved.Invoke(e.Delta);
}
}
private void MouseMove(object sender, MouseEventArgs e)
{
if(mouseMoved.GetInvocationList().Length != 0)
{
mouseMoved.Invoke(e.X, e.Y);
}
}
private void DragDrop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
fileDropped.Invoke((string)e.Data.GetData(DataFormats.FileDrop));
}
}
}
}
| mit | C# |
7e6f7208b89d7e2bc3cfeda31e1a0db59d56a8f1 | fix corniflex shit PR | Sirush/UDHBot,Sirush/UDHBot | Skin/XpBarInfoSkinModule.cs | Skin/XpBarInfoSkinModule.cs | using System;
using DiscordBot.Domain;
using ImageMagick;
namespace DiscordBot.Skin
{
public class XpBarInfoSkinModule : BaseTextSkinModule
{
public override Drawables GetDrawables(ProfileData data)
{
Text = $"{data.XpShown:#,##0} / {data.MaxXpShown:N0} ({Math.Floor(data.XpPercentage * 100):0}%)";
return base.GetDrawables(data);
}
public XpBarInfoSkinModule()
{
StrokeWidth = 1;
FillColor = MagickColors.Black.ToString();
StrokeColor = MagickColors.Transparent.ToString();
FontPointSize = 17;
}
}
}
| using DiscordBot.Domain;
using ImageMagick;
namespace DiscordBot.Skin
{
public class XpBarInfoSkinModule : BaseTextSkinModule
{
public override Drawables GetDrawables(ProfileData data)
{
Text = $"{data.XpShown:#,##0} / {data.MaxXpShown:N0} ({Math.Floor(data.XpPercentage * 100):0}%)";
return base.GetDrawables(data);
}
public XpBarInfoSkinModule()
{
StrokeWidth = 1;
FillColor = MagickColors.Black.ToString();
StrokeColor = MagickColors.Transparent.ToString();
FontPointSize = 17;
}
}
}
| mit | C# |
877790f38a0f80b67e6a434cbb3fa9f47eea6774 | reset to v1 | shiftkey/Shimmer.Samples | src/desktop/DesktopSample/Properties/AssemblyInfo.cs | src/desktop/DesktopSample/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Shimmer.DesktopDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shimmer.DesktopDemo")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Shimmer.DesktopDemo")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Shimmer.DesktopDemo")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
73b40a01fc2d908f9b6ad21bdd66ec3ad8a16513 | Fix Bug IStyle | chickeaterbanana/BBT-MindMap | BBT/IStyle.cs | BBT/IStyle.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace BBT
{
interface IStyle
{
/// <summary>
///
/// </summary>
/// <returns>Farbe und True, wenn gefüllt</returns>
Tuple<Color, bool> getColor();
void setColor(Tuple<Color, bool> color);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
namespace BBT
{
interface IStyle
{
/// <summary>
///
/// </summary>
/// <returns>Farbe und True, wenn gefüllt</returns>
Tuple<Color, bool> getColor();
void setColor(Tuple<Color, bool);
}
}
| mit | C# |
2771241f3652aa04fd4a621439483ca6c45940a6 | Resolve #AG41 and WIP #AG52 - Assign ticket to type as it is created | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.ObjectMaps/Tickets/TicketTypeToTicketTypeDtoProfile.cs | Agiil.ObjectMaps/Tickets/TicketTypeToTicketTypeDtoProfile.cs | using System;
using Agiil.Domain.Tickets;
using Agiil.ObjectMaps.Resolvers;
using Agiil.Web.Models.Tickets;
using AutoMapper;
namespace Agiil.ObjectMaps.Tickets
{
public class TicketTypeToTicketTypeDtoProfile : Profile
{
public TicketTypeToTicketTypeDtoProfile()
{
CreateMap<TicketType,TicketTypeDto>()
.ForMember(x => x.Id, opts => opts.ResolveUsing<IdentityValueResolver>());
}
}
}
| using System;
using Agiil.Domain.Tickets;
using Agiil.Web.Models.Tickets;
using AutoMapper;
namespace Agiil.ObjectMaps.Tickets
{
public class TicketTypeToTicketTypeDtoProfile : Profile
{
public TicketTypeToTicketTypeDtoProfile()
{
CreateMap<TicketType,TicketTypeDto>();
}
}
}
| mit | C# |
65c35f9f25f95e7b021a4e0f16707ec7c3ddcd7a | remove unused minimize functionality from ConcatenatedScript | rolembergfilho/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,TukekeSoft/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,TukekeSoft/Serenity,volkanceylan/Serenity,TukekeSoft/Serenity,linpiero/Serenity,linpiero/Serenity,linpiero/Serenity,linpiero/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,dfaruque/Serenity,volkanceylan/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,TukekeSoft/Serenity,linpiero/Serenity,WasimAhmad/Serenity,dfaruque/Serenity,volkanceylan/Serenity | Serenity.Web/Script/DynamicScriptTypes/ConcatenatedScript.cs | Serenity.Web/Script/DynamicScriptTypes/ConcatenatedScript.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Serenity.Web
{
public class ConcatenatedScript : IDynamicScript
{
private EventHandler scriptChanged;
private IEnumerable<Func<string>> scriptParts;
public ConcatenatedScript(IEnumerable<Func<string>> scriptParts)
{
if (scriptParts == null)
throw new ArgumentNullException("scriptParts");
this.scriptParts = scriptParts;
}
public string GetScript()
{
StringBuilder sb = new StringBuilder();
foreach (var part in scriptParts)
{
string partSource = part();
sb.AppendLine(partSource);
sb.AppendLine("\r\n");
}
return sb.ToString();
}
public void CheckRights()
{
}
public void Changed()
{
if (scriptChanged != null)
scriptChanged(this, new EventArgs());
}
public bool NonCached
{
get { return false; }
}
public event EventHandler ScriptChanged
{
add { scriptChanged += value; }
remove { scriptChanged -= value; }
}
}
} | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Serenity.Web
{
public class ConcatenatedScript : IDynamicScript
{
private bool minimize;
private EventHandler scriptChanged;
private IEnumerable<Func<string>> scriptParts;
public ConcatenatedScript(
IEnumerable<Func<string>> scriptParts)
{
if (scriptParts == null)
throw new ArgumentNullException("scriptParts");
this.scriptParts = scriptParts;
}
public bool Minimize
{
get { return minimize; }
set
{
if (minimize != value)
{
minimize = value;
Changed();
}
}
}
public string GetScript()
{
StringBuilder sb = new StringBuilder();
foreach (var part in scriptParts)
{
string partSource = part();
/*if (minimize)
{
try
{
partSource = JavaScriptMinifier.Minify(partSource);
}
catch
{
// ignore minification errors
}
}*/
sb.AppendLine(partSource);
sb.AppendLine("\r\n");
}
return sb.ToString();
}
public void CheckRights()
{
}
public void Changed()
{
if (scriptChanged != null)
scriptChanged(this, new EventArgs());
}
public bool NonCached
{
get { return false; }
}
public event EventHandler ScriptChanged
{
add { scriptChanged += value; }
remove { scriptChanged -= value; }
}
}
} | mit | C# |
4db68cd7c9d5062d7acc8423fa87da2dc7ebcb62 | Fix comment | Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module | Activities/ManagePersonsPermissionCheckerTask.cs | Activities/ManagePersonsPermissionCheckerTask.cs | using Lombiq.TrainingDemo.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Localization;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Lombiq.TrainingDemo.Activities;
// A simple workflow task that accepts a username as a TextField input and checks whether the user has ManagePersons Permission or not.
public class ManagePersonsPermissionCheckerTask : TaskActivity
{
private readonly IAuthorizationService _authorizationService;
private readonly IUserService _userService;
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;
private readonly IStringLocalizer S;
public ManagePersonsPermissionCheckerTask(
IAuthorizationService authorizationService,
IUserService userService,
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<ManagePersonsPermissionCheckerTask> localizer)
{
_authorizationService = authorizationService;
_userService = userService;
_expressionEvaluator = expressionEvaluator;
S = localizer;
}
// The technical name of the activity. Activities on a workflow definition reference this name.
public override string Name => nameof(ManagePersonsPermissionCheckerTask);
// The displayed name of the activity, so it can use localization.
public override LocalizedString DisplayText => S["Manage Persons Permission Checker Task"];
// The category to which this activity belongs. The activity picker groups activities by this category.
public override LocalizedString Category => S["User"];
// The username to evaluate for ManagePersons permission.
public WorkflowExpression<string> UserName
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
// Returns the possible outcomes of this activity.
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Outcomes(S["HasPermission"], S["NoPermission"]);
}
// This is the heart of the activity and actually performs the work to be done.
public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var userName = await _expressionEvaluator.EvaluateAsync(UserName, workflowContext, null);
User user = (User)await _userService.GetUserAsync(userName);
if (user != null)
{
var userClaim = await _userService.CreatePrincipalAsync(user);
if (await _authorizationService.AuthorizeAsync(userClaim, PersonPermissions.ManagePersons))
{
return Outcomes("HasPermission");
}
}
return Outcomes("NoPermission");
}
}
// NEXT STATION: ViewModels/ManagePersonsPermissionCheckerTaskViewModel.cs
| using Lombiq.TrainingDemo.Permissions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OrchardCore.Users.Models;
using OrchardCore.Users.Services;
using OrchardCore.Workflows.Abstractions.Models;
using OrchardCore.Workflows.Activities;
using OrchardCore.Workflows.Models;
using OrchardCore.Workflows.Services;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Lombiq.TrainingDemo.Activities;
// A simple workflow task that accepts a username as a TextField input and checks whether the user has ManagePersons Permission or not.
public class ManagePersonsPermissionCheckerTask : TaskActivity
{
private readonly IAuthorizationService _authorizationService;
private readonly IUserService _userService;
private readonly IWorkflowExpressionEvaluator _expressionEvaluator;
private readonly IStringLocalizer S;
public ManagePersonsPermissionCheckerTask(
IAuthorizationService authorizationService,
IUserService userService,
IWorkflowExpressionEvaluator expressionEvaluator,
IStringLocalizer<ManagePersonsPermissionCheckerTask> localizer)
{
_authorizationService = authorizationService;
_userService = userService;
_expressionEvaluator = expressionEvaluator;
S = localizer;
}
// The technical name of the activity. Activities on a workflow definition reference this name.
public override string Name => nameof(ManagePersonsPermissionCheckerTask);
// The displayed name of the activity, so it can use localization.
public override LocalizedString DisplayText => S["Manage Persons Permission Checker Task"];
// The category to which this activity belongs. The activity picker groups activities by this category.
public override LocalizedString Category => S["User"];
// A description of this activity's purpose.
public WorkflowExpression<string> UserName
{
get => GetProperty(() => new WorkflowExpression<string>());
set => SetProperty(value);
}
// Returns the possible outcomes of this activity.
public override IEnumerable<Outcome> GetPossibleOutcomes(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
return Outcomes(S["HasPermission"], S["NoPermission"]);
}
// This is the heart of the activity and actually performs the work to be done.
public override async Task<ActivityExecutionResult> ExecuteAsync(WorkflowExecutionContext workflowContext, ActivityContext activityContext)
{
var userName = await _expressionEvaluator.EvaluateAsync(UserName, workflowContext, null);
User user = (User)await _userService.GetUserAsync(userName);
if (user != null)
{
var userClaim = await _userService.CreatePrincipalAsync(user);
if (await _authorizationService.AuthorizeAsync(userClaim, PersonPermissions.ManagePersons))
{
return Outcomes("HasPermission");
}
}
return Outcomes("NoPermission");
}
}
// NEXT STATION: ViewModels/ManagePersonsPermissionCheckerTaskViewModel.cs
| bsd-3-clause | C# |
641257189b32cc54b541d8a22b6e982a2c47d1ea | Update version number | loicteixeira/gj-unity-api | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | Assets/Plugins/GameJolt/Scripts/API/Constants.cs | using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.0.1";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "http://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION + "/";
public const string API_USERS_AUTH = "users/auth/";
public const string API_USERS_FETCH = "users/";
public const string API_SESSIONS_OPEN = "sessions/open/";
public const string API_SESSIONS_PING = "sessions/ping/";
public const string API_SESSIONS_CLOSE = "sessions/close/";
public const string API_SCORES_ADD = "scores/add/";
public const string API_SCORES_FETCH = "scores/";
public const string API_SCORES_TABLES_FETCH = "scores/tables/";
public const string API_TROPHIES_ADD = "trophies/add-achieved/";
public const string API_TROPHIES_FETCH = "trophies/";
public const string API_DATASTORE_SET = "data-store/set/";
public const string API_DATASTORE_UPDATE = "data-store/update/";
public const string API_DATASTORE_FETCH = "data-store/";
public const string API_DATASTORE_REMOVE = "data-store/remove/";
public const string API_DATASTORE_KEYS_FETCH = "data-store/get-keys/";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| using UnityEngine;
using System.Collections;
namespace GameJolt.API
{
public static class Constants
{
public const string VERSION = "2.0.0";
public const string SETTINGS_ASSET_NAME = "GJAPISettings";
public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset";
public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/";
public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME;
public const string MANAGER_ASSET_NAME = "GameJoltAPI";
public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab";
public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/";
public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME;
public const string API_PROTOCOL = "http://";
public const string API_ROOT = "gamejolt.com/api/game/";
public const string API_VERSION = "1";
public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION + "/";
public const string API_USERS_AUTH = "users/auth/";
public const string API_USERS_FETCH = "users/";
public const string API_SESSIONS_OPEN = "sessions/open/";
public const string API_SESSIONS_PING = "sessions/ping/";
public const string API_SESSIONS_CLOSE = "sessions/close/";
public const string API_SCORES_ADD = "scores/add/";
public const string API_SCORES_FETCH = "scores/";
public const string API_SCORES_TABLES_FETCH = "scores/tables/";
public const string API_TROPHIES_ADD = "trophies/add-achieved/";
public const string API_TROPHIES_FETCH = "trophies/";
public const string API_DATASTORE_SET = "data-store/set/";
public const string API_DATASTORE_UPDATE = "data-store/update/";
public const string API_DATASTORE_FETCH = "data-store/";
public const string API_DATASTORE_REMOVE = "data-store/remove/";
public const string API_DATASTORE_KEYS_FETCH = "data-store/get-keys/";
public const string IMAGE_RESOURCE_REL_PATH = "Images/";
public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar";
public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME;
public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification";
public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME;
public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy";
public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME;
}
}
| mit | C# |
69c8349a36f132d89fa1a7520d5423a1162d95d9 | Remove empty line | Sl0vi/algorithms | Algorithms.Tests/FisherYatesShuffleTests.cs | Algorithms.Tests/FisherYatesShuffleTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Algorithms.Tests
{
[TestFixture]
public class FisherYatesShuffleTests
{
[Test]
public void Shuffe()
{
var random = new Random(243);
var sorted = new[] { 1, 2, 3, 4, 5, 6 };
var expected = new[] { 5, 2, 1, 3, 6, 4 };
int[] shuffled = null;
Assert.DoesNotThrow(() => shuffled = sorted.Shuffle(random).ToArray());
Assert.That(shuffled, Is.Not.Null);
Assert.That(shuffled.Length, Is.EqualTo(sorted.Length));
Assert.That(shuffled, Is.EqualTo(expected));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Algorithms.Tests
{
[TestFixture]
public class FisherYatesShuffleTests
{
[Test]
public void Shuffe()
{
var random = new Random(243);
var sorted = new[] { 1, 2, 3, 4, 5, 6 };
var expected = new[] { 5, 2, 1, 3, 6, 4 };
int[] shuffled = null;
Assert.DoesNotThrow(() => shuffled = sorted.Shuffle(random).ToArray());
Assert.That(shuffled, Is.Not.Null);
Assert.That(shuffled.Length, Is.EqualTo(sorted.Length));
Assert.That(shuffled, Is.EqualTo(expected));
}
}
}
| mit | C# |
d9633afe1a5e0ca8a572216ae7a5356f64bcfc4b | Fix health state to be 1, 19, 20, 20, 20, 20 thresholds (#7921) | 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.Server/MobState/States/NormalMobState.cs | Content.Server/MobState/States/NormalMobState.cs | using System;
using Content.Shared.Alert;
using Content.Shared.Damage;
using Content.Shared.FixedPoint;
using Content.Shared.MobState.Components;
using Content.Shared.MobState.State;
using Robust.Shared.GameObjects;
namespace Content.Server.MobState.States
{
public sealed class NormalMobState : SharedNormalMobState
{
public override void UpdateState(EntityUid entity, FixedPoint2 threshold, IEntityManager entityManager)
{
base.UpdateState(entity, threshold, entityManager);
if (!entityManager.TryGetComponent(entity, out DamageableComponent? damageable))
{
return;
}
if (!entityManager.TryGetComponent(entity, out MobStateComponent? stateComponent))
{
return;
}
short modifier = 0;
if (stateComponent.TryGetEarliestIncapacitatedState(threshold, out _, out var earliestThreshold) && damageable.TotalDamage != 0)
{
modifier = (short)(damageable.TotalDamage / (earliestThreshold / 5) + 1);
}
EntitySystem.Get<AlertsSystem>().ShowAlert(entity, AlertType.HumanHealth, modifier);
}
}
}
| using System;
using Content.Shared.Alert;
using Content.Shared.Damage;
using Content.Shared.FixedPoint;
using Content.Shared.MobState.Components;
using Content.Shared.MobState.State;
using Robust.Shared.GameObjects;
namespace Content.Server.MobState.States
{
public sealed class NormalMobState : SharedNormalMobState
{
public override void UpdateState(EntityUid entity, FixedPoint2 threshold, IEntityManager entityManager)
{
base.UpdateState(entity, threshold, entityManager);
if (!entityManager.TryGetComponent(entity, out DamageableComponent? damageable))
{
return;
}
if (!entityManager.TryGetComponent(entity, out MobStateComponent? stateComponent))
{
return;
}
short modifier = 0;
if (stateComponent.TryGetEarliestIncapacitatedState(threshold, out _, out var earliestThreshold) && damageable.TotalDamage > 0)
{
modifier = (short) MathF.Max((float) (damageable.TotalDamage / (earliestThreshold / 6f)),1);
//if hurt at all we skip to the first hurt state with Max(), anything else will end up falling to 5 at maximum before crit
}
EntitySystem.Get<AlertsSystem>().ShowAlert(entity, AlertType.HumanHealth, modifier);
}
}
}
| mit | C# |
b22f9903681698b68174a11f325900c7aeec0040 | fix url | BD-IATI/edi,BD-IATI/edi,BD-IATI/edi,BD-IATI/edi | AIMS_BD_IATI.Web/Views/Home/Index.cshtml | AIMS_BD_IATI.Web/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home";
}
<div class="jumbotron">
<h1>AIMS IATI Data Import</h1>
<p class="lead">
Using this tool Activities in IATI data store can be mapped with Projects in AIMS
</p>
<p><a href="/app/home.html" class="btn btn-primary btn-large">Map Project</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
Start mapping project
</p>
<p><a class="btn btn-default" href="/app/home.html">Map Project »</a></p>
</div>
<div class="col-md-4">
<h2>Convertion Tool</h2>
<p>
This API can be used to convert data from IATI v1.x to v2.x.<br />
<b>API URL:</b>"/api/ApiIatiConverter/ConvertIATI?org=[orgidentifier]&country=[countryprefix]"
</p>
<p>
<a class="btn btn-default" href="/api/ApiIatiConverter/ConvertIATI?org=CA-3&country=BD">Convert IATI v1.05 »</a>
</p>
</div>
<div class="col-md-4">
<h2>Convert AIMS to IATI format</h2>
<p>
Projects from AIMS can also be converted into IATI format using following API.<br />
<b>API URL:</b>"/api/ApiIatiConverter/ConvertAIMStoIATI?org=[orgidentifier]"
</p>
<p><a class="btn btn-default" href="/api/ApiIatiConverter/ConvertAIMStoIATI?org=CA-3|XM-DAC-301-3">Convert AIMS »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home";
}
<div class="jumbotron">
<h1>AIMS IATI Data Import</h1>
<p class="lead">
Using this tool Activities in IATI data store can be mapped with Projects in AIMS
</p>
<p><a href="/app/home.html" class="btn btn-primary btn-large">Map Project</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
Start mapping project
</p>
<p><a class="btn btn-default" href="/app/home.html">Map Project »</a></p>
</div>
<div class="col-md-4">
<h2>Convertion Tool</h2>
<p>
This API can be used to convert data from IATI v1.x to v2.x.<br />
<b>API URL:</b>"/api/ApiIatiConverter/ConvertIATI?org=[orgidentifier]&country=[countryprefix]"
</p>
<p>
<a class="btn btn-default" href="/api/ApiIatiConverter/ConvertIATI?org=CA-3&country=BD">Convert IATI v1.05 »</a>
</p>
</div>
<div class="col-md-4">
<h2>Convert AIMS to IATI format</h2>
<p>
Projects from AIMS can also be converted into IATI format using following API.<br />
<b>API URL:</b>"/api/ApiIatiConverter/ConvertAIMStoIATI?org=[orgidentifier]"
</p>
<p><a class="btn btn-default" href="/api/ApiIatiConverter/ConvertAIMStoIATI?org=CA-3">Convert AIMS »</a></p>
</div>
</div> | agpl-3.0 | C# |
76032c4d18cd59dd3720649460bc0db7ed8f17b9 | Update RestUser.cs | Aux/NTwitch,Aux/NTwitch | src/NTwitch.Rest/Entities/Users/RestUser.cs | src/NTwitch.Rest/Entities/Users/RestUser.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NTwitch.Rest
{
public class RestUser : IUser
{
public TwitchRestClient Client { get; }
public DateTime CreatedAt { get; }
public DateTime UpdatedAt { get; }
public uint Id { get; }
public string Name { get; }
public string DisplayName { get; }
public string Bio { get; }
public string LogoUrl { get; }
public TwitchLinks Links { get; }
public Task<IChannelFollow> GetFollowAsync(string channel)
{
throw new NotImplementedException();
}
public Task<IChannelFollow> GetFollowAsync(IChannel channel)
{
throw new NotImplementedException();
}
public Task<IEnumerable<IChannel>> GetFollowsAsync(SortMode sort = SortMode.CreatedAt, SortDirection direction = SortDirection.Ascending, int limit = 10, int page = 1)
{
throw new NotImplementedException();
}
public override string ToString()
=> DisplayName;
}
}
| using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Twitch.Rest
{
public class RestUser : IUser
{
public TwitchRestClient Client { get; }
public DateTime CreatedAt { get; }
public DateTime UpdatedAt { get; }
public uint Id { get; }
public string Name { get; }
public string DisplayName { get; }
public string Bio { get; }
public string LogoUrl { get; }
public string[] Links { get; }
public Task<IChannelFollow> GetFollowAsync(string channel)
{
throw new NotImplementedException();
}
public Task<IChannelFollow> GetFollowAsync(IChannel channel)
{
throw new NotImplementedException();
}
public Task<IEnumerable<IChannel>> GetFollowsAsync(SortMode sort = SortMode.CreatedAt, SortDirection direction = SortDirection.Ascending, int limit = 10, int page = 1)
{
throw new NotImplementedException();
}
public override string ToString()
=> DisplayName;
}
}
| mit | C# |
e10ee93f61935c55388f7b510ad4852a684a96d4 | fix indentation of example file (#1251) | robkeim/xcsharp,exercism/xcsharp,exercism/xcsharp,robkeim/xcsharp | exercises/two-fer/TwoFer.cs | exercises/two-fer/TwoFer.cs | using System;
public static class TwoFer
{
public static string Name(string input = null)
{
throw new NotImplementedException("You need to implement this function.");
}
}
| using System;
public static class TwoFer
{
public static string Name(string input = null)
{
throw new NotImplementedException("You need to implement this function.");
}
}
| mit | C# |
967b4c9f5353e0f7d251c4319f3ab0e75dfe56d7 | refactor entity cache | carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate | src/Abp/Domain/Entities/Caching/EntityCache.cs | src/Abp/Domain/Entities/Caching/EntityCache.cs | using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using Abp.Runtime.Caching;
namespace Abp.Domain.Entities.Caching
{
public class EntityCache<TEntity, TCacheItem> :
EntityCache<TEntity, TCacheItem, int>,
IEntityCache<TCacheItem>
where TEntity : class, IEntity<int>
{
public EntityCache(
ICacheManager cacheManager,
IRepository<TEntity, int> repository,
string cacheName = null)
: base(
cacheManager,
repository,
cacheName)
{
}
}
public class EntityCache<TEntity, TCacheItem, TPrimaryKey> :
EntityCacheBase<TEntity, TCacheItem, TPrimaryKey>,
IEventHandler<EntityChangedEventData<TEntity>>,
IEntityCache<TCacheItem, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
public ITypedCache<TPrimaryKey, TCacheItem> InternalCache
{
get
{
return CacheManager.GetCache<TPrimaryKey, TCacheItem>(CacheName);
}
}
public EntityCache(
ICacheManager cacheManager,
IRepository<TEntity, TPrimaryKey> repository,
string cacheName = null)
: base(
cacheManager,
repository,
cacheName)
{
}
public override TCacheItem Get(TPrimaryKey id)
{
return InternalCache.Get(id, () => GetCacheItemFromDataSource(id));
}
public override Task<TCacheItem> GetAsync(TPrimaryKey id)
{
return InternalCache.GetAsync(id, () => GetCacheItemFromDataSourceAsync(id));
}
public virtual void HandleEvent(EntityChangedEventData<TEntity> eventData)
{
InternalCache.Remove(eventData.Entity.Id);
}
public override string ToString()
{
return string.Format("EntityCache {0}", CacheName);
}
}
}
| using System.Threading.Tasks;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using Abp.Runtime.Caching;
namespace Abp.Domain.Entities.Caching
{
public class EntityCache<TEntity, TCacheItem> :
EntityCache<TEntity, TCacheItem, int>,
IEntityCache<TCacheItem>
where TEntity : class, IEntity<int>
{
public EntityCache(
ICacheManager cacheManager,
IRepository<TEntity, int> repository,
string cacheName = null)
: base(
cacheManager,
repository,
cacheName)
{
}
}
public class EntityCache<TEntity, TCacheItem, TPrimaryKey> :
EntityCacheBase<TEntity, TCacheItem, TPrimaryKey>,
IEventHandler<EntityChangedEventData<TEntity>>, IEntityCache<TCacheItem, TPrimaryKey>
where TEntity : class, IEntity<TPrimaryKey>
{
public ITypedCache<TPrimaryKey, TCacheItem> InternalCache
{
get
{
return CacheManager.GetCache<TPrimaryKey, TCacheItem>(CacheName);
}
}
public EntityCache(
ICacheManager cacheManager,
IRepository<TEntity, TPrimaryKey> repository,
string cacheName = null)
: base(
cacheManager,
repository,
cacheName)
{
}
public override TCacheItem Get(TPrimaryKey id)
{
return InternalCache.Get(id, () => GetCacheItemFromDataSource(id));
}
public override Task<TCacheItem> GetAsync(TPrimaryKey id)
{
return InternalCache.GetAsync(id, () => GetCacheItemFromDataSourceAsync(id));
}
public virtual void HandleEvent(EntityChangedEventData<TEntity> eventData)
{
InternalCache.Remove(eventData.Entity.Id);
}
public override string ToString()
{
return string.Format("EntityCache {0}", CacheName);
}
}
}
| mit | C# |
9d52064154258ec9e37d2dcad8805cc72835178d | add kernel binding to ninject | PriceIsByte/WebAPI,PriceIsByte/WebAPI | CountingKs/App_Start/NinjectWebCommon.cs | CountingKs/App_Start/NinjectWebCommon.cs | [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(CountingKs.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(CountingKs.App_Start.NinjectWebCommon), "Stop")]
namespace CountingKs.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using CountingKs.Data;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICountingKsRepository>().To<CountingKsRepository>();
kernel.Bind<CountingKsContext>().To<CountingKsContext>();
}
}
}
| [assembly: WebActivatorEx.PreApplicationStartMethod(typeof(CountingKs.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(CountingKs.App_Start.NinjectWebCommon), "Stop")]
namespace CountingKs.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
}
}
}
| unlicense | C# |
2612c63369bca4234a74a556b05bafc4af521f35 | Fix another nullability warning | EamonNerbonne/ExpressionToCode | ExpressionToCodeTest/TopLevelProgramTest.cs | ExpressionToCodeTest/TopLevelProgramTest.cs | using System;
using TopLevelProgramExample;
using Xunit;
using static TopLevelProgramExample.TopLevelProgramMarker;
namespace ExpressionToCodeTest
{
public class TopLevelProgramTest
{
[Fact]
public void CanRunTopLevelProgram()
{
LambdaInsideLocalFunction = LambdaToMyVar = LambdaInsideNestedClassMethod = null;
var topLevelProgram = (Action<string[]>)Delegate.CreateDelegate(typeof(Action<string[]>), typeof(TopLevelProgramMarker).Assembly.EntryPoint ?? throw new("Expected non-null return"));
topLevelProgram(new[] { "test" });
Assert.Equal("() => myVariable", LambdaToMyVar);
Assert.Equal("() => InnerClass.StaticInt + InstanceInt", LambdaInsideNestedClassMethod);
Assert.Equal("() => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * 27", LambdaInsideLocalFunction);
}
}
}
| using System;
using TopLevelProgramExample;
using Xunit;
using static TopLevelProgramExample.TopLevelProgramMarker;
namespace ExpressionToCodeTest
{
public class TopLevelProgramTest
{
[Fact]
public void CanRunTopLevelProgram()
{
LambdaInsideLocalFunction = LambdaToMyVar = LambdaInsideNestedClassMethod = null;
var topLevelProgram = (Action<string[]>)Delegate.CreateDelegate(typeof(Action<string[]>), typeof(TopLevelProgramMarker).Assembly.EntryPoint);
topLevelProgram(new[] { "test" });
Assert.Equal("() => myVariable", LambdaToMyVar);
Assert.Equal("() => InnerClass.StaticInt + InstanceInt", LambdaInsideNestedClassMethod);
Assert.Equal("() => inLocalFunction + myVariable.Length - arg - withImplicitType.A.Length * 27", LambdaInsideLocalFunction);
}
}
}
| apache-2.0 | C# |
88194d8020e6007caef3a2c0d1f5af74db1538d5 | Simplify PoseInterface through inheriting from InterfaceGameObject. | grobm/OSVR-Unity,grobm/OSVR-Unity,DuFF14/OSVR-Unity,OSVR/OSVR-Unity,JeroMiya/OSVR-Unity | OSVR-Unity/Assets/OSVRUnity/src/PoseInterface.cs | OSVR-Unity/Assets/OSVRUnity/src/PoseInterface.cs | /* OSVR-Unity Connection
*
* <http://sensics.com/osvr>
* Copyright 2014 Sensics, Inc.
* All rights reserved.
*
* Final version intended to be licensed under Apache v2.0
*/
using System;
using UnityEngine;
namespace OSVR
{
namespace Unity
{
/// <summary>
/// Pose interface: continually (or rather, when OSVR updates) updates its position and orientation based on the incoming tracker data.
///
/// Attach to a GameObject that you'd like to have updated in this way.
/// </summary>
public class PoseInterface : InterfaceGameObject
{
new void Start()
{
osvrInterface.RegisterCallback(callback);
}
private void callback(string source, Vector3 position, Quaternion rotation)
{
transform.localPosition = position;
transform.localRotation = rotation;
}
}
}
} | /* OSVR-Unity Connection
*
* <http://sensics.com/osvr>
* Copyright 2014 Sensics, Inc.
* All rights reserved.
*
* Final version intended to be licensed under Apache v2.0
*/
using System;
using UnityEngine;
namespace OSVR
{
namespace Unity
{
/// <summary>
/// Pose interface: continually (or rather, when OSVR updates) updates its position and orientation based on the incoming tracker data.
///
/// Attach to a GameObject that you'd like to have updated in this way.
/// </summary>
public class PoseInterface : MonoBehaviour
{
/// <summary>
/// The interface path you want to connect to.
/// </summary>
public string path;
private OSVR.ClientKit.Interface iface;
private OSVR.ClientKit.PoseCallback cb;
void Start()
{
if (0 == path.Length)
{
Debug.LogError("Missing path for PoseInterface " + gameObject.name);
return;
}
iface = OSVR.Unity.ClientKit.instance.context.getInterface(path);
cb = new OSVR.ClientKit.PoseCallback(callback);
iface.registerCallback(cb, IntPtr.Zero);
}
private void callback(IntPtr userdata, ref OSVR.ClientKit.TimeValue timestamp, ref OSVR.ClientKit.PoseReport report)
{
transform.localPosition = Math.ConvertPosition(report.pose.translation);
transform.localRotation = Math.ConvertOrientation(report.pose.rotation);
}
void OnDestroy()
{
iface = null;
}
}
}
} | apache-2.0 | C# |
75c241469f75792e96879711010101994987c938 | update fix | xirqlz/blueprint41 | Blueprint41.Modeller/Schemas/View/Entity.cs | Blueprint41.Modeller/Schemas/View/Entity.cs | using Blueprint41.Modeller.Schemas;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blueprint41.Modeller.Schemas
{
public partial class Entity
{
protected override void InitializeView()
{
}
// This is a helper properties for relationships
public string OutEntityReferenceGuid
{
get { return Guid; }
}
public string InEntityReferenceGuid
{
get { return Guid; }
}
}
}
| using Blueprint41.Modeller.Schemas;
using Microsoft.Msagl.Drawing;
using Microsoft.Msagl.GraphViewerGdi;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blueprint41.Modeller.Schemas
{
public partial class Entity
{
protected override void InitializeView()
{
}
}
}
| mit | C# |
969648a395039dee86b59cce0388e470ebb5bc7f | tag modification didn't pass through due to incorrect array serialization | ceee/PocketSharp | PocketSharp/Models/Parameters/ActionParameter.cs | PocketSharp/Models/Parameters/ActionParameter.cs | using System;
using System.Collections.Generic;
namespace PocketSharp.Models
{
/// <summary>
/// All parameters which can be passed for a modify action
/// </summary>
public class ActionParameter
{
/// <summary>
/// Gets or sets the action.
/// </summary>
/// <value>
/// The action.
/// </value>
public string Action { get; set; }
/// <summary>
/// Gets or sets the ID.
/// </summary>
/// <value>
/// The ID.
/// </value>
public int ID { get; set; }
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public DateTime? Time { get; set; }
// specific params
/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>
/// The tags.
/// </value>
public string[] Tags { get; set; }
/// <summary>
/// Gets or sets the old tag.
/// </summary>
/// <value>
/// The old tag.
/// </value>
public string OldTag { get; set; }
/// <summary>
/// Gets or sets the new tag.
/// </summary>
/// <value>
/// The new tag.
/// </value>
public string NewTag { get; set; }
/// <summary>
/// Converts this instance to a parameter list.
/// </summary>
/// <returns></returns>
public object Convert()
{
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "item_id", ID },
{ "action", Action }
};
if (Time != null)
parameters.Add("time", Utilities.GetUnixTimestamp(Time));
if (Tags != null)
parameters.Add("tags", Tags);
if (OldTag != null)
parameters.Add("old_tag", OldTag);
if (NewTag != null)
parameters.Add("new_tag", NewTag);
return parameters;
}
}
}
| using System;
using System.Collections.Generic;
namespace PocketSharp.Models
{
/// <summary>
/// All parameters which can be passed for a modify action
/// </summary>
public class ActionParameter
{
/// <summary>
/// Gets or sets the action.
/// </summary>
/// <value>
/// The action.
/// </value>
public string Action { get; set; }
/// <summary>
/// Gets or sets the ID.
/// </summary>
/// <value>
/// The ID.
/// </value>
public int ID { get; set; }
/// <summary>
/// Gets or sets the time.
/// </summary>
/// <value>
/// The time.
/// </value>
public DateTime? Time { get; set; }
// specific params
/// <summary>
/// Gets or sets the tags.
/// </summary>
/// <value>
/// The tags.
/// </value>
public string[] Tags { get; set; }
/// <summary>
/// Gets or sets the old tag.
/// </summary>
/// <value>
/// The old tag.
/// </value>
public string OldTag { get; set; }
/// <summary>
/// Gets or sets the new tag.
/// </summary>
/// <value>
/// The new tag.
/// </value>
public string NewTag { get; set; }
/// <summary>
/// Converts this instance to a parameter list.
/// </summary>
/// <returns></returns>
public object Convert()
{
Dictionary<string, object> parameters = new Dictionary<string, object>
{
{ "item_id", ID },
{ "action", Action }
};
if (Time != null)
parameters.Add("time", Utilities.GetUnixTimestamp(Time));
if (Tags != null)
parameters.Add("tags", String.Join(",", Tags));
if (OldTag != null)
parameters.Add("old_tag", OldTag);
if (NewTag != null)
parameters.Add("new_tag", NewTag);
return parameters;
}
}
}
| mit | C# |
f64c7ba5ab60ded1581c88ac9218ec3e3d811404 | bump version to 3.0.0 | piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker,piwik/piwik-dotnet-tracker | Piwik.Tracker/Properties/AssemblyInfo.cs | Piwik.Tracker/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("PiwikTracker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Piwik")]
[assembly: AssemblyProduct("PiwikTracker")]
[assembly: AssemblyCopyright("")]
[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("8121d06f-a801-42d2-a144-0036a0270bf3")]
// 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("3.0.0")]
[assembly: InternalsVisibleTo("Piwik.Tracker.Tests")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PiwikTracker")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Piwik")]
[assembly: AssemblyProduct("PiwikTracker")]
[assembly: AssemblyCopyright("")]
[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("8121d06f-a801-42d2-a144-0036a0270bf3")]
// 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("2.16.0")]
[assembly: InternalsVisibleTo("Piwik.Tracker.Tests")] | bsd-3-clause | C# |
8e18ad1f5ccfc8fb59e8bd9b58c66854a2bcc9a8 | Exclude packaes folder | jbwilliamson/MaximiseWFScaffolding,jbwilliamson/MaximiseWFScaffolding | RandomSchool/RandomSchool/Site.Master.cs | RandomSchool/RandomSchool/Site.Master.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RandomSchool
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace RandomSchool
{
public partial class SiteMaster : MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
} | apache-2.0 | C# |
f269d18b18a924730cb124e4815698e7a9f8bb53 | Comment out code to initialize UIManagerModule constants until unit tested. | lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows | ReactNative/UIManager/UIManagerModule.cs | ReactNative/UIManager/UIManagerModule.cs |
using ReactNative.Bridge;
using ReactNative.UIManager;
using ReactNative.Views;
using System.Collections.Generic;
using Windows.UI.Xaml;
namespace ReactNative.UIManager
{
/// <summary>
/// Native module to allow JS to create and update native Views.
/// </summary>
public partial class UIManagerModule : NativeModuleBase
{
private readonly UIImplementation _uiImplementation;
private readonly IDictionary<string, object> _moduleConstants;
private int nextRootTag = 1;
public UIManagerModule(ReactApplicationContext reactContext,
IReadOnlyList<ViewManager<FrameworkElement, ReactShadowNode>> viewManagerList,
UIImplementation uiImplementation)
{
_uiImplementation = uiImplementation;
//_moduleConstants = CreateConstants(viewManagerList);
}
public override string Name
{
get
{
return "RKUIManager";
}
}
/// <summary>
/// Registers a new root view. JS can use the returned tag with manageChildren to add/remove
/// children to this view.
///
/// TODO:
/// 1.This needs to be more formally implemented so that it takes <see cref="ThemedReactContext" /> into consideration. This is a
/// temporary implementation
/// </summary>
/// <param name="rootView"></param>
/// <returns></returns>
public int AddMeasuredRootView(ReactRootView rootView)
{
var tag = nextRootTag;
nextRootTag += 10;
rootView.BindTagToView(nextRootTag);
return tag;
}
}
}
|
using ReactNative.Bridge;
using ReactNative.UIManager;
using ReactNative.Views;
using System.Collections.Generic;
using Windows.UI.Xaml;
namespace ReactNative.UIManager
{
/// <summary>
/// Native module to allow JS to create and update native Views.
/// </summary>
public partial class UIManagerModule : NativeModuleBase
{
private readonly UIImplementation _uiImplementation;
private readonly IDictionary<string, object> _moduleConstants;
private int nextRootTag = 1;
public UIManagerModule(ReactApplicationContext reactContext,
IReadOnlyList<ViewManager<FrameworkElement, ReactShadowNode>> viewManagerList,
UIImplementation uiImplementation)
{
_uiImplementation = uiImplementation;
_moduleConstants = CreateConstants(viewManagerList);
}
public override string Name
{
get
{
return "RKUIManager";
}
}
/// <summary>
/// Registers a new root view. JS can use the returned tag with manageChildren to add/remove
/// children to this view.
///
/// TODO:
/// 1.This needs to be more formally implemented so that it takes <see cref="ThemedReactContext" /> into consideration. This is a
/// temporary implementation
/// </summary>
/// <param name="rootView"></param>
/// <returns></returns>
public int AddMeasuredRootView(ReactRootView rootView)
{
var tag = nextRootTag;
nextRootTag += 10;
rootView.BindTagToView(nextRootTag);
return tag;
}
}
}
| mit | C# |
cf8780991b3dccb19d451a7e8126ada040e02f0e | Update LevelGrading.cs | afroraydude/First_Unity_Game,afroraydude/First_Unity_Game,afroraydude/First_Unity_Game | Real_Game/Assets/Scripts/LevelGrading.cs | Real_Game/Assets/Scripts/LevelGrading.cs | using UnityEngine;
using System.Collections;
public class LevelGrading : MonoBehaviour {
public float finalScore; // This is the final score you recieve
public string finalScoreLetter; //
public float[] timeGrading = new float[5]; // 5 for the 5 grades (A, B, C D, F)
public int[] deathGrading = new int[5]; // 5 for the 5 grades (A, B, C D, F)
void Start() {
}
void Update() {
//Probably would be empty
}
void OnGUI() {
// I might want to do the GUI
}
}
| using UnityEngine;
using System.Collections;
public class LevelGrading : MonoBehaviour {
//public int;
void Start() {
}
void Update() {
}
}
| mit | C# |
62baee8261600acb28556e8486a091ae291b631a | Fix issues in description of val command | codeflood/revolver,codeflood/revolver,codeflood/revolver | Revolver.Core/Commands/ValidateFields.cs | Revolver.Core/Commands/ValidateFields.cs | using Sitecore.Data.Items;
using System.Text;
using System.Text.RegularExpressions;
namespace Revolver.Core.Commands {
/// <summary>
/// Validate each field individually using the regex for each field.
/// </summary>
[Command("val")]
public class ValidateFields : BaseCommand {
[NumberedParameter(0, "path")]
[Description("The path of the item to validate. If not specified the current item is used.")]
public string Path { get; set; }
public ValidateFields() {
Path = string.Empty;
}
public override CommandResult Run() {
using (ContextSwitcher cs = new ContextSwitcher(Context, Path)) {
if (cs.Result.Status != CommandStatus.Success)
return cs.Result;
StringBuilder sb = new StringBuilder(500);
Item item = Context.CurrentItem;
// TODO: Review using item.Fields here. Check source item is of type document ('a' wasn't during testing)
for (int i = 0; i < item.Template.Fields.Length; i++) {
// Get regex from template field def
string regexStr = item.Template.Fields[i].Validation;
Sitecore.Data.ID id = item.Template.Fields[i].ID;
if (regexStr != null && regexStr != string.Empty) {
if (!Regex.Match(item.Fields[id].Value, item.Fields[id].Validation).Success) {
if (sb.Length > 0)
Formatter.PrintLine(string.Empty, sb);
sb.Append("\"");
sb.Append(item.Fields[id].ValidationText);
sb.Append("\" in field ");
sb.Append(item.Fields[id].Name);
}
}
}
if (sb.Length > 0)
{
var output = new StringBuilder();
Formatter.PrintLine("FAILED: Validation failed for " + item.Paths.FullPath, output);
output.Append(sb);
return new CommandResult(CommandStatus.Success, output.ToString());
} else
return new CommandResult(CommandStatus.Success, "PASSED: Validation passed for " + item.Paths.FullPath);
}
}
public override string Description() {
return "Performs field validation for the item";
}
public override void Help(HelpDetails details) {
details.AddExample("/sitecore/content/home/a");
}
}
}
| using Sitecore.Data.Items;
using System.Text;
using System.Text.RegularExpressions;
namespace Revolver.Core.Commands {
/// <summary>
/// Validate each field individually using the regex for each field.
/// </summary>
[Command("val")]
public class ValidateFields : BaseCommand {
[NumberedParameter(0, "path")]
[Description("The path of the source item to copy including the new name. If not specified the current item is used.")]
public string Path { get; set; }
public ValidateFields() {
Path = string.Empty;
}
public override CommandResult Run() {
using (ContextSwitcher cs = new ContextSwitcher(Context, Path)) {
if (cs.Result.Status != CommandStatus.Success)
return cs.Result;
StringBuilder sb = new StringBuilder(500);
Item item = Context.CurrentItem;
// TODO: Review using item.Fields here. Check source item is of type document ('a' wasn't during testing)
for (int i = 0; i < item.Template.Fields.Length; i++) {
// Get regex from template field def
string regexStr = item.Template.Fields[i].Validation;
Sitecore.Data.ID id = item.Template.Fields[i].ID;
if (regexStr != null && regexStr != string.Empty) {
if (!Regex.Match(item.Fields[id].Value, item.Fields[id].Validation).Success) {
if (sb.Length > 0)
Formatter.PrintLine(string.Empty, sb);
sb.Append("\"");
sb.Append(item.Fields[id].ValidationText);
sb.Append("\" in field ");
sb.Append(item.Fields[id].Name);
}
}
}
if (sb.Length > 0)
{
var output = new StringBuilder();
Formatter.PrintLine("FAILED: Validation failed for " + item.Paths.FullPath, output);
output.Append(sb);
return new CommandResult(CommandStatus.Success, output.ToString());
} else
return new CommandResult(CommandStatus.Success, "PASSED: Validation passed for " + item.Paths.FullPath);
}
}
public override string Description() {
return "Performs field validation for the item";
}
public override void Help(HelpDetails details) {
details.AddExample("/sitecore/content/home/a");
}
}
}
| mit | C# |
ae08deaaaa34a5b1ee39e42b1e3b3371b91eb1e3 | Use the assigned UUID in the AssemblyInfo | sbennett1990/KeePass-SalsaCipher | Salsa20Cipher/Properties/AssemblyInfo.cs | Salsa20Cipher/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("Salsa20 Cipher")]
[assembly: AssemblyDescription("Enables KeePass to encrypt databases using the Salsa20 algorithm.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Scott Bennett")]
[assembly: AssemblyProduct("KeePass Plugin")]
[assembly: AssemblyCopyright("Copyright (c) 2015 Scott Bennett")]
[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("716E1C8A-EE17-4BDC-93AE-A977B882833A")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.6.1")]
[assembly: AssemblyFileVersion("0.6.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("Salsa20 Cipher")]
[assembly: AssemblyDescription("Enables KeePass to encrypt databases using the Salsa20 algorithm.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Scott Bennett")]
[assembly: AssemblyProduct("KeePass Plugin")]
[assembly: AssemblyCopyright("Copyright (c) 2015 Scott Bennett")]
[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("b7efe84d-4e52-44cb-8761-29d58d1004d9")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.6.1")]
[assembly: AssemblyFileVersion("0.6.1")]
| bsd-2-clause | C# |
64d74356d486140157489b14ca65b619275a5171 | add Checked member to CheckboxItem | peterhumbert/YARTE | YARTE/YARTE/CheckboxItem.cs | YARTE/YARTE/CheckboxItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YARTE
{
public class CheckboxItem
{
private string strLabel;
private string strIdentifier;
private bool blnCheckd = false;
public CheckboxItem(string label, string identifier)
{
strLabel = label;
strIdentifier = identifier;
}
public CheckboxItem(string label, string identifier, bool checkd) : this(label, identifier)
{
blnCheckd = checkd;
}
public string Label
{
get { return strLabel; }
set { strLabel = value; }
}
public string Identifier
{
get { return strIdentifier; }
set { strIdentifier = value; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YARTE
{
public class CheckboxItem
{
private string strLabel;
private string strIdentifier;
public CheckboxItem(string label, string identifier)
{
strLabel = label;
strIdentifier = identifier;
}
public string Label
{
get { return strLabel; }
set { strLabel = value; }
}
public string Identifier
{
get { return strIdentifier; }
set { strIdentifier = value; }
}
}
}
| apache-2.0 | C# |
b6bb807422c746413d029968567964e6f0515c4b | Update DummyConsoleSink.cs | serilog/serilog,CaioProiete/serilog,serilog/serilog | test/TestDummies/Console/DummyConsoleSink.cs | test/TestDummies/Console/DummyConsoleSink.cs | using System;
using Serilog.Core;
using Serilog.Events;
using TestDummies.Console.Themes;
namespace TestDummies.Console
{
public class DummyConsoleSink : ILogEventSink
{
public DummyConsoleSink(ConsoleTheme? theme = null)
{
Theme = theme ?? ConsoleTheme.None;
}
[ThreadStatic]
public static ConsoleTheme? Theme;
public void Emit(LogEvent logEvent)
{
}
}
}
| using System;
using Serilog.Core;
using Serilog.Events;
using TestDummies.Console.Themes;
namespace TestDummies.Console
{
public class DummyConsoleSink : ILogEventSink
{
public DummyConsoleSink(ConsoleTheme? theme = null)
{
Theme = theme ?? ConsoleTheme.None;
}
[ThreadStatic]
public static ConsoleTheme Theme = null!;
public void Emit(LogEvent logEvent)
{
}
}
}
| apache-2.0 | C# |
489014e018183b1c6a0c1a82dd6b87fa6a5d7542 | Add trace to check effective bug | Seddryck/NBi,Seddryck/NBi | NBi.Core/Batch/SqlServer/BatchRunCommand.cs | NBi.Core/Batch/SqlServer/BatchRunCommand.cs | using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Batch.SqlServer
{
class BatchRunCommand : IDecorationCommandImplementation
{
private readonly string connectionString;
private readonly string fullPath;
public BatchRunCommand(IBatchRunCommand command, SqlConnection connection)
{
this.connectionString = connection.ConnectionString;
this.fullPath = command.FullPath;
}
public void Execute()
{
if (!File.Exists(fullPath))
throw new ExternalDependencyNotFoundException(fullPath);
var script = File.ReadAllText(fullPath);
Trace.WriteLineIf(NBiTraceSwitch.TraceVerbose, script);
var server = new Server();
server.ConnectionContext.ConnectionString = connectionString;
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
| using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NBi.Core.Batch.SqlServer
{
class BatchRunCommand : IDecorationCommandImplementation
{
private readonly string connectionString;
private readonly string fullPath;
public BatchRunCommand(IBatchRunCommand command, SqlConnection connection)
{
this.connectionString = connection.ConnectionString;
this.fullPath = command.FullPath;
}
public void Execute()
{
if (!File.Exists(fullPath))
throw new ExternalDependencyNotFoundException(fullPath);
var script = File.ReadAllText(fullPath);
var server = new Server();
server.ConnectionContext.ConnectionString = connectionString;
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
| apache-2.0 | C# |
b40836e28f8f1f7fe8101f24fb04e184074a9891 | Revert "Remove Duplicate Path Parameters" | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | src/Server/Bit.WebApi/Implementations/SwaggerDefaultValuesOperationFilter.cs | src/Server/Bit.WebApi/Implementations/SwaggerDefaultValuesOperationFilter.cs | using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http.Description;
namespace Bit.WebApi.Implementations
{
/// <summary>
/// Represents the Swagger/Swashbuckle operation filter used to provide default values.
/// </summary>
/// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
/// Once they are fixed and published, this class can be removed.</remarks>
public class SwaggerDefaultValuesOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the filter to the specified operation using the given context.
/// </summary>
/// <param name="operation">The operation to apply the filter to.</param>
/// <param name="schemaRegistry">The API schema registry.</param>
/// <param name="apiDescription">The API description being filtered.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
{
return;
}
foreach (Parameter parameter in operation.parameters)
{
ApiParameterDescription description = apiDescription.ParameterDescriptions.First(p => p.Name == parameter.name);
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1101
if (parameter.description == null)
{
parameter.description = description.Documentation;
}
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1089
// REF: https://github.com/domaindrivendev/Swashbuckle/pull/1090
if (parameter.@default == null)
{
parameter.@default = description.ParameterDescriptor?.DefaultValue;
}
}
}
}
}
| using Swashbuckle.Swagger;
using System.Linq;
using System.Web.Http.Description;
namespace Bit.WebApi.Implementations
{
/// <summary>
/// Represents the Swagger/Swashbuckle operation filter used to provide default values.
/// </summary>
/// <remarks>This <see cref="IOperationFilter"/> is only required due to bugs in the <see cref="SwaggerGenerator"/>.
/// Once they are fixed and published, this class can be removed.</remarks>
public class SwaggerDefaultValuesOperationFilter : IOperationFilter
{
/// <summary>
/// Applies the filter to the specified operation using the given context.
/// </summary>
/// <param name="operation">The operation to apply the filter to.</param>
/// <param name="schemaRegistry">The API schema registry.</param>
/// <param name="apiDescription">The API description being filtered.</param>
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters == null)
{
return;
}
foreach (Parameter parameter in operation.parameters)
{
var parameterName = parameter.name;
if (parameterName.Contains('.'))
parameterName = parameter.name.Split('.')[0];
ApiParameterDescription description = apiDescription.ParameterDescriptions.First(p => p.Name == parameterName);
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1101
if (parameter.description == null)
{
parameter.description = description.Documentation;
}
// REF: https://github.com/domaindrivendev/Swashbuckle/issues/1089
// REF: https://github.com/domaindrivendev/Swashbuckle/pull/1090
if (parameter.@default == null)
{
parameter.@default = description.ParameterDescriptor?.DefaultValue;
}
}
}
}
}
| mit | C# |
4f5708c11b2d90e050d3ff4d588f79dc433422f1 | fix possible value bug | RoninWest/Ronin.ML | Ronin.ML.Text/RegularExpressionTokenizer.cs | Ronin.ML.Text/RegularExpressionTokenizer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Ronin.ML.Text
{
/// <summary>
/// Split string using provided expression
/// </summary>
public class RegularExpressionTokenizer : IStringTokenizer
{
readonly Regex _exp;
readonly bool _exclusion;
/// <summary>
/// Instantiate with expression and optional param
/// </summary>
/// <param name="expression">regular expression, required</param>
/// <param name="exclusion">optional exclusion flag. when true will split by the provided expression and when false (default) will capture only the provided expression</param>
public RegularExpressionTokenizer(Regex expression, bool exclusion = false)
{
if (expression == null)
throw new ArgumentNullException("expression");
_exp = expression;
_exclusion = exclusion;
}
/// <summary>
/// Required: regular expression
/// </summary>
public Regex Expression
{
get { return _exp; }
}
/// <summary>
/// ReadOnly: optional exclusion flag. when true will split by the provided expression and when false (default) will capture only the provided expression.
/// </summary>
public bool Exclusion
{
get { return _exclusion; }
}
public virtual IEnumerable<WordToken> Process(string data)
{
ICollection<WordToken> wlist;
MatchCollection mc = _exp.Matches(data);
if (mc.Count > 10000)
wlist = new LinkedList<WordToken>();
else
wlist = new List<WordToken>(mc.Count);
if (_exclusion)
{
for (int i = 0; i < mc.Count; i++)
{
Match cur = mc[i];
Match last;
int start, len;
if (i == 0)
{
last = null;
start = 0;
len = cur.Index;
}
else
{
last = mc[i - 1];
start = last.Index + last.Length;
len = cur.Index - start;
if (len <= 0)
continue;
}
string value = data.Substring(start, len);
if (!string.IsNullOrEmpty(value))
wlist.Add(new WordToken(value, start));
if(i == mc.Count - 1)
{
start = cur.Index + cur.Length;
value = data.Substring(start);
if(!string.IsNullOrEmpty(value))
wlist.Add(new WordToken(value, start));
}
}
}
else
{
foreach (Match m in mc)
{
wlist.Add(new WordToken(m.Value, m.Index));
}
}
return wlist;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace Ronin.ML.Text
{
/// <summary>
/// Split string using provided expression
/// </summary>
public class RegularExpressionTokenizer : IStringTokenizer
{
readonly Regex _exp;
readonly bool _exclusion;
/// <summary>
/// Instantiate with expression and optional param
/// </summary>
/// <param name="expression">regular expression, required</param>
/// <param name="exclusion">optional exclusion flag. when true will split by the provided expression and when false (default) will capture only the provided expression</param>
public RegularExpressionTokenizer(Regex expression, bool exclusion = false)
{
if (expression == null)
throw new ArgumentNullException("expression");
_exp = expression;
_exclusion = exclusion;
}
/// <summary>
/// Required: regular expression
/// </summary>
public Regex Expression
{
get { return _exp; }
}
/// <summary>
/// ReadOnly: optional exclusion flag. when true will split by the provided expression and when false (default) will capture only the provided expression.
/// </summary>
public bool Exclusion
{
get { return _exclusion; }
}
public virtual IEnumerable<WordToken> Process(string data)
{
ICollection<WordToken> wlist;
MatchCollection mc = _exp.Matches(data);
if (mc.Count > 10000)
wlist = new LinkedList<WordToken>();
else
wlist = new List<WordToken>(mc.Count);
if (_exclusion)
{
for (int i = 0; i < mc.Count; i++)
{
Match cur = mc[i];
Match last;
int start, len;
if (i == 0)
{
last = null;
start = 0;
len = cur.Index;
}
else
{
last = mc[i - 1];
start = last.Index + last.Length;
len = cur.Index - start;
if (len <= 0)
continue;
}
string value = data.Substring(start, len);
if (!string.IsNullOrEmpty(value))
wlist.Add(new WordToken(value, start));
if(i == mc.Count - 1)
{
start = cur.Index + cur.Length;
value = data.Substring(start);
wlist.Add(new WordToken(value, start));
}
}
}
else
{
foreach (Match m in mc)
{
wlist.Add(new WordToken(m.Value, m.Index));
}
}
return wlist;
}
}
}
| agpl-3.0 | C# |
f6303a28558cba4a0eee8b4b5695d18789d4e4f4 | Fix songselect blur potentially never being applied | 2yangk23/osu,peppy/osu,UselessToucan/osu,ppy/osu,naoey/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,naoey/osu,ppy/osu,peppy/osu-new,ZLima12/osu,NeoAdonis/osu,DrabWeb/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,ZLima12/osu,smoogipooo/osu,DrabWeb/osu,DrabWeb/osu,naoey/osu,2yangk23/osu | osu.Game/Screens/BlurrableBackgroundScreen.cs | osu.Game/Screens/BlurrableBackgroundScreen.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.Transforms;
using osu.Game.Graphics.Backgrounds;
using osuTK;
namespace osu.Game.Screens
{
public abstract class BlurrableBackgroundScreen : BackgroundScreen
{
protected Background Background;
protected Vector2 BlurTarget;
public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None)
{
BlurTarget = sigma;
return Background?.BlurTo(BlurTarget, duration, easing);
}
}
}
| // 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.Transforms;
using osu.Game.Graphics.Backgrounds;
using osuTK;
namespace osu.Game.Screens
{
public abstract class BlurrableBackgroundScreen : BackgroundScreen
{
protected Background Background;
protected Vector2 BlurTarget;
public TransformSequence<Background> BlurTo(Vector2 sigma, double duration, Easing easing = Easing.None)
=> Background?.BlurTo(BlurTarget = sigma, duration, easing);
}
}
| mit | C# |
753acf4e05d0051ffae3c63b0f10c520db1c9e41 | Disable sqlite test | studio-nine/Nine.Storage,yufeih/Nine.Storage | test/Nine.Storage.Client.Test/StorageTest.cs | test/Nine.Storage.Client.Test/StorageTest.cs | namespace Nine.Storage
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite.Net.Platform.Win32;
using Xunit;
public class StorageTest : StorageSpec<StorageTest>
{
public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
{
return new[]
{
// TODO: add it back when we know how to copy native binaries on dnx project
// new TestFactory<IStorage<TestStorageObject>>(typeof(SqliteStorage<>), () => new SqliteStorage<TestStorageObject>($"sqlite-{ Environment.TickCount }.db", new SQLitePlatformWin32())),
new TestFactory<IStorage<TestStorageObject>>(typeof(MemoryStorage<>), () => new MemoryStorage<TestStorageObject>()),
new TestFactory<IStorage<TestStorageObject>>(typeof(MemoryStorage<>), () => new MemoryStorage<TestStorageObject>(true)),
new TestFactory<IStorage<TestStorageObject>>(typeof(RecycledStorage<>), () => new RecycledStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>())),
new TestFactory<IStorage<TestStorageObject>>(typeof(CachedStorage<>), () => new CachedStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>())),
new TestFactory<IStorage<TestStorageObject>>(typeof(CachedStorage<>), () => new CachedStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>(), new MemoryStorage<CachedStorageItems<TestStorageObject>>())),
};
}
[Fact]
public async Task it_should_put_deleted_items_into_recycle_bin()
{
var recycleBin = new MemoryStorage<TestStorageObject>();
var storage = new RecycledStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), recycleBin);
await storage.Put(new TestStorageObject("1"));
Assert.Null(await recycleBin.Get("1"));
await storage.Delete("1");
var deleted = await recycleBin.Get("1");
Assert.NotNull(deleted);
Assert.Equal("1", deleted.Id);
}
}
}
| namespace Nine.Storage
{
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite.Net.Platform.Win32;
using Xunit;
public class StorageTest : StorageSpec<StorageTest>
{
public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
{
return new[]
{
new TestFactory<IStorage<TestStorageObject>>(typeof(SqliteStorage<>), () => new SqliteStorage<TestStorageObject>($"sqlite-{ Environment.TickCount }.db", new SQLitePlatformWin32())),
new TestFactory<IStorage<TestStorageObject>>(typeof(MemoryStorage<>), () => new MemoryStorage<TestStorageObject>()),
new TestFactory<IStorage<TestStorageObject>>(typeof(MemoryStorage<>), () => new MemoryStorage<TestStorageObject>(true)),
new TestFactory<IStorage<TestStorageObject>>(typeof(RecycledStorage<>), () => new RecycledStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>())),
new TestFactory<IStorage<TestStorageObject>>(typeof(CachedStorage<>), () => new CachedStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>())),
new TestFactory<IStorage<TestStorageObject>>(typeof(CachedStorage<>), () => new CachedStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), new MemoryStorage<TestStorageObject>(), new MemoryStorage<CachedStorageItems<TestStorageObject>>())),
};
}
[Fact]
public async Task it_should_put_deleted_items_into_recycle_bin()
{
var recycleBin = new MemoryStorage<TestStorageObject>();
var storage = new RecycledStorage<TestStorageObject>(new MemoryStorage<TestStorageObject>(), recycleBin);
await storage.Put(new TestStorageObject("1"));
Assert.Null(await recycleBin.Get("1"));
await storage.Delete("1");
var deleted = await recycleBin.Get("1");
Assert.NotNull(deleted);
Assert.Equal("1", deleted.Id);
}
}
}
| mit | C# |
12ef63bc04476f9b3d1839260ab766c6b6678429 | Exclude tests class from coverage result | HangfireIO/Cronos | build.cake | build.cake | #tool "nuget:?package=xunit.runner.console"
#tool "nuget:?package=OpenCover"
var configuration = Argument("configuration", "Release");
var version = Argument<string>("buildVersion", null);
var target = Argument("target", "Default");
Task("Restore")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectory("./build");
StartProcess("dotnet", "clean -c:" + configuration);
});
Task("SpecifyPackageVersion")
.WithCriteria(AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
version = AppVeyor.Environment.Build.Version;
if (AppVeyor.Environment.Repository.Tag.IsTag)
{
var tagName = AppVeyor.Environment.Repository.Tag.Name;
if(tagName.StartsWith("v"))
{
version = tagName.Substring(1);
}
AppVeyor.UpdateBuildVersion(version);
}
});
Task("Build")
.IsDependentOn("SpecifyPackageVersion")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(()=>
{
var buildSettings = new DotNetCoreBuildSettings { Configuration = configuration };
if(!string.IsNullOrEmpty(version)) buildSettings.ArgumentCustomization = args => args.Append("/p:Version=" + version);
DotNetCoreBuild("src/Cronos/Cronos.csproj", buildSettings);
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings
{
Configuration = "Release",
ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false")
});
});
Task("OpenCover")
.IsDependentOn("Test")
.Does(() =>
{
OpenCover(
tool => { tool.XUnit2("tests/Cronos.Tests/bin/" + configuration + "/**/Cronos.Tests.dll", new XUnit2Settings { ShadowCopy = false }); },
new FilePath("coverage.xml"),
new OpenCoverSettings()
.WithFilter("+[Cronos]*")
.WithFilter("-[Cronos.Tests]*"));
});
Task("Pack")
.IsDependentOn("OpenCover")
.Does(()=>
{
CreateDirectory("build");
CopyFiles(GetFiles("./src/Cronos/bin/**/*.nupkg"), "build");
Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip");
});
Task("Default")
.IsDependentOn("Pack");
Task("CI")
.IsDependentOn("Pack");
RunTarget(target); | #tool "nuget:?package=xunit.runner.console"
#tool "nuget:?package=OpenCover"
var configuration = Argument("configuration", "Release");
var version = Argument<string>("buildVersion", null);
var target = Argument("target", "Default");
Task("Restore")
.Does(()=>
{
DotNetCoreRestore();
});
Task("Clean")
.Does(()=>
{
CleanDirectory("./build");
StartProcess("dotnet", "clean -c:" + configuration);
});
Task("SpecifyPackageVersion")
.WithCriteria(AppVeyor.IsRunningOnAppVeyor)
.Does(() =>
{
version = AppVeyor.Environment.Build.Version;
if (AppVeyor.Environment.Repository.Tag.IsTag)
{
var tagName = AppVeyor.Environment.Repository.Tag.Name;
if(tagName.StartsWith("v"))
{
version = tagName.Substring(1);
}
AppVeyor.UpdateBuildVersion(version);
}
});
Task("Build")
.IsDependentOn("SpecifyPackageVersion")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(()=>
{
var buildSettings = new DotNetCoreBuildSettings { Configuration = configuration };
if(!string.IsNullOrEmpty(version)) buildSettings.ArgumentCustomization = args => args.Append("/p:Version=" + version);
DotNetCoreBuild("src/Cronos/Cronos.csproj", buildSettings);
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./tests/Cronos.Tests/Cronos.Tests.csproj", new DotNetCoreTestSettings
{
Configuration = "Release",
ArgumentCustomization = args => args.Append("/p:BuildProjectReferences=false")
});
});
Task("OpenCover")
.IsDependentOn("Test")
.Does(() =>
{
OpenCover(
tool => { tool.XUnit2("tests/Cronos.Tests/bin/" + configuration + "/**/Cronos.Tests.dll", new XUnit2Settings { ShadowCopy = false }); },
new FilePath("coverage.xml"),
new OpenCoverSettings());
});
Task("Pack")
.IsDependentOn("OpenCover")
.Does(()=>
{
CreateDirectory("build");
CopyFiles(GetFiles("./src/Cronos/bin/**/*.nupkg"), "build");
Zip("./src/Cronos/bin/" + configuration, "build/Cronos-" + version +".zip");
});
Task("Default")
.IsDependentOn("Pack");
Task("CI")
.IsDependentOn("Pack");
RunTarget(target); | mit | C# |
f2aa695836cbf98827b64dc290ac9b14cda90c4a | Reformat code in metdata provider | valdisiljuconoks/LocalizationProvider | src/DbLocalizationProvider/DataAnnotations/ModelMetadataLocalizationHelper.cs | src/DbLocalizationProvider/DataAnnotations/ModelMetadataLocalizationHelper.cs | using System;
using DbLocalizationProvider.Internal;
namespace DbLocalizationProvider.DataAnnotations
{
internal class ModelMetadataLocalizationHelper
{
internal static string GetTranslation(string resourceKey)
{
var result = resourceKey;
if(!ConfigurationContext.Current.EnableLocalization())
return result;
var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey);
result = localizedDisplayName;
if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode())
return result;
// for the legacy purposes - we need to look for this resource value as resource translation
// once again - this will make sure that existing XPath resources are still working
if(localizedDisplayName.StartsWith("/"))
result = LocalizationProvider.Current.GetString(localizedDisplayName);
// If other data annotations exists execept for [Display], an exception is thrown when displayname is ""
// It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty
return string.IsNullOrWhiteSpace(localizedDisplayName) ? null : result;
}
internal static string GetTranslation(Type containerType, string propertyName)
{
var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName);
return GetTranslation(resourceKey);
}
}
}
| using System;
using DbLocalizationProvider.Internal;
namespace DbLocalizationProvider.DataAnnotations
{
internal class ModelMetadataLocalizationHelper
{
internal static string GetTranslation(string resourceKey)
{
var result = resourceKey;
if(!ConfigurationContext.Current.EnableLocalization())
{
return result;
}
var localizedDisplayName = LocalizationProvider.Current.GetString(resourceKey);
result = localizedDisplayName;
if(!ConfigurationContext.Current.ModelMetadataProviders.EnableLegacyMode())
return result;
// for the legacy purposes - we need to look for this resource value as resource translation
// once again - this will make sure that existing XPath resources are still working
if(localizedDisplayName.StartsWith("/"))
{
result = LocalizationProvider.Current.GetString(localizedDisplayName);
}
//If other data annotations exists execept for [Display], an exception is thrown when displayname is ""
//It should be null to avoid exception as ModelMetadata.GetDisplayName only checks for null and not String.Empty
if (string.IsNullOrWhiteSpace(localizedDisplayName))
{
return null;
}
return result;
}
internal static string GetTranslation(Type containerType, string propertyName)
{
var resourceKey = ResourceKeyBuilder.BuildResourceKey(containerType, propertyName);
return GetTranslation(resourceKey);
}
}
}
| apache-2.0 | C# |
e8cfb1ad42f43fe2850d3a3d14eeeef7f69f54ea | Add space | KirillOsenkov/roslyn,heejaechang/roslyn,diryboy/roslyn,KevinRansom/roslyn,davkean/roslyn,panopticoncentral/roslyn,aelij/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,stephentoub/roslyn,sharwell/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,genlu/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,tmat/roslyn,wvdd007/roslyn,heejaechang/roslyn,dotnet/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,tmat/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,KevinRansom/roslyn,eriawan/roslyn,diryboy/roslyn,tannergooding/roslyn,gafter/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,davkean/roslyn,AlekseyTs/roslyn,davkean/roslyn,eriawan/roslyn,jmarolf/roslyn,genlu/roslyn,physhi/roslyn,stephentoub/roslyn,AmadeusW/roslyn,aelij/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,dotnet/roslyn,diryboy/roslyn,bartdesmet/roslyn,aelij/roslyn,genlu/roslyn,stephentoub/roslyn,brettfo/roslyn,tannergooding/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,sharwell/roslyn,eriawan/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,mavasani/roslyn,bartdesmet/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,gafter/roslyn,reaction1989/roslyn,gafter/roslyn,wvdd007/roslyn,reaction1989/roslyn,physhi/roslyn | src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.SymbolMoniker.cs | src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.SymbolMoniker.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.
#nullable enable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.LanguageServiceIndexFormat;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor.FindUsages
{
using static FindUsagesHelpers;
internal abstract partial class AbstractFindUsagesService
{
private static async Task FindSymbolMonikerReferencesAsync(
IFindSymbolMonikerUsagesService monikerUsagesService,
ISymbol definition,
IFindUsagesContext context,
CancellationToken cancellationToken)
{
var moniker = SymbolMoniker.TryCreate(definition);
if (moniker == null)
return;
// Let the find-refs window know we have outstanding work
await using var _ = await context.ProgressTracker.AddSingleItemAsync().ConfigureAwait(false);
var displayParts = GetDisplayParts(definition).AddRange(new[]
{
new TaggedText(TextTags.Space, " "),
new TaggedText(TextTags.Text, EditorFeaturesResources.external),
});
var definitionItem = DefinitionItem.CreateNonNavigableItem(
tags: GlyphTags.GetTags(definition.GetGlyph()),
displayParts,
originationParts: DefinitionItem.GetOriginationParts(definition));
var monikers = ImmutableArray.Create(moniker);
var first = true;
await foreach (var referenceItem in monikerUsagesService.FindReferencesByMoniker(
definitionItem, monikers, context.ProgressTracker, cancellationToken))
{
if (first)
{
// found some results. Add the definition item to the context.
first = false;
await context.OnDefinitionFoundAsync(definitionItem).ConfigureAwait(false);
}
await context.OnExternalReferenceFoundAsync(referenceItem).ConfigureAwait(false);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.LanguageServiceIndexFormat;
using Microsoft.CodeAnalysis.FindUsages;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor.FindUsages
{
using static FindUsagesHelpers;
internal abstract partial class AbstractFindUsagesService
{
private static async Task FindSymbolMonikerReferencesAsync(
IFindSymbolMonikerUsagesService monikerUsagesService,
ISymbol definition,
IFindUsagesContext context,
CancellationToken cancellationToken)
{
var moniker = SymbolMoniker.TryCreate(definition);
if (moniker == null)
return;
// Let the find-refs window know we have outstanding work
await using var _ = await context.ProgressTracker.AddSingleItemAsync().ConfigureAwait(false);
var displayParts = GetDisplayParts(definition).Add(
new TaggedText(TextTags.Text, EditorFeaturesResources.external));
var definitionItem = DefinitionItem.CreateNonNavigableItem(
tags: GlyphTags.GetTags(definition.GetGlyph()),
displayParts,
originationParts: DefinitionItem.GetOriginationParts(definition));
var monikers = ImmutableArray.Create(moniker);
var first = true;
await foreach (var referenceItem in monikerUsagesService.FindReferencesByMoniker(
definitionItem, monikers, context.ProgressTracker, cancellationToken))
{
if (first)
{
// found some results. Add the definition item to the context.
first = false;
await context.OnDefinitionFoundAsync(definitionItem).ConfigureAwait(false);
}
await context.OnExternalReferenceFoundAsync(referenceItem).ConfigureAwait(false);
}
}
}
}
| mit | C# |
5189349073918fd96e4a81b5c65ca1671d79dd66 | Update assembly file version | ailn/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,lygasch/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,dasha91/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,makhdumi/azure-sdk-for-net,cwickham3/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,nacaspi/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,zaevans/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,smithab/azure-sdk-for-net,relmer/azure-sdk-for-net,xindzhan/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,juvchan/azure-sdk-for-net,olydis/azure-sdk-for-net,naveedaz/azure-sdk-for-net,pankajsn/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,yoreddy/azure-sdk-for-net,robertla/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,pomortaz/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,alextolp/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,r22016/azure-sdk-for-net,hyonholee/azure-sdk-for-net,btasdoven/azure-sdk-for-net,olydis/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,pilor/azure-sdk-for-net,smithab/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,r22016/azure-sdk-for-net,akromm/azure-sdk-for-net,ogail/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,hovsepm/azure-sdk-for-net,atpham256/azure-sdk-for-net,nemanja88/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pinwang81/azure-sdk-for-net,gubookgu/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,guiling/azure-sdk-for-net,enavro/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,jamestao/azure-sdk-for-net,rohmano/azure-sdk-for-net,stankovski/azure-sdk-for-net,atpham256/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,lygasch/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shuagarw/azure-sdk-for-net,dominiqa/azure-sdk-for-net,amarzavery/azure-sdk-for-net,robertla/azure-sdk-for-net,vladca/azure-sdk-for-net,r22016/azure-sdk-for-net,samtoubia/azure-sdk-for-net,pattipaka/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,tpeplow/azure-sdk-for-net,mihymel/azure-sdk-for-net,makhdumi/azure-sdk-for-net,relmer/azure-sdk-for-net,pattipaka/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,pilor/azure-sdk-for-net,ogail/azure-sdk-for-net,scottrille/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,oaastest/azure-sdk-for-net,Nilambari/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,pinwang81/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,djyou/azure-sdk-for-net,xindzhan/azure-sdk-for-net,begoldsm/azure-sdk-for-net,juvchan/azure-sdk-for-net,jamestao/azure-sdk-for-net,djyou/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,dasha91/azure-sdk-for-net,AzCiS/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,alextolp/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,oaastest/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,nacaspi/azure-sdk-for-net,nathannfan/azure-sdk-for-net,peshen/azure-sdk-for-net,pinwang81/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,shutchings/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,pomortaz/azure-sdk-for-net,enavro/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,naveedaz/azure-sdk-for-net,AzCiS/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,relmer/azure-sdk-for-net,hovsepm/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,akromm/azure-sdk-for-net,AuxMon/azure-sdk-for-net,pattipaka/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,bgold09/azure-sdk-for-net,herveyw/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,robertla/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,yoreddy/azure-sdk-for-net,nathannfan/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,mihymel/azure-sdk-for-net,Nilambari/azure-sdk-for-net,zaevans/azure-sdk-for-net,makhdumi/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,kagamsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,kagamsft/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,AzCiS/azure-sdk-for-net,marcoippel/azure-sdk-for-net,guiling/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,AuxMon/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,tpeplow/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pomortaz/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,marcoippel/azure-sdk-for-net,oburlacu/azure-sdk-for-net,hovsepm/azure-sdk-for-net,rohmano/azure-sdk-for-net,scottrille/azure-sdk-for-net,xindzhan/azure-sdk-for-net,dominiqa/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,nathannfan/azure-sdk-for-net,bgold09/azure-sdk-for-net,shutchings/azure-sdk-for-net,guiling/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,ailn/azure-sdk-for-net,shuagarw/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,stankovski/azure-sdk-for-net,yoreddy/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,tpeplow/azure-sdk-for-net,samtoubia/azure-sdk-for-net,kagamsft/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,hyonholee/azure-sdk-for-net,peshen/azure-sdk-for-net,alextolp/azure-sdk-for-net,jtlibing/azure-sdk-for-net,btasdoven/azure-sdk-for-net,ailn/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,abhing/azure-sdk-for-net,pilor/azure-sdk-for-net,herveyw/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,smithab/azure-sdk-for-net,vladca/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,oaastest/azure-sdk-for-net,jtlibing/azure-sdk-for-net,jamestao/azure-sdk-for-net,dasha91/azure-sdk-for-net,cwickham3/azure-sdk-for-net,marcoippel/azure-sdk-for-net,oburlacu/azure-sdk-for-net,ogail/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jtlibing/azure-sdk-for-net,pankajsn/azure-sdk-for-net,pankajsn/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,mabsimms/azure-sdk-for-net,nemanja88/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,rohmano/azure-sdk-for-net,markcowl/azure-sdk-for-net,lygasch/azure-sdk-for-net,AuxMon/azure-sdk-for-net,btasdoven/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,begoldsm/azure-sdk-for-net,oburlacu/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,amarzavery/azure-sdk-for-net,mabsimms/azure-sdk-for-net,gubookgu/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,begoldsm/azure-sdk-for-net,scottrille/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,zaevans/azure-sdk-for-net,samtoubia/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jamestao/azure-sdk-for-net,abhing/azure-sdk-for-net,atpham256/azure-sdk-for-net,djyou/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,hyonholee/azure-sdk-for-net,vladca/azure-sdk-for-net,Nilambari/azure-sdk-for-net,shipram/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,olydis/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,amarzavery/azure-sdk-for-net,mabsimms/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,peshen/azure-sdk-for-net,samtoubia/azure-sdk-for-net,mihymel/azure-sdk-for-net,gubookgu/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,shipram/azure-sdk-for-net,enavro/azure-sdk-for-net,shipram/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,abhing/azure-sdk-for-net,juvchan/azure-sdk-for-net,shutchings/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,nemanja88/azure-sdk-for-net,naveedaz/azure-sdk-for-net,herveyw/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,cwickham3/azure-sdk-for-net,akromm/azure-sdk-for-net,dominiqa/azure-sdk-for-net,bgold09/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,shuagarw/azure-sdk-for-net | src/ResourceManagement/Resource/ResourceManagement/Properties/AssemblyInfo.cs | src/ResourceManagement/Resource/ResourceManagement/Properties/AssemblyInfo.cs | //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.18.2.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| //
// Copyright (c) Microsoft. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft Azure Resource Management Library")]
[assembly: AssemblyDescription("Provides Microsoft Azure resource management operations including Resource Groups.")]
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.18.1.0")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Azure .NET SDK")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
| mit | C# |
e689cfd65e739070f58654d6240f4ec3346bb496 | add using | albertodall/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers | src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs | src/Services/Ordering/Ordering.Infrastructure/Repositories/OrderRepository.cs | using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Exceptions;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
var order = await _context
.Orders
.Include(x => x.Address)
.FirstOrDefaultAsync(o => o.Id == orderId);
if (order == null)
{
order = _context
.Orders
.Local
.FirstOrDefault(o => o.Id == orderId);
}
if (order != null)
{
await _context.Entry(order)
.Collection(i => i.OrderItems).LoadAsync();
await _context.Entry(order)
.Reference(i => i.OrderStatus).LoadAsync();
}
return order;
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
| using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.AggregatesModel.OrderAggregate;
using Microsoft.eShopOnContainers.Services.Ordering.Domain.Seedwork;
using Ordering.Domain.Exceptions;
using System;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.Services.Ordering.Infrastructure.Repositories
{
public class OrderRepository
: IOrderRepository
{
private readonly OrderingContext _context;
public IUnitOfWork UnitOfWork
{
get
{
return _context;
}
}
public OrderRepository(OrderingContext context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public Order Add(Order order)
{
return _context.Orders.Add(order).Entity;
}
public async Task<Order> GetAsync(int orderId)
{
var order = await _context
.Orders
.Include(x => x.Address)
.FirstOrDefaultAsync(o => o.Id == orderId);
if (order == null)
{
order = _context
.Orders
.Local
.FirstOrDefault(o => o.Id == orderId);
}
if (order != null)
{
await _context.Entry(order)
.Collection(i => i.OrderItems).LoadAsync();
await _context.Entry(order)
.Reference(i => i.OrderStatus).LoadAsync();
}
return order;
}
public void Update(Order order)
{
_context.Entry(order).State = EntityState.Modified;
}
}
}
| mit | C# |
88b5567bcabd3a7db4115d74b4e31ab78ab60751 | Make the delegate test more challenging | jonathanvdc/ecsc | tests/cs/delegate-typedef/DelegateTypedef.cs | tests/cs/delegate-typedef/DelegateTypedef.cs | using System;
public delegate T2 Map<T1, T2>(T1 x);
public static class Program
{
private static int Apply(Map<int, int> f, int x)
{
return f(x);
}
private static int Square(int x)
{
return x * x;
}
public static void Main()
{
Console.WriteLine(Apply(Square, 10));
}
} | using System;
public delegate int IntMap(int x);
public static class Program
{
private static int Apply(IntMap f, int x)
{
return f(x);
}
private static int Square(int x)
{
return x * x;
}
public static void Main()
{
Console.WriteLine(Apply(Square, 10));
}
} | mit | C# |
380766a26c492b3791cdb6a813df6b0a2a3af2d5 | fix sample | bertt/quantized-mesh-tile-cs,bertt/quantized-mesh-tile-cs | samples/console/Program.cs | samples/console/Program.cs | using System;
using System.IO;
using System.Net.Http;
using Terrain.Tiles;
namespace quantized_mesh_tile_sample_console
{
class Program
{
static void Main(string[] args)
{
const string terrainTileUrl = @"https://maps.tilehosting.com/data/terrain-quantized-mesh/9/536/391.terrain?key=wYrAjVu6bV6ycoXliAPl";
var client = new HttpClient();
var bytes = client.GetByteArrayAsync(terrainTileUrl).Result;
var stream = new MemoryStream(bytes);
var terrainTile = TerrainTileParser.Parse(stream);
var triangles = terrainTile.GetTriangles(536, 391, 9);
var count = triangles.Count;
var first_x = triangles[0].Coordinate1.X;
var first_y = triangles[0].Coordinate1.Y;
var first_z = triangles[0].Coordinate1.Height;
Console.WriteLine($"Number of triangles: {count}");
Console.WriteLine($"Coordinates first triangle, first vertice: {first_x}, {first_y}, {first_z}");
Console.ReadLine();
}
}
}
| using System;
using System.IO;
using System.Net;
using System.Net.Http;
using Terrain.Tiles;
namespace quantized_mesh_tile_sample_console
{
class Program
{
static void Main(string[] args)
{
const string terrainTileUrl = "https://assets.cesium.com/1/0/0/0.terrain?v=1.1.0";
var cesiumClient = GetCesiumWebClient();
var bytes = cesiumClient.GetByteArrayAsync(terrainTileUrl).Result;
var stream = new MemoryStream(bytes);
var terrainTile = TerrainTileParser.Parse(stream);
var triangles = terrainTile.GetTriangles(0, 0, 0);
var count = triangles.Count;
var first_x = triangles[0].Coordinate1.X;
var first_y = triangles[0].Coordinate1.Y;
var first_z = triangles[0].Coordinate1.Height;
Console.WriteLine($"Number of triangles: {count}");
Console.WriteLine($"Coordinates first triangle, first vertice: {first_x}, {first_y}, {first_z}");
Console.ReadLine();
}
private static HttpClient GetCesiumWebClient()
{
var cesiumWebClient = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
});
cesiumWebClient.DefaultRequestHeaders.Add("accept", "application/vnd.quantized-mesh,application/octet-stream;q=0.9,*/*;q=0.01,*/*;access_token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkNDhkYmU1My04ZGQxLTQzNDgtOWUzOC05NmM0ZmY3NjU4ODEiLCJpZCI6MjU5LCJhc3NldHMiOnsiMSI6eyJ0eXBlIjoiVEVSUkFJTiIsImV4dGVuc2lvbnMiOlt0cnVlLHRydWUsdHJ1ZV19fSwic3JjIjoiNzkzNTg3YTEtYTk5Yi00ZGQ2LWJiODctMGJjNDMyNmQ1ODUwIiwiaWF0IjoxNTQxNTc4OTMxLCJleHAiOjE1NDE1ODI1MzF9.zZuQxTqsnyOPG_Mzr3-ZBEN7gHEELhvB3FhmzraL6Pg");
return cesiumWebClient;
}
}
}
| mit | C# |
f66e5b2215a9e925aa01719a25fd49793507443f | 修改命名空间。 | yuleyule66/Util,yuleyule66/Util | test/Util.Datas.Tests.Integration/SqlServer/Confis/ConnectionUtil.cs | test/Util.Datas.Tests.Integration/SqlServer/Confis/ConnectionUtil.cs | using System;
using System.Data.SqlClient;
using System.IO;
namespace Util.Datas.Tests.SqlServer.Confis
{
public static class ConnectionUtil
{
private const string DatabaseVariable = "SqlServer_DatabaseName";
private const string ConnectionStringTemplateVariable = "SqlServer_ConnectionStringTemplate";
private const string MasterDatabaseName = "master";
private const string DefaultDatabaseName = @"UtilTest";
private const string DefaultConnectionStringTemplate =
@"Server=.\\sql2014;Initial Catalog={0};User Id=sa;Password=sa;MultipleActiveResultSets=True";
public static string GetDatabaseName()
{
return Environment.GetEnvironmentVariable(DatabaseVariable) ?? DefaultDatabaseName;
}
public static string GetMasterConnectionString()
{
return string.Format(GetConnectionStringTemplate(), MasterDatabaseName);
}
public static string GetConnectionString()
{
return string.Format(GetConnectionStringTemplate(), GetDatabaseName());
}
private static string GetConnectionStringTemplate()
{
return
Environment.GetEnvironmentVariable(ConnectionStringTemplateVariable) ??
DefaultConnectionStringTemplate;
}
public static SqlConnection CreateConnection(string connectionString = null)
{
connectionString = connectionString ?? GetConnectionString();
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
public static string GetScript()
{
var scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database.sql");
return File.ReadAllText(scriptPath);
}
}
} | using System;
using System.Data.SqlClient;
using System.IO;
namespace DotNetCore.CAP.SqlServer.Test
{
public static class ConnectionUtil
{
private const string DatabaseVariable = "SqlServer_DatabaseName";
private const string ConnectionStringTemplateVariable = "SqlServer_ConnectionStringTemplate";
private const string MasterDatabaseName = "master";
private const string DefaultDatabaseName = @"UtilTest";
private const string DefaultConnectionStringTemplate =
@"Server=.\\sql2014;Initial Catalog={0};User Id=sa;Password=sa;MultipleActiveResultSets=True";
public static string GetDatabaseName()
{
return Environment.GetEnvironmentVariable(DatabaseVariable) ?? DefaultDatabaseName;
}
public static string GetMasterConnectionString()
{
return string.Format(GetConnectionStringTemplate(), MasterDatabaseName);
}
public static string GetConnectionString()
{
return string.Format(GetConnectionStringTemplate(), GetDatabaseName());
}
private static string GetConnectionStringTemplate()
{
return
Environment.GetEnvironmentVariable(ConnectionStringTemplateVariable) ??
DefaultConnectionStringTemplate;
}
public static SqlConnection CreateConnection(string connectionString = null)
{
connectionString = connectionString ?? GetConnectionString();
var connection = new SqlConnection(connectionString);
connection.Open();
return connection;
}
public static string GetScript()
{
var scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "database.sql");
return File.ReadAllText(scriptPath);
}
}
} | mit | C# |
99fe6b6463d5e27608ca28a1bb91145ea0c2baf4 | Remove nullable disable | ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework.Tests/Containers/TestSceneEnumeratorVersion.cs | osu.Framework.Tests/Containers/TestSceneEnumeratorVersion.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 NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Containers
{
public class TestSceneEnumeratorVersion : FrameworkTestScene
{
private Container parent = null!;
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = parent = new Container
{
Child = new Container()
};
});
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var _ in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Clear();
}
}));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using NUnit.Framework;
using osu.Framework.Graphics.Containers;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Containers
{
public class TestSceneEnumeratorVersion : FrameworkTestScene
{
private Container parent;
[SetUp]
public void SetUp() => Schedule(() =>
{
Child = parent = new Container
{
Child = new Container()
};
});
[Test]
public void TestEnumeratingNormally()
{
AddStep("iterate through parent doing nothing", () => Assert.DoesNotThrow(() =>
{
foreach (var _ in parent)
{
}
}));
}
[Test]
public void TestAddChildDuringEnumerationFails()
{
AddStep("adding child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Add(new Container());
}
}));
}
[Test]
public void TestRemoveChildDuringEnumerationFails()
{
AddStep("removing child during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var child in parent)
{
parent.Remove(child, true);
}
}));
}
[Test]
public void TestClearDuringEnumerationFails()
{
AddStep("clearing children during enumeration fails", () => Assert.Throws<InvalidOperationException>(() =>
{
foreach (var _ in parent)
{
parent.Clear();
}
}));
}
}
}
| mit | C# |
97776bf6b2015ce8e65ef843ccf7b78e350c35e1 | fix type | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Responses/GetApprenticeshipUpdatesResponse.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Responses/GetApprenticeshipUpdatesResponse.cs | using System;
using System.Collections.Generic;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.CommitmentsV2.Types.Dtos;
namespace SFA.DAS.CommitmentsV2.Api.Types.Responses
{
public class GetApprenticeshipUpdatesResponse
{
public IReadOnlyCollection<ApprenticeshipUpdate> ApprenticeshipUpdates { get; set; }
public class ApprenticeshipUpdate
{
public long Id { get; set; }
public long ApprenticeshipId { get; set; }
public Party OriginatingParty { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DeliveryModel? DeliveryModel { get; set; }
public DateTime? EmploymentEndDate { get; set; }
public int? EmploymentPrice { get; set; }
public ProgrammeType? TrainingType { get; set; }
public string TrainingCode { get; set; }
public string Version { get; set; }
public string Option { get; set; }
public string TrainingName { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime? DateOfBirth { get; set; }
}
}
}
| using System;
using System.Collections.Generic;
using SFA.DAS.CommitmentsV2.Types;
using SFA.DAS.CommitmentsV2.Types.Dtos;
namespace SFA.DAS.CommitmentsV2.Api.Types.Responses
{
public class GetApprenticeshipUpdatesResponse
{
public IReadOnlyCollection<ApprenticeshipUpdate> ApprenticeshipUpdates { get; set; }
public class ApprenticeshipUpdate
{
public long Id { get; set; }
public long ApprenticeshipId { get; set; }
public Party OriginatingParty { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DeliveryModel? DeliveryModel { get; set; }
public DateTime? EmploymentEndDate { get; set; }
public decimal? EmploymentPrice { get; set; }
public ProgrammeType? TrainingType { get; set; }
public string TrainingCode { get; set; }
public string Version { get; set; }
public string Option { get; set; }
public string TrainingName { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime? DateOfBirth { get; set; }
}
}
}
| mit | C# |
0fd798df9599e5f4892592327ca76b23b26b45b5 | Fix - AbstractDataType wasn't set properly for RowVersionColumnSpecificationBuilder | dr-noise/PolyGen | src/NoiseLab.PolyGen.Core/Builders/ColumnSpecifications/RowVersionColumnSpecificationBuilder.cs | src/NoiseLab.PolyGen.Core/Builders/ColumnSpecifications/RowVersionColumnSpecificationBuilder.cs | using NoiseLab.PolyGen.Core.Database;
namespace NoiseLab.PolyGen.Core.Builders.ColumnSpecifications
{
public class RowVersionColumnSpecificationBuilder : ColumnSpecificationBuilderBase
{
public new RowVersionColumnSpecificationBuilder MaxLength(int maxLength)
{
base.MaxLength(maxLength);
return this;
}
public new RowVersionColumnSpecificationBuilder Nullable()
{
base.Nullable();
return this;
}
public new RowVersionColumnSpecificationBuilder PrimaryKey()
{
// TODO: Does it make sense to set RowVersion column as a (part of) Primary Key?
base.PrimaryKey();
return this;
}
public new RowVersionColumnSpecificationBuilder Identity()
{
base.Identity();
return this;
}
public new RowVersionColumnSpecificationBuilder Computed()
{
// TODO: Does it make sense to set RowVersion column as Computed?
base.Computed();
return this;
}
protected internal override AbstractDataType DataType { get; } = AbstractDataType.RowVersion;
internal RowVersionColumnSpecificationBuilder(ColumnBuilder columnFactory)
: base(columnFactory)
{
}
}
}
| using NoiseLab.PolyGen.Core.Database;
namespace NoiseLab.PolyGen.Core.Builders.ColumnSpecifications
{
public class RowVersionColumnSpecificationBuilder : ColumnSpecificationBuilderBase
{
public new RowVersionColumnSpecificationBuilder MaxLength(int maxLength)
{
base.MaxLength(maxLength);
return this;
}
public new RowVersionColumnSpecificationBuilder Nullable()
{
base.Nullable();
return this;
}
public new RowVersionColumnSpecificationBuilder PrimaryKey()
{
// TODO: Does it make sense to set RowVersion column as a (part of) Primary Key?
base.PrimaryKey();
return this;
}
public new RowVersionColumnSpecificationBuilder Identity()
{
base.Identity();
return this;
}
public new RowVersionColumnSpecificationBuilder Computed()
{
// TODO: Does it make sense to set RowVersion column as Computed?
base.Computed();
return this;
}
protected internal override AbstractDataType DataType { get; }
internal RowVersionColumnSpecificationBuilder(ColumnBuilder columnFactory)
: base(columnFactory)
{
}
}
}
| mit | C# |
b1cbf4c1fe50dcdbf7cf47d8630db11e1ee217fe | Reduce number of passive ports for ProFtpd. | robinrodricks/FluentFTP,robinrodricks/FluentFTP,robinrodricks/FluentFTP | FluentFTP.Xunit/Docker/Containers/ProFtpdContainer.cs | FluentFTP.Xunit/Docker/Containers/ProFtpdContainer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
namespace FluentFTP.Xunit.Docker.Containers {
internal class ProFtpdContainer : DockerFtpContainer {
public ProFtpdContainer() {
ServerType = FtpServer.ProFTPD;
ServerName = "proftpd";
DockerImage = "proftpd:fluentftp";
DockerImageOriginal = "kibatic/proftpd";
DockerGithub = "https://github.com/kibatic/docker-proftpd";
//RunCommand = "docker run -d --net host -e FTP_LIST=\"fluentroot:fluentpass\" -e MASQUERADE_ADDRESS=1.2.3.4 proftpd:fluentftp";
}
/// <summary>
/// For help creating this section see https://github.com/testcontainers/testcontainers-dotnet#supported-commands
/// </summary>
public override ITestcontainersBuilder<TestcontainersContainer> Configure(ITestcontainersBuilder<TestcontainersContainer> builder) {
builder = ExposePortRange(builder, 50000, 50010);
builder = builder
.WithEnvironment("FTP_LIST", DockerFtpConfig.FtpUser + ":" + DockerFtpConfig.FtpPass)
.WithEnvironment("PASSIVE_MIN_PORT", "50000")
.WithEnvironment("PASSIVE_MAX_PORT", "50010")
.WithEnvironment("MASQUERADE_ADDRESS", "127.0.0.1");
return builder;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DotNet.Testcontainers.Builders;
using DotNet.Testcontainers.Containers;
namespace FluentFTP.Xunit.Docker.Containers {
internal class ProFtpdContainer : DockerFtpContainer {
public ProFtpdContainer() {
ServerType = FtpServer.ProFTPD;
ServerName = "proftpd";
DockerImage = "proftpd:fluentftp";
DockerImageOriginal = "kibatic/proftpd";
DockerGithub = "https://github.com/kibatic/docker-proftpd";
//RunCommand = "docker run -d --net host -e FTP_LIST=\"fluentroot:fluentpass\" -e MASQUERADE_ADDRESS=1.2.3.4 proftpd:fluentftp";
}
/// <summary>
/// For help creating this section see https://github.com/testcontainers/testcontainers-dotnet#supported-commands
/// </summary>
public override ITestcontainersBuilder<TestcontainersContainer> Configure(ITestcontainersBuilder<TestcontainersContainer> builder) {
builder = ExposePortRange(builder, 50000, 50100);
builder = builder
.WithEnvironment("FTP_LIST", DockerFtpConfig.FtpUser + ":" + DockerFtpConfig.FtpPass)
.WithEnvironment("PASSIVE_MIN_PORT", "50000")
.WithEnvironment("PASSIVE_MAX_PORT", "50100")
.WithEnvironment("MASQUERADE_ADDRESS", "127.0.0.1");
return builder;
}
}
}
| mit | C# |
2bc0a173a9c9641cce56e687fcfda06f76910b6f | Update Gun.cs | daybson/LaserRaycast | Assets/Gun.cs | Assets/Gun.cs | /*
* Copyright 2014
* author: Daybson B.S. Paisante
* daybson.paisante@outlook.com
* http://daybsonpaisante.wordpress.com/
*/
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
private LineRenderer lineRenderer;
void Start ()
{
lineRenderer = this.GetComponent<LineRenderer> ();
}
void Update ()
{
RaycastHit hit;
//line origin
lineRenderer.SetPosition (0, this.transform.position);
//if the ray hits something, fill hit with the contact point informations
if (Physics.Raycast (this.transform.position, this.transform.forward, out hit))
//line ending is set as the contact point
lineRenderer.SetPosition (1, hit.point);
else
//if hits anything, line goes to infinity foward the player
lineRenderer.SetPosition (1, transform.forward * 99999999);
}
}
| /*
* Copyright 2014
* autor: Daybson B.S. Paisante
* email: daybsonbsp@gmail.com
* encontrado em: http://daybsonpaisante.wordpress.com/
*/
using UnityEngine;
using System.Collections;
public class Gun : MonoBehaviour
{
private LineRenderer lineRenderer;
void Start ()
{
var MyNewVar = this.transform.GetComponent<Rigidbody> ();
//salva referência ao LineRenderer
lineRenderer = this.GetComponent<LineRenderer> ();
}
void Update ()
{
//objeto do contato do raio lançado
RaycastHit hit;
//origem da linha
lineRenderer.SetPosition (0, this.transform.position);
//se raio tocar em algo, hit é preenchido com informações do contato
if (Physics.Raycast (this.transform.position, this.transform.forward, out hit))
//seta final da linha no ponto de contato
lineRenderer.SetPosition (1, hit.point);
else
//seta final da linha rumo ao infinito na direção frontal do player.
lineRenderer.SetPosition (1, transform.forward * 99999999);
}
} | mit | C# |
dff80d2d5281abe2e38959ee76d891fe38728796 | Update GroupKeyInvalidException.cs (#709) | vknet/vk,vknet/vk | VkNet/Exception/GroupKeyInvalidException.cs | VkNet/Exception/GroupKeyInvalidException.cs | using System;
using VkNet.Utils;
namespace VkNet.Exception
{
/// <inheritdoc />
/// <summary>
/// Ключ доступа сообщества недействителен.
/// Код ошибки - 27
/// </summary>
[Serializable]
public class GroupKeyInvalidException : VkApiMethodInvokeException
{
/// <inheritdoc />
public GroupKeyInvalidException(VkResponse response) : base(message: response[key: "error_msg"])
{
}
}
}
| using System;
using VkNet.Utils;
namespace VkNet.Exception
{
/// <inheritdoc />
/// <summary>
/// Ключ доступа сообщества недействителен.
/// Код ошибки - 27
/// </summary>
[Serializable]
public class GroupKeyInvalidException : VkApiMethodInvokeException
{
/// <inheritdoc />
public GroupKeyInvalidException(VkResponse error) : base(message: error)
{
}
}
} | mit | C# |
382c3b0e4234c5942a3b739fb38b0518ebdb259b | Update WalletWasabi.Gui/CrashReport/ViewModels/CrashReportWindowViewModel.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/CrashReport/ViewModels/CrashReportWindowViewModel.cs | WalletWasabi.Gui/CrashReport/ViewModels/CrashReportWindowViewModel.cs | using ReactiveUI;
using Splat;
using System;
using System.Reactive;
using System.Reactive.Linq;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.CrashReport.ViewModels
{
public class CrashReportWindowViewModel : ViewModelBase
{
private bool _closeTrigger;
public CrashReportWindowViewModel()
{
var global = Locator.Current.GetService<Global>();
CrashReporter = global.CrashReporter;
OpenLogCommand = ReactiveCommand.CreateFromTask(async () => await FileHelpers.OpenFileInTextEditorAsync(Logger.FilePath));
OkCommand = ReactiveCommand.Create(() =>
{
CloseTrigger = true;
});
Observable
.Merge(OpenLogCommand.ThrownExceptions)
.Merge(OkCommand.ThrownExceptions)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
private CrashReporter CrashReporter { get; }
public int MinWidth => 520;
public int MinHeight => 280;
public string Title => "Wasabi Wallet - Crash Reporting";
public string Details => $"Wasabi has crashed. You can check the details here, open the log file, or report the crash to the support team.{Environment.NewLine}{Environment.NewLine}Please always consider your privacy before sharing any information!";
public string Message => CrashReporter?.SerializedException?.Message;
public bool CloseTrigger
{
get => _closeTrigger;
set => this.RaiseAndSetIfChanged(ref _closeTrigger, value);
}
public ReactiveCommand<Unit, Unit> OpenLogCommand { get; }
public ReactiveCommand<Unit, Unit> OkCommand { get; }
}
}
| using ReactiveUI;
using Splat;
using System;
using System.Reactive;
using System.Reactive.Linq;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Gui.ViewModels;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.CrashReport.ViewModels
{
public class CrashReportWindowViewModel : ViewModelBase
{
private bool _closeTrigger;
public CrashReportWindowViewModel()
{
var global = Locator.Current.GetService<Global>();
CrashReporter = global.CrashReporter;
OpenLogCommand = ReactiveCommand.CreateFromTask(async () => await FileHelpers.OpenFileInTextEditorAsync(Logger.FilePath));
OkCommand = ReactiveCommand.Create(() =>
{
CloseTrigger = true;
});
Observable
.Merge(OpenLogCommand.ThrownExceptions)
.Merge(OkCommand.ThrownExceptions)
.ObserveOn(RxApp.TaskpoolScheduler)
.Subscribe(ex => Logger.LogError(ex));
}
private CrashReporter CrashReporter { get; }
public int MinWidth => 520;
public int MinHeight => 280;
public string Title => "Wasabi Wallet - Crash Reporting";
public string Details => $"Wasabi has crashed. You can check the details here, open the log file, or report the crash to the support team. {Environment.NewLine}{Environment.NewLine}Please always consider your privacy before sharing any information!";
public string Message => CrashReporter?.SerializedException?.Message;
public bool CloseTrigger
{
get => _closeTrigger;
set => this.RaiseAndSetIfChanged(ref _closeTrigger, value);
}
public ReactiveCommand<Unit, Unit> OpenLogCommand { get; }
public ReactiveCommand<Unit, Unit> OkCommand { get; }
}
}
| mit | C# |
3fd393ee5ea1e7e9c219b6ee2673b3635b80f6f8 | Fix check if domain events has to be transferred | Codelet/Codelet | Database/Domain/DomainModelDatabaseEntity.cs | Database/Domain/DomainModelDatabaseEntity.cs | namespace Codelet.Database.Domain
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using Codelet.Database.Entities;
using Codelet.Domain;
/// <summary>
/// The database entity for domain models base class.
/// </summary>
/// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
/// <typeparam name="TModel">The type of the model.</typeparam>
public abstract class DomainModelDatabaseEntity<TIdentifier, TModel>
: DatabaseEntityWithModel<TIdentifier, TModel>, IDomainModelDatabaseEntity
where TModel : DomainModel
{
/// <summary>
/// Initializes a new instance of the <see cref="DomainModelDatabaseEntity{TIdentifier, TModel}"/> class.
/// </summary>
/// <param name="model">The model.</param>
protected DomainModelDatabaseEntity(TModel model)
: base(model)
{
this.Timer.Start();
this.SkipFirstEventsTransfer = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="DomainModelDatabaseEntity{TIdentifier, TModel}"/> class.
/// </summary>
[Obsolete(ForEntityFrameworkOnlyObsoleteReason)]
protected DomainModelDatabaseEntity()
{
this.Timer.Start();
this.SkipFirstEventsTransfer = false;
}
private bool SkipFirstEventsTransfer { get; set; }
private DateTimeOffset Created { get; } = DateTimeOffset.UtcNow;
private Stopwatch Timer { get; } = new Stopwatch();
private ConcurrentBag<Func<IDomainEventsSerializer, DomainEventDatabaseEntity>> DomainEvents { get; }
= new ConcurrentBag<Func<IDomainEventsSerializer, DomainEventDatabaseEntity>>();
/// <inheritdoc />
IEnumerable<DomainEventDatabaseEntity> IDomainModelDatabaseEntity.TransferDomainEvents(
IDomainEventsSerializer serializer)
{
if (this.SkipFirstEventsTransfer)
{
this.SkipFirstEventsTransfer = false;
yield break;
}
while (this.DomainEvents.TryTake(out var domainEvent))
{
yield return domainEvent(serializer);
}
}
/// <summary>
/// Raises the domain event.
/// </summary>
/// <typeparam name="TDatabaseEntity">The type of the database entity.</typeparam>
/// <typeparam name="TDomainEventArgs">The type of the domain event arguments.</typeparam>
/// <param name="args">The <typeparamref name="TDomainEventArgs"/> instance containing the event data.</param>
protected void RaiseDomainEvent<TDatabaseEntity, TDomainEventArgs>(TDomainEventArgs args)
where TDatabaseEntity : DomainModelDatabaseEntity<TIdentifier, TModel>
where TDomainEventArgs : DomainEventArgs<TModel>
=> this.DomainEvents.Add(serializer
=> DomainEventDatabaseEntity.Create<TModel, TDomainEventArgs, TDatabaseEntity, TIdentifier>(
this.Created + this.Timer.Elapsed,
this.Id,
serializer.Serialize<TModel, TDomainEventArgs>(args)));
}
} | namespace Codelet.Database.Domain
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using Codelet.Database.Entities;
using Codelet.Domain;
/// <summary>
/// The database entity for domain models base class.
/// </summary>
/// <typeparam name="TIdentifier">The type of the identifier.</typeparam>
/// <typeparam name="TModel">The type of the model.</typeparam>
public abstract class DomainModelDatabaseEntity<TIdentifier, TModel>
: DatabaseEntityWithModel<TIdentifier, TModel>, IDomainModelDatabaseEntity
where TModel : DomainModel
{
/// <summary>
/// Initializes a new instance of the <see cref="DomainModelDatabaseEntity{TIdentifier, TModel}"/> class.
/// </summary>
/// <param name="model">The model.</param>
protected DomainModelDatabaseEntity(TModel model)
: base(model)
{
this.Timer.Start();
}
/// <summary>
/// Initializes a new instance of the <see cref="DomainModelDatabaseEntity{TIdentifier, TModel}"/> class.
/// </summary>
[Obsolete(ForEntityFrameworkOnlyObsoleteReason)]
protected DomainModelDatabaseEntity()
{
this.Timer.Start();
}
private DateTimeOffset Created { get; } = DateTimeOffset.UtcNow;
private Stopwatch Timer { get; } = new Stopwatch();
private ConcurrentBag<Func<IDomainEventsSerializer, DomainEventDatabaseEntity>> DomainEvents { get; }
= new ConcurrentBag<Func<IDomainEventsSerializer, DomainEventDatabaseEntity>>();
/// <inheritdoc />
public IEnumerable<DomainEventDatabaseEntity> TransferDomainEvents(
IDomainEventsSerializer serializer)
{
if (this.Id == default)
{
yield break;
}
while (this.DomainEvents.TryTake(out var domainEvent))
{
yield return domainEvent(serializer);
}
}
/// <summary>
/// Raises the domain event.
/// </summary>
/// <typeparam name="TDatabaseEntity">The type of the database entity.</typeparam>
/// <typeparam name="TDomainEventArgs">The type of the domain event arguments.</typeparam>
/// <param name="args">The <typeparamref name="TDomainEventArgs"/> instance containing the event data.</param>
protected void RaiseDomainEvent<TDatabaseEntity, TDomainEventArgs>(TDomainEventArgs args)
where TDatabaseEntity : DomainModelDatabaseEntity<TIdentifier, TModel>
where TDomainEventArgs : DomainEventArgs<TModel>
=> this.DomainEvents.Add(serializer
=> DomainEventDatabaseEntity.Create<TModel, TDomainEventArgs, TDatabaseEntity, TIdentifier>(
this.Created + this.Timer.Elapsed,
this.Id,
serializer.Serialize<TModel, TDomainEventArgs>(args)));
}
} | mit | C# |
4c7f18f9cb47b591336ac2d14c4a1ec7c35a1c5a | Update version | sergeyshushlyapin/Sitecore.FakeDb | src/AssemblyVersionInfo.cs | src/AssemblyVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0.0")]
[assembly: AssemblyInformationalVersion("2.0.0-beta1")] | using System.Reflection;
[assembly: AssemblyVersion("2.0.0.0")]
[assembly: AssemblyFileVersion("2.0.0-alpha1")]
[assembly: AssemblyInformationalVersion("2.0.0-alpha1")] | mit | C# |
3f042a3d01748c3ab9b4c0a305ffe7ce2589a455 | Revert "allow test of eidas signitures" | crocs-muni/roca,crocs-muni/roca,crocs-muni/roca,crocs-muni/roca | csharp/RocaTest/Program.cs | csharp/RocaTest/Program.cs | using System;
using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
namespace RocaTest
{
class Program
{
static void Main(string[] args)
{
foreach (string certFile in Directory.GetFiles("data"))
{
if (TestCert(certFile))
Console.WriteLine(certFile + " - contains RSA public key vulnerable to ROCA (CVE-2017-15361)");
else
Console.WriteLine(certFile + " - Certificate does not contain RSA public key vulnerable to ROCA (CVE-2017-15361)");
}
}
static bool TestCert(string certFile)
{
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(File.ReadAllBytes(certFile));
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
return RocaTest.IsVulnerable(rsaKeyParameters);
}
}
}
| using System;
using System.IO;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.X509;
using iTextSharp.text.pdf;
using System.Collections.Generic;
using System.Security.Cryptography.Pkcs;
namespace RocaTest
{
class Program
{
static void Main(string[] args)
{
foreach (string certFile in Directory.GetFiles("data")) {
if (certFile.EndsWith(".pdf")) {
TestPDF(certFile);
} else {
if (certFile.EndsWith(".pem")) {
Console.WriteLine(certFile + " - contains RSA public key vulnerable to ROCA (CVE-2017-15361)");
} else {
Console.WriteLine(certFile + " - Certificate does not contain RSA public key vulnerable to ROCA (CVE-2017-15361)");
}
}
Console.ReadLine();
}
}
static void TestPDF(string path)
{
Console.WriteLine("processing PDF");
AcroFields acroFields = new PdfReader(path).AcroFields;
List<string> names = acroFields.GetSignatureNames();
foreach (var name in names) {
try {
Console.WriteLine(name);
PdfDictionary dict = acroFields.GetSignatureDictionary(name);
PdfString contents = (PdfString)PdfReader.GetPdfObject(dict.Get(PdfName.CONTENTS));
byte[] PKCS7 = contents.GetOriginalBytes();
var signedData = new SignedCms();
signedData.Decode(PKCS7);
Console.WriteLine(signedData.Certificates.Count);
int i = 0;
foreach (var certificate in signedData.Certificates) {
i++;
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(certificate.GetRawCertData());
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
if (RocaTest.IsVulnerable(rsaKeyParameters)) {
Console.WriteLine("Cetificate #" + i + " is vulnerable. Cert Hash: " + certificate.GetCertHashString());
} else {
Console.WriteLine("Cetificate #" + i + " is NOT vulnerable");
}
}
} catch (Exception exc) {
Console.WriteLine(exc.Message);
}
}
}
static bool TestCert(string certFile)
{
X509CertificateParser x509CertificateParser = new X509CertificateParser();
X509Certificate x509Certificate = x509CertificateParser.ReadCertificate(File.ReadAllBytes(certFile));
RsaKeyParameters rsaKeyParameters = x509Certificate.GetPublicKey() as RsaKeyParameters;
return RocaTest.IsVulnerable(rsaKeyParameters);
}
}
}
| mit | C# |
8518535395703aeae8a0a6440c6492bed675ff3a | Update company name and copyright. | M15sy/postalcodefinder,martincostello/postalcodefinder,martincostello/postalcodefinder,TeamArachne/postalcodefinder,TeamArachne/postalcodefinder,M15sy/postalcodefinder | postalcodefinder/postalcodefinder/Properties/AssemblyInfo.cs | postalcodefinder/postalcodefinder/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("postalcodefinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Experian")]
[assembly: AssemblyProduct("postalcodefinder")]
[assembly: AssemblyCopyright("Copyright © Experian 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("6a604569-bbd4-4f13-b308-ff3969ff7549")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("postalcodefinder")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("postalcodefinder")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("6a604569-bbd4-4f13-b308-ff3969ff7549")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| apache-2.0 | C# |
8552e86ca4b0cbd934a2668d43fb628dd4cc7b88 | Fix test for requires availability for params argument. | SergeyTeplyakov/CodeContractor,SergeyTeplyakov/CodeContracts.Analyzer,SergeyTeplyakov/CodeContractor,SergeyTeplyakov/CodeContracts.Analyzer | src/CodeContractor.UnitTests/Contracts/AddNotNullRequires/AddNotNullRequiresAvailabilityTests.cs | src/CodeContractor.UnitTests/Contracts/AddNotNullRequires/AddNotNullRequiresAvailabilityTests.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CodeContractor.Refactorings;
using NUnit.Framework;
namespace CodeContractor.UnitTests.Contracts
{
[TestFixture]
public class AddNotNullRequiresAvailabilityTests
{
[TestCaseSource("RefactoringAvailabilitySource")]
public async Task<bool> Test_Refactoring_Availability(string method)
{
var doc = await ClassTemplate.FromMethodAsync(method);
var refactoring = await AddNotNullRequiresRefactoring.Create(doc.SelectedNode, doc.Document);
return await refactoring.IsAvailableAsync(CancellationToken.None);
}
private static IEnumerable<TestCaseData> RefactoringAvailabilitySource()
{
yield return new TestCaseData(
@"public static void Foo(string s{caret}tr)
{
}")
.Returns(true);
yield return new TestCaseData(
@"public static void Foo(string str)
{
Console.WriteLine(s{caret}tr);
}")
.Returns(true);
yield return new TestCaseData(
@"public abstract void Foo(string s{caret}tr);")
.Returns(false);
yield return new TestCaseData(
@"public void Foo(string str)
{
if (s{caret}tr == null)
{
Console.WriteLine(42);
}
}")
.Returns(true);
yield return new TestCaseData(
@"public void Foo(string s{caret}tr)
{
Contract.Requires(str != null);
}")
.Returns(false);
// Not Implemented yet!
yield return new TestCaseData(
@"public void Foo(string str)
{
Contract.Requires(!string.IsNullOrEmpty(str));
}")
.Returns(false).Ignore();
yield return new TestCaseData(
@"public void Foo(string str)
{
Contract.Requires(string.IsNullOrEmpty(str));
}")
.Returns(false).Ignore();
// Not Implemented yet!
yield return new TestCaseData(
@"public void Foo(string str)
{
if (str == null) throw new ArgumentNullException(""str"");
}")
.Returns(false).Ignore();
yield return new TestCaseData(
@"public void EnabledOnParamsArguments(params object[] argume{caret}nts)
{}")
.Returns(true);
yield return new TestCaseData(
@"public void DisabledBecauseAlreadyCheckedInFirstComplex(string s1, string s2{caret})
{
Contract.Requires((s1 != null || s1.Length == 0) && s2 != null);
}")
.Returns(false);
}
}
} | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using CodeContractor.Refactorings;
using NUnit.Framework;
namespace CodeContractor.UnitTests.Contracts
{
[TestFixture]
public class AddNotNullRequiresAvailabilityTests
{
[TestCaseSource("RefactoringAvailabilitySource")]
public async Task<bool> Test_Refactoring_Availability(string method)
{
var doc = await ClassTemplate.FromMethodAsync(method);
var refactoring = await AddNotNullRequiresRefactoring.Create(doc.SelectedNode, doc.Document);
return await refactoring.IsAvailableAsync(CancellationToken.None);
}
private static IEnumerable<TestCaseData> RefactoringAvailabilitySource()
{
yield return new TestCaseData(
@"public static void Foo(string s{caret}tr)
{
}")
.Returns(true);
yield return new TestCaseData(
@"public static void Foo(string str)
{
Console.WriteLine(s{caret}tr);
}")
.Returns(true);
yield return new TestCaseData(
@"public abstract void Foo(string s{caret}tr);")
.Returns(false);
yield return new TestCaseData(
@"public void Foo(string str)
{
if (s{caret}tr == null)
{
Console.WriteLine(42);
}
}")
.Returns(true);
yield return new TestCaseData(
@"public void Foo(string s{caret}tr)
{
Contract.Requires(str != null);
}")
.Returns(false);
// Not Implemented yet!
yield return new TestCaseData(
@"public void Foo(string str)
{
Contract.Requires(!string.IsNullOrEmpty(str));
}")
.Returns(false).Ignore();
yield return new TestCaseData(
@"public void Foo(string str)
{
Contract.Requires(string.IsNullOrEmpty(str));
}")
.Returns(false).Ignore();
// Not Implemented yet!
yield return new TestCaseData(
@"public void Foo(string str)
{
if (str == null) throw new ArgumentNullException(""str"");
}")
.Returns(false).Ignore();
yield return new TestCaseData(
@"public void EnabledOnParamsArguments(params object[] arguments{caret})
{}")
.Returns(true);
yield return new TestCaseData(
@"public void DisabledBecauseAlreadyCheckedInFirstComplex(string s1, string s2{caret})
{
Contract.Requires((s1 != null || s1.Length == 0) && s2 != null);
}")
.Returns(false);
}
}
} | mit | C# |
f7707864c01b0d6c0e54f1af2b6ddd252b2a94e5 | correct FixType error | thorgeirk11/code-cracker,carloscds/code-cracker,baks/code-cracker,giggio/code-cracker,modulexcite/code-cracker,jhancock93/code-cracker,dlsteuer/code-cracker,dmgandini/code-cracker,robsonalves/code-cracker,akamud/code-cracker,code-cracker/code-cracker,andrecarlucci/code-cracker,f14n/code-cracker,ElemarJR/code-cracker,code-cracker/code-cracker,carloscds/code-cracker,kindermannhubert/code-cracker,AlbertoMonteiro/code-cracker,thomaslevesque/code-cracker,GuilhermeSa/code-cracker,eriawan/code-cracker,eirielson/code-cracker,caioadz/code-cracker,adraut/code-cracker,jwooley/code-cracker,gerryaobrien/code-cracker | src/CSharp/CodeCracker/Style/TaskNameAsyncCodeFixProvider.cs | src/CSharp/CodeCracker/Style/TaskNameAsyncCodeFixProvider.cs | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Rename;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CodeCracker.Style
{
[ExportCodeFixProvider("CodeCrackerTaskNameAsyncCodeFixProvider", LanguageNames.CSharp), Shared]
public class TaskNameAsyncCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> GetFixableDiagnosticIds() => ImmutableArray.Create(TaskNameAsyncAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task ComputeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().First();
context.RegisterFix(CodeAction.Create("Change method name including 'Async'.", c => ChangeMethodNameAsync(context.Document, declaration, c)), diagnostic);
}
private async Task<Solution> ChangeMethodNameAsync(Document document, MethodDeclarationSyntax methodStatement, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var newName = methodStatement.Identifier.ToString()+"Async";
var solution = document.Project.Solution;
if (solution == null) return null;
var symbol = semanticModel.GetDeclaredSymbol(methodStatement, cancellationToken);
if (symbol == null) return null;
var options = solution.Workspace.Options;
var newSolution = await Renamer.RenameSymbolAsync(solution, symbol, newName,
options, cancellationToken).ConfigureAwait(false);
return newSolution;
}
}
} | using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Rename;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace CodeCracker.Style
{
[ExportCodeFixProvider("CodeCrackerTaskNameAsyncCodeFixProvider", LanguageNames.CSharp), Shared]
public class TaskNameAsyncCodeFixProvider : CodeFixProvider
{
public sealed override ImmutableArray<string> GetFixableDiagnosticIds() => ImmutableArray.Create(TaskNameAsyncAnalyzer.DiagnosticId);
public sealed override FixAllProvider GetFixAllProvider()
{
return WellKnownFixAllProviders.BatchFixer;
}
public sealed override async Task ComputeFixesAsync(CodeFixContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostic = context.Diagnostics.First();
var diagnosticSpan = diagnostic.Location.SourceSpan;
var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().First();
context.RegisterFix(CodeAction.Create("Change method name including 'Async'.", c => ChangeMethodNameAsync(context.Document, declaration, c, FixType.PrivateFix)), diagnostic);
}
private async Task<Solution> ChangeMethodNameAsync(Document document, MethodDeclarationSyntax methodStatement, CancellationToken cancellationToken, FixType fixType)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
var newName = methodStatement.Identifier.ToString()+"Async";
var solution = document.Project.Solution;
if (solution == null) return null;
var symbol = semanticModel.GetDeclaredSymbol(methodStatement, cancellationToken);
if (symbol == null) return null;
var options = solution.Workspace.Options;
var newSolution = await Renamer.RenameSymbolAsync(solution, symbol, newName,
options, cancellationToken).ConfigureAwait(false);
return newSolution;
}
}
} | apache-2.0 | C# |
1b5f90884bbca95c5f4e8cf45deff66e5793fab1 | Move inside the div | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Views/TestItems/_TestItemsForm.cshtml | Anlab.Mvc/Views/TestItems/_TestItemsForm.cshtml | @using System.Runtime.InteropServices.ComTypes
@model Anlab.Core.Domain.TestItem
@Html.HiddenFor(a => a.Category)
<div class="col">
<div class="form-group">
<label asp-for="Analysis" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Analysis" class="form-control" />
<span asp-validation-for="Analysis" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Category" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Categories" class="form-control" multiple="multiple">
@foreach (var category in TestCategories.All)
{
<option value="@category">@category</option>
}
</select>
<span asp-validation-for="Category" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Group" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Group" class="form-control" />
<span asp-validation-for="Group" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Public" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Public" class="form-control" >
<option value="true">Yes</option>
<option value="false">No</option>
</select>
<span asp-validation-for="Public" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Notes" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="Notes" class="form-control" rows="3"> </textarea>
<span asp-validation-for="Notes" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="AdditionalInfoPrompt" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="AdditionalInfoPrompt" class="form-control" rows="3"> </textarea>
<span asp-validation-for="AdditionalInfoPrompt" class="text-danger"></span>
</div>
</div>
</div>
| @using System.Runtime.InteropServices.ComTypes
@model Anlab.Core.Domain.TestItem
@Html.HiddenFor(a => a.Category)
<div class="col">
<div class="form-group">
<label asp-for="Analysis" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Analysis" class="form-control" />
<span asp-validation-for="Analysis" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Category" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Categories" class="form-control" multiple="multiple">
@foreach (var category in TestCategories.All)
{
<option value="@category">@category</option>
}
</select>
<span asp-validation-for="Category" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Group" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Group" class="form-control" />
<span asp-validation-for="Group" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Public" class="col-md-2 control-label"></label>
<div class="col-md-10">
<select asp-for="Public" class="form-control" >
<option value="true">Yes</option>
<option value="false">No</option>
</select>
<span asp-validation-for="Public" class="text-danger"></span>
</div>
</div>
<div class="form-group">
<label asp-for="Notes" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="Notes" class="form-control" rows="3"> </textarea>
<span asp-validation-for="Notes" class="text-danger"></span>
</div>
</div>
</div>
<div class="form-group">
<label asp-for="AdditionalInfoPrompt" class="col-md-2 control-label"></label>
<div class="col-md-10">
<textarea asp-for="AdditionalInfoPrompt" class="form-control" rows="3"> </textarea>
<span asp-validation-for="AdditionalInfoPrompt" class="text-danger"></span>
</div>
</div>
| mit | C# |
c1093ac52150af7fac615c3c0ad958c2108998dc | Print in reversed order method | ozim/CakeStuff | ReverseWords/LinkedListInOrderInsertion/LinkedList.cs | ReverseWords/LinkedListInOrderInsertion/LinkedList.cs | namespace LinkedListInOrderInsertion
{
using System;
using System.Collections.Generic;
public class LinkedList
{
private Element Head = null;
private Element Iterator = new Element();
internal void Add(int value)
{
Element insertedElement = new Element { Value = value };
if (Head == null) {
Head = insertedElement;
Iterator.Next = Head;
} else
{
Element current = Head;
if(current.Value > insertedElement.Value) {
Head = insertedElement;
Head.Next = current;
Iterator.Next = Head;
return;
}
while(current.Next != null) {
if(current.Next.Value > insertedElement.Value) {
insertedElement.Next = current.Next;
current.Next = insertedElement;
return;
}
current = current.Next;
}
current.Next = insertedElement;
}
}
internal int Last()
{
Element current = Head;
while (current.Next != null)
{
current = current.Next;
}
return current.Value;
}
internal void PrintInReversedOrder(Element startElement) {
if (startElement == null)
{
return;
}
PrintInReversedOrder(startElement.Next);
Console.WriteLine(startElement.Value);
}
internal IEnumerable<Element> Next()
{
if(Iterator.Next != null) {
yield return Iterator.Next;
}
}
}
}
| namespace LinkedListInOrderInsertion
{
using System;
using System.Collections.Generic;
public class LinkedList
{
private Element Head = null;
private Element Iterator = new Element();
internal void Add(int value)
{
Element insertedElement = new Element { Value = value };
if (Head == null) {
Head = insertedElement;
Iterator.Next = Head;
} else
{
Element current = Head;
if(current.Value > insertedElement.Value) {
Head = insertedElement;
Head.Next = current;
Iterator.Next = Head;
return;
}
while(current.Next != null) {
if(current.Next.Value > insertedElement.Value) {
insertedElement.Next = current.Next;
current.Next = insertedElement;
return;
}
current = current.Next;
}
current.Next = insertedElement;
}
}
internal int Last()
{
Element current = Head;
while (current.Next != null)
{
current = current.Next;
}
return current.Value;
}
internal IEnumerable<Element> Next()
{
if(Iterator.Next != null) {
yield return Iterator.Next;
}
}
}
}
| apache-2.0 | C# |
78372fcc56c17e5581551b1c471158c9c5d5bc80 | Test apphorbor deploy. | razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum | Source/SvNaumApp.Web/Views/Home/Index.cshtml | Source/SvNaumApp.Web/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET Test Apphorbor deploy.</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="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="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> | mit | C# |
54a6f3ac7f0f82ca1f6f2e16225799e098443768 | Update ProtectColumnWorksheet.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Worksheets/Security/ProtectColumnWorksheet.cs | Examples/CSharp/Worksheets/Security/ProtectColumnWorksheet.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security
{
public class ProtectColumnWorksheet
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.Worksheets[0];
// Define the style object.
Style style;
// Define the styleflag object.
StyleFlag flag;
// Loop through all the columns in the worksheet and unlock them.
for (int i = 0; i <= 255; i++)
{
style = sheet.Cells.Columns[(byte)i].Style;
style.IsLocked = false;
flag = new StyleFlag();
flag.Locked = true;
sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag);
}
// Get the first column style.
style = sheet.Cells.Columns[0].Style;
// Lock it.
style.IsLocked = true;
// Instantiate the flag.
flag = new StyleFlag();
// Set the lock setting.
flag.Locked = true;
// Apply the style to the first column.
sheet.Cells.Columns[0].ApplyStyle(style, flag);
// Protect the sheet.
sheet.Protect(ProtectionType.All);
// Save the excel file.
wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003);
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Worksheets.Security
{
public class ProtectColumnWorksheet
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
// Create a new workbook.
Workbook wb = new Workbook();
// Create a worksheet object and obtain the first sheet.
Worksheet sheet = wb.Worksheets[0];
// Define the style object.
Style style;
// Define the styleflag object.
StyleFlag flag;
// Loop through all the columns in the worksheet and unlock them.
for (int i = 0; i <= 255; i++)
{
style = sheet.Cells.Columns[(byte)i].Style;
style.IsLocked = false;
flag = new StyleFlag();
flag.Locked = true;
sheet.Cells.Columns[(byte)i].ApplyStyle(style, flag);
}
// Get the first column style.
style = sheet.Cells.Columns[0].Style;
// Lock it.
style.IsLocked = true;
// Instantiate the flag.
flag = new StyleFlag();
// Set the lock setting.
flag.Locked = true;
// Apply the style to the first column.
sheet.Cells.Columns[0].ApplyStyle(style, flag);
// Protect the sheet.
sheet.Protect(ProtectionType.All);
// Save the excel file.
wb.Save(dataDir + "output.out.xls", SaveFormat.Excel97To2003);
}
}
} | mit | C# |
a4726d7fc7269bab8586734a28c10b3e4677b630 | Fix a rebase error | FatturaElettronicaPA/FatturaElettronicaPA | FatturaElettronicaBody/DatiBeniServizi/AltriDatiGestionali.cs | FatturaElettronicaBody/DatiBeniServizi/AltriDatiGestionali.cs | using System;
using System.Xml;
using FatturaElettronica.Common;
namespace FatturaElettronica.FatturaElettronicaBody.DatiBeniServizi
{
/// <summary>
/// Blocco che consente di inserire, con riferimento ad una linea di dettaglio, diverse tipologie di informazioni utili ai fini
/// amministrativi, gestionali, etc.
/// </summary>
public class AltriDatiGestionali : BaseClassSerializable
{
public AltriDatiGestionali() { }
public AltriDatiGestionali(XmlReader r) : base(r) { }
/// <summary>
/// Codice che identifica la tipologia di informazione
/// </summary>
[DataProperty]
public string TipoDato { get; set; }
/// <summary>
/// Campo in cui inserire un valore alfanumerico riferito alla tipologia di informazione.
/// </summary>
[DataProperty]
public string RiferimentoTesto { get; set; }
/// <summary>
/// Campo in cui inserire un valore numerico riferito alla tipologia di informazione.
/// </summary>
[DataProperty]
public decimal RiferimentoNumero { get; set; }
/// <summary>
/// Campo in cui inserire una data riferita alla tiplogia di informazione.
/// </summary>
[DataProperty]
public DateTime? RiferimentoData { get; set; }
}
}
| using System;
using System.Xml;
using FatturaElettronica.Common;
namespace FatturaElettronica.FatturaElettronicaBody.DatiBeniServizi
{
/// <summary>
/// Blocco che consente di inserire, con riferimento ad una linea di dettaglio, diverse tipologie di informazioni utili ai fini
/// amministrativi, gestionali, etc.
/// </summary>
public class AltriDatiGestionali : BaseClassSerializable
{
public AltriDatiGestionali() { }
public AltriDatiGestionali(XmlReader r) : base(r) { }
protected override List<Validator> CreateRules() {
var rules = base.CreateRules();
rules.Add( new AndCompositeValidator("TipoDato", new List<Validator> {new FRequiredValidator(), new FLengthValidator(1, 10)}));
rules.Add(new FLengthValidator("RiferimentoTesto", 1, 60));
return rules;
}
#region Properties
/// <summary>
/// Codice che identifica la tipologia di informazione
/// </summary>
[DataProperty]
public string TipoDato { get; set; }
/// <summary>
/// Campo in cui inserire un valore alfanumerico riferito alla tipologia di informazione.
/// </summary>
[DataProperty]
public string RiferimentoTesto { get; set; }
/// <summary>
/// Campo in cui inserire un valore numerico riferito alla tipologia di informazione.
/// </summary>
[DataProperty]
public decimal RiferimentoNumero { get; set; }
/// <summary>
/// Campo in cui inserire una data riferita alla tiplogia di informazione.
/// </summary>
[DataProperty]
public DateTime? RiferimentoData { get; set; }
}
}
| bsd-3-clause | C# |
c71f98bd0689661127645b8d1678e017b145d64a | Add extension methods to run guaranteed synchronous disposal | peppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework | osu.Framework/Graphics/DrawableExtensions.cs | osu.Framework/Graphics/DrawableExtensions.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Development;
using osu.Framework.Graphics.Containers;
namespace osu.Framework.Graphics
{
/// <summary>
/// Holds extension methods for <see cref="Drawable"/>.
/// </summary>
public static class DrawableExtensions
{
/// <summary>
/// Adjusts specified properties of a <see cref="Drawable"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param>
/// <param name="adjustment">The adjustment function.</param>
/// <returns>The given <see cref="Drawable"/>.</returns>
public static T With<T>(this T drawable, Action<T> adjustment)
where T : Drawable
{
adjustment?.Invoke(drawable);
return drawable;
}
/// <summary>
/// Forces removal of this drawable from its parent, followed by immediate synchronous disposal.
/// </summary>
/// <remarks>
/// This is intended as a temporary solution for the fact that there is no way to easily dispose
/// a component in a way that is guaranteed to be synchronously run on the update thread.
///
/// Eventually components will have a better method for unloading.
/// </remarks>
/// <param name="drawable">The <see cref="Drawable"/> to be disposed.</param>
public static void RemoveAndDisposeImmediately(this Drawable drawable)
{
ThreadSafety.EnsureUpdateThread();
switch (drawable.Parent)
{
case Container cont:
cont.Remove(drawable);
break;
case CompositeDrawable comp:
comp.RemoveInternal(drawable);
break;
}
drawable.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;
namespace osu.Framework.Graphics
{
/// <summary>
/// Holds extension methods for <see cref="Drawable"/>.
/// </summary>
public static class DrawableExtensions
{
/// <summary>
/// Adjusts specified properties of a <see cref="Drawable"/>.
/// </summary>
/// <param name="drawable">The <see cref="Drawable"/> whose properties should be adjusted.</param>
/// <param name="adjustment">The adjustment function.</param>
/// <returns>The given <see cref="Drawable"/>.</returns>
public static T With<T>(this T drawable, Action<T> adjustment)
where T : Drawable
{
adjustment?.Invoke(drawable);
return drawable;
}
}
}
| mit | C# |
2daf56f8afac7427a1b3ac2d1913569f8e3e87f7 | fix https validation | CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper,CecilCable/Ingress-ScoreKeeper | Upchurch.Ingress.Infrastructure/SendMessageToSlack.cs | Upchurch.Ingress.Infrastructure/SendMessageToSlack.cs | using System.Net;
using System.Web;
using RestSharp;
namespace Upchurch.Ingress.Infrastructure
{
public class SendMessageToSlack : ISlackSender
{
private readonly string _slackApiUrl;
public SendMessageToSlack(string slackApiUrl)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
_slackApiUrl = slackApiUrl;
}
public void Send(string text)
{
var client = new RestClient(_slackApiUrl);
var request = new RestRequest(Method.POST);
request.AddJsonBody(new payload {text = text});
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int) response.StatusCode, "Error Sending To Slack. " + response.ErrorMessage);
}
}
private class payload
{
public string text { get; set; }
}
}
} | using System.Net;
using System.Web;
using RestSharp;
namespace Upchurch.Ingress.Infrastructure
{
public class SendMessageToSlack : ISlackSender
{
private readonly string _slackApiUrl;
public SendMessageToSlack(string slackApiUrl)
{
_slackApiUrl = slackApiUrl;
}
public void Send(string text)
{
var client = new RestClient(_slackApiUrl);
var request = new RestRequest(Method.POST);
request.AddJsonBody(new payload {text = text});
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK)
{
throw new HttpException((int) response.StatusCode, "Error Sending To Slack. " + response.ErrorMessage);
}
}
private class payload
{
public string text { get; set; }
}
}
} | mit | C# |
6bcffed9ed447df23b50f42b18e03e5c6365398e | Use includeCurrentData parameter | grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation,grahammendick/navigation | NavigationSample/Views/Person/Listing.cshtml | NavigationSample/Views/Person/Listing.cshtml | @model PersonSearchModel
<!DOCTYPE html>
<html>
<head>
<title>Person Search</title>
<style>
table{border-collapse:collapse;}table,td,th{border:1px #000 solid;}
ul{list-style-type:none;padding:0;margin:0;}li{float:left;padding-right:3px;}
</style>
</head>
<body>
@Ajax.RefreshPanel("panel", "sortExpression,startRowIndex,maximumRows,name",
@<div>
@using (Html.BeginRefreshForm(new NavigationData(true), __razor_template_writer))
{
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
<input type="submit" name="search" value="Search" />
}
Page size
@Html.RefreshLink("5", new NavigationData() { { "startRowIndex", null }, { "maximumRows", 5 } }, true)
@Html.RefreshLink("10", new NavigationData() { { "startRowIndex", null }, { "maximumRows", null } }, true)
<table>
<thead>
<tr>
<th>@Html.Sorter("Name", "Name")</th>
<th>Date of Birth</th>
</tr>
</thead>
<tbody>
@foreach (var person in Model.People)
{
<tr>
<td>
@Html.NavigationLink(person.Name, "Select", new NavigationData { { "id", person.Id } })
</td>
<td>@person.DateOfBirth.ToShortDateString()</td>
</tr>
}
</tbody>
</table>
@Html.Pager("First", "Previous", "Next", "Last")
@string.Format("Total Count {0}", StateContext.Bag.totalRowCount)
</div>)
<script src="~/Scripts/navigation.mvc.js"></script>
</body>
</html>
| @model PersonSearchModel
<!DOCTYPE html>
<html>
<head>
<title>Person Search</title>
<style>
table{border-collapse:collapse;}table,td,th{border:1px #000 solid;}
ul{list-style-type:none;padding:0;margin:0;}li{float:left;padding-right:3px;}
</style>
</head>
<body>
@Ajax.RefreshPanel("panel", "sortExpression,startRowIndex,maximumRows,name",
@<div>
@using (Html.BeginRefreshForm(new NavigationData(true), __razor_template_writer))
{
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
<input type="submit" name="search" value="Search" />
}
Page size
@Html.RefreshLink("5", new NavigationData(true) { { "startRowIndex", null }, { "maximumRows", 5 } })
@Html.RefreshLink("10", new NavigationData(true) { { "startRowIndex", null }, { "maximumRows", null } })
<table>
<thead>
<tr>
<th>@Html.Sorter("Name", "Name")</th>
<th>Date of Birth</th>
</tr>
</thead>
<tbody>
@foreach (var person in Model.People)
{
<tr>
<td>
@Html.NavigationLink(person.Name, "Select", new NavigationData { { "id", person.Id } })
</td>
<td>@person.DateOfBirth.ToShortDateString()</td>
</tr>
}
</tbody>
</table>
@Html.Pager("First", "Previous", "Next", "Last")
@string.Format("Total Count {0}", StateContext.Bag.totalRowCount)
</div>)
<script src="~/Scripts/navigation.mvc.js"></script>
</body>
</html>
| apache-2.0 | C# |
6e8dcbc12b921fbc502b2f0234e02970532b8173 | remove unneeded Pulse() call | cra0zy/xwt,antmicro/xwt,akrisiun/xwt,steffenWi/xwt,mminns/xwt,hwthomas/xwt,lytico/xwt,mminns/xwt,TheBrainTech/xwt,mono/xwt,sevoku/xwt,hamekoz/xwt,directhex/xwt,iainx/xwt,residuum/xwt | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | Xwt.Gtk/Xwt.GtkBackend/ProgressBarBackend.cs | //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Timers;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
Timer timer = new Timer (100);
public ProgressBarBackend ()
{
}
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
timer.Elapsed += Pulse;
Widget.Show ();
timer.Start ();
}
private void Pulse (object sender, ElapsedEventArgs args)
{
Application.Invoke (() => Widget.Pulse ());
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetFraction (double? fraction)
{
if (fraction == null)
{
timer.Start ();
Widget.Fraction = 0.1;
} else {
timer.Stop ();
Widget.Fraction = fraction.Value;
}
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (timer != null) {
timer.Stop ();
timer.Dispose ();
timer = null;
}
}
}
}
| //
// ProgressBarBackend.cs
//
// Author:
// Andres G. Aragoneses <knocte@gmail.com>
//
// Copyright (c) 2012 Andres G. Aragoneses
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Timers;
using Xwt.Backends;
using Xwt.Engine;
namespace Xwt.GtkBackend
{
public class ProgressBarBackend: WidgetBackend, IProgressBarBackend
{
Timer timer = new Timer (100);
public ProgressBarBackend ()
{
}
public override void Initialize ()
{
var progressBar = new Gtk.ProgressBar ();
Widget = progressBar;
progressBar.Pulse ();
timer.Elapsed += Pulse;
Widget.Show ();
timer.Start ();
}
private void Pulse (object sender, ElapsedEventArgs args)
{
Application.Invoke (() => Widget.Pulse ());
}
protected new Gtk.ProgressBar Widget {
get { return (Gtk.ProgressBar)base.Widget; }
set { base.Widget = value; }
}
public void SetFraction (double? fraction)
{
if (fraction == null)
{
timer.Start ();
Widget.Fraction = 0.1;
} else {
timer.Stop ();
Widget.Fraction = fraction.Value;
}
}
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (timer != null) {
timer.Stop ();
timer.Dispose ();
timer = null;
}
}
}
}
| mit | C# |
e0c1fe35fcd30f82d27c9dccb9bc85c7eb87bc45 | Add DebuggerDisplay to GitIgnoreTemplate | daukantas/octokit.net,ivandrofly/octokit.net,M-Zuber/octokit.net,hitesh97/octokit.net,eriawan/octokit.net,ivandrofly/octokit.net,rlugojr/octokit.net,shiftkey/octokit.net,SamTheDev/octokit.net,forki/octokit.net,fake-organization/octokit.net,dampir/octokit.net,gdziadkiewicz/octokit.net,nsrnnnnn/octokit.net,hahmed/octokit.net,kolbasov/octokit.net,editor-tools/octokit.net,shiftkey/octokit.net,fffej/octokit.net,chunkychode/octokit.net,Sarmad93/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,alfhenrik/octokit.net,adamralph/octokit.net,octokit-net-test-org/octokit.net,geek0r/octokit.net,dlsteuer/octokit.net,editor-tools/octokit.net,devkhan/octokit.net,khellang/octokit.net,naveensrinivasan/octokit.net,SamTheDev/octokit.net,mminns/octokit.net,shiftkey-tester/octokit.net,ChrisMissal/octokit.net,hahmed/octokit.net,shana/octokit.net,thedillonb/octokit.net,octokit-net-test/octokit.net,brramos/octokit.net,TattsGroup/octokit.net,gabrielweyer/octokit.net,dampir/octokit.net,gdziadkiewicz/octokit.net,shana/octokit.net,kdolan/octokit.net,octokit-net-test-org/octokit.net,khellang/octokit.net,octokit/octokit.net,mminns/octokit.net,darrelmiller/octokit.net,Sarmad93/octokit.net,eriawan/octokit.net,M-Zuber/octokit.net,takumikub/octokit.net,devkhan/octokit.net,gabrielweyer/octokit.net,Red-Folder/octokit.net,michaKFromParis/octokit.net,magoswiat/octokit.net,nsnnnnrn/octokit.net,TattsGroup/octokit.net,rlugojr/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SmithAndr/octokit.net,alfhenrik/octokit.net,octokit/octokit.net,SmithAndr/octokit.net,shiftkey-tester/octokit.net,chunkychode/octokit.net,cH40z-Lord/octokit.net,thedillonb/octokit.net,SLdragon1989/octokit.net,bslliw/octokit.net | Octokit/Models/Response/GitIgnoreTemplate.cs | Octokit/Models/Response/GitIgnoreTemplate.cs | using System;
using System.Diagnostics;
using System.Globalization;
namespace Octokit
{
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class GitIgnoreTemplate
{
public GitIgnoreTemplate(string name, string source)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(source, "source");
Name = name;
Source = source;
}
public GitIgnoreTemplate()
{
}
public string Name { get; protected set; }
public string Source { get; protected set; }
internal string DebuggerDisplay
{
get
{
return String.Format(CultureInfo.InvariantCulture, "GitIgnore: {0}", Name);
}
}
}
}
| namespace Octokit
{
public class GitIgnoreTemplate
{
public GitIgnoreTemplate(string name, string source)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Ensure.ArgumentNotNullOrEmptyString(source, "source");
Name = name;
Source = source;
}
public GitIgnoreTemplate()
{
}
public string Name { get; protected set; }
public string Source { get; protected set; }
}
}
| mit | C# |
9bf20da25f074cb1e84a1e3912d22c035cb2fa48 | Add support for minutes in date extensions | ahanusa/facile.net,peasy/Samples,ahanusa/Peasy.NET,peasy/Samples,peasy/Peasy.NET,peasy/Samples | Orders.com.Core/Extensions/DateExtensions.cs | Orders.com.Core/Extensions/DateExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class Extensions
{
public static MinuteResult Minutes(this int minutes)
{
return new MinuteResult(minutes);
}
public static DayResult Days(this int days)
{
return new DayResult(days);
}
public static YearResult Years(this int years)
{
return new YearResult(years);
}
public static DateTime Ago(this MinuteResult result)
{
return DateTime.Now.AddMinutes(-result.NumberOfMinutes);
}
public static DateTime Ago(this DayResult result)
{
return DateTime.Now.AddDays(-result.NumberOfDays);
}
public static DateTime Ago(this YearResult result)
{
return DateTime.Now.AddYears(-result.NumberOfYears);
}
public static DateTime FromNow(this DayResult result)
{
return DateTime.Now.AddDays(result.NumberOfDays);
}
public static DateTime FromNow(this YearResult result)
{
return DateTime.Now.AddYears(result.NumberOfYears);
}
}
public class MinuteResult
{
public MinuteResult(int numberOfMinutes)
{
NumberOfMinutes = numberOfMinutes;
}
public int NumberOfMinutes { get; private set; }
}
public class DayResult
{
public DayResult(int numberOfDays)
{
NumberOfDays = numberOfDays;
}
public int NumberOfDays { get; private set; }
}
public class YearResult
{
public YearResult(int numberOfYears)
{
NumberOfYears = numberOfYears;
}
public int NumberOfYears { get; private set; }
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class Extensions
{
public static DayResult Days(this int days)
{
return new DayResult(days);
}
public static YearResult Years(this int years)
{
return new YearResult(years);
}
public static DateTime Ago(this DayResult result)
{
return DateTime.Now.AddDays(-result.NumberOfDays);
}
public static DateTime Ago(this YearResult result)
{
return DateTime.Now.AddYears(-result.NumberOfYears);
}
public static DateTime FromNow(this DayResult result)
{
return DateTime.Now.AddDays(result.NumberOfDays);
}
public static DateTime FromNow(this YearResult result)
{
return DateTime.Now.AddYears(result.NumberOfYears);
}
}
public class DayResult
{
public DayResult(int numberOfDays)
{
NumberOfDays = numberOfDays;
}
public int NumberOfDays { get; private set; }
}
public class YearResult
{
public YearResult(int numberOfYears)
{
NumberOfYears = numberOfYears;
}
public int NumberOfYears { get; private set; }
}
| mit | C# |
719b718c20353cb815e50384ccf49de9c45a68de | Add application/manifest+json to ContentType | ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework | Source/Boilerplate.AspNetCore/ContentType.cs | Source/Boilerplate.AspNetCore/ContentType.cs | namespace Boilerplate.AspNetCore
{
/// <summary>
/// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of
/// data that a file contains. Web browsers use them to determine how to display, output or handle files and search
/// engines use them to classify data files on the web.
/// </summary>
public static class ContentType
{
/// <summary>Atom feeds.</summary>
public const string Atom = "application/atom+xml";
/// <summary>HTML; Defined in RFC 2854.</summary>
public const string Html = "text/html";
/// <summary>Form URL Encoded.</summary>
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Gif = "image/gif";
/// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Jpg = "image/jpeg";
/// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary>
public const string Json = "application/json";
/// <summary>Web App Manifest.</summary>
public const string Manifest = "application/manifest+json";
/// <summary>Multi-part form daata; Defined in RFC 2388.</summary>
public const string MultipartFormData = "multipart/form-data";
/// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary>
public const string Png = "image/png";
/// <summary>Rich Site Summary; Defined by Harvard Law.</summary>
public const string Rss = "application/rss+xml";
/// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary>
public const string Text = "text/plain";
/// <summary>Extensible Markup Language; Defined in RFC 3023</summary>
public const string Xml = "application/xml";
/// <summary>Compressed ZIP.</summary>
public const string Zip = "application/zip";
}
}
| namespace Boilerplate.AspNetCore
{
/// <summary>
/// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of
/// data that a file contains. Web browsers use them to determine how to display, output or handle files and search
/// engines use them to classify data files on the web.
/// </summary>
public static class ContentType
{
/// <summary>Atom feeds.</summary>
public const string Atom = "application/atom+xml";
/// <summary>HTML; Defined in RFC 2854.</summary>
public const string Html = "text/html";
/// <summary>Form URL Encoded.</summary>
public const string FormUrlEncoded = "application/x-www-form-urlencoded";
/// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Gif = "image/gif";
/// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary>
public const string Jpg = "image/jpeg";
/// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary>
public const string Json = "application/json";
/// <summary>Multi-part form daata; Defined in RFC 2388.</summary>
public const string MultipartFormData = "multipart/form-data";
/// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary>
public const string Png = "image/png";
/// <summary>Rich Site Summary; Defined by Harvard Law.</summary>
public const string Rss = "application/rss+xml";
/// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary>
public const string Text = "text/plain";
/// <summary>Extensible Markup Language; Defined in RFC 3023</summary>
public const string Xml = "application/xml";
/// <summary>Compressed ZIP.</summary>
public const string Zip = "application/zip";
}
}
| mit | C# |
865cdf8a1e29b033c8b06c0ea823c7ef87547487 | Fix outdated docs | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix.Data/Repositories/PromotionActionEventRepositoryBase.cs | Modix.Data/Repositories/PromotionActionEventRepositoryBase.cs | using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using Modix.Data.Messages;
using Modix.Data.Models.Promotions;
namespace Modix.Data.Repositories
{
/// <summary>
/// Describes a repository that creates <see cref="PromotionActionEntity"/> records in the datastore, This publishes
/// <see cref="PromotionActionCreated"/> messages when actions are created.
/// </summary>
public abstract class PromotionActionEventRepositoryBase : RepositoryBase
{
private readonly IMediator _mediator;
/// <summary>
/// Constructs a new <see cref="PromotionActionEventRepositoryBase"/> object, with the given injected dependencies.
/// See <see cref="RepositoryBase(ModixContext)"/>.
/// </summary>
public PromotionActionEventRepositoryBase(ModixContext modixContext, IMediator mediator)
: base(modixContext)
{
_mediator = mediator;
}
/// <summary>
/// Notifies listeners that a new <see cref="PromotionActionEntity"/> has been created.
/// </summary>
/// <param name="promotionAction">The <see cref="PromotionActionEntity"/> that was created.</param>
/// <returns>A <see cref="Task"/> that will complete when the operation has completed.</returns>
internal protected Task RaisePromotionActionCreatedAsync(PromotionActionEntity promotionAction)
=> _mediator.Publish(new PromotionActionCreated
{
PromotionActionId = promotionAction.Id,
PromotionActionCreationData = new PromotionActionCreationData
{
Created = promotionAction.Created,
CreatedById = promotionAction.CreatedById,
GuildId = promotionAction.GuildId,
Type = promotionAction.Type
}
});
}
}
| using System.Collections.Generic;
using System.Threading.Tasks;
using MediatR;
using Modix.Data.Messages;
using Modix.Data.Models.Promotions;
namespace Modix.Data.Repositories
{
/// <summary>
/// Describes a repository that creates <see cref="PromotionActionEntity"/> records in the datastore,
/// and thus consumes <see cref="IPromotionActionEventHandler"/> objects.
/// </summary>
public abstract class PromotionActionEventRepositoryBase : RepositoryBase
{
private readonly IMediator _mediator;
/// <summary>
/// Constructs a new <see cref="PromotionActionEventRepositoryBase"/> object, with the given injected dependencies.
/// See <see cref="RepositoryBase(ModixContext)"/>.
/// </summary>
public PromotionActionEventRepositoryBase(ModixContext modixContext, IMediator mediator)
: base(modixContext)
{
_mediator = mediator;
}
/// <summary>
/// Notifies <see cref="PromotionActionEventHandlers"/> that a new <see cref="PromotionActionEntity"/> has been created.
/// </summary>
/// <param name="promotionAction">The <see cref="PromotionActionEntity"/> that was created.</param>
/// <returns>A <see cref="Task"/> that will complete when the operation has completed.</returns>
internal protected Task RaisePromotionActionCreatedAsync(PromotionActionEntity promotionAction)
=> _mediator.Publish(new PromotionActionCreated
{
PromotionActionId = promotionAction.Id,
PromotionActionCreationData = new PromotionActionCreationData
{
Created = promotionAction.Created,
CreatedById = promotionAction.CreatedById,
GuildId = promotionAction.GuildId,
Type = promotionAction.Type
}
});
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.