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 |
---|---|---|---|---|---|---|---|---|
07bf7b4fde825bae377928d076d097107a3b433f | Add in a cost property in IGameItem interface | liam-middlebrook/Navier-Boats | Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/IGameItem.cs | Navier-Boats/Navier-Boats/Navier-Boats/Engine/Inventory/IGameItem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Navier_Boats.Engine.Entities;
namespace Navier_Boats.Engine.Inventory
{
public interface IGameItem : IInteractable
{
Texture2D InventoryTexture
{
get;
set;
}
Texture2D ItemTexture
{
get;
set;
}
int MaxStack
{
get;
set;
}
int Cost
{
get;
set;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Navier_Boats.Engine.Entities;
namespace Navier_Boats.Engine.Inventory
{
public interface IGameItem : IInteractable
{
Texture2D InventoryTexture
{
get;
set;
}
Texture2D ItemTexture
{
get;
set;
}
int MaxStack
{
get;
set;
}
}
}
| apache-2.0 | C# |
6992cbaa8c400daf5f49b4bfc82f0f8816e5e91e | Add DateTime to NSDate cast | haithemaraissia/monotouch-samples,W3SS/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,hongnguyenpro/monotouch-samples,davidrynn/monotouch-samples,kingyond/monotouch-samples,nervevau2/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,robinlaide/monotouch-samples,robinlaide/monotouch-samples,a9upam/monotouch-samples,xamarin/monotouch-samples,andypaul/monotouch-samples,robinlaide/monotouch-samples,nervevau2/monotouch-samples,kingyond/monotouch-samples,YOTOV-LIMITED/monotouch-samples,sakthivelnagarajan/monotouch-samples,peteryule/monotouch-samples,davidrynn/monotouch-samples,peteryule/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,peteryule/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,albertoms/monotouch-samples,sakthivelnagarajan/monotouch-samples,YOTOV-LIMITED/monotouch-samples,hongnguyenpro/monotouch-samples,andypaul/monotouch-samples,W3SS/monotouch-samples,markradacz/monotouch-samples,davidrynn/monotouch-samples,robinlaide/monotouch-samples,peteryule/monotouch-samples,markradacz/monotouch-samples,sakthivelnagarajan/monotouch-samples,a9upam/monotouch-samples,kingyond/monotouch-samples,nelzomal/monotouch-samples,xamarin/monotouch-samples,davidrynn/monotouch-samples,andypaul/monotouch-samples,xamarin/monotouch-samples,nervevau2/monotouch-samples,andypaul/monotouch-samples,markradacz/monotouch-samples,hongnguyenpro/monotouch-samples,nelzomal/monotouch-samples,haithemaraissia/monotouch-samples,W3SS/monotouch-samples,haithemaraissia/monotouch-samples,iFreedive/monotouch-samples,labdogg1003/monotouch-samples,nelzomal/monotouch-samples,a9upam/monotouch-samples,YOTOV-LIMITED/monotouch-samples,nervevau2/monotouch-samples,haithemaraissia/monotouch-samples,a9upam/monotouch-samples | MTDWalkthrough/AppDelegate.cs | MTDWalkthrough/AppDelegate.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using MonoTouch.Dialog;
namespace MTDWalkthrough
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
UIWindow _window;
UINavigationController _nav;
DialogViewController _rootVC;
RootElement _rootElement;
UIBarButtonItem _addButton;
int n = 0;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
_window = new UIWindow (UIScreen.MainScreen.Bounds);
_rootElement = new RootElement ("To Do List"){
new Section ()
};
_rootVC = new DialogViewController (_rootElement);
_nav = new UINavigationController (_rootVC);
_addButton = new UIBarButtonItem (UIBarButtonSystemItem.Add);
_rootVC.NavigationItem.RightBarButtonItem = _addButton;
_addButton.Clicked += (sender, e) => {
++n;
var task = new Task{Name = "task " + n, DueDate = DateTime.Now};
var element = new EntryElement (task.Name, "Enter task description", task.Description);
var dateElement = new FutureDateElement ("Due Date", task.DueDate);
var taskElement = (Element)new RootElement (task.Name){
new Section () {
element
},
new Section () {
dateElement
},
new Section ("Demo Retrieving Element Value") {
new StringElement ("Output Task Description",
delegate { Console.WriteLine (element.Value); })
}
};
_rootElement [0].Add (taskElement);
};
_window.RootViewController = _nav;
_window.MakeKeyAndVisible ();
return true;
}
}
public class FutureDateElement : DateElement
{
public FutureDateElement(string caption, DateTime date) : base(caption,date)
{
}
public override UIDatePicker CreatePicker ()
{
UIDatePicker futureDatePicker = base.CreatePicker ();
futureDatePicker.BackgroundColor = UIColor.White;
futureDatePicker.MinimumDate = (NSDate)DateTime.Today;
return futureDatePicker;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
using MonoTouch.Dialog;
namespace MTDWalkthrough
{
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
UIWindow _window;
UINavigationController _nav;
DialogViewController _rootVC;
RootElement _rootElement;
UIBarButtonItem _addButton;
int n = 0;
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
_window = new UIWindow (UIScreen.MainScreen.Bounds);
_rootElement = new RootElement ("To Do List"){
new Section ()
};
_rootVC = new DialogViewController (_rootElement);
_nav = new UINavigationController (_rootVC);
_addButton = new UIBarButtonItem (UIBarButtonSystemItem.Add);
_rootVC.NavigationItem.RightBarButtonItem = _addButton;
_addButton.Clicked += (sender, e) => {
++n;
var task = new Task{Name = "task " + n, DueDate = DateTime.Now};
var element = new EntryElement (task.Name, "Enter task description", task.Description);
var dateElement = new FutureDateElement ("Due Date", task.DueDate);
var taskElement = (Element)new RootElement (task.Name){
new Section () {
element
},
new Section () {
dateElement
},
new Section ("Demo Retrieving Element Value") {
new StringElement ("Output Task Description",
delegate { Console.WriteLine (element.Value); })
}
};
_rootElement [0].Add (taskElement);
};
_window.RootViewController = _nav;
_window.MakeKeyAndVisible ();
return true;
}
}
public class FutureDateElement : DateElement
{
public FutureDateElement(string caption, DateTime date) : base(caption,date)
{
}
public override UIDatePicker CreatePicker ()
{
UIDatePicker futureDatePicker = base.CreatePicker ();
futureDatePicker.BackgroundColor = UIColor.White;
futureDatePicker.MinimumDate = DateTime.Today;
return futureDatePicker;
}
}
}
| mit | C# |
8b85401de5eba9f770d5c26754212cc908334dc6 | Use library format | shuhari/Shuhari.WinTools | Shuhari.WinTools.Core/Features/Encode/Providers/MD5EncodeProvider.cs | Shuhari.WinTools.Core/Features/Encode/Providers/MD5EncodeProvider.cs | using System.Security.Cryptography;
using System.Text;
using Shuhari.Library.Common.Utils;
namespace Shuhari.WinTools.Core.Features.Encode.Providers
{
public class MD5EncodeProvider : EncodeProvider
{
public override EncodeProviderMetadata Metadata
{
get { return new EncodeProviderMetadata("MD5", 0, EncodeProviderFunctions.Encode); }
}
public override string Encode(string input, Encoding encoding)
{
var csp = new MD5CryptoServiceProvider();
byte[] value = encoding.GetBytes(input);
byte[] hash = csp.ComputeHash(value);
csp.Clear();
return hash.ToHexString();
}
}
}
| using System.Security.Cryptography;
using System.Text;
namespace Shuhari.WinTools.Core.Features.Encode.Providers
{
public class MD5EncodeProvider : EncodeProvider
{
public override EncodeProviderMetadata Metadata
{
get { return new EncodeProviderMetadata("MD5", 0, EncodeProviderFunctions.Encode); }
}
public override string Encode(string input, Encoding encoding)
{
var csp = new MD5CryptoServiceProvider();
byte[] value = encoding.GetBytes(input);
byte[] hash = csp.ComputeHash(value);
csp.Clear();
StringBuilder sb = new StringBuilder();
for (int i = 0, len = hash.Length; i < len; i++)
{
sb.Append(hash[i].ToString("x").PadLeft(2, '0'));
}
return sb.ToString();
}
}
}
| mit | C# |
4d98319d5dd54ab53d9e9c226c3704be81adea07 | add a little wait to the tests so that parallel behavior can be better observed | gasparnagy/SpecFlow.xUnitAdapter | src/tests/SpecFlow.xUnitAdapter.TestProject/StepDefinitions.cs | src/tests/SpecFlow.xUnitAdapter.TestProject/StepDefinitions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using TechTalk.SpecFlow;
using Xunit;
using Xunit.Abstractions;
namespace SpecFlow.xUnitAdapter.TestProject
{
[Binding]
public sealed class StepDefinitions : Steps
{
private List<int> numbers = new List<int>();
private int? result;
[Given(@"there is a new calcualtor")]
public void GivenThereIsANewCalcualtor()
{
numbers.Clear();
}
[Given("I have entered (.*) into the calculator")]
public void GivenIHaveEnteredSomethingIntoTheCalculator(int number)
{
System.Threading.Thread.Sleep(100);
var outputHelper = ScenarioContext.ScenarioContainer.Resolve<ITestOutputHelper>();
outputHelper.WriteLine("Sample output through ITestOutputHelper");
Console.WriteLine("Running Given step");
numbers.Add(number);
}
[Given(@"I have entered the following numbers into the calculator:")]
public void GivenIHaveEnteredTheFollowingNumbersIntoTheCalculator(Table table)
{
foreach (var tableRow in table.Rows)
{
GivenIHaveEnteredSomethingIntoTheCalculator(int.Parse(tableRow["number"]));
}
}
[When("I press add")]
public void WhenIPressAdd()
{
Console.WriteLine("Running When step");
result = numbers.Sum();
}
[When(@"there is a failing step")]
public void WhenThereIsAFailingStep()
{
throw new Exception("this has failed");
}
[Then("the result should be (.*) on the screen")]
public void ThenTheResultShouldBe(int expectedResult)
{
Console.WriteLine("Running Then step");
Assert.Equal(expectedResult, result);
}
[AfterScenario]
public void AfterScenario()
{
Console.WriteLine("after scenario");
}
[AfterFeature]
public static void AfterFeature()
{
Console.WriteLine("after feature");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using TechTalk.SpecFlow;
using Xunit;
using Xunit.Abstractions;
namespace SpecFlow.xUnitAdapter.TestProject
{
[Binding]
public sealed class StepDefinitions : Steps
{
private List<int> numbers = new List<int>();
private int? result;
[Given(@"there is a new calcualtor")]
public void GivenThereIsANewCalcualtor()
{
numbers.Clear();
}
[Given("I have entered (.*) into the calculator")]
public void GivenIHaveEnteredSomethingIntoTheCalculator(int number)
{
var outputHelper = ScenarioContext.ScenarioContainer.Resolve<ITestOutputHelper>();
outputHelper.WriteLine("Sample output through ITestOutputHelper");
Console.WriteLine("Running Given step");
numbers.Add(number);
}
[Given(@"I have entered the following numbers into the calculator:")]
public void GivenIHaveEnteredTheFollowingNumbersIntoTheCalculator(Table table)
{
foreach (var tableRow in table.Rows)
{
GivenIHaveEnteredSomethingIntoTheCalculator(int.Parse(tableRow["number"]));
}
}
[When("I press add")]
public void WhenIPressAdd()
{
Console.WriteLine("Running When step");
result = numbers.Sum();
}
[When(@"there is a failing step")]
public void WhenThereIsAFailingStep()
{
throw new Exception("this has failed");
}
[Then("the result should be (.*) on the screen")]
public void ThenTheResultShouldBe(int expectedResult)
{
Console.WriteLine("Running Then step");
Assert.Equal(expectedResult, result);
}
[AfterScenario]
public void AfterScenario()
{
Console.WriteLine("after scenario");
}
[AfterFeature]
public static void AfterFeature()
{
Console.WriteLine("after feature");
}
}
}
| apache-2.0 | C# |
f842c3290c5c39c1624571eaa107db0d7620faf8 | fix xaml transformer. | wieslawsoltes/Perspex,jkoritzinsky/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia | src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlResolveByNameMarkupExtensionReplacer.cs | src/Markup/Avalonia.Markup.Xaml/XamlIl/CompilerExtensions/Transformers/AvaloniaXamlIlResolveByNameMarkupExtensionReplacer.cs | using System.Collections;
using System.Collections.Generic;
using System.Linq;
using XamlX.Ast;
using XamlX.Transform;
using XamlX.TypeSystem;
#nullable enable
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
class AvaloniaXamlIlResolveByNameMarkupExtensionReplacer : IXamlAstTransformer
{
public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
if (!(node is XamlAstXamlPropertyValueNode propertyValueNode)) return node;
if (!(propertyValueNode.Property is XamlAstClrProperty clrProperty)) return node;
IEnumerable<IXamlCustomAttribute> attributes = propertyValueNode.Property.GetClrProperty().CustomAttributes;
if (propertyValueNode.Property is XamlAstClrProperty referenceNode &&
referenceNode.Getter != null)
{
attributes = attributes.Concat(referenceNode.Getter.CustomAttributes);
}
if (attributes.All(attribute => attribute.Type.FullName != "Avalonia.Controls.ResolveByNameAttribute"))
return node;
if (propertyValueNode.Values.Count != 1 || !(propertyValueNode.Values.First() is XamlAstTextNode))
return node;
var newNode = new XamlAstObjectNode(
propertyValueNode.Values[0],
new XamlAstClrTypeReference(propertyValueNode.Values[0],
context.GetAvaloniaTypes().ResolveByNameExtension, true))
{
Arguments = new List<IXamlAstValueNode> { propertyValueNode.Values[0] }
};
if (XamlTransformHelpers.TryConvertMarkupExtension(context, newNode, out var extensionNode))
{
propertyValueNode.Values[0] = extensionNode;
}
return node;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using System.Linq;
using XamlX.Ast;
using XamlX.Transform;
using XamlX.TypeSystem;
#nullable enable
namespace Avalonia.Markup.Xaml.XamlIl.CompilerExtensions.Transformers
{
class AvaloniaXamlIlResolveByNameMarkupExtensionReplacer : IXamlAstTransformer
{
public IXamlAstNode Transform(AstTransformationContext context, IXamlAstNode node)
{
if (!(node is XamlAstXamlPropertyValueNode propertyValueNode)) return node;
IEnumerable<IXamlCustomAttribute> attributes = propertyValueNode.Property.GetClrProperty().CustomAttributes;
if (propertyValueNode.Property is XamlAstClrProperty referenceNode &&
referenceNode.Getter != null)
{
attributes = attributes.Concat(referenceNode.Getter.CustomAttributes);
}
if (attributes.All(attribute => attribute.Type.FullName != "Avalonia.Controls.ResolveByNameAttribute"))
return node;
if (propertyValueNode.Values.Count != 1 || !(propertyValueNode.Values.First() is XamlAstTextNode))
return node;
var newNode = new XamlAstObjectNode(
propertyValueNode.Values[0],
new XamlAstClrTypeReference(propertyValueNode.Values[0],
context.GetAvaloniaTypes().ResolveByNameExtension, true))
{
Arguments = new List<IXamlAstValueNode> { propertyValueNode.Values[0] }
};
if (XamlTransformHelpers.TryConvertMarkupExtension(context, newNode, out var extensionNode))
{
propertyValueNode.Values[0] = extensionNode;
}
return node;
}
}
}
| mit | C# |
766e7a1d582e58e8f7e9ea2e9e38a8c549deccc8 | Fix bug with n-level undo of child objects. | rockfordlhotka/csla,JasonBock/csla,JasonBock/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,BrettJaner/csla,MarimerLLC/csla,MarimerLLC/csla,BrettJaner/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light,jonnybee/csla,ronnymgm/csla-light,BrettJaner/csla | cslatest/Csla.Test/LazyLoad/AParent.cs | cslatest/Csla.Test/LazyLoad/AParent.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Csla.Test.LazyLoad
{
[Serializable]
public class AParent : Csla.BusinessBase<AParent>
{
private Guid _id;
public Guid Id
{
get { return _id; }
set
{
_id = value;
PropertyHasChanged();
}
}
private static PropertyInfo<AChildList> ChildListProperty =
RegisterProperty<AChildList>(typeof(AParent), new PropertyInfo<AChildList>("ChildList", "Child list"));
public AChildList ChildList
{
get
{
if (!FieldManager.FieldExists(ChildListProperty))
LoadProperty<AChildList>(ChildListProperty, new AChildList());
return GetProperty<AChildList>(ChildListProperty);
}
}
//private AChildList _children;
//public AChildList ChildList
//{
// get
// {
// if (_children == null)
// {
// _children = new AChildList();
// for (int count = 0; count < EditLevel; count++)
// ((Csla.Core.IUndoableObject)_children).CopyState(EditLevel);
// }
// return _children;
// }
//}
public AChildList GetChildList()
{
if (FieldManager.FieldExists(ChildListProperty))
return ReadProperty<AChildList>(ChildListProperty);
else
return null;
//return _children;
}
public int EditLevel
{
get { return base.EditLevel; }
}
protected override object GetIdValue()
{
return _id;
}
public AParent()
{
_id = Guid.NewGuid();
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Csla.Test.LazyLoad
{
[Serializable]
public class AParent : Csla.BusinessBase<AParent>
{
private Guid _id;
public Guid Id
{
get { return _id; }
set
{
_id = value;
PropertyHasChanged();
}
}
private AChildList _children;
public AChildList ChildList
{
get
{
if (_children == null)
{
_children = new AChildList();
for (int count = 0; count < EditLevel; count++)
((Csla.Core.IUndoableObject)_children).CopyState(EditLevel);
}
return _children;
}
}
public AChildList GetChildList()
{
return _children;
}
public int EditLevel
{
get { return base.EditLevel; }
}
protected override object GetIdValue()
{
return _id;
}
public AParent()
{
_id = Guid.NewGuid();
}
}
}
| mit | C# |
6a9a753ca4f0d5b7cfcd939aee58720e29f700ef | Remove extra references from Startup | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/WebSites/SecurityWebSite/Startup.cs | test/WebSites/SecurityWebSite/Startup.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace SecurityWebSite
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddAntiforgery();
services.AddAuthentication();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = "/Home/Login",
LogoutPath = "/Home/Logout",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace SecurityWebSite
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddAntiforgery();
services.AddAuthentication();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
LoginPath = "/Home/Login",
LogoutPath = "/Home/Logout",
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
| apache-2.0 | C# |
ff4ad28bca32795c0df7bd61bb8c792c1eb73436 | Fix GtkTestRunner so that test assembly is added to NUnit args | iainx/xwt,hamekoz/xwt,mminns/xwt,cra0zy/xwt,mono/xwt,akrisiun/xwt,directhex/xwt,sevoku/xwt,lytico/xwt,antmicro/xwt,TheBrainTech/xwt,mminns/xwt,steffenWi/xwt,hwthomas/xwt,residuum/xwt | Testing/GtkTestRunner/Main.cs | Testing/GtkTestRunner/Main.cs | //
// Main.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// 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 Xwt;
using System.Collections.Generic;
using System.Threading;
namespace GtkTestRunner
{
class MainClass
{
public static void Main (string[] args)
{
Xwt.Application.Initialize (Xwt.ToolkitType.Gtk);
ReferenceImageManager.Init ("GtkTestRunner");
var list = new List<string> (args);
list.Add ("-domain=None");
list.Add ("-noshadow");
list.Add ("-nothread");
list.Add (typeof (MainClass).Assembly.Location);
NUnit.ConsoleRunner.Runner.Main (list.ToArray ());
ReferenceImageManager.ShowImageVerifier ();
}
}
}
| //
// Main.cs
//
// Author:
// Lluis Sanchez <[email protected]>
//
// Copyright (c) 2013 Xamarin Inc.
//
// 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 Xwt;
using System.Collections.Generic;
using System.Threading;
namespace GtkTestRunner
{
class MainClass
{
public static void Main (string[] args)
{
Xwt.Application.Initialize (Xwt.ToolkitType.Gtk);
ReferenceImageManager.Init ("GtkTestRunner");
var list = new List<string> (args);
list.Add ("-domain=None");
list.Add ("-noshadow");
list.Add ("-nothread");
NUnit.ConsoleRunner.Runner.Main (list.ToArray ());
ReferenceImageManager.ShowImageVerifier ();
}
}
}
| mit | C# |
1789f72b7ef2a7c3f48134577253fc0f2ccdb00a | Add license terms. | yonglehou/msgpack-rpc-cli,yfakariya/msgpack-rpc-cli | src/MsgPack.Rpc.Client/Rpc/Client/Protocols/ProtocolTrace.FromRpcError.cs | src/MsgPack.Rpc.Client/Rpc/Client/Protocols/ProtocolTrace.FromRpcError.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// 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 -- License Terms --
using System;
using System.Diagnostics;
namespace MsgPack.Rpc.Client.Protocols
{
partial class MsgPackRpcClientProtocolsTrace
{
internal static void TraceRpcError( RpcError rpcError, string format, params object[] args )
{
_source.TraceEvent( GetTypeForRpcError( rpcError ), GetIdForRpcError( rpcError ), format, args );
}
private static TraceEventType GetTypeForRpcError( RpcError rpcError )
{
if ( 0 < rpcError.ErrorCode || rpcError.ErrorCode == -31 )
{
return TraceEventType.Warning;
}
switch ( rpcError.ErrorCode % 10 )
{
case -2:
case -4:
{
return TraceEventType.Warning;
}
case -1:
case -3:
{
return TraceEventType.Critical;
}
default:
{
return TraceEventType.Error;
}
}
}
private static int GetIdForRpcError( RpcError rpcError )
{
if ( 0 < rpcError.ErrorCode )
{
return 20000;
}
else
{
return 10000 + ( rpcError.ErrorCode * -1 );
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace MsgPack.Rpc.Client.Protocols
{
partial class MsgPackRpcClientProtocolsTrace
{
internal static void TraceRpcError( RpcError rpcError, string format, params object[] args )
{
_source.TraceEvent( GetTypeForRpcError( rpcError ), GetIdForRpcError( rpcError ), format, args );
}
private static TraceEventType GetTypeForRpcError( RpcError rpcError )
{
if ( 0 < rpcError.ErrorCode || rpcError.ErrorCode == -31 )
{
return TraceEventType.Warning;
}
switch ( rpcError.ErrorCode % 10 )
{
case -2:
case -4:
{
return TraceEventType.Warning;
}
case -1:
case -3:
{
return TraceEventType.Critical;
}
default:
{
return TraceEventType.Error;
}
}
}
private static int GetIdForRpcError( RpcError rpcError )
{
if ( 0 < rpcError.ErrorCode )
{
return 20000;
}
else
{
return 10000 + ( rpcError.ErrorCode * -1 );
}
}
}
}
| apache-2.0 | C# |
993642dae0e570a63d63c3757b3e3bce7c16005d | Add comment | shyamnamboodiripad/roslyn,mavasani/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,mavasani/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn | src/Workspaces/Core/Portable/Indentation/FormattingOptions.IndentStyle.cs | src/Workspaces/Core/Portable/Indentation/FormattingOptions.IndentStyle.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Formatting
{
public static partial class FormattingOptions
{
// Publicly exposed. Keep in sync with <see cref="FormattingOptions2.IndentStyle"/> in the CodeStyle layer.
public enum IndentStyle
{
None = 0,
Block = 1,
Smart = 2
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.Formatting
{
public static partial class FormattingOptions
{
// Publicly exposed. Keep in sync with IndentStyle2 in the CodeStyle layer.
public enum IndentStyle
{
None = 0,
Block = 1,
Smart = 2
}
}
}
| mit | C# |
85e3cd88ded5826e5403f5e3d221a6794201a646 | Fix snapshots for #252. | ExRam/ExRam.Gremlinq | test/ExRam.Gremlinq.PublicApi.Tests/PublicApiTests.JanusGraph.verified.cs | test/ExRam.Gremlinq.PublicApi.Tests/PublicApiTests.JanusGraph.verified.cs | namespace ExRam.Gremlinq.Core
{
public static class GremlinQueryEnvironmentExtensions
{
public static ExRam.Gremlinq.Core.IGremlinQueryEnvironment UseJanusGraph(this ExRam.Gremlinq.Core.IGremlinQueryEnvironment environment, System.Func<ExRam.Gremlinq.Providers.JanusGraph.IJanusGraphConfigurationBuilder, ExRam.Gremlinq.Core.IGremlinQueryExecutorBuilder> transformation) { }
}
}
namespace ExRam.Gremlinq.Providers.JanusGraph
{
public interface IJanusGraphConfigurationBuilder
{
ExRam.Gremlinq.Providers.JanusGraph.IJanusGraphConfigurationBuilderWithUri At(System.Uri uri);
}
public interface IJanusGraphConfigurationBuilderWithUri : ExRam.Gremlinq.Core.IGremlinQueryExecutorBuilder
{
ExRam.Gremlinq.Core.IGremlinQueryExecutorBuilder ConfigureWebSocket(System.Func<ExRam.Gremlinq.Providers.WebSocket.IWebSocketGremlinQueryExecutorBuilder, ExRam.Gremlinq.Providers.WebSocket.IWebSocketGremlinQueryExecutorBuilder> transformation);
}
} | namespace ExRam.Gremlinq.Core
{
public static class GremlinQueryEnvironmentExtensions
{
public static ExRam.Gremlinq.Core.IGremlinQueryEnvironment UseJanusGraph(this ExRam.Gremlinq.Core.IGremlinQueryEnvironment environment, System.Func<ExRam.Gremlinq.Providers.WebSocket.IWebSocketGremlinQueryExecutorBuilder, ExRam.Gremlinq.Providers.WebSocket.IWebSocketGremlinQueryExecutorBuilder> builderAction) { }
}
} | mit | C# |
82a3c458dd09899b0a38a76483b549f60c0d92f6 | Bump version to 0.1.9. | FacilityApi/Facility,ejball/Facility | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("0.1.9.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("0.1.8.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
ffac9884bf6a0a3af9b3ecef14fe254c672eda6a | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.2.0.26")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.2.0.25")] | mit | C# |
fa294bbe248882b786a82c556bcabab99e476092 | Add properties & methods to IAuthenticationClient | wadewegner/Force.com-Toolkit-for-NET,developerforce/Force.com-Toolkit-for-NET,developerforce/Force.com-Toolkit-for-NET | src/CommonLibrariesForNET/IAuthenticationClient.cs | src/CommonLibrariesForNET/IAuthenticationClient.cs | using System.Threading.Tasks;
namespace Salesforce.Common
{
public interface IAuthenticationClient
{
string InstanceUrl { get; set; }
string AccessToken { get; set; }
string RefreshToken { get; set; }
string Id { get; set; }
string ApiVersion { get; set; }
Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password);
Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password, string tokenRequestEndpointUrl);
Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code);
Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code, string tokenRequestEndpointUrl);
Task TokenRefreshAsync(string clientId, string refreshToken, string clientSecret = "");
Task TokenRefreshAsync(string clientId, string refreshToken, string clientSecret, string tokenRequestEndpointUrl);
void Dispose();
}
}
| using System.Threading.Tasks;
namespace Salesforce.Common
{
public interface IAuthenticationClient
{
string InstanceUrl { get; set; }
string AccessToken { get; set; }
string ApiVersion { get; set; }
Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password);
Task UsernamePasswordAsync(string clientId, string clientSecret, string username, string password, string tokenRequestEndpointUrl);
Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code);
Task WebServerAsync(string clientId, string clientSecret, string redirectUri, string code, string tokenRequestEndpointUrl);
void Dispose();
}
}
| bsd-3-clause | C# |
014be649834ed7973de4eca31d1ced814a63dc6c | Check the user-agent string for "Trident" in order to identify IE11 as an IE browser. This is only needed for a workaround for comments within select elements in IE below version 10 and should be abandoned when possible. | vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb,vc3/ExoWeb | ExoWeb/Templates/MicrosoftAjax/AjaxPage.cs | ExoWeb/Templates/MicrosoftAjax/AjaxPage.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ExoWeb.Templates.MicrosoftAjax
{
/// <summary>
/// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports
/// parsing and loading templates using the Microsoft AJAX syntax.
/// </summary>
internal class AjaxPage : Page
{
internal AjaxPage()
{
IsIE = HttpContext.Current != null &&
(HttpContext.Current.Request.Browser.IsBrowser("IE") ||
(!string.IsNullOrEmpty(HttpContext.Current.Request.UserAgent) && HttpContext.Current.Request.UserAgent.Contains("Trident")));
}
int nextControlId;
internal string NextControlId
{
get
{
return "exo" + nextControlId++;
}
}
internal bool IsIE { get; private set; }
public override ITemplate Parse(string name, string template)
{
return Template.Parse(name, template);
}
public override IEnumerable<ITemplate> ParseTemplates(string source, string template)
{
return Block.Parse(source, template).OfType<ITemplate>();
}
public override IEnumerable<ITemplate> LoadTemplates(string path)
{
return Template.Load(path).Cast<ITemplate>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace ExoWeb.Templates.MicrosoftAjax
{
/// <summary>
/// Microsoft AJAX specific implementation of <see cref="ExoWeb.Templates.Page"/> that supports
/// parsing and loading templates using the Microsoft AJAX syntax.
/// </summary>
internal class AjaxPage : Page
{
internal AjaxPage()
{
IsIE = HttpContext.Current != null && HttpContext.Current.Request.Browser.IsBrowser("IE");
}
int nextControlId;
internal string NextControlId
{
get
{
return "exo" + nextControlId++;
}
}
internal bool IsIE { get; private set; }
public override ITemplate Parse(string name, string template)
{
return Template.Parse(name, template);
}
public override IEnumerable<ITemplate> ParseTemplates(string source, string template)
{
return Block.Parse(source, template).OfType<ITemplate>();
}
public override IEnumerable<ITemplate> LoadTemplates(string path)
{
return Template.Load(path).Cast<ITemplate>();
}
}
}
| mit | C# |
b6091830abac9019cd3bffcad55101038492418a | Support RequestedAt being nullable | stripe/stripe-dotnet | src/Stripe.net/Entities/Capabilities/Capability.cs | src/Stripe.net/Entities/Capabilities/Capability.cs | namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class Capability : StripeEntity<Capability>, IHasId, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object’s type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
#region Expandable Account
/// <summary>
/// ID of the account the capability is associated with.
/// </summary>
[JsonIgnore]
public string AccountId
{
get => this.InternalAccount?.Id;
set => this.InternalAccount = SetExpandableFieldId(value, this.InternalAccount);
}
[JsonIgnore]
public Account Account
{
get => this.InternalAccount?.ExpandedObject;
set => this.InternalAccount = SetExpandableFieldObject(value, this.InternalAccount);
}
[JsonProperty("account")]
[JsonConverter(typeof(ExpandableFieldConverter<Account>))]
internal ExpandableField<Account> InternalAccount { get; set; }
#endregion
/// <summary>
/// Whether the capability has been requested.
/// </summary>
[JsonProperty("requested")]
public bool Requested { get; set; }
/// <summary>
/// Time at which the capability was requested. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("requested_at")]
[JsonConverter(typeof(DateTimeConverter))]
public DateTime? RequestedAt { get; set; }
/// <summary>
/// Information about the requirements for this capability, including what information
/// needs to be collected, and by when.
/// </summary>
[JsonProperty("requirements")]
public CapabilityRequirements Requirements { get; set; }
/// <summary>
/// The status of the capability. Can be <c>active</c>, <c>inactive</c>, <c>pending</c>, or
/// <c>unrequested</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
| namespace Stripe
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class Capability : StripeEntity<Capability>, IHasId, IHasObject
{
/// <summary>
/// Unique identifier for the object.
/// </summary>
[JsonProperty("id")]
public string Id { get; set; }
/// <summary>
/// String representing the object’s type. Objects of the same type share the same value.
/// </summary>
[JsonProperty("object")]
public string Object { get; set; }
#region Expandable Account
/// <summary>
/// ID of the account the capability is associated with.
/// </summary>
[JsonIgnore]
public string AccountId
{
get => this.InternalAccount?.Id;
set => this.InternalAccount = SetExpandableFieldId(value, this.InternalAccount);
}
[JsonIgnore]
public Account Account
{
get => this.InternalAccount?.ExpandedObject;
set => this.InternalAccount = SetExpandableFieldObject(value, this.InternalAccount);
}
[JsonProperty("account")]
[JsonConverter(typeof(ExpandableFieldConverter<Account>))]
internal ExpandableField<Account> InternalAccount { get; set; }
#endregion
/// <summary>
/// Whether the capability has been requested.
/// </summary>
[JsonProperty("requested")]
public bool Requested { get; set; }
/// <summary>
/// Time at which the capability was requested. Measured in seconds since the Unix epoch.
/// </summary>
[JsonProperty("requested_at")]
[JsonConverter(typeof(DateTimeConverter))]
public DateTime RequestedAt { get; set; }
/// <summary>
/// Information about the requirements for this capability, including what information
/// needs to be collected, and by when.
/// </summary>
[JsonProperty("requirements")]
public CapabilityRequirements Requirements { get; set; }
/// <summary>
/// The status of the capability. Can be <c>active</c>, <c>inactive</c>, <c>pending</c>, or
/// <c>unrequested</c>.
/// </summary>
[JsonProperty("status")]
public string Status { get; set; }
}
}
| apache-2.0 | C# |
1be441166f91dea03c374350f3383f59409d1f85 | Update DevelopexTechClub.cshtml | dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua | src/WebSite/Views/Content/DevelopexTechClub.cshtml | src/WebSite/Views/Content/DevelopexTechClub.cshtml | <h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-8">
<img src="https://127fc3e2e552.blob.core.windows.net/devdigest/developex.png" alt="Developex Tech Club" class="img-responsive" />
</div>
<div class="col-md-4">
</div>
</div>
<div class="row">
<div class="col-md-12">
What is Developex Tech Club? These is a small monthly meetups on various technical topics. Especially for you we select the best specialists and invite them to share their knowledge and experience.<br />
<br />
You can find all latest news and announces at official <a href="https://www.facebook.com/Developex-Tech-Club-584649545203672/">Facebook Page</a>.<br />
</div>
</div>
| <h1>@ViewData["Title"]</h1>
<div class="row">
<div class="col-md-8">
<img src="https://scontent-frx5-1.xx.fbcdn.net/v/t1.0-9/26804441_584652555203371_5742271135022082853_n.jpg?oh=6dd4e26a84aaf9b735db6413947c9015&oe=5AF49877" class="img-responsive" />
</div>
<div class="col-md-4">
</div>
</div>
<div class="row">
<div class="col-md-12">
What is Developex Tech Club? These is a small monthly meetups on various technical topics. Especially for you we select the best specialists and invite them to share their knowledge and experience.<br />
<br />
You can find all latest news and announces at official <a href="https://www.facebook.com/Developex-Tech-Club-584649545203672/">Facebook Page</a>.<br />
</div>
</div> | mit | C# |
66dca64d85cc5d9282d5d564901bfa7a9a25a093 | update gateId | janbin16/ParkingSpace,janbin16/ParkingSpace,janbin16/ParkingSpace | ParkingSpace.Web/Views/GateIn/Index.cshtml | ParkingSpace.Web/Views/GateIn/Index.cshtml | @using ParkingSpace.Models
@{
ViewBag.Title = "Index";
var ticket = (ParkingTicket)TempData["newTicket"];
}
<h2>Gate In </h2>
<div class="well well-sm"><h2>[@ViewBag.GateId]</h2></div>
@using(Html.BeginForm("CreateTicket", "GateIn")) {
<div class="row">
<div class="col-lg-2">
Plate No. :
</div>
<div class="col-lg-3">
@Html.TextBox("plateNo")
</div>
</div>
<div class="row">
<div class="col-lg-3 col-lg-offset-2">
<button type="submit" class="btn btn-success">Issue Parking Ticket</button>
</div>
</div>
}
@if (ticket != null) {
<div class="well">
@ticket.Id <br />
@ticket.PlateNumber <br />
@ticket.DateIn
</div>
}
| @using ParkingSpace.Models
@{
ViewBag.Title = "Index";
var ticket = (ParkingTicket)TempData["newTicket"];
}
<h2>Gate In [@ViewBag.GateId]</h2>
@using(Html.BeginForm("CreateTicket", "GateIn")) {
<div class="row">
<div class="col-lg-2">
Plate No. :
</div>
<div class="col-lg-3">
@Html.TextBox("plateNo")
</div>
</div>
<div class="row">
<div class="col-lg-3 col-lg-offset-2">
<button type="submit" class="btn btn-success">Issue Parking Ticket</button>
</div>
</div>
}
@if (ticket != null) {
<div class="well">
@ticket.Id <br />
@ticket.PlateNumber <br />
@ticket.DateIn
</div>
}
| mit | C# |
6647832c1e46513fc55b085535fd4ea7925a8d40 | Update WeaverInitialiserTests.cs | Fody/Fody,GeertvanHorrik/Fody | Tests/FodyIsolated/WeaverInitialiserTests.cs | Tests/FodyIsolated/WeaverInitialiserTests.cs | using System.Collections.Generic;
using System.Linq;
using Fody;
using Mono.Cecil;
using ObjectApproval;
using Xunit;
using Xunit.Abstractions;
public class WeaverInitialiserTests :
XunitLoggingBase
{
[Fact]
public void ValidPropsFromBase()
{
var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);
var resolver = new MockAssemblyResolver();
var innerWeaver = BuildInnerWeaver(moduleDefinition, resolver);
innerWeaver.SplitUpReferences();
var weaverEntry = new WeaverEntry
{
Element = "<foo/>",
AssemblyPath = @"c:\FakePath\Assembly.dll"
};
var moduleWeaver = new ValidFromBaseModuleWeaver();
innerWeaver.SetProperties(weaverEntry, moduleWeaver);
SerializerBuilder.IgnoreMembersWithType<ModuleDefinition>();
ObjectApprover.Verify(moduleWeaver);
}
static InnerWeaver BuildInnerWeaver(ModuleDefinition moduleDefinition, AssemblyResolver resolver)
{
return new InnerWeaver
{
Logger = new MockBuildLogger(),
AssemblyFilePath = "AssemblyFilePath",
ProjectDirectoryPath = "ProjectDirectoryPath",
ProjectFilePath = "ProjectFilePath",
SolutionDirectoryPath = "SolutionDirectoryPath",
DocumentationFilePath = "DocumentationFile",
ReferenceCopyLocalPaths = new List<string>
{
"CopyRef1",
"CopyRef2"
},
References = "Ref1;Ref2",
ModuleDefinition = moduleDefinition,
DefineConstants = new List<string>
{
"Debug",
"Release"
},
assemblyResolver = resolver,
TypeCache = new TypeCache(resolver.Resolve)
};
}
public WeaverInitialiserTests(ITestOutputHelper output) :
base(output)
{
}
}
public class ValidFromBaseModuleWeaver : BaseModuleWeaver
{
public bool ExecuteCalled;
public override void Execute()
{
ExecuteCalled = true;
}
public override IEnumerable<string> GetAssembliesForScanning()
{
return Enumerable.Empty<string>();
}
} | using System.Collections.Generic;
using System.Linq;
using Fody;
using Mono.Cecil;
using Xunit;
using Xunit.Abstractions;
public class WeaverInitialiserTests :
XunitLoggingBase
{
[Fact]
public void ValidPropsFromBase()
{
var moduleDefinition = ModuleDefinition.CreateModule("Foo", ModuleKind.Dll);
var resolver = new MockAssemblyResolver();
var innerWeaver = BuildInnerWeaver(moduleDefinition, resolver);
innerWeaver.SplitUpReferences();
var weaverEntry = new WeaverEntry
{
Element = "<foo/>",
AssemblyPath = @"c:\FakePath\Assembly.dll"
};
var moduleWeaver = new ValidFromBaseModuleWeaver();
innerWeaver.SetProperties(weaverEntry, moduleWeaver);
SerializerBuilder.IgnoreMembersWithType<ModuleDefinition>();
ObjectApprover.Verify(moduleWeaver);
}
static InnerWeaver BuildInnerWeaver(ModuleDefinition moduleDefinition, AssemblyResolver resolver)
{
return new InnerWeaver
{
Logger = new MockBuildLogger(),
AssemblyFilePath = "AssemblyFilePath",
ProjectDirectoryPath = "ProjectDirectoryPath",
ProjectFilePath = "ProjectFilePath",
SolutionDirectoryPath = "SolutionDirectoryPath",
DocumentationFilePath = "DocumentationFile",
ReferenceCopyLocalPaths = new List<string>
{
"CopyRef1",
"CopyRef2"
},
References = "Ref1;Ref2",
ModuleDefinition = moduleDefinition,
DefineConstants = new List<string>
{
"Debug",
"Release"
},
assemblyResolver = resolver,
TypeCache = new TypeCache(resolver.Resolve)
};
}
public WeaverInitialiserTests(ITestOutputHelper output) :
base(output)
{
}
}
public class ValidFromBaseModuleWeaver : BaseModuleWeaver
{
public bool ExecuteCalled;
public override void Execute()
{
ExecuteCalled = true;
}
public override IEnumerable<string> GetAssembliesForScanning()
{
return Enumerable.Empty<string>();
}
} | mit | C# |
d66a7815fdb313101ada04ee535bdc9448c975dc | increment patch version, | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.13")]
[assembly: AssemblyInformationalVersion("0.8.13")]
/*
* Version 0.8.13
*
* While publishing v0.8.12 to NuGet server, exception was thrown,
* so v0.8.13 is published to ignore the exception.
*
* Rename some properties of FirstClassCommand to clarify
*
* BREAKING CHANGE
* FirstClassCommand class
* before:
* Method
* after:
* DeclaredMethod
*
* before:
* TestCase
* after:
* TestMethod
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.12")]
[assembly: AssemblyInformationalVersion("0.8.12")]
/*
* Version 0.8.12
*
* Rename some properties of FirstClassCommand to clarify
*
* BREAKING CHANGE
* FirstClassCommand class
* before:
* Method
* after:
* DeclaredMethod
*
* before:
* TestCase
* after:
* TestMethod
*/ | mit | C# |
aa48f34f99754be62b2cba2904d090ede0117c15 | test pushing package to symbol server. | jwChung/Experimentalism,jwChung/Experimentalism | build/CommonAssemblyInfo.cs | build/CommonAssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.3")]
[assembly: AssemblyInformationalVersion("0.8.3-test")]
/*
* Version 0.8.3-test
*
* Initializes a test-fixture only when necessary rather than every time.
*
* Fixes that fixture factory passed from ConvertToTestCommand should take
* MethodInfo of a test delegate rather than it of a test method, which is
* adorned with FisrtClassTheoremAttribute.
*
* BREAKING CHANGE
* - ITestCase, TestCase
* ITestCommand ConvertToTestCommand(IMethodInfo, ITestFixture)
* -> ITestCommand ConvertToTestCommand(IMethodInfo, Func<MethodInfo, ITestFixture>)
*
* Issue
* - https://github.com/jwChung/Experimentalism/issues/28
*
* Pull request
* - https://github.com/jwChung/Experimentalism/pull/29
*/ | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Jin-Wook Chung")]
[assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyVersion("0.8.3")]
[assembly: AssemblyInformationalVersion("0.8.3")]
/*
* Version 0.8.3
*
* Initializes a test-fixture only when necessary rather than every time.
*
* Fixes that fixture factory passed from ConvertToTestCommand should take
* MethodInfo of a test delegate rather than it of a test method, which is
* adorned with FisrtClassTheoremAttribute.
*
* BREAKING CHANGE
* - ITestCase, TestCase
* ITestCommand ConvertToTestCommand(IMethodInfo, ITestFixture)
* -> ITestCommand ConvertToTestCommand(IMethodInfo, Func<MethodInfo, ITestFixture>)
*
* Issue
* - https://github.com/jwChung/Experimentalism/issues/28
*
* Pull request
* - https://github.com/jwChung/Experimentalism/pull/29
*/ | mit | C# |
7a8f3bbdcf2536506b2f234815a1d8badf6d7bac | Update HeightCalculatorFromBones.cs | cwesnow/Net_Fiddle | 2017oct/HeightCalculatorFromBones.cs | 2017oct/HeightCalculatorFromBones.cs | // Original Source Information
// Author: GitGub on Reddit
// Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/
// Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW
using System;
public class Program
{
static Random random = new Random();
enum Bones { Femur, Tibia, Humerus, Radius }
enum Gender { Male = 1, Female = 2 }
public static void Main()
{
for(int x = 0; x < 5; x++) {
// Get Randome Values
float length = randomLength();
Bones bone = randomBone();
Gender gender = randomGender();
int age = randomAge();
// Result
Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}",
gender, age, bone, length, calculateHeight(bone, length, gender, age));
}
}
private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age)
{
float height = 0;
switch(bone) {
case Bones.Femur:
height = (gender == Gender.Male) ?
69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f;
break;
case Bones.Tibia:
height = (gender == Gender.Male) ?
81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f;
break;
case Bones.Humerus:
height = (gender == Gender.Male) ?
height = 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f;
break;
case Bones.Radius:
height = (gender == Gender.Male) ?
80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f;
break;
default: break;
}
return height;
}
private static float randomLength() { return (float)random.NextDouble()*3; }
private static Bones randomBone() { return (Bones)random.Next(1,4); }
private static Gender randomGender() { return (Gender)random.Next(0,2); } // 1,2 & 0,1 always gave the same gender
private static int randomAge() { return random.Next(16, 99); }
}
| // Original Source Information
// Author: GitGub on Reddit
// Link: https://www.reddit.com/r/learnprogramming/comments/77a49n/c_help_refactoring_an_ugly_method_with_lots_of_if/
// Refactored using .NET Fiddle - https://dotnetfiddle.net/F8UcJW
using System;
public class Program
{
static Random random = new Random();
enum Bones { Femur, Tibia, Humerus, Radius }
enum Gender { Male = 1, Female = 2 }
public static void Main()
{
for(int x = 0; x < 5; x++) {
// Get Randome Values
float length = randomLength();
Bones bone = randomBone();
Gender gender = randomGender();
int age = randomAge();
// Result
Console.WriteLine("\nGender: {0}\nAge: {1}\nBone: {2}\nLength: {3}\nHeight: {4}",
gender, age, bone, length, calculateHeight(bone, length, gender, age));
}
}
private static float calculateHeight(Bones bone, float boneLength, Gender gender, int age)
{
float height = 0;
switch(bone) {
case Bones.Femur:
height = (gender == Gender.Male) ?
69.089f + (2.238f * boneLength) - age * 0.06f : 61.412f + (2.317f * boneLength) - age * 0.06f;
break;
case Bones.Tibia:
height = (gender == Gender.Male) ?
81.688f + (2.392f * boneLength) - age * 0.06f : 72.572f + (2.533f * boneLength) - age * 0.06f;
break;
case Bones.Humerus:
height = (gender == Gender.Male) ?
height = 73.570f + (2.970f * boneLength) - age * 0.06f : 64.977f + (3.144f * boneLength) - age * 0.06f;
break;
case Bones.Radius:
height = (gender == Gender.Male) ?
80.405f + (3.650f * boneLength) - age * 0.06f : 73.502f + (3.876f * boneLength) - age * 0.06f;
break;
default: break;
}
return height;
}
private static float randomLength() { return (float)random.NextDouble()*3; }
private static Bones randomBone() { return (Bones)random.Next(1,4); }
private static Gender randomGender() { return (Gender)random.Next(1,2); }
private static int randomAge() { return random.Next(16, 99); }
}
| mit | C# |
97093e87807c841256734a66d94d9f49c16ab3ab | Update PointShapeExtensions.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.ViewModels/Shapes/Extensions/PointShapeExtensions.cs | src/Draw2D.ViewModels/Shapes/Extensions/PointShapeExtensions.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Spatial;
namespace Draw2D.ViewModels.Shapes
{
public static class PointShapeExtensions
{
public static Point2 ToPoint2(this IPointShape point)
{
return new Point2(point.X, point.Y);
}
public static IPointShape FromPoint2(this Point2 point, IBaseShape template = null)
{
return new PointShape(point.X, point.Y, template);
}
public static double DistanceTo(this IPointShape point, IPointShape other)
{
return point.ToPoint2().DistanceTo(other.ToPoint2());
}
public static Rect2 ToRect2(this IPointShape center, double radius)
{
return Rect2.FromPoints(
center.X - radius,
center.Y - radius,
center.X + radius,
center.Y + radius);
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Spatial;
namespace Draw2D.ViewModels.Shapes
{
public static class PointShapeExtensions
{
public static Point2 ToPoint2(this IPointShape point)
{
return new Point2(point.X, point.Y);
}
public static IPointShape FromPoint2(this Point2 point, IBaseShape template = null)
{
return new PointShape(point.X, point.Y, template);
}
public static double DistanceTo(this IPointShape point, IPointShape other)
{
return point.ToPoint2().DistanceTo(other.ToPoint2());
}
}
}
| mit | C# |
fd99aa89f20c5bf07615bb887862a22189283ef3 | Update AuthTest. | jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples | auth/AuthTest/AuthTest.cs | auth/AuthTest/AuthTest.cs | /*
* Copyright (c) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Xunit;
namespace GoogleCloudSamples
{
public class AuthTest
{
static readonly CommandLineRunner s_runner = new CommandLineRunner
{
Command = "AuthSample.exe",
VoidMain = AuthSample.Main,
};
string JsonPath
{
get
{
return System.Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
}
}
[Theory]
[InlineData("cloud")]
[InlineData("api")]
[InlineData("http")]
void TestImplicit(string cmd)
{
var output = s_runner.Run(cmd);
Assert.Equal(0, output.ExitCode);
Assert.False(string.IsNullOrWhiteSpace(output.Stdout));
}
[Theory]
[InlineData("cloud")]
[InlineData("api")]
[InlineData("http")]
void TestExplicit(string cmd)
{
var output = s_runner.Run(cmd, "-j", JsonPath);
Assert.Equal(0, output.ExitCode);
Assert.False(string.IsNullOrWhiteSpace(output.Stdout));
}
}
}
| /*
* Copyright (c) 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
using Xunit;
namespace GoogleCloudSamples
{
public class AuthTest
{
private static readonly CommandLineRunner s_runner = new CommandLineRunner
{
Command = "Storage.exe",
VoidMain = AuthSample.Main,
};
[Fact]
void Test()
{
var bucket = System.Environment.GetEnvironmentVariable(
"GOOGLE_CLOUD_STORAGE_BUCKET"
);
var output = s_runner.Run(bucket);
Assert.Equal(0, output.ExitCode);
}
}
}
| apache-2.0 | C# |
9530b7611dd98f19d336e5e1a7d3807ff44af87e | Stop on ctrl-c. | themotleyfool/NuGet.Lucene,googol/NuGet.Lucene,Stift/NuGet.Lucene | source/NuGet.Lucene.Web.OwinHost.Sample/Program.cs | source/NuGet.Lucene.Web.OwinHost.Sample/Program.cs | using System;
using Microsoft.Owin.Hosting;
using System.Threading;
namespace NuGet.Lucene.Web.OwinHost.Sample
{
class Program
{
static void Main(string[] args)
{
const string baseAddress = "http://localhost:9000/";
var cancelToken = new CancellationTokenSource();
Console.CancelKeyPress += (_, __) => cancelToken.Cancel();
try
{
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Listening on " + baseAddress + ". Press <ctrl>+c to stop listening.");
cancelToken.Token.WaitHandle.WaitOne();
}
}
catch (Exception ex)
{
WriteExceptionChain(ex);
}
Console.WriteLine("Press enter to quit.");
Console.ReadLine();
}
private static void WriteExceptionChain(Exception ex)
{
while (ex != null)
{
Console.Error.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message);
Console.Error.WriteLine(ex.StackTrace);
ex = ex.InnerException;
}
}
}
}
| using System;
using Microsoft.Owin.Hosting;
namespace NuGet.Lucene.Web.OwinHost.Sample
{
class Program
{
static void Main(string[] args)
{
const string baseAddress = "http://localhost:9000/";
try
{
using (WebApp.Start<Startup>(baseAddress))
{
Console.WriteLine("Listening on " + baseAddress + ". Press enter to stop listening.");
Console.ReadLine();
}
}
catch (Exception ex)
{
WriteExceptionChain(ex);
}
Console.WriteLine("Press enter to quit.");
Console.ReadLine();
}
private static void WriteExceptionChain(Exception ex)
{
while (ex != null)
{
Console.Error.WriteLine("{0}: {1}", ex.GetType().FullName, ex.Message);
Console.Error.WriteLine(ex.StackTrace);
ex = ex.InnerException;
}
}
}
}
| apache-2.0 | C# |
aeeaaf0e8fd9f32e8178e406481c11dfd72184a5 | Add missing call to set content root on WebHostBuilder | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | samples/MusicStore/Program.cs | samples/MusicStore/Program.cs | using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
| using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
| apache-2.0 | C# |
b30597b8f167064a127328de20f33e4b727a1e68 | Change the seed saved in NBXplorer to hot wallet (#1652) | btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver | BTCPayServer/Views/Wallets/WalletSigningMenu.cshtml | BTCPayServer/Views/Wallets/WalletSigningMenu.cshtml | @model (string CryptoCode, bool NBXSeedAvailable)
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="SendMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Sign with...
</button>
<div class="dropdown-menu" aria-labelledby="SendMenu">
@if (Model.CryptoCode == "BTC")
{
<button name="command" type="submit" class="dropdown-item" value="vault">... a hardware wallet</button>
}
<button name="command" type="submit" class="dropdown-item" value="seed">... an HD private key or mnemonic seed</button>
<button name="command" type="submit" class="dropdown-item" value="analyze-psbt">... a wallet supporting PSBT</button>
@if (Model.NBXSeedAvailable)
{
<button id="spendWithNBxplorer" name="command" type="submit" class="dropdown-item" value="nbx-seed">... the hot wallet</button>
}
</div>
</div>
| @model (string CryptoCode, bool NBXSeedAvailable)
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="SendMenu" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Sign with...
</button>
<div class="dropdown-menu" aria-labelledby="SendMenu">
@if (Model.CryptoCode == "BTC")
{
<button name="command" type="submit" class="dropdown-item" value="vault">... a hardware wallet</button>
}
<button name="command" type="submit" class="dropdown-item" value="seed">... an HD private key or mnemonic seed</button>
<button name="command" type="submit" class="dropdown-item" value="analyze-psbt">... a wallet supporting PSBT</button>
@if (Model.NBXSeedAvailable)
{
<button id="spendWithNBxplorer" name="command" type="submit" class="dropdown-item" value="nbx-seed">... the seed saved in NBXplorer</button>
}
</div>
</div>
| mit | C# |
7719c91694f96f0e36194a035ffdeb67885b3778 | remove default route | PriceIsByte/WebAPI,PriceIsByte/WebAPI | CountingKs/App_Start/WebApiConfig.cs | CountingKs/App_Start/WebApiConfig.cs | using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
namespace CountingKs
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Food",
routeTemplate: "api/nutrition/foods/{id}",
defaults: new { controller = "Foods", id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
} | using Newtonsoft.Json.Serialization;
using System.Linq;
using System.Net.Http.Formatting;
using System.Web.Http;
namespace CountingKs
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "Food",
routeTemplate: "api/nutrition/foods/{id}",
defaults: new { controller = "Foods", id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().FirstOrDefault();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
} | unlicense | C# |
9fe0a20dd8eb6818726f10b4c9e4e21dc2402ccb | fix namespace | Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen | Dashen/Infrastructure/JsonContent.cs | Dashen/Infrastructure/JsonContent.cs | using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Dashen.Infrastructure
{
public class JsonContent : HttpContent
{
private readonly JToken _value;
public JsonContent(JToken value)
{
_value = value;
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
protected override Task SerializeToStreamAsync(Stream stream,
TransportContext context)
{
var jw = new JsonTextWriter(new StreamWriter(stream))
{
Formatting = Formatting.Indented
};
_value.WriteTo(jw);
jw.Flush();
return Task.FromResult<object>(null);
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
} | using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace Dashen.Endpoints.Stats
{
public class JsonContent : HttpContent
{
private readonly JToken _value;
public JsonContent(JToken value)
{
_value = value;
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
protected override Task SerializeToStreamAsync(Stream stream,
TransportContext context)
{
var jw = new JsonTextWriter(new StreamWriter(stream))
{
Formatting = Formatting.Indented
};
_value.WriteTo(jw);
jw.Flush();
return Task.FromResult<object>(null);
}
protected override bool TryComputeLength(out long length)
{
length = -1;
return false;
}
}
} | lgpl-2.1 | C# |
a65237072d13b94435850546637a4b948475d9e9 | Clean up publish code | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/GitHub.App/Services/RepositoryPublishService.cs | src/GitHub.App/Services/RepositoryPublishService.cs | using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using GitHub.Api;
using GitHub.Models;
using LibGit2Sharp;
namespace GitHub.Services
{
[Export(typeof(IRepositoryPublishService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class RepositoryPublishService : IRepositoryPublishService
{
readonly IGitClient gitClient;
readonly IRepository activeRepository;
[ImportingConstructor]
public RepositoryPublishService(IGitClient gitClient, IVSGitServices vsGitServices)
{
this.gitClient = gitClient;
this.activeRepository = vsGitServices.GetActiveRepo();
}
public string LocalRepositoryName
{
get
{
if (!string.IsNullOrEmpty(activeRepository?.Info?.WorkingDirectory))
return new DirectoryInfo(activeRepository.Info.WorkingDirectory).Name ?? "";
return string.Empty;
}
}
public IObservable<Octokit.Repository> PublishRepository(
Octokit.NewRepository newRepository,
IAccount account,
IApiClient apiClient)
{
return Observable.Defer(() => apiClient.CreateRepository(newRepository, account.Login, account.IsUser)
.Select(remoteRepo => new { RemoteRepo = remoteRepo, LocalRepo = activeRepository }))
.Select(async repo =>
{
await gitClient.SetRemote(repo.LocalRepo, "origin", new Uri(repo.RemoteRepo.CloneUrl));
await gitClient.Push(repo.LocalRepo, "master", "origin");
await gitClient.Fetch(repo.LocalRepo, "origin");
await gitClient.SetTrackingBranch(repo.LocalRepo, "master", "origin");
return repo.RemoteRepo;
})
.Select(t => t.Result);
}
}
}
| using System;
using System.ComponentModel.Composition;
using System.IO;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using GitHub.Api;
using GitHub.Models;
using LibGit2Sharp;
namespace GitHub.Services
{
[Export(typeof(IRepositoryPublishService))]
[PartCreationPolicy(CreationPolicy.Shared)]
public class RepositoryPublishService : IRepositoryPublishService
{
readonly IGitClient gitClient;
readonly IRepository activeRepository;
[ImportingConstructor]
public RepositoryPublishService(IGitClient gitClient, IVSGitServices vsGitServices)
{
this.gitClient = gitClient;
this.activeRepository = vsGitServices.GetActiveRepo();
}
public string LocalRepositoryName
{
get
{
if (!string.IsNullOrEmpty(activeRepository?.Info?.WorkingDirectory))
return new DirectoryInfo(activeRepository.Info.WorkingDirectory).Name ?? "";
return string.Empty;
}
}
public IObservable<Octokit.Repository> PublishRepository(
Octokit.NewRepository newRepository,
IAccount account,
IApiClient apiClient)
{
return Observable.Defer(() => apiClient.CreateRepository(newRepository, account.Login, account.IsUser)
.Select(remoteRepo => new { RemoteRepo = remoteRepo, LocalRepo = activeRepository }))
.SelectMany(repo => gitClient.SetRemote(repo.LocalRepo, "origin", new Uri(repo.RemoteRepo.CloneUrl)).ToObservable().Select(_ => repo))
.SelectMany(repo => gitClient.Push(repo.LocalRepo, "master", "origin").ToObservable().Select(_ => repo))
.SelectMany(repo => gitClient.Fetch(repo.LocalRepo, "origin").ToObservable().Select(_ => repo))
.SelectMany(repo => gitClient.SetTrackingBranch(repo.LocalRepo, "master", "origin").ToObservable().Select(_ => repo.RemoteRepo));
}
}
}
| mit | C# |
c90bc0e39b124ec57604fc8727548f475faa81e8 | Update default converter to handle exception type | stoiveyp/alexa-skills-dotnet,timheuer/alexa-skills-dotnet | Alexa.NET/Request/Type/Converters/DefaultRequestTypeConverter.cs | Alexa.NET/Request/Type/Converters/DefaultRequestTypeConverter.cs | namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest" || requestType == "System.ExceptionEncountered";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
}
| namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
} | mit | C# |
56799c4378680bd2b1ec395784154f301f3ce565 | change the way caculate price for order item | phamhuyhoang95/online-store-dotnetcore | Database/Services.cs/CartServices.cs | Database/Services.cs/CartServices.cs |
using System.Collections.Generic;
namespace project.Services
{
public class CartServices : ICartServices
{
private readonly CartRespository cartRespository;
private readonly ProductRepository productRepository;
private readonly OrderProductRespository orderProductRespository;
public CartServices()
{
cartRespository = new CartRespository();
productRepository = new ProductRepository();
orderProductRespository = new OrderProductRespository();
}
public int addOrder(Cart order)
{
// insert order to database
var orderCode = cartRespository.Add(order);
// insert to OrderProduct
// get list product by ids
foreach(var product in order.products){
// get product information
var p = productRepository.GetByID(product.productId);
// insert order
var newOrderProduct = new Entities.OrderProduct();
newOrderProduct.netPrice = p.netPrice * product.number;
newOrderProduct.price = p.Price *product.number;
newOrderProduct.number = product.number;
newOrderProduct.orderCode = orderCode;
newOrderProduct.productId = p.ProductId;
newOrderProduct.productCode = p.code;
// insert mapping
orderProductRespository.Add(newOrderProduct);
}
return orderCode;
}
public void deleteOrder(int orderId)
{
// delete from Cart table
cartRespository.Delete(orderId);
// delete from mapping table
orderProductRespository.Delete(orderId);
}
public IEnumerable<Cart> getAllOrder()
{
return cartRespository.getAll();
}
public Cart getOrder(int orderId)
{
// get order
var order = cartRespository.GetByID(orderId);
order.listProducts = orderProductRespository.GetById(orderId);
return order;
}
public void updateOrder()
{
throw new System.NotImplementedException();
}
}
} |
using System.Collections.Generic;
namespace project.Services
{
public class CartServices : ICartServices
{
private readonly CartRespository cartRespository;
private readonly ProductRepository productRepository;
private readonly OrderProductRespository orderProductRespository;
public CartServices()
{
cartRespository = new CartRespository();
productRepository = new ProductRepository();
orderProductRespository = new OrderProductRespository();
}
public int addOrder(Cart order)
{
// insert order to database
var orderCode = cartRespository.Add(order);
// insert to OrderProduct
// get list product by ids
foreach(var product in order.products){
// get product information
var p = productRepository.GetByID(product.productId);
// insert order
var newOrderProduct = new Entities.OrderProduct();
newOrderProduct.netPrice = p.netPrice;
newOrderProduct.price = p.Price;
newOrderProduct.number = product.number;
newOrderProduct.orderCode = orderCode;
newOrderProduct.productId = p.ProductId;
newOrderProduct.productCode = p.code;
// insert mapping
orderProductRespository.Add(newOrderProduct);
}
return orderCode;
}
public void deleteOrder(int orderId)
{
// delete from Cart table
cartRespository.Delete(orderId);
// delete from mapping table
orderProductRespository.Delete(orderId);
}
public IEnumerable<Cart> getAllOrder()
{
return cartRespository.getAll();
}
public Cart getOrder(int orderId)
{
// get order
var order = cartRespository.GetByID(orderId);
order.listProducts = orderProductRespository.GetById(orderId);
return order;
}
public void updateOrder()
{
throw new System.NotImplementedException();
}
}
} | mit | C# |
43ece6172f8805572749e25b54baacedec730899 | Bump version | oozcitak/imagelistview | ImageListView/Properties/AssemblyInfo.cs | ImageListView/Properties/AssemblyInfo.cs | // ImageListView - A listview control for image files
// Copyright (C) 2009 Ozgur Ozcitak
//
// 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.
//
// Ozgur Ozcitak ([email protected])
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ImageListView")]
[assembly: AssemblyDescription("A ListView like control for displaying image files with asynchronously loaded thumbnails.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Özgür Özçıtak")]
[assembly: AssemblyProduct("ImageListView")]
[assembly: AssemblyCopyright("Copyright © 2013 Özgür Özçıtak")]
[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("3eb67a8d-4c80-4c11-944d-c99ef0ec7eb9")]
// 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("13.5.0.0")]
[assembly: AssemblyFileVersion("13.5.0.0")]
| // ImageListView - A listview control for image files
// Copyright (C) 2009 Ozgur Ozcitak
//
// 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.
//
// Ozgur Ozcitak ([email protected])
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ImageListView")]
[assembly: AssemblyDescription("A ListView like control for displaying image files with asynchronously loaded thumbnails.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Özgür Özçıtak")]
[assembly: AssemblyProduct("ImageListView")]
[assembly: AssemblyCopyright("Copyright © 2013 Özgür Özçıtak")]
[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("3eb67a8d-4c80-4c11-944d-c99ef0ec7eb9")]
// 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("13.4.0.0")]
[assembly: AssemblyFileVersion("13.4.0.0")]
| apache-2.0 | C# |
0ff5aee88dee0b6634f84abe3b8f8b3a05f5bbef | Add description to envelope. | NaosFramework/Naos.MessageBus,NaosProject/Naos.MessageBus | Naos.MessageBus.DataContract/Envelope.cs | Naos.MessageBus.DataContract/Envelope.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Envelope.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.MessageBus.DataContract
{
using System;
/// <summary>
/// Container object to use when re-hydrating a message.
/// </summary>
public sealed class Envelope
{
/// <summary>
/// Gets or sets the description of the message in the envelope.
/// </summary>
public string Description { get; set; }
/// <summary>
/// Gets or sets the namespace of the type of the message.
/// </summary>
public string MessageTypeNamespace { get; set; }
/// <summary>
/// Gets or sets the name of the type of the message.
/// </summary>
public string MessageTypeName { get; set; }
/// <summary>
/// Gets or sets the qualified name of the assembly of the type of the message.
/// </summary>
public string MessageTypeAssemblyQualifiedName { get; set; }
/// <summary>
/// Gets or sets the message in JSON format.
/// </summary>
public string MessageAsJson { get; set; }
/// <summary>
/// Gets or sets the channel the message should be broadcasted on.
/// </summary>
public Channel Channel { get; set; }
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="Envelope.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.MessageBus.DataContract
{
using System;
/// <summary>
/// Container object to use when re-hydrating a message.
/// </summary>
public sealed class Envelope
{
/// <summary>
/// Gets or sets the namespace of the type of the message.
/// </summary>
public string MessageTypeNamespace { get; set; }
/// <summary>
/// Gets or sets the name of the type of the message.
/// </summary>
public string MessageTypeName { get; set; }
/// <summary>
/// Gets or sets the qualified name of the assembly of the type of the message.
/// </summary>
public string MessageTypeAssemblyQualifiedName { get; set; }
/// <summary>
/// Gets or sets the message in JSON format.
/// </summary>
public string MessageAsJson { get; set; }
/// <summary>
/// Gets or sets the channel the message should be broadcasted on.
/// </summary>
public Channel Channel { get; set; }
}
}
| mit | C# |
0d316e1d37ea78a5adee0c13f9a444f1a60cc0e2 | work on CivtracApiError returning | buzzware/cascade | StandardExceptionsDotNet/StandardExceptions/StandardException.cs | StandardExceptionsDotNet/StandardExceptions/StandardException.cs | using System;
namespace StandardExceptions {
public class StandardException : Exception {
public const string DefaultMessage = "An error occurred that could not be identified";
public const int DefaultStatus = 500;
public int Status { get; private set; }
public object Result { get; set; } = null;
public object Error { get; set; } = null;
public StandardException (string aMessage=DefaultMessage, Exception aInnerException = null, int aStatus = DefaultStatus) : base (aMessage,aInnerException) {
Status = aStatus;
}
}
}
| using System;
namespace StandardExceptions {
public class StandardException : Exception {
public const string DefaultMessage = "An error occurred that could not be identified";
public const int DefaultStatus = 500;
public int Status { get; private set; }
public object Data { get; set; } = null;
public StandardException (string aMessage=DefaultMessage, Exception aInnerException = null, int aStatus = DefaultStatus) : base (aMessage,aInnerException) {
Status = aStatus;
}
}
}
| mit | C# |
20daf0649fa9d132684a5e9c001e3ffcce07b0db | Add stubbed clean target. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | bootstrapping/DefaultBuild.cs | bootstrapping/DefaultBuild.cs | using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
// This is the application entry point for the build.
// It also defines the default target to execute.
public static void Main () => Execute<DefaultBuild>(x => x.Compile);
Target Clean => _ => _
// Disabled for safety.
.OnlyWhen(() => false)
.Executes(() => DeleteDirectories(GlobDirectories(SolutionDirectory, "**/bin", "**/obj")))
.Executes(() => PrepareCleanDirectory(OutputDirectory));
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
// Remove tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
NuGetRestore(SolutionFile);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// When having xproj-based projects, using VS2015 is necessary.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.EnvironmentInfo;
class DefaultBuild : GitHubBuild
{
// This is the application entry point for the build.
// It also defines the default target to execute.
public static void Main () => Execute<DefaultBuild>(x => x.Compile);
Target Restore => _ => _
.Executes(() =>
{
// Remove restore tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
NuGetRestore(SolutionFile);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// If you have xproj-based projects, you need to downgrade to VS2015.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| mit | C# |
2d56d02bea6cc23c4d87247d828507e6410f21f0 | Fix wrong sorting and order numbers | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/ModelExtensions/DivisionExtensions.cs | R7.University/ModelExtensions/DivisionExtensions.cs | //
// DivisionExtensions.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
namespace R7.University.ModelExtensions
{
public static class DivisionExtensions
{
public static IEnumerable<TDivision> CalculateLevelAndPath<TDivision> (this IEnumerable<TDivision> divisions)
where TDivision: IDivision
{
var rootDivisions = divisions.Where (d => d.ParentDivisionID == null);
foreach (var root in rootDivisions) {
CalculateLevelAndPath (root, -1, string.Empty);
}
return divisions;
}
private static void CalculateLevelAndPath<TDivision> (TDivision division, int level, string path)
where TDivision: IDivision
{
division.Level = level + 1;
division.Path = path + "/" + division.DivisionID.ToString ().PadLeft (10, '0');
if (division.SubDivisions != null) {
foreach (var subDivision in division.SubDivisions) {
CalculateLevelAndPath (subDivision, division.Level, division.Path);
}
}
}
}
}
| //
// DivisionExtensions.cs
//
// Author:
// Roman M. Yagodin <[email protected]>
//
// Copyright (c) 2016 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections.Generic;
using System.Linq;
using R7.University.Models;
namespace R7.University.ModelExtensions
{
public static class DivisionExtensions
{
public static IEnumerable<TDivision> CalculateLevelAndPath<TDivision> (this IEnumerable<TDivision> divisions)
where TDivision: IDivision
{
var rootDivisions = divisions.Where (d => d.ParentDivisionID == null);
foreach (var root in rootDivisions) {
CalculateLevelAndPath (root, 0, string.Empty);
}
return divisions;
}
private static void CalculateLevelAndPath<TDivision> (TDivision division, int level, string path)
where TDivision: IDivision
{
division.Level = level;
division.Path = path;
if (division.SubDivisions != null) {
foreach (var subDivision in division.SubDivisions) {
CalculateLevelAndPath (subDivision, level + 1,
path + "/" + subDivision.ParentDivisionID.ToString ().PadLeft (10, '0')
);
}
}
}
}
}
| agpl-3.0 | C# |
7b99fc92a1f26e5f910c70b3deed2929136e512f | test failing build compile error | jezzay/Test-Travis-CI,jezzay/Test-Travis-CI | TestWebApp/TestWebApp/Controllers/HomeController.cs | TestWebApp/TestWebApp/Controllers/HomeController.cs | using System.Web.Mvc;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test"
return View();
}
}
}
| using System.Web.Mvc;
namespace TestWebApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page test";
return View();
}
}
} | mit | C# |
9991ff58499d23317e9109972acdb93deba3052e | Update WalletWasabi/Services/Terminate/TerminateService.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Services/Terminate/TerminateService.cs | WalletWasabi/Services/Terminate/TerminateService.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// Terminates the application.
/// </summary>
/// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Terminate application was started.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Logging;
namespace WalletWasabi.Services.Terminate
{
public class TerminateService
{
private Func<Task> _terminateApplicationAsync;
private const long TerminateStatusIdle = 0;
private const long TerminateStatusInProgress = 1;
private const long TerminateFinished = 2;
private long _terminateStatus;
public TerminateService(Func<Task> terminateApplicationAsync)
{
_terminateApplicationAsync = terminateApplicationAsync;
AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;
Console.CancelKeyPress += Console_CancelKeyPress;
}
private void CurrentDomain_ProcessExit(object? sender, EventArgs e)
{
Logger.LogDebug("ProcessExit was called.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
Terminate();
}
private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e)
{
Logger.LogWarning("Process was signaled for termination.");
// This must be a blocking call because after this the OS will terminate Wasabi process if exists.
// In some cases CurrentDomain_ProcessExit is called after this by the OS.
Terminate();
}
/// <summary>
/// This will terminate the application. This is a blocking method and no return after this call as it will exit the application.
/// </summary>
public void Terminate(int exitCode = 0)
{
var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle);
Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}");
if (prevValue != TerminateStatusIdle)
{
// Secondary callers will be blocked until the end of the termination.
while (_terminateStatus != TerminateFinished)
{
}
return;
}
// First caller starts the terminate procedure.
Logger.LogDebug("Terminate application was started.");
// Async termination has to be started on another thread otherwise there is a possibility of deadlock.
// We still need to block the caller so ManualResetEvent applied.
using ManualResetEvent resetEvent = new ManualResetEvent(false);
Task.Run(async () =>
{
try
{
await _terminateApplicationAsync().ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.LogWarning(ex.ToTypeMessageString());
}
resetEvent.Set();
});
resetEvent.WaitOne();
AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit;
Console.CancelKeyPress -= Console_CancelKeyPress;
// Indicate that the termination procedure finished. So other callers can return.
Interlocked.Exchange(ref _terminateStatus, TerminateFinished);
Environment.Exit(exitCode);
}
public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle;
}
}
| mit | C# |
bbc435a34673e5babc596284cf365448aa6fc093 | Make helper class public | deckar01/libsodium-net,deckar01/libsodium-net,adamcaudill/libsodium-net,fraga/libsodium-net,fraga/libsodium-net,bitbeans/libsodium-net,tabrath/libsodium-core,adamcaudill/libsodium-net,BurningEnlightenment/libsodium-net,BurningEnlightenment/libsodium-net,bitbeans/libsodium-net | libsodium-net/Helper.cs | libsodium-net/Helper.cs | using System;
using System.Linq;
namespace Sodium
{
/// <summary>
/// Various utility methods.
/// </summary>
public static class Helper
{
/// <summary>
/// Takes a byte array and returns a hex-encoded string
/// </summary>
/// <param name="data">Data to be encoded</param>
/// <returns>Hex-encoded string, lowercase.</returns>
public static string BinaryToHex(byte[] data)
{
//TODO: Find a faster version of this...
return string.Concat(data.Select(b => b.ToString("x2")));
}
/// <summary>
/// Converts a hex-encoded string to a byte array
/// </summary>
/// <param name="hex">Hex-encoded data</param>
/// <returns></returns>
/// <remarks>
/// Shamelessly pulled from http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array
/// </remarks>
public static byte[] HexToBinary(string hex)
{
if (hex.Length % 2 == 1)
{
throw new ArgumentException("The binary key cannot have an odd number of digits");
}
var arr = new byte[hex.Length >> 1];
for (var i = 0; i < (hex.Length >> 1); ++i)
{
arr[i] = (byte)((_GetHexVal(hex[i << 1]) << 4) + (_GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
private static int _GetHexVal(char hex)
{
int val = hex;
return val - (val < 58 ? 48 : 87);
}
}
}
| using System;
using System.Linq;
namespace Sodium
{
internal static class Helper
{
/// <summary>
/// Takes a byte array and returns a hex-encoded string
/// </summary>
/// <param name="data">Data to be encoded</param>
/// <returns>Hex-encoded string, lowercase.</returns>
public static string BinaryToHex(byte[] data)
{
//TODO: Find a faster version of this...
return string.Concat(data.Select(b => b.ToString("x2")));
}
/// <summary>
/// Converts a hex-encoded string to a byte array
/// </summary>
/// <param name="hex">Hex-encoded data</param>
/// <returns></returns>
/// <remarks>
/// Shamelessly pulled from http://stackoverflow.com/questions/321370/convert-hex-string-to-byte-array
/// </remarks>
public static byte[] HexToBinary(string hex)
{
if (hex.Length % 2 == 1)
{
throw new ArgumentException("The binary key cannot have an odd number of digits");
}
var arr = new byte[hex.Length >> 1];
for (int i = 0; i < hex.Length >> 1; ++i)
{
arr[i] = (byte)((_GetHexVal(hex[i << 1]) << 4) + (_GetHexVal(hex[(i << 1) + 1])));
}
return arr;
}
private static int _GetHexVal(char hex)
{
int val = hex;
return val - (val < 58 ? 48 : 87);
}
}
}
| mit | C# |
61f25dbae71b3a14e8b4a101f1fd485cfcefbe5a | Update AzureBlobTests.cs | A51UK/File-Repository | File-Repository-Tests/AzureBlobTests.cs | File-Repository-Tests/AzureBlobTests.cs | /*
* Copyright 2017 Craig Lee Mark Adams
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace ile_Repository_Tests
{
[TestClass]
class AzureBlobTests
{
}
}
| using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace ile_Repository_Tests
{
[TestClass]
class AzureBlobTests
{
}
}
| apache-2.0 | C# |
9d1210bfa4dfd42ffe8f15b7284a55d0f25f61af | Change prop type to CorLibTypeSig | Arthur2e5/dnlib,ilkerhalil/dnlib,picrap/dnlib,kiootic/dnlib,jorik041/dnlib,modulexcite/dnlib,0xd4d/dnlib,yck1509/dnlib,ZixiangBoy/dnlib | dot10/dotNET/Hi/ICorLibTypes.cs | dot10/dotNET/Hi/ICorLibTypes.cs | namespace dot10.dotNET.Hi {
/// <summary>
/// Access to .NET core library's simple types
/// </summary>
public interface ICorLibTypes {
/// <summary>
/// Gets a <c>System.Void</c>
/// </summary>
CorLibTypeSig Void { get; }
/// <summary>
/// Gets a <c>System.Boolean</c>
/// </summary>
CorLibTypeSig Boolean { get; }
/// <summary>
/// Gets a <c>System.Char</c>
/// </summary>
CorLibTypeSig Char { get; }
/// <summary>
/// Gets a <c>System.SByte</c>
/// </summary>
CorLibTypeSig SByte { get; }
/// <summary>
/// Gets a <c>System.Byte</c>
/// </summary>
CorLibTypeSig Byte { get; }
/// <summary>
/// Gets a <c>System.Int16</c>
/// </summary>
CorLibTypeSig Int16 { get; }
/// <summary>
/// Gets a <c>System.UInt16</c>
/// </summary>
CorLibTypeSig UInt16 { get; }
/// <summary>
/// Gets a <c>System.Int32</c>
/// </summary>
CorLibTypeSig Int32 { get; }
/// <summary>
/// Gets a <c>System.UInt32</c>
/// </summary>
CorLibTypeSig UInt32 { get; }
/// <summary>
/// Gets a <c>System.Int64</c>
/// </summary>
CorLibTypeSig Int64 { get; }
/// <summary>
/// Gets a <c>System.UInt64</c>
/// </summary>
CorLibTypeSig UInt64 { get; }
/// <summary>
/// Gets a <c>System.Single</c>
/// </summary>
CorLibTypeSig Single { get; }
/// <summary>
/// Gets a <c>System.Double</c>
/// </summary>
CorLibTypeSig Double { get; }
/// <summary>
/// Gets a <c>System.String</c>
/// </summary>
CorLibTypeSig String { get; }
/// <summary>
/// Gets a <c>System.TypedReference</c>
/// </summary>
CorLibTypeSig TypedReference { get; }
/// <summary>
/// Gets a <c>System.IntPtr</c>
/// </summary>
CorLibTypeSig IntPtr { get; }
/// <summary>
/// Gets a <c>System.UIntPtr</c>
/// </summary>
CorLibTypeSig UIntPtr { get; }
/// <summary>
/// Gets a <c>System.Object</c>
/// </summary>
CorLibTypeSig Object { get; }
/// <summary>
/// Gets the assembly reference to the core library
/// </summary>
AssemblyRef AssemblyRef { get; }
}
}
| namespace dot10.dotNET.Hi {
/// <summary>
/// Access to .NET core library's simple types
/// </summary>
public interface ICorLibTypes {
/// <summary>
/// Gets a <c>System.Void</c>
/// </summary>
ITypeSig Void { get; }
/// <summary>
/// Gets a <c>System.Boolean</c>
/// </summary>
ITypeSig Boolean { get; }
/// <summary>
/// Gets a <c>System.Char</c>
/// </summary>
ITypeSig Char { get; }
/// <summary>
/// Gets a <c>System.SByte</c>
/// </summary>
ITypeSig SByte { get; }
/// <summary>
/// Gets a <c>System.Byte</c>
/// </summary>
ITypeSig Byte { get; }
/// <summary>
/// Gets a <c>System.Int16</c>
/// </summary>
ITypeSig Int16 { get; }
/// <summary>
/// Gets a <c>System.UInt16</c>
/// </summary>
ITypeSig UInt16 { get; }
/// <summary>
/// Gets a <c>System.Int32</c>
/// </summary>
ITypeSig Int32 { get; }
/// <summary>
/// Gets a <c>System.UInt32</c>
/// </summary>
ITypeSig UInt32 { get; }
/// <summary>
/// Gets a <c>System.Int64</c>
/// </summary>
ITypeSig Int64 { get; }
/// <summary>
/// Gets a <c>System.UInt64</c>
/// </summary>
ITypeSig UInt64 { get; }
/// <summary>
/// Gets a <c>System.Single</c>
/// </summary>
ITypeSig Single { get; }
/// <summary>
/// Gets a <c>System.Double</c>
/// </summary>
ITypeSig Double { get; }
/// <summary>
/// Gets a <c>System.String</c>
/// </summary>
ITypeSig String { get; }
/// <summary>
/// Gets a <c>System.TypedReference</c>
/// </summary>
ITypeSig TypedReference { get; }
/// <summary>
/// Gets a <c>System.IntPtr</c>
/// </summary>
ITypeSig IntPtr { get; }
/// <summary>
/// Gets a <c>System.UIntPtr</c>
/// </summary>
ITypeSig UIntPtr { get; }
/// <summary>
/// Gets a <c>System.Object</c>
/// </summary>
ITypeSig Object { get; }
/// <summary>
/// Gets the assembly reference to the core library
/// </summary>
AssemblyRef AssemblyRef { get; }
}
}
| mit | C# |
c10dc6ee84b9587fcb97d4d0add601157793679b | test commit | dekloni/MarketPlace,dekloni/MarketPlace,dekloni/MarketPlace | MarketPlaceUI/App_Start/BundleConfig.cs | MarketPlaceUI/App_Start/BundleConfig.cs | using System.Web;
using System.Web.Optimization;
namespace MarketPlaceUI
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-theme.css",
"~/Content/site.css"));
}
}
}
| using System.Web;
using System.Web.Optimization;
namespace MarketPlaceUI
{
public class BundleConfig
{
// For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at http://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/bootstrap-theme.css",
"~/Content/site.css"));
}
}
}
| unlicense | C# |
23c5256f3f6723e1a7dd8b70f12e51119985ba81 | Fix issue with AllRowsConstraint and markdown failure messages | Seddryck/NBi,Seddryck/NBi | NBi.NUnit/Query/AllRowsConstraint.cs | NBi.NUnit/Query/AllRowsConstraint.cs | using System;
using System.Data;
using System.Linq;
using NBi.Core;
using NBi.Core.ResultSet;
using NBi.Core.Calculation;
using NBi.Framework.FailureMessage;
using NUnitCtr = NUnit.Framework.Constraints;
using NBi.Framework;
namespace NBi.NUnit.Query
{
public class AllRowsConstraint : RowCountFilterConstraint
{
public AllRowsConstraint(IResultSetFilter filter)
:base(null, filter)
{
filterFunction = filter.AntiApply;
}
protected override bool doMatch(int actual)
{
return filterResultSet.Rows.Count == 0;
}
public override void WriteDescriptionTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
else
writer.WritePredicate($"all rows validate the predicate '{filter.Describe()}'.");
}
public override void WriteFilterMessageTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
writer.WriteLine("Rows not validating the predicate:");
}
public override void WriteActualValueTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
var value = filterResultSet.Rows.Count;
writer.WriteLine($"{value} row{(value > 1 ? "s" : string.Empty)} do{(value == 1 ? "es" : string.Empty)}n't validate the predicate '{filter.Describe()}'.");
}
}
} | using System;
using System.Data;
using System.Linq;
using NBi.Core;
using NBi.Core.ResultSet;
using NBi.Core.Calculation;
using NBi.Framework.FailureMessage;
using NUnitCtr = NUnit.Framework.Constraints;
using NBi.Framework;
namespace NBi.NUnit.Query
{
public class AllRowsConstraint : RowCountFilterConstraint
{
public AllRowsConstraint(IResultSetFilter filter)
:base(null, filter)
{
filterFunction = filter.AntiApply;
}
protected override bool doMatch(int actual)
{
return filterResultSet.Rows.Count == 0;
}
public override void WriteMessageTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
writer.Write(Failure.RenderMessage());
}
public override void WriteDescriptionTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
else
writer.WritePredicate($"all rows validate the predicate '{filter.Describe()}'.");
}
public override void WriteFilterMessageTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
writer.WriteLine("Rows not validating the predicate:");
}
public override void WriteActualValueTo(NUnitCtr.MessageWriter writer)
{
if (Configuration.FailureReportProfile.Format == FailureReportFormat.Json)
return;
var value = filterResultSet.Rows.Count;
writer.WriteLine($"{value} row{(value > 1 ? "s" : string.Empty)} do{(value == 1 ? "es" : string.Empty)}n't validate the predicate '{filter.Describe()}'.");
}
}
} | apache-2.0 | C# |
0b638d87c7339e914d6c0b6fdfd74575c482c0ad | Use Pins, not ints. We ain't Arduino! | treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk | NET/Demos/Console/SoftPwm/Program.cs | NET/Demos/Console/SoftPwm/Program.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
await board.ConnectAsync();
var pin = board[1];
pin.SoftPwm.Enabled = true;
pin.SoftPwm.DutyCycle = 0.8;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
int pinNumber = 10;
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
Console.WriteLine(String.Format("Connecting to {0} and starting SoftPwm on Pin{1}", board, pinNumber));
await board.ConnectAsync();
board[pinNumber].SoftPwm.Enabled = true;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
| mit | C# |
ca7e68788d4cba97d973c808f3cab484e5b0e7ef | update quickstart region tag | jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,jsimonweb/csharp-docs-samples,jsimonweb/csharp-docs-samples | video/api/QuickStart/Program.cs | video/api/QuickStart/Program.cs | // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START video_quickstart]
using Google.Cloud.VideoIntelligence.V1;
using System;
namespace GoogleCloudSamples.VideoIntelligence
{
public class QuickStart
{
public static void Main(string[] args)
{
var client = VideoIntelligenceServiceClient.Create();
var request = new AnnotateVideoRequest()
{
InputUri = @"gs://demomaker/cat.mp4",
Features = { Feature.LabelDetection }
};
var op = client.AnnotateVideo(request).PollUntilCompleted();
foreach (var result in op.Result.AnnotationResults)
{
foreach (var annotation in result.SegmentLabelAnnotations)
{
Console.WriteLine($"Video label: {annotation.Entity.Description}");
foreach (var entity in annotation.CategoryEntities)
{
Console.WriteLine($"Video label category: {entity.Description}");
}
foreach (var segment in annotation.Segments)
{
Console.Write("Segment location: ");
Console.Write(segment.Segment.StartTimeOffset);
Console.Write(":");
Console.WriteLine(segment.Segment.EndTimeOffset);
System.Console.WriteLine($"Confidence: {segment.Confidence}");
}
}
}
}
}
}
// [END video_quickstart]
| // Copyright(c) 2017 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START videointelligence_quickstart]
using Google.Cloud.VideoIntelligence.V1;
using System;
namespace GoogleCloudSamples.VideoIntelligence
{
public class QuickStart
{
public static void Main(string[] args)
{
var client = VideoIntelligenceServiceClient.Create();
var request = new AnnotateVideoRequest()
{
InputUri = @"gs://demomaker/cat.mp4",
Features = { Feature.LabelDetection }
};
var op = client.AnnotateVideo(request).PollUntilCompleted();
foreach (var result in op.Result.AnnotationResults)
{
foreach (var annotation in result.SegmentLabelAnnotations)
{
Console.WriteLine($"Video label: {annotation.Entity.Description}");
foreach (var entity in annotation.CategoryEntities)
{
Console.WriteLine($"Video label category: {entity.Description}");
}
foreach (var segment in annotation.Segments)
{
Console.Write("Segment location: ");
Console.Write(segment.Segment.StartTimeOffset);
Console.Write(":");
Console.WriteLine(segment.Segment.EndTimeOffset);
System.Console.WriteLine($"Confidence: {segment.Confidence}");
}
}
}
}
}
}
// [END videointelligence_quickstart]
| apache-2.0 | C# |
0afdf5b343941ea59f936f5692b097c23200998a | Use ORM instead of open-coded SQL | Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy,Dynalon/Rainy | Rainy/WebService/Admin/StatusService.cs | Rainy/WebService/Admin/StatusService.cs | using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
using Tomboy.Db;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = (int)conn.Count<DBUser> ();
s.TotalNumberOfNotes = (int)conn.Count<DBNote> ();
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
} | using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser");
s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote");
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
} | agpl-3.0 | C# |
e44667e5e073016b471c13d7cce1427d0db89be5 | Use MinValue instead | smoogipoo/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,ppy/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu | osu.Game/Overlays/OnlineOverlay.cs | osu.Game/Overlays/OnlineOverlay.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public abstract class OnlineOverlay<T> : FullscreenOverlay<T>
where T : OverlayHeader
{
protected override Container<Drawable> Content => content;
protected readonly OverlayScrollContainer ScrollFlow;
protected readonly LoadingLayer Loading;
private readonly Container content;
protected OnlineOverlay(OverlayColourScheme colourScheme)
: base(colourScheme)
{
base.Content.AddRange(new Drawable[]
{
ScrollFlow = new OverlayScrollContainer
{
RelativeSizeAxes = Axes.Both,
ScrollbarVisible = false,
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
Header.With(h => h.Depth = float.MinValue),
content = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
}
}
}
},
Loading = new LoadingLayer(true)
});
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Overlays
{
public abstract class OnlineOverlay<T> : FullscreenOverlay<T>
where T : OverlayHeader
{
protected override Container<Drawable> Content => content;
protected readonly OverlayScrollContainer ScrollFlow;
protected readonly LoadingLayer Loading;
private readonly Container content;
protected OnlineOverlay(OverlayColourScheme colourScheme)
: base(colourScheme)
{
base.Content.AddRange(new Drawable[]
{
ScrollFlow = new OverlayScrollContainer
{
RelativeSizeAxes = Axes.Both,
ScrollbarVisible = false,
Child = new FillFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Direction = FillDirection.Vertical,
Children = new Drawable[]
{
Header.With(h => h.Depth = -float.MaxValue),
content = new Container
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y
}
}
}
},
Loading = new LoadingLayer(true)
});
}
}
}
| mit | C# |
38807299b3fd6d442bb86407c98c61c9e3df016c | Update code | sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014 | RxSample/MouseRx2Wpf/MainWindow.xaml.cs | RxSample/MouseRx2Wpf/MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty DeltaProperty =
DependencyProperty.Register(nameof(Delta), typeof(Vector?), typeof(MainWindow), new PropertyMetadata(null, (d, e) => DeltaChanged((MainWindow)d)));
public Vector? Delta
{
get { return (Vector?)GetValue(DeltaProperty); }
set { SetValue(DeltaProperty, value); }
}
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(nameof(Orientation), typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public string Orientation
{
get { return (string)GetValue(OrientationProperty); }
private set { SetValue(OrientationProperty, value); }
}
public MainWindow()
{
InitializeComponent();
var events = new EventsExtension(this);
events.MouseDrag.Subscribe(d => d.Subscribe(v => Delta = v, () => Delta = null));
}
static void DeltaChanged(MainWindow window)
{
window.Orientation = window.Delta == null ? null : ToOrientation(window.Delta.Value);
}
const double π = Math.PI;
static readonly string[] orientationSymbols = new[] { "→", "↘", "↓", "↙", "←", "↖", "↑", "↗" };
static readonly double zoneAngleRange = 2 * π / orientationSymbols.Length;
static string ToOrientation(Vector v)
{
var angle = 2 * π + Math.Atan2(v.Y, v.X);
var zone = (int)Math.Round(angle / zoneAngleRange) % orientationSymbols.Length;
return orientationSymbols[zone];
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MouseRx2Wpf
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public static readonly DependencyProperty DeltaProperty =
DependencyProperty.Register(nameof(Delta), typeof(Vector?), typeof(MainWindow), new PropertyMetadata(null, (d, e) => DeltaChanged((MainWindow)d)));
public Vector? Delta
{
get { return (Vector?)GetValue(DeltaProperty); }
set { SetValue(DeltaProperty, value); }
}
public static readonly DependencyProperty OrientationProperty =
DependencyProperty.Register(nameof(Orientation), typeof(string), typeof(MainWindow), new PropertyMetadata(null));
public string Orientation
{
get { return (string)GetValue(OrientationProperty); }
private set { SetValue(OrientationProperty, value); }
}
public MainWindow()
{
InitializeComponent();
var events = new EventsExtension(this);
events.MouseDrag.Subscribe(d => d.Subscribe(v => Delta = v, () => Delta = null));
}
const double π = Math.PI;
static readonly string[] orientationSymbols = new[] { "→", "↘", "↓", "↙", "←", "↖", "↑", "↗" };
static readonly double zoneAngleRange = 2 * π / orientationSymbols.Length;
static string ToOrientation(Vector v)
{
var angle = 2 * π + Math.Atan2(v.Y, v.X);
var zone = (int)Math.Round(angle / zoneAngleRange) % orientationSymbols.Length;
return orientationSymbols[zone];
}
static void DeltaChanged(MainWindow window)
{
window.Orientation = window.Delta == null ? null : ToOrientation(window.Delta.Value);
}
}
}
| mit | C# |
b5fa3b5ff057a5f36e899b3668cd3b640d081efe | Update demo | sunkaixuan/SqlSugar | Src/Asp.Net/SqlServerTest/Program.cs | Src/Asp.Net/SqlServerTest/Program.cs | using System;
namespace OrmTest
{
class Program
{
/// <summary>
/// Set up config.cs file and start directly F5
/// 设置Config.cs文件直接F5启动例子
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Demo
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo6_Queue.Init();
Demo7_Ado.Init();
Demo8_Saveable.Init();
Demo9_EntityMain.Init();
DemoA_DbMain.Init();
DemoB_Aop.Init();
DemoC_GobalFilter.Init();
DemoD_DbFirst.Init();;
DemoE_CodeFirst.Init();
DemoF_Utilities.Init();
DemoG_SimpleClient.Init();
DemoH_Tenant.Init();
DemoJ_Report.Init()
//Unit test
//NewUnitTest.Init();
//Rest Data
NewUnitTest.RestData();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
| using System;
namespace OrmTest
{
class Program
{
/// <summary>
/// Set up config.cs file and start directly F5
/// 设置Config.cs文件直接F5启动例子
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//Demo
Demo0_SqlSugarClient.Init();
Demo1_Queryable.Init();
Demo2_Updateable.Init();
Demo3_Insertable.Init();
Demo4_Deleteable.Init();
Demo5_SqlQueryable.Init();
Demo6_Queue.Init();
Demo7_Ado.Init();
Demo8_Saveable.Init();
Demo9_EntityMain.Init();
DemoA_DbMain.Init();
DemoB_Aop.Init();
DemoC_GobalFilter.Init();
DemoD_DbFirst.Init();;
DemoE_CodeFirst.Init();
DemoF_Utilities.Init();
DemoG_SimpleClient.Init();
DemoH_Tenant.Init();
//Unit test
//NewUnitTest.Init();
//Rest Data
NewUnitTest.RestData();
Console.WriteLine("all successfully.");
Console.ReadKey();
}
}
}
| apache-2.0 | C# |
de9a81b03b1558c10e6fb7042438b02ff48e45dd | add time | NDark/ndinfrastructure,NDark/ndinfrastructure | Unity/StateMachine/StateIndexBase.cs | Unity/StateMachine/StateIndexBase.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateIndexBase<T>
{
public StateIndexBase()
{
}
public StateIndexBase( T _InitState )
{
m_NextValue = m_CurrentValue = m_PreviousValue = _InitState ;
}
public virtual void CallInit( Dictionary<T,TransitionSet> _Transitions )
{
m_Transitions = _Transitions ;
}
public virtual void TryAddTransitionSet( T _State , TransitionSet _Set )
{
if( !m_Transitions.ContainsKey( _State) )
{
m_Transitions.Add( _State , _Set ) ;
}
else
{
m_Transitions[_State] = _Set ;
}
}
public virtual void ChangeState( T _Next , float _TimeNow )
{
if( m_CurrentValue.Equals( _Next ) )
{
return ;
}
if( m_NextValue.Equals( _Next ) )
{
return ;
}
m_NextValue = _Next ;
m_IsInTransition = true ;
m_ChangeTime = _TimeNow ;
}
// Update is called once per frame
public virtual void CallUpdate ( float _DeltaTime )
{
TransitionSet currentStateFuncs = null ;
m_Transitions.TryGetValue( m_CurrentValue , out currentStateFuncs ) ;
if( false == m_IsInTransition )
{
if( null != currentStateFuncs )
{
currentStateFuncs.OnUpdate( _DeltaTime ) ;
}
}
else
{
m_Transitions.TryGetValue( m_CurrentValue , out currentStateFuncs ) ;
if( null != currentStateFuncs )
{
currentStateFuncs.OnExit() ;
}
m_PreviousValue = m_CurrentValue ;
m_CurrentValue = m_NextValue ;
m_Transitions.TryGetValue( m_CurrentValue , out currentStateFuncs ) ;
if( null != currentStateFuncs )
{
currentStateFuncs.OnEnter() ;
currentStateFuncs.OnUpdate( _DeltaTime ) ;
}
m_IsInTransition = false ;
}
}
public T CurrentValue
{
get { return m_CurrentValue ; }
}
public T PreviousValue
{
get { return m_PreviousValue ; }
}
public T NextValue
{
get { return m_NextValue ; }
}
public float ChangeTime
{
get { return m_ChangeTime ;}
}
public float GetElapsedTime( float _TimeNow )
{
return _TimeNow - m_ChangeTime ;
}
bool m_IsInTransition = false ;
T m_CurrentValue ;
T m_PreviousValue ;
T m_NextValue ;
Dictionary<T,TransitionSet> m_Transitions = new Dictionary<T, TransitionSet>() ;
float m_ChangeTime = 0.0f ;
}
public class TransitionSet
{
public System.Action OnEnter = new System.Action( ()=>{} ) ;
public System.Action<float> OnUpdate = new System.Action<float>( (deltaTime)=>{} ) ;
public System.Action OnExit = new System.Action( ()=>{} ) ;
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StateIndexBase<T>
{
public StateIndexBase()
{
}
public StateIndexBase( T _InitState )
{
m_NextValue = m_CurrentValue = m_PreviousValue = _InitState ;
}
public virtual void CallInit( Dictionary<T,TransitionSet> _Transitions )
{
m_Transitions = _Transitions ;
}
public virtual void TryAddTransitionSet( T _State , TransitionSet _Set )
{
if( !m_Transitions.ContainsKey( _State) )
{
m_Transitions.Add( _State , _Set ) ;
}
else
{
m_Transitions[_State] = _Set ;
}
}
public virtual void ChangeState( T _Next )
{
if( m_CurrentValue.Equals( _Next ) )
{
return ;
}
if( m_NextValue.Equals( _Next ) )
{
return ;
}
m_NextValue = _Next ;
m_IsInTransition = true ;
}
// Update is called once per frame
public virtual void CallUpdate ( float _DeltaTime )
{
TransitionSet currentStateFuncs = null ;
m_Transitions.TryGetValue( m_CurrentValue , out currentStateFuncs ) ;
if( false == m_IsInTransition )
{
if( null != currentStateFuncs )
{
currentStateFuncs.OnUpdate( _DeltaTime ) ;
}
}
else
{
m_PreviousValue = m_CurrentValue ;
m_CurrentValue = m_NextValue ;
m_Transitions.TryGetValue( m_CurrentValue , out currentStateFuncs ) ;
if( null != currentStateFuncs )
{
currentStateFuncs.OnEnter() ;
currentStateFuncs.OnUpdate( _DeltaTime ) ;
}
m_IsInTransition = false ;
}
}
public T CurrentValue
{
get { return m_CurrentValue ; }
}
public T PreviousValue
{
get { return m_PreviousValue ; }
}
public T NextValue
{
get { return m_NextValue ; }
}
bool m_IsInTransition = false ;
T m_CurrentValue ;
T m_PreviousValue ;
T m_NextValue ;
Dictionary<T,TransitionSet> m_Transitions = new Dictionary<T, TransitionSet>() ;
}
public class TransitionSet
{
public System.Action OnEnter = new System.Action( ()=>{} ) ;
public System.Action<float> OnUpdate = new System.Action<float>( (deltaTime)=>{} ) ;
public System.Action OnExit = new System.Action( ()=>{} ) ;
} | mit | C# |
fd9b8f7c81681e63e1b849e25930a6be2e8a1271 | Fix wrong parsing of tower state. | babelshift/SteamWebAPI2 | SteamWebAPI2/Models/DOTA2/TowerState.cs | SteamWebAPI2/Models/DOTA2/TowerState.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SteamWebAPI2.Models.DOTA2
{
public class TowerState
{
public TowerState(int towerState)
{
IsAncientBottomAlive = ((towerState >> 10) & 1) == 1 ? true : false;
IsAncientTopAlive = ((towerState >> 9) & 1) == 1 ? true : false;
IsBottomTier3Alive = ((towerState >> 8) & 1) == 1 ? true : false;
IsBottomTier2Alive = ((towerState >> 7) & 1) == 1 ? true : false;
IsBottomTier1Alive = ((towerState >> 6) & 1) == 1 ? true : false;
IsMiddleTier3Alive = ((towerState >> 5) & 1) == 1 ? true : false;
IsMiddleTier2Alive = ((towerState >> 4) & 1) == 1 ? true : false;
IsMiddleTier1Alive = ((towerState >> 3) & 1) == 1 ? true : false;
IsTopTier3Alive = ((towerState >> 2) & 1) == 1 ? true : false;
IsTopTier2Alive = ((towerState >> 1) & 1) == 1 ? true : false;
IsTopTier1Alive = ((towerState >> 0) & 1) == 1 ? true : false;
}
public bool IsAncientTopAlive { get; set; }
public bool IsAncientBottomAlive { get; set; }
public bool IsBottomTier3Alive { get; set; }
public bool IsBottomTier2Alive { get; set; }
public bool IsBottomTier1Alive { get; set; }
public bool IsMiddleTier3Alive { get; set; }
public bool IsMiddleTier2Alive { get; set; }
public bool IsMiddleTier1Alive { get; set; }
public bool IsTopTier3Alive { get; set; }
public bool IsTopTier2Alive { get; set; }
public bool IsTopTier1Alive { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SteamWebAPI2.Models.DOTA2
{
public class TowerState
{
public TowerState(int towerState)
{
IsAncientTopAlive = ((towerState >> 10) & 1) == 1 ? true : false;
IsAncientBottomAlive = ((towerState >> 9) & 1) == 1 ? true : false;
IsBottomTier3Alive = ((towerState >> 8) & 1) == 1 ? true : false;
IsBottomTier2Alive = ((towerState >> 7) & 1) == 1 ? true : false;
IsBottomTier1Alive = ((towerState >> 6) & 1) == 1 ? true : false;
IsMiddleTier3Alive = ((towerState >> 5) & 1) == 1 ? true : false;
IsMiddleTier2Alive = ((towerState >> 4) & 1) == 1 ? true : false;
IsMiddleTier1Alive = ((towerState >> 3) & 1) == 1 ? true : false;
IsTopTier3Alive = ((towerState >> 2) & 1) == 1 ? true : false;
IsTopTier2Alive = ((towerState >> 1) & 1) == 1 ? true : false;
IsTopTier1Alive = ((towerState >> 0) & 1) == 1 ? true : false;
}
public bool IsAncientTopAlive { get; set; }
public bool IsAncientBottomAlive { get; set; }
public bool IsBottomTier3Alive { get; set; }
public bool IsBottomTier2Alive { get; set; }
public bool IsBottomTier1Alive { get; set; }
public bool IsMiddleTier3Alive { get; set; }
public bool IsMiddleTier2Alive { get; set; }
public bool IsMiddleTier1Alive { get; set; }
public bool IsTopTier3Alive { get; set; }
public bool IsTopTier2Alive { get; set; }
public bool IsTopTier1Alive { get; set; }
}
}
| mit | C# |
8d668a9c15f891fd3858414c836a9f6af84be275 | Add MethodImplAttributes.AggressiveOptimization (dotnet/coreclr#20274) (#32930) | mmitche/corefx,BrennanConroy/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,mmitche/corefx,BrennanConroy/corefx,BrennanConroy/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,ericstj/corefx,ViktorHofer/corefx,mmitche/corefx,ptoonen/corefx,mmitche/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,shimingsg/corefx,mmitche/corefx,shimingsg/corefx,ptoonen/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,wtgodbe/corefx,shimingsg/corefx,ptoonen/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,ptoonen/corefx,ViktorHofer/corefx,ViktorHofer/corefx,wtgodbe/corefx,mmitche/corefx,shimingsg/corefx,ptoonen/corefx,ptoonen/corefx | src/Common/src/CoreLib/System/Reflection/MethodImplAttributes.cs | src/Common/src/CoreLib/System/Reflection/MethodImplAttributes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Reflection
{
// This Enum matchs the CorMethodImpl defined in CorHdr.h
public enum MethodImplAttributes
{
// code impl mask
CodeTypeMask = 0x0003, // Flags about code type.
IL = 0x0000, // Method impl is IL.
Native = 0x0001, // Method impl is native.
OPTIL = 0x0002, // Method impl is OPTIL
Runtime = 0x0003, // Method impl is provided by the runtime.
// end code impl mask
// managed mask
ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged.
Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed.
Managed = 0x0000, // Method impl is managed.
// end managed mask
// implementation info and interop
ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios.
PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared.
InternalCall = 0x1000, // Internal Call...
Synchronized = 0x0020, // Method is single threaded through the body.
NoInlining = 0x0008, // Method may not be inlined.
AggressiveInlining = 0x0100, // Method should be inlined if possible.
NoOptimization = 0x0040, // Method may not be optimized.
AggressiveOptimization = 0x0200, // Method may contain hot code and should be aggressively optimized.
MaxMethodImplVal = 0xffff,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Reflection
{
// This Enum matchs the CorMethodImpl defined in CorHdr.h
public enum MethodImplAttributes
{
// code impl mask
CodeTypeMask = 0x0003, // Flags about code type.
IL = 0x0000, // Method impl is IL.
Native = 0x0001, // Method impl is native.
OPTIL = 0x0002, // Method impl is OPTIL
Runtime = 0x0003, // Method impl is provided by the runtime.
// end code impl mask
// managed mask
ManagedMask = 0x0004, // Flags specifying whether the code is managed or unmanaged.
Unmanaged = 0x0004, // Method impl is unmanaged, otherwise managed.
Managed = 0x0000, // Method impl is managed.
// end managed mask
// implementation info and interop
ForwardRef = 0x0010, // Indicates method is not defined; used primarily in merge scenarios.
PreserveSig = 0x0080, // Indicates method sig is exported exactly as declared.
InternalCall = 0x1000, // Internal Call...
Synchronized = 0x0020, // Method is single threaded through the body.
NoInlining = 0x0008, // Method may not be inlined.
AggressiveInlining = 0x0100, // Method should be inlined if possible.
NoOptimization = 0x0040, // Method may not be optimized.
MaxMethodImplVal = 0xffff,
}
}
| mit | C# |
9ec7beb2992b6f08017b2e53212bdfd5049626d9 | Adjust XML documentation | zedr0n/AngleSharp.Local,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,Livven/AngleSharp,Livven/AngleSharp,Livven/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,FlorianRappl/AngleSharp,AngleSharp/AngleSharp | AngleSharp/Dom/StyleSheetList.cs | AngleSharp/Dom/StyleSheetList.cs | namespace AngleSharp.Dom
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A collection of CSS elements.
/// </summary>
sealed class StyleSheetList : IStyleSheetList
{
#region Fields
readonly IEnumerable<IStyleSheet> _sheets;
#endregion
#region ctor
/// <summary>
/// Creates a new stylesheet class.
/// </summary>
/// <param name="sheets">The list to enumerate.</param>
internal StyleSheetList(IEnumerable<IStyleSheet> sheets)
{
_sheets = sheets;
}
#endregion
#region Index
/// <summary>
/// Gets the stylesheet at the specified index.
/// If index is greater than or equal to the number
/// of style sheets in the list, this returns null.
/// </summary>
/// <param name="index">The index of the element.</param>
/// <returns>The stylesheet.</returns>
public IStyleSheet this[Int32 index]
{
get { return _sheets.Skip(index).FirstOrDefault(); }
}
#endregion
#region Properties
/// <summary>
/// Gets the number of elements in the list of stylesheets.
/// </summary>
public Int32 Length
{
get { return _sheets.Count(); }
}
#endregion
#region Public methods
/// <summary>
/// Returns an enumerator that iterates through the stylesheets.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<IStyleSheet> GetEnumerator()
{
return _sheets.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| namespace AngleSharp.Dom
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// A collection of CSS elements.
/// </summary>
sealed class StyleSheetList : IStyleSheetList
{
#region Fields
readonly IEnumerable<IStyleSheet> _sheets;
#endregion
#region ctor
/// <summary>
/// Creates a new stylesheet class.
/// </summary>
/// <param name="parent">The parent responsible for this list.</param>
internal StyleSheetList(IEnumerable<IStyleSheet> sheets)
{
_sheets = sheets;
}
#endregion
#region Index
/// <summary>
/// Gets the stylesheet at the specified index.
/// If index is greater than or equal to the number
/// of style sheets in the list, this returns null.
/// </summary>
/// <param name="index">The index of the element.</param>
/// <returns>The stylesheet.</returns>
public IStyleSheet this[Int32 index]
{
get { return _sheets.Skip(index).FirstOrDefault(); }
}
#endregion
#region Properties
/// <summary>
/// Gets the number of elements in the list of stylesheets.
/// </summary>
public Int32 Length
{
get { return _sheets.Count(); }
}
#endregion
#region Public methods
/// <summary>
/// Returns an enumerator that iterates through the stylesheets.
/// </summary>
/// <returns>The enumerator.</returns>
public IEnumerator<IStyleSheet> GetEnumerator()
{
return _sheets.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>The enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
}
}
| mit | C# |
aeaf7f237c686a9fd3ecf0d9e6f7a12cd1efa7a3 | Refactor AnimationOffset routine, for fewer calls. Solves issue #3. | jguarShark/Unity2D-Components,cmilr/Unity2D-Components | Behaviours/AnimationBehaviour.cs | Behaviours/AnimationBehaviour.cs | using UnityEngine;
using System.Collections;
public class AnimationBehaviour : CacheBehaviour {
protected float previousX = 0f;
protected float previousY = 0f;
protected void OffsetAnimation(float xOffset, float yOffset)
{
if (xOffset != previousX || yOffset != previousY)
transform.localPosition = new Vector3(xOffset, yOffset, 0);
previousX = xOffset;
previousY = yOffset;
}
}
| using UnityEngine;
using System.Collections;
public class AnimationBehaviour : CacheBehaviour {
protected void OffsetAnimation(float xOffset, float yOffset)
{
transform.localPosition = new Vector3(xOffset, yOffset, 0);
}
}
| mit | C# |
cbaf99ac0fe7595d4fefebe43d8ddb8b6017c8f0 | Make Counter.Value a property instead of a field | bretcope/BosunReporter.NET | BosunReporter/Metrics/Counter.cs | BosunReporter/Metrics/Counter.cs | using System;
using System.Threading;
using BosunReporter.Infrastructure;
namespace BosunReporter.Metrics
{
/// <summary>
/// A general-purpose manually incremented long-integer counter.
/// See https://github.com/bretcope/BosunReporter.NET/blob/master/docs/MetricTypes.md#counter
/// </summary>
public class Counter : BosunMetric
{
/// <summary>
/// The underlying field for <see cref="Value"/>. This allows for direct manipulation via Interlocked methods.
/// </summary>
protected long _value;
/// <summary>
/// The current value of the counter.
/// </summary>
public long Value => _value;
/// <summary>
/// The metric type (counter, in this case).
/// </summary>
public override string MetricType => "counter";
/// <summary>
/// Serializes the counter.
/// </summary>
protected override void Serialize(MetricWriter writer, DateTime now)
{
WriteValue(writer, Value, now);
}
/// <summary>
/// Instantiates a new counter. You should typically use a method on <see cref="MetricsCollector"/>, such as CreateMetric, instead of instantiating
/// directly via this constructor.
/// </summary>
public Counter()
{
}
/// <summary>
/// Increments the counter by <paramref name="amount"/>. This method is thread-safe.
/// </summary>
public void Increment(long amount = 1)
{
AssertAttached();
Interlocked.Add(ref _value, amount);
}
}
}
| using System;
using System.Threading;
using BosunReporter.Infrastructure;
namespace BosunReporter.Metrics
{
/// <summary>
/// A general-purpose manually incremented long-integer counter.
/// See https://github.com/bretcope/BosunReporter.NET/blob/master/docs/MetricTypes.md#counter
/// </summary>
public class Counter : BosunMetric
{
public long Value = 0;
/// <summary>
/// The metric type (counter, in this case).
/// </summary>
public override string MetricType => "counter";
/// <summary>
/// Serializes the counter.
/// </summary>
protected override void Serialize(MetricWriter writer, DateTime now)
{
WriteValue(writer, Value, now);
}
/// <summary>
/// Instantiates a new counter. You should typically use a method on <see cref="MetricsCollector"/>, such as CreateMetric, instead of instantiating
/// directly via this constructor.
/// </summary>
public Counter()
{
}
/// <summary>
/// Increments the counter by <paramref name="amount"/>. This method is thread-safe.
/// </summary>
public void Increment(long amount = 1)
{
AssertAttached();
Interlocked.Add(ref Value, amount);
}
}
}
| mit | C# |
9999830b506028ef9c1b25cce697bbcd70552875 | Change IsPortUnused() implementation because of SO_REUSEPORT on Linux | Abc-Arbitrage/Zebus | src/Abc.Zebus/Util/TcpUtil.cs | src/Abc.Zebus/Util/TcpUtil.cs | using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Abc.Zebus.Util
{
internal static class TcpUtil
{
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public static bool IsPortUnused(int port)
{
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var activeTcpListeners = ipGlobalProperties.GetActiveTcpListeners();
return activeTcpListeners.All(endpoint => endpoint.Port != port);
}
}
}
| using System;
using System.Net;
using System.Net.Sockets;
namespace Abc.Zebus.Util
{
internal static class TcpUtil
{
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public static bool IsPortUnused(int port)
{
var listener = new TcpListener(IPAddress.Any, port);
try
{
listener.Start();
}
catch (Exception)
{
return false;
}
listener.Stop();
return true;
}
}
} | mit | C# |
c0af3632f18d37ebcf6a0092dae79a9bbb70f3c2 | Fix race condition in NUnit integration | csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay | CSF.Screenplay.NUnit/IntegrationReader.cs | CSF.Screenplay.NUnit/IntegrationReader.cs | using System;
using System.Reflection;
using CSF.Screenplay.Integration;
using NUnit.Framework.Interfaces;
namespace CSF.Screenplay.NUnit
{
/// <summary>
/// Helper type which provides access to the current Screenplay integration.
/// </summary>
public class IntegrationReader
{
static object syncRoot;
static IScreenplayIntegration integration;
/// <summary>
/// Gets the integration from a given NUnit test method.
/// </summary>
/// <returns>The integration.</returns>
/// <param name="method">Method.</param>
public IScreenplayIntegration GetIntegration(IMethodInfo method)
{
lock(syncRoot)
{
if(integration == null)
{
var assembly = method?.MethodInfo?.DeclaringType?.Assembly;
if(assembly == null)
{
throw new ArgumentException($"The method must have an associated {nameof(Assembly)}.",
nameof(method));
}
var assemblyAttrib = assembly.GetCustomAttribute<ScreenplayAssemblyAttribute>();
if(assemblyAttrib == null)
{
var message = $"All test methods must be contained within assemblies which are " +
$"decorated with `{nameof(ScreenplayAssemblyAttribute)}'.";
throw new InvalidOperationException(message);
}
integration = assemblyAttrib.Integration;
}
}
return integration;
}
/// <summary>
/// Gets the integration from a given NUnit test instance.
/// </summary>
/// <returns>The integration.</returns>
/// <param name="test">Test.</param>
public IScreenplayIntegration GetIntegration(ITest test)
{
if(test.Method == null)
throw new ArgumentException("The test must specify a method.", nameof(test));
return GetIntegration(test.Method);
}
/// <summary>
/// Initializes the <see cref="T:CSF.Screenplay.NUnit.IntegrationReader"/> class.
/// </summary>
static IntegrationReader()
{
syncRoot = new object();
}
}
}
| using System;
using System.Reflection;
using CSF.Screenplay.Integration;
using NUnit.Framework.Interfaces;
namespace CSF.Screenplay.NUnit
{
/// <summary>
/// Helper type which provides access to the current Screenplay integration.
/// </summary>
public class IntegrationReader
{
IScreenplayIntegration cachedIntegration;
/// <summary>
/// Gets the integration from a given NUnit test method.
/// </summary>
/// <returns>The integration.</returns>
/// <param name="method">Method.</param>
public IScreenplayIntegration GetIntegration(IMethodInfo method)
{
if(cachedIntegration == null)
{
var assembly = method?.MethodInfo?.DeclaringType?.Assembly;
if(assembly == null)
{
throw new ArgumentException($"The method must have an associated {nameof(Assembly)}.",
nameof(method));
}
var assemblyAttrib = assembly.GetCustomAttribute<ScreenplayAssemblyAttribute>();
if(assemblyAttrib == null)
{
var message = $"All test methods must be contained within assemblies which are " +
$"decorated with `{nameof(ScreenplayAssemblyAttribute)}'.";
throw new InvalidOperationException(message);
}
cachedIntegration = assemblyAttrib.Integration;
}
return cachedIntegration;
}
/// <summary>
/// Gets the integration from a given NUnit test instance.
/// </summary>
/// <returns>The integration.</returns>
/// <param name="test">Test.</param>
public IScreenplayIntegration GetIntegration(ITest test)
{
if(test.Method == null)
throw new ArgumentException("The test must specify a method.", nameof(test));
return GetIntegration(test.Method);
}
}
}
| mit | C# |
8feae0306a66cee795fe589f2d04e9106e8ebdbb | Bump version to 0.8.5 | quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot | CactbotOverlay/Properties/AssemblyInfo.cs | CactbotOverlay/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.8.5.0")]
[assembly: AssemblyFileVersion("0.8.5.0")] | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.8.4.0")]
[assembly: AssemblyFileVersion("0.8.4.0")] | apache-2.0 | C# |
60b5ace93d16dcfff7c60845fd85bda1ff3d113b | improve reliability of test | splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net,splitice/IPTables.Net | IPTables.Net.Tests/IptablesLibraryTest.cs | IPTables.Net.Tests/IptablesLibraryTest.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using IPTables.Net.Iptables.NativeLibrary;
using NUnit.Framework;
namespace IPTables.Net.Tests
{
[TestFixture]
class IptablesLibraryTest
{
public static bool IsLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
[TestFixtureSetUp]
public void TestStartup()
{
if (IsLinux)
{
Process.Start("/sbin/iptables", "-N test");
Process.Start("/sbin/iptables", "-A test -j ACCEPT");
}
}
[TestFixtureTearDown]
public void TestDestroy()
{
if (IsLinux)
{
Process.Start("/sbin/iptables", "-D test -j ACCEPT");
Process.Start("/sbin/iptables", "-X test");
}
}
[Test]
public void TestRuleOutput()
{
if (IsLinux)
{
IptcInterface iptc = new IptcInterface("filter");
var rules = iptc.GetRules("test");
Assert.AreEqual(1,rules.Count);
Assert.AreEqual("-A test -j ACCEPT", rules[0]);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using IPTables.Net.Iptables.NativeLibrary;
using NUnit.Framework;
namespace IPTables.Net.Tests
{
[TestFixture]
class IptablesLibraryTest
{
public static bool IsLinux
{
get
{
int p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
[TestFixtureSetUp]
public void TestStartup()
{
if (IsLinux)
{
Process.Start("/sbin/iptables", "-A INPUT -j ACCEPT");
}
}
[TestFixtureTearDown]
public void TestDestroy()
{
if (IsLinux)
{
Process.Start("/sbin/iptables", "-D INPUT -j ACCEPT");
}
}
[Test]
public void TestRuleOutput()
{
if (IsLinux)
{
IptcInterface iptc = new IptcInterface("filter");
var rules = iptc.GetRules("INPUT");
Assert.AreEqual(1,rules.Count);
Assert.AreEqual("-A INPUT -j ACCEPT", rules[0]);
}
}
}
}
| apache-2.0 | C# |
588cbc7ea8aa5ba40a375db769428f78f606c0bd | Add missing TestAttribute to SystemClockTest. | malcolmr/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,jskeet/nodatime,nodatime/nodatime,BenJenkinson/nodatime | src/NodaTime.Test/SystemClockTest.cs | src/NodaTime.Test/SystemClockTest.cs | // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
[Test]
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2011, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2020, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
| // Copyright 2011 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
namespace NodaTime.Test
{
public class SystemClockTest
{
public void InstanceNow()
{
long frameworkNowTicks = NodaConstants.BclEpoch.PlusTicks(DateTime.UtcNow.Ticks).ToUnixTimeTicks();
long nodaTicks = SystemClock.Instance.GetCurrentInstant().ToUnixTimeTicks();
Assert.Less(Math.Abs(nodaTicks - frameworkNowTicks), Duration.FromSeconds(1).BclCompatibleTicks);
}
[Test]
public void Sanity()
{
// Previously all the conversions missed the SystemConversions.DateTimeEpochTicks,
// so they were self-consistent but not consistent with sanity.
Instant minimumExpected = Instant.FromUtc(2011, 8, 1, 0, 0);
Instant maximumExpected = Instant.FromUtc(2020, 1, 1, 0, 0);
Instant now = SystemClock.Instance.GetCurrentInstant();
Assert.Less(minimumExpected.ToUnixTimeTicks(), now.ToUnixTimeTicks());
Assert.Less(now.ToUnixTimeTicks(), maximumExpected.ToUnixTimeTicks());
}
}
}
| apache-2.0 | C# |
ae6f6904024a40cba6f85b919b31537021c71b89 | Add NeedsCpp to LinkWithAttribute | cwensley/maccore,jorik041/maccore,mono/maccore | src/ObjCRuntime/LinkWithAttribute.cs | src/ObjCRuntime/LinkWithAttribute.cs | //
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
public bool NeedsCpp {
get; set;
}
}
}
| //
// Authors: Jeffrey Stedfast
//
// Copyright 2011 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
namespace MonoMac.ObjCRuntime {
[Flags]
public enum LinkTarget {
Simulator = 1,
ArmV6 = 2,
ArmV7 = 4,
Thumb = 8,
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple=true)]
public class LinkWithAttribute : Attribute {
public LinkWithAttribute (string libraryName, LinkTarget target, string linkerFlags)
{
LibraryName = libraryName;
LinkerFlags = linkerFlags;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName, LinkTarget target)
{
LibraryName = libraryName;
LinkTarget = target;
}
public LinkWithAttribute (string libraryName)
{
LibraryName = libraryName;
}
public bool ForceLoad {
get; set;
}
public string LibraryName {
get; private set;
}
public string LinkerFlags {
get; set;
}
public LinkTarget LinkTarget {
get; set;
}
}
}
| apache-2.0 | C# |
cc4ee2df0591301b420675255a28e0612862654f | add ToString() override to Beatmap class | EVAST9919/osu,UselessToucan/osu,2yangk23/osu,ZLima12/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,ppy/osu,ZLima12/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Beatmaps/Beatmap.cs | osu.Game/Beatmaps/Beatmap.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps.Timing;
using osu.Game.Rulesets.Objects;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps.ControlPoints;
using Newtonsoft.Json;
using osu.Game.IO.Serialization.Converters;
namespace osu.Game.Beatmaps
{
/// <summary>
/// A Beatmap containing converted HitObjects.
/// </summary>
public class Beatmap<T> : IBeatmap
where T : HitObject
{
public BeatmapInfo BeatmapInfo { get; set; } = new BeatmapInfo
{
Metadata = new BeatmapMetadata
{
Artist = @"Unknown",
Title = @"Unknown",
AuthorString = @"Unknown Creator",
},
Version = @"Normal",
BaseDifficulty = new BeatmapDifficulty()
};
[JsonIgnore]
public BeatmapMetadata Metadata => BeatmapInfo?.Metadata ?? BeatmapInfo?.BeatmapSet?.Metadata;
public ControlPointInfo ControlPointInfo { get; set; } = new ControlPointInfo();
public List<BreakPeriod> Breaks { get; set; } = new List<BreakPeriod>();
/// <summary>
/// Total amount of break time in the beatmap.
/// </summary>
[JsonIgnore]
public double TotalBreakTime => Breaks.Sum(b => b.Duration);
/// <summary>
/// The HitObjects this Beatmap contains.
/// </summary>
[JsonConverter(typeof(TypedListConverter<HitObject>))]
public List<T> HitObjects = new List<T>();
IReadOnlyList<HitObject> IBeatmap.HitObjects => HitObjects;
public virtual IEnumerable<BeatmapStatistic> GetStatistics() => Enumerable.Empty<BeatmapStatistic>();
IBeatmap IBeatmap.Clone() => Clone();
public Beatmap<T> Clone() => (Beatmap<T>)MemberwiseClone();
}
public class Beatmap : Beatmap<HitObject>
{
public new Beatmap Clone() => (Beatmap)base.Clone();
public override string ToString() => BeatmapInfo?.ToString();
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Game.Beatmaps.Timing;
using osu.Game.Rulesets.Objects;
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps.ControlPoints;
using Newtonsoft.Json;
using osu.Game.IO.Serialization.Converters;
namespace osu.Game.Beatmaps
{
/// <summary>
/// A Beatmap containing converted HitObjects.
/// </summary>
public class Beatmap<T> : IBeatmap
where T : HitObject
{
public BeatmapInfo BeatmapInfo { get; set; } = new BeatmapInfo
{
Metadata = new BeatmapMetadata
{
Artist = @"Unknown",
Title = @"Unknown",
AuthorString = @"Unknown Creator",
},
Version = @"Normal",
BaseDifficulty = new BeatmapDifficulty()
};
[JsonIgnore]
public BeatmapMetadata Metadata => BeatmapInfo?.Metadata ?? BeatmapInfo?.BeatmapSet?.Metadata;
public ControlPointInfo ControlPointInfo { get; set; } = new ControlPointInfo();
public List<BreakPeriod> Breaks { get; set; } = new List<BreakPeriod>();
/// <summary>
/// Total amount of break time in the beatmap.
/// </summary>
[JsonIgnore]
public double TotalBreakTime => Breaks.Sum(b => b.Duration);
/// <summary>
/// The HitObjects this Beatmap contains.
/// </summary>
[JsonConverter(typeof(TypedListConverter<HitObject>))]
public List<T> HitObjects = new List<T>();
IReadOnlyList<HitObject> IBeatmap.HitObjects => HitObjects;
public virtual IEnumerable<BeatmapStatistic> GetStatistics() => Enumerable.Empty<BeatmapStatistic>();
IBeatmap IBeatmap.Clone() => Clone();
public Beatmap<T> Clone() => (Beatmap<T>)MemberwiseClone();
}
public class Beatmap : Beatmap<HitObject>
{
public new Beatmap Clone() => (Beatmap)base.Clone();
}
}
| mit | C# |
f93cdc8d19994cb78133a874b0676bcf9dccb30f | Fix Android compilation issues | peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework | osu.Framework.Android/AndroidGameWindow.cs | osu.Framework.Android/AndroidGameWindow.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osuTK;
using osuTK.Graphics;
namespace osu.Framework.Android
{
public class AndroidGameWindow : OsuTKWindow
{
public override IGraphicsContext Context
=> View.GraphicsContext;
internal static AndroidGameView View;
public override bool Focused
=> true;
public override Platform.WindowState WindowState
{
get => Platform.WindowState.Normal;
set { }
}
public AndroidGameWindow()
: base(View)
{
}
public override void SetupWindow(FrameworkConfigManager config)
{
}
protected override IEnumerable<WindowMode> DefaultSupportedWindowModes => new[]
{
Configuration.WindowMode.Fullscreen,
};
public override void Run()
{
View.Run();
}
public override void Run(double updateRate)
{
View.Run(updateRate);
}
protected override DisplayDevice CurrentDisplayDevice
{
get => DisplayDevice.Default;
set => throw new InvalidOperationException();
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Configuration;
using osu.Framework.Platform;
using osuTK;
using osuTK.Graphics;
using WindowState = osuTK.WindowState;
namespace osu.Framework.Android
{
public class AndroidGameWindow : OsuTKWindow
{
public override IGraphicsContext Context
=> View.GraphicsContext;
internal static AndroidGameView View;
public override bool Focused
=> true;
public override WindowState WindowState
{
get => WindowState.Normal;
set { }
}
public AndroidGameWindow()
: base(View)
{
}
public override void SetupWindow(FrameworkConfigManager config)
{
}
protected override IEnumerable<WindowMode> DefaultSupportedWindowModes => new[]
{
Configuration.WindowMode.Fullscreen,
};
public override void Run()
{
View.Run();
}
public override void Run(double updateRate)
{
View.Run(updateRate);
}
protected override DisplayDevice CurrentDisplayDevice
{
get => DisplayDevice.Default;
set => throw new InvalidOperationException();
}
}
}
| mit | C# |
e07aa94fc8701f0a2807ef04cbca20d26f75566c | Allow reloading ipc source | NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,ZLima12/osu,2yangk23/osu,ppy/osu | osu.Game.Tournament/Screens/SetupScreen.cs | osu.Game.Tournament/Screens/SetupScreen.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Screens.Edit.Setup.Components.LabelledComponents;
using osu.Game.Tournament.IPC;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament.Screens
{
public class SetupScreen : TournamentScreen
{
[Resolved]
private MatchIPCInfo ipc { get; set; }
[BackgroundDependencyLoader]
private void load()
{
reload();
}
private void reload()
{
var fileBasedIpc = ipc as FileBasedIPC;
InternalChildren = new Drawable[]
{
new ActionableInfo
{
Label = "Current IPC source",
ButtonText = "Refresh",
Action = () =>
{
fileBasedIpc?.LocateStableStorage();
reload();
},
Value = fileBasedIpc?.Storage?.GetFullPath(string.Empty) ?? "Not found",
Failing = fileBasedIpc?.Storage == null,
Description = "The osu!stable installation which is currently being used as a data source. If a source is not found, make sure you have created an empty ipc.txt in your stable cutting-edge installation, and that it is registered as the default osu! install."
}
};
}
private class ActionableInfo : LabelledComponent
{
private OsuButton button;
public ActionableInfo()
: base(true)
{
}
public string ButtonText
{
set => button.Text = value;
}
public string Value
{
set => valueText.Text = value;
}
public bool Failing
{
set => valueText.Colour = value ? Color4.Red : Color4.White;
}
public Action Action;
private OsuSpriteText valueText;
protected override Drawable CreateComponent() => new Container
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Children = new Drawable[]
{
valueText = new OsuSpriteText
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
},
button = new TriangleButton
{
Anchor = Anchor.CentreRight,
Origin = Anchor.CentreRight,
Size = new Vector2(100, 30),
Action = () => Action?.Invoke()
},
}
};
}
}
}
| // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Sprites;
using osu.Game.Tournament.IPC;
namespace osu.Game.Tournament.Screens
{
public class SetupScreen : TournamentScreen
{
[Resolved]
private MatchIPCInfo ipc { get; set; }
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new SpriteText
{
Text = (ipc as FileBasedIPC)?.Storage.GetFullPath(string.Empty)
});
}
}
}
| mit | C# |
3b42e9fd8746d7475ed699cac6394e617e8083ae | Return int or decimal for usage stats | MasterOfSomeTrades/CommentEverythingCommunications | CEComms/ClassLibrary1/Communications/Twilio/User/Usage.cs | CEComms/ClassLibrary1/Communications/Twilio/User/Usage.cs | using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public decimal GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return (decimal) record.Usage;
}
public int GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return (int) Math.Round(record.Usage);
}
}
}
| using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public double GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return record.Usage;
}
public double GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return record.Usage;
}
}
}
| mit | C# |
5497b0f31f27a477f2c79f8d855dcf1a71f5d292 | comment Localizable | Lentosy/FileBrowser | MusicFiles/Models/Language/Localizable.cs | MusicFiles/Models/Language/Localizable.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileBrowser.Models.Language {
/// <summary>
/// Interface that allows a class to be localized
/// </summary>
public interface Localizable {
void UpdateText();
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileBrowser.Models.Language {
public interface Localizable {
void UpdateText();
}
}
| apache-2.0 | C# |
f3b162adb1ee8abda460a119e2772eeb106b9025 | add register service test | lvermeulen/Nanophone | test/Nanophone.RegistryHost.ConsulRegistry.Tests/ConsulRegistryHostShould.cs | test/Nanophone.RegistryHost.ConsulRegistry.Tests/ConsulRegistryHostShould.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using Nanophone.Core;
using Xunit;
namespace Nanophone.RegistryHost.ConsulRegistry.Tests
{
public class ConsulRegistryHostShould
{
private readonly IRegistryHost _registryHost;
public ConsulRegistryHostShould()
{
var configuration = new ConsulRegistryHostConfiguration();
_registryHost = new ConsulRegistryHost(configuration);
}
[Fact]
public async Task FindServices()
{
var services = await _registryHost.FindServiceInstancesAsync("consul");
Assert.NotNull(services);
Assert.True(services.Any());
}
[Fact]
public async Task RegisterService()
{
var serviceName = nameof(ConsulRegistryHostShould);
_registryHost.RegisterServiceAsync(serviceName, serviceName, new Uri("http://localhost:1234"))
.Wait();
Func<string, Task<RegistryInformation>> findTenant = async s => (await ((ConsulRegistryHost)_registryHost).FindAllServicesAsync())
.FirstOrDefault(x => x.Name == s);
var tenant = findTenant(serviceName).Result;
Assert.NotNull(tenant);
await _registryHost.DeregisterServiceAsync(tenant.Id);
Assert.Null(findTenant(serviceName).Result);
}
[Fact]
public async Task UseKeyValueStore()
{
const string KEY = "hello";
DateTime dateValue = new DateTime(2016, 5, 28);
await _registryHost.KeyValuePutAsync(KEY, dateValue);
var value = await _registryHost.KeyValueGetAsync<DateTime>("hello");
Assert.Equal(dateValue, value);
await _registryHost.KeyValueDeleteAsync(KEY);
}
[Fact]
public async Task UseKeyValueStoreWithFolders()
{
const string FOLDER = "folder/hello/world/";
const string KEY = "date";
DateTime dateValue = new DateTime(2016, 5, 28);
await _registryHost.KeyValuePutAsync(FOLDER + KEY, dateValue);
var value = await _registryHost.KeyValueGetAsync<DateTime>(FOLDER + KEY);
Assert.Equal(dateValue, value);
await _registryHost.KeyValueDeleteTreeAsync(FOLDER);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using Nanophone.Core;
using Xunit;
namespace Nanophone.RegistryHost.ConsulRegistry.Tests
{
public class ConsulRegistryHostShould
{
private readonly IRegistryHost _registryHost;
public ConsulRegistryHostShould()
{
var configuration = new ConsulRegistryHostConfiguration();
_registryHost = new ConsulRegistryHost(configuration);
}
[Fact]
public async Task FindServices()
{
var services = await _registryHost.FindServiceInstancesAsync("consul");
Assert.NotNull(services);
Assert.True(services.Any());
}
[Fact]
public async Task UseKeyValueStore()
{
const string KEY = "hello";
DateTime dateValue = new DateTime(2016, 5, 28);
await _registryHost.KeyValuePutAsync(KEY, dateValue);
var value = await _registryHost.KeyValueGetAsync<DateTime>("hello");
Assert.Equal(dateValue, value);
await _registryHost.KeyValueDeleteAsync(KEY);
}
[Fact]
public async Task UseKeyValueStoreWithFolders()
{
const string FOLDER = "folder/hello/world/";
const string KEY = "date";
DateTime dateValue = new DateTime(2016, 5, 28);
await _registryHost.KeyValuePutAsync(FOLDER + KEY, dateValue);
var value = await _registryHost.KeyValueGetAsync<DateTime>(FOLDER + KEY);
Assert.Equal(dateValue, value);
await _registryHost.KeyValueDeleteTreeAsync(FOLDER);
}
}
}
| mit | C# |
bed5e857df7d2af44ae5f4bbfa304f04be741da1 | Add missing license header and remove unused usings | peppy/osu-new,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu | osu.Game/Rulesets/Mods/IApplicableToAudio.cs | osu.Game/Rulesets/Mods/IApplicableToAudio.cs | // Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Mods
{
public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample
{
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace osu.Game.Rulesets.Mods
{
public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample
{
}
}
| mit | C# |
b25d4a49dabc883ee4628fad81b6c518b1efbf5d | Fix test namespaces | brentstineman/nether,brentstineman/nether,navalev/nether,stuartleeks/nether,vflorusso/nether,stuartleeks/nether,ankodu/nether,brentstineman/nether,ankodu/nether,navalev/nether,vflorusso/nether,oliviak/nether,stuartleeks/nether,krist00fer/nether,vflorusso/nether,ankodu/nether,brentstineman/nether,brentstineman/nether,vflorusso/nether,ankodu/nether,navalev/nether,MicrosoftDX/nether,vflorusso/nether,navalev/nether,stuartleeks/nether,stuartleeks/nether | tests/Leaderboard/Nether.Leaderboard.Web.Tests/LeaderboardControllerTests.cs | tests/Leaderboard/Nether.Leaderboard.Web.Tests/LeaderboardControllerTests.cs | using Microsoft.AspNetCore.Mvc;
using Moq;
using Nether.Leaderboard.Data;
using Nether.Leaderboard.Web.Controllers;
using Nether.Leaderboard.Web.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Leaderboard.Web.Tests
{
public class LeaderboardControllerTests
{
[Fact(DisplayName = "WhenPostedScoreIsNegativeThenReturnHTTP400")]
public async Task WhenPostedScoreIsNegative_ThenTheApiReturns400Response()
{
// Arrange
var leaderboardStore = new Mock<ILeaderboardStore>();
var controller = new LeaderboardController(leaderboardStore.Object);
// Act
var result = await controller.Post(new ScoreRequestModel
{
Gamertag = "anonymous",
Score = -1
});
// Assert
var statusCodeResult = Assert.IsType<StatusCodeResult>(result);
Assert.Equal(400, statusCodeResult.StatusCode);
}
[Fact]
public async Task WhenPostedScoreIsNegative_ThenTheApiDoesNotSaveScore()
{
// Arrange
var leaderboardStore = new Mock<ILeaderboardStore>();
var controller = new LeaderboardController(leaderboardStore.Object);
// Act
var result = await controller.Post(new ScoreRequestModel
{
Gamertag = "anonymous",
Score = -1
});
// Assert
leaderboardStore.Verify(o => o.SaveScoreAsync(It.IsAny<string>(), It.IsAny<int>()), Times.Never);
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Moq;
using Nether.Leaderboard.Data;
using Nether.Leaderboard.Web.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Leaderboard.Web.Tests
{
public class LeaderboardControllerTests
{
[Fact(DisplayName = "WhenPostedScoreIsNegativeThenReturnHTTP400")]
public async Task WhenPostedScoreIsNegative_ThenTheApiReturns400Response()
{
// Arrange
var leaderboardStore = new Mock<ILeaderboardStore>();
var controller = new LeaderboardController(leaderboardStore.Object);
// Act
var result = await controller.Post(new ScoreRequestModel
{
Gamertag = "anonymous",
Score = -1
});
// Assert
var statusCodeResult = Assert.IsType<StatusCodeResult>(result);
Assert.Equal(400, statusCodeResult.StatusCode);
}
[Fact]
public async Task WhenPostedScoreIsNegative_ThenTheApiDoesNotSaveScore()
{
// Arrange
var leaderboardStore = new Mock<ILeaderboardStore>();
var controller = new LeaderboardController(leaderboardStore.Object);
// Act
var result = await controller.Post(new ScoreRequestModel
{
Gamertag = "anonymous",
Score = -1
});
// Assert
leaderboardStore.Verify(o => o.SaveScoreAsync(It.IsAny<string>(), It.IsAny<int>()), Times.Never);
}
}
}
| mit | C# |
765b631cd8e4cbf38429f44ecaa495e0e0f82cca | Simplify merge tables method | paiden/Nett | Source/Nett.Coma/MergedConfig.cs | Source/Nett.Coma/MergedConfig.cs | namespace Nett.Coma
{
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Diagnostics.Debug;
internal class MergedConfig : IPersistableConfig
{
private const string AssertAtLeastOneConfig =
"Constructor should check that there is a config and the configs should not get modified later on";
private readonly IEnumerable<IPersistableConfig> configs;
public MergedConfig(IEnumerable<IPersistableConfig> configs)
{
if (configs == null) { throw new ArgumentNullException(nameof(configs)); }
if (configs.Count() <= 0) { throw new ArgumentException("There needs to be at least one config", nameof(configs)); }
this.configs = configs;
}
public bool EnsureExists(TomlTable content)
{
Assert(this.configs.Count() > 0, AssertAtLeastOneConfig);
return this.configs.First().EnsureExists(content);
}
public TomlTable Load()
{
Assert(this.configs.Count() > 0, AssertAtLeastOneConfig);
TomlTable merged = this.configs.First().Load();
foreach (var c in this.configs.Skip(1))
{
merged.OverwriteWithValuesFrom(c.Load());
}
return merged;
}
public void Save(TomlTable content)
{
throw new NotImplementedException();
}
}
}
| namespace Nett.Coma
{
using System;
using System.Collections.Generic;
using System.Linq;
using static System.Diagnostics.Debug;
internal class MergedConfig : IPersistableConfig
{
private const string AssertAtLeastOneConfig =
"Constructor should check that there is a config and the configs should not get modified later on";
private readonly IEnumerable<IPersistableConfig> configs;
public MergedConfig(IEnumerable<IPersistableConfig> configs)
{
if (configs == null) { throw new ArgumentNullException(nameof(configs)); }
if (configs.Count() <= 0) { throw new ArgumentException("There needs to be at least one config", nameof(configs)); }
this.configs = configs;
}
public bool EnsureExists(TomlTable content)
{
Assert(this.configs.Count() > 0, AssertAtLeastOneConfig);
return this.configs.First().EnsureExists(content);
}
public TomlTable Load()
{
Assert(this.configs.Count() > 0, AssertAtLeastOneConfig);
TomlTable merged = null;
foreach (var c in this.configs)
{
if (merged == null)
{
merged = c.Load();
}
else
{
merged.OverwriteWithValuesFrom(c.Load());
}
}
return merged;
}
public void Save(TomlTable content)
{
throw new NotImplementedException();
}
}
}
| mit | C# |
9dd7ed117ed150ab760286bb65bb7922b5778705 | change form acrion from non-existent Logoff to Logout | dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers | src/Services/Identity/Identity.API/Views/Shared/_LoginPartial.cshtml | src/Services/Identity/Identity.API/Views/Shared/_LoginPartial.cshtml | @using Microsoft.AspNetCore.Identity
@using Microsoft.eShopOnContainers.Services.Identity.API.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
| @using Microsoft.AspNetCore.Identity
@using Microsoft.eShopOnContainers.Services.Identity.API.Models
@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager
@if (SignInManager.IsSignedIn(User))
{
<form asp-area="" asp-controller="Account" asp-action="LogOff" method="post" id="logoutForm" class="navbar-right">
<ul class="nav navbar-nav navbar-right">
<li>
<a asp-area="" asp-controller="Manage" asp-action="Index" title="Manage">Hello @UserManager.GetUserName(User)!</a>
</li>
<li>
<button type="submit" class="btn btn-link navbar-btn navbar-link">Log off</button>
</li>
</ul>
</form>
}
else
{
<ul class="nav navbar-nav navbar-right">
<li><a asp-area="" asp-controller="Account" asp-action="Register">Register</a></li>
<li><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></li>
</ul>
}
| mit | C# |
1488a3767c77ce533f095a9e220773d099c99e61 | Update root lib to Glimpse.Common | Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype | src/Glimpse.Common/Reflection/ReflectionDiscoverableCollection.cs | src/Glimpse.Common/Reflection/ReflectionDiscoverableCollection.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse.Common";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
} | using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
} | mit | C# |
9c86b648fab5f306da951a11184315c09247cd3b | Fix ByondExecutableLock | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server | src/Tgstation.Server.Host/Components/Byond/ByondExecutableLock.cs | src/Tgstation.Server.Host/Components/Byond/ByondExecutableLock.cs | using System;
namespace Tgstation.Server.Host.Components.Byond
{
/// <inheritdoc />
sealed class ByondExecutableLock : IByondExecutableLock
{
/// <inheritdoc />
public Version Version { get; }
/// <inheritdoc />
public string DreamDaemonPath { get; }
/// <inheritdoc />
public string DreamMakerPath { get; }
/// <summary>
/// Construct a <see cref="ByondExecutableLock"/>
/// </summary>
/// <param name="version">The value of <see cref="Version"/></param>
/// <param name="dreamDaemonPath">The value of <see cref="DreamDaemonPath"/></param>
/// <param name="dreamMakerPath">The value of <see cref="DreamMakerPath"/></param>
public ByondExecutableLock(Version version, string dreamDaemonPath, string dreamMakerPath)
{
Version = version ?? throw new ArgumentNullException(nameof(version));
DreamDaemonPath = dreamDaemonPath ?? throw new ArgumentNullException(nameof(dreamDaemonPath));
DreamMakerPath = dreamMakerPath ?? throw new ArgumentNullException(nameof(dreamMakerPath));
}
//at one point in design, byond versions were to delete themselves if they werent the active version
//That changed at some point so these functions are intentioanlly left blank
/// <inheritdoc />
public void Dispose() { }
/// <inheritdoc />
public void DoNotDeleteThisSession() { }
}
}
| using System;
namespace Tgstation.Server.Host.Components.Byond
{
/// <inheritdoc />
sealed class ByondExecutableLock : IByondExecutableLock
{
/// <inheritdoc />
public Version Version { get; }
/// <inheritdoc />
public string DreamDaemonPath { get; }
/// <inheritdoc />
public string DreamMakerPath { get; }
/// <summary>
/// Construct a <see cref="ByondExecutableLock"/>
/// </summary>
/// <param name="version">The value of <see cref="Version"/></param>
/// <param name="dreamDaemonPath">The value of <see cref="DreamDaemonPath"/></param>
/// <param name="dreamMakerPath">The value of <see cref="DreamMakerPath"/></param>
public ByondExecutableLock(Version version, string dreamDaemonPath, string dreamMakerPath)
{
Version = version ?? throw new ArgumentNullException(nameof(version));
dreamDaemonPath = dreamDaemonPath ?? throw new ArgumentNullException(nameof(dreamDaemonPath));
dreamMakerPath = dreamMakerPath ?? throw new ArgumentNullException(nameof(dreamMakerPath));
}
//at one point in design, byond versions were to delete themselves if they werent the active version
//That changed at some point so these functions are intentioanlly left blank
/// <inheritdoc />
public void Dispose() { }
/// <inheritdoc />
public void DoNotDeleteThisSession() { }
}
}
| agpl-3.0 | C# |
8b8be8f784c9df0957c70e5b0d5c938dba776235 | Fix code inspections. | PombeirP/Unity.TypedFactories | src/Unity.TypedFactories/ConstructorArgumentsMismatchException.cs | src/Unity.TypedFactories/ConstructorArgumentsMismatchException.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConstructorArgumentsMismatchException.cs" company="Developer In The Flow">
// 2012 Pedro Pombeiro
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Unity.TypedFactories
{
using System;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.Practices.Unity;
/// <summary>
/// Exception thrown when the arguments supplied in a typed factory method do not fulfill the arguments required by a concrete class' constructors.
/// </summary>
public class ConstructorArgumentsMismatchException : Exception
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorArgumentsMismatchException"/> class.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
/// <param name="typedFactoryType">
/// The type of the factory interface.
/// </param>
/// <param name="nonMatchingParameters">
/// The list of non-matching parameters.
/// </param>
/// <param name="innerException">
/// The inner exception, documenting the resolution failure.
/// </param>
public ConstructorArgumentsMismatchException(string message, Type typedFactoryType, ParameterInfo[] nonMatchingParameters, ResolutionFailedException innerException)
: base(message, innerException)
{
this.TypedFactoryType = typedFactoryType;
this.NonMatchingParameters = nonMatchingParameters;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the list of parameters from the factory method which were not found in the concrete type's constructor.
/// </summary>
[PublicAPI]
public ParameterInfo[] NonMatchingParameters { get; private set; }
/// <summary>
/// Gets the <see cref="Type"/> of the Typed Factory interface.
/// </summary>
[PublicAPI]
public Type TypedFactoryType { get; private set; }
#endregion
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConstructorArgumentsMismatchException.cs" company="Developer In The Flow">
// 2012 Pedro Pombeiro
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Unity.TypedFactories
{
using System;
using System.Reflection;
using Microsoft.Practices.Unity;
/// <summary>
/// Exception thrown when the arguments supplied in a typed factory method do not fulfill the arguments required by a concrete class' constructors.
/// </summary>
public class ConstructorArgumentsMismatchException : Exception
{
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="ConstructorArgumentsMismatchException"/> class.
/// </summary>
/// <param name="message">
/// The message.
/// </param>
/// <param name="typedFactoryType">
/// The type of the factory interface.
/// </param>
/// <param name="nonMatchingParameters">
/// The list of non-matching parameters.
/// </param>
/// <param name="innerException">
/// The inner exception, documenting the resolution failure.
/// </param>
public ConstructorArgumentsMismatchException(string message, Type typedFactoryType, ParameterInfo[] nonMatchingParameters, ResolutionFailedException innerException)
: base(message, innerException)
{
this.TypedFactoryType = typedFactoryType;
this.NonMatchingParameters = nonMatchingParameters;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the list of parameters from the factory method which were not found in the concrete type's constructor.
/// </summary>
public ParameterInfo[] NonMatchingParameters { get; private set; }
/// <summary>
/// Gets the <see cref="Type"/> of the Typed Factory interface.
/// </summary>
public Type TypedFactoryType { get; private set; }
#endregion
}
} | mit | C# |
08d7fde620f063274c58a2bc06c64e5f95cff6d9 | fix Microsoft.AspNetCore.Mvc.ControllerBase | BigBabay/AsyncConverter,BigBabay/AsyncConverter | AsyncConverter/AsyncHelpers/RenameCheckers/ControllerRenameChecker.cs | AsyncConverter/AsyncHelpers/RenameCheckers/ControllerRenameChecker.cs | using System.Linq;
using System.Collections.Generic;
using JetBrains.Metadata.Reader.Impl;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.Util;
namespace AsyncConverter.AsyncHelpers.RenameCheckers
{
[SolutionComponent]
internal class ControllerRenameChecker : IConcreateRenameChecker
{
private readonly HashSet<ClrTypeName> controllerClasses = new HashSet<ClrTypeName>
{
new ClrTypeName("System.Web.Mvc.Controller"),
new ClrTypeName("System.Web.Http.ApiController"),
new ClrTypeName("Microsoft.AspNetCore.Mvc.Controller"),
new ClrTypeName("Microsoft.AspNetCore.Mvc.ControllerBase"),
};
public bool SkipRename(IMethodDeclaration method)
{
var @class = method.DeclaredElement?.GetContainingType() as IClass;
if (@class == null)
return false;
var superTypes = @class.GetSuperTypesWithoutCircularDependent();
if (superTypes.Any(superType => controllerClasses.Contains(superType.GetClrName())))
return true;
return false;
}
}
} | using System.Linq;
using System.Collections.Generic;
using JetBrains.Metadata.Reader.Impl;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Util;
using JetBrains.Util;
namespace AsyncConverter.AsyncHelpers.RenameCheckers
{
[SolutionComponent]
internal class ControllerRenameChecker : IConcreateRenameChecker
{
private readonly HashSet<ClrTypeName> controllerClasses = new HashSet<ClrTypeName>
{
new ClrTypeName("System.Web.Mvc.Controller"),
new ClrTypeName("System.Web.Http.ApiController"),
new ClrTypeName("Microsoft.AspNetCore.Mvc.Controller"),
};
public bool SkipRename(IMethodDeclaration method)
{
var @class = method.DeclaredElement?.GetContainingType() as IClass;
if (@class == null)
return false;
var superTypes = @class.GetSuperTypesWithoutCircularDependent();
if (superTypes.Any(superType => controllerClasses.Contains(superType.GetClrName())))
return true;
return false;
}
}
} | mit | C# |
fc6617827fa0bf647498acd7e333200b3a76b942 | change assembly version | dinobenz/toda-api | src/toda-api/Properties/AssemblyInfo.cs | src/toda-api/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("toda.api")]
[assembly: AssemblyDescription("Thailan Open Data API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("toda.api")]
[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("58493744-b5f1-4b08-bd01-25e994ac03b5")]
// 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("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.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("toda.api")]
[assembly: AssemblyDescription("Thailan Open Data API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("toda.api")]
[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("58493744-b5f1-4b08-bd01-25e994ac03b5")]
// 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")]
| mit | C# |
503a04b47b402ce4042b53beb3b4458837faf42b | Make UserArn readonly | carbon/Amazon | src/Amazon.Rds/Models/UserArn.cs | src/Amazon.Rds/Models/UserArn.cs | namespace Amazon.Rds
{
public readonly struct UserArn
{
private readonly string name;
public UserArn(
AwsRegion region,
string accountId,
string databaseId,
string userName)
{
this.name = $"arn:aws:rds-db:{region.Name}:{accountId}:dbuser:{databaseId}/{userName}";
}
public override string ToString() => name;
}
// arn:aws:rds-db:us-west-2:12345678:dbuser:db-12ABC34DEFG5HIJ6KLMNOP78QR/jane_doe
} | namespace Amazon.Rds
{
public struct UserArn
{
private readonly string name;
public UserArn(
AwsRegion region,
string accountId,
string databaseId,
string userName)
{
this.name = $"arn:aws:rds-db:{region.Name}:{accountId}:dbuser:{databaseId}/{userName}";
}
public override string ToString() => name;
}
// arn:aws:rds-db:us-west-2:12345678:dbuser:db-12ABC34DEFG5HIJ6KLMNOP78QR/jane_doe
} | mit | C# |
cf58fa9da5a759a079c58139ee5a56db65919363 | Add comment for versioning | kovalikp/nuproj,zbrad/nuproj,ericstj/nuproj,faustoscardovi/nuproj,NN---/nuproj,oliver-feng/nuproj,AArnott/nuproj,PedroLamas/nuproj,nuproj/nuproj | src/Common/CommonAssemblyInfo.cs | src/Common/CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.codeplex.com")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.codeplex.com/license")]
// NOTE: When updating the version, you also need to update the Identity/@Version
// attribtute in src\NuProj.Package\source.extension.vsixmanifest.
[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Immo Landwerth")]
[assembly: AssemblyProduct("NuProj")]
[assembly: AssemblyCopyright("Copyright © Immo Landwerth")]
[assembly: AssemblyTrademark("")]
[assembly : AssemblyMetadata("PreRelease", "Beta")]
[assembly : AssemblyMetadata("ProjectUrl", "http://nuproj.codeplex.com")]
[assembly : AssemblyMetadata("LicenseUrl", "http://nuproj.codeplex.com/license")]
[assembly: AssemblyVersion("0.9.2.0")]
[assembly: AssemblyFileVersion("0.9.2.0")]
| mit | C# |
cedf2abaecc229835ebaa89737eb967bbc1f5aa0 | Update CuidCorrelationServiceTests.cs | tiksn/TIKSN-Framework | TIKSN.UnitTests.Shared/Integration/Correlation/CuidCorrelationServiceTests.cs | TIKSN.UnitTests.Shared/Integration/Correlation/CuidCorrelationServiceTests.cs | using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using System;
using TIKSN.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.Integration.Correlation.Tests
{
public class CuidCorrelationServiceTests
{
private readonly ICorrelationService _correlationService;
private readonly ITestOutputHelper _testOutputHelper;
public CuidCorrelationServiceTests(ITestOutputHelper testOutputHelper)
{
var services = new ServiceCollection();
services.AddFrameworkPlatform();
services.AddSingleton<ICorrelationService, CuidCorrelationService>();
var serviceProvider = services.BuildServiceProvider();
_correlationService = serviceProvider.GetRequiredService<ICorrelationService>();
_testOutputHelper = testOutputHelper ?? throw new System.ArgumentNullException(nameof(testOutputHelper));
}
[Fact]
public void GenerateCoupleOfIds()
{
LogOutput(_correlationService.Generate(), "Correlation ID 1");
LogOutput(_correlationService.Generate(), "Correlation ID 2");
LogOutput(_correlationService.Generate(), "Correlation ID 3");
}
[Fact]
public void GenerateAndParse()
{
var correlationID = _correlationService.Generate();
LogOutput(correlationID, nameof(correlationID));
var correlationIDFromString = _correlationService.Create(correlationID.ToString());
var correlationIDFromBytes = _correlationService.Create(correlationID.ToByteArray());
correlationIDFromString.Should().Be(correlationID);
correlationIDFromBytes.Should().Be(correlationID);
correlationIDFromString.Should().Be(correlationIDFromBytes);
}
private void LogOutput(CorrelationID correlationID, string name)
{
_testOutputHelper.WriteLine("-------------------------");
_testOutputHelper.WriteLine(name);
_testOutputHelper.WriteLine(correlationID.ToString());
_testOutputHelper.WriteLine(BitConverter.ToString(correlationID.ToByteArray()));
_testOutputHelper.WriteLine("");
}
[Fact]
public void ParseExample()
{
var cuid = _correlationService.Create("ch72gsb320000udocl363eofy");
}
}
} | using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using System;
using TIKSN.DependencyInjection;
using Xunit;
using Xunit.Abstractions;
namespace TIKSN.Integration.Correlation.Tests
{
public class CuidCorrelationServiceTests
{
private readonly ICorrelationService _correlationService;
private readonly ITestOutputHelper _testOutputHelper;
public CuidCorrelationServiceTests(ITestOutputHelper testOutputHelper)
{
var services = new ServiceCollection();
services.AddFrameworkPlatform();
services.AddSingleton<ICorrelationService, CuidCorrelationService>();
var serviceProvider = services.BuildServiceProvider();
_correlationService = serviceProvider.GetRequiredService<ICorrelationService>();
_testOutputHelper = testOutputHelper ?? throw new System.ArgumentNullException(nameof(testOutputHelper));
}
[Fact]
public void GenerateAndParse()
{
var correlationID = _correlationService.Generate();
LogOutput(correlationID, nameof(correlationID));
var correlationIDFromString = _correlationService.Create(correlationID.ToString());
var correlationIDFromBytes = _correlationService.Create(correlationID.ToByteArray());
correlationIDFromString.Should().Be(correlationID);
correlationIDFromBytes.Should().Be(correlationID);
correlationIDFromString.Should().Be(correlationIDFromBytes);
}
private void LogOutput(CorrelationID correlationID, string name)
{
_testOutputHelper.WriteLine("-------------------------");
_testOutputHelper.WriteLine(name);
_testOutputHelper.WriteLine(correlationID.ToString());
_testOutputHelper.WriteLine(BitConverter.ToString(correlationID.ToByteArray()));
}
[Fact]
public void ParseExample()
{
var cuid = _correlationService.Create("ch72gsb320000udocl363eofy");
}
}
} | mit | C# |
af2917ddf5d5da88f1e582e733e488acdcd24d99 | bump version | user1568891/PropertyChanged,Fody/PropertyChanged,0x53A/PropertyChanged | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("1.50.1")]
[assembly: AssemblyFileVersion("1.50.1")]
| using System.Reflection;
[assembly: AssemblyTitle("PropertyChanged")]
[assembly: AssemblyProduct("PropertyChanged")]
[assembly: AssemblyCompany("Simon Cropp and Contributors")]
[assembly: AssemblyDescription("Fody add-in for injecting INotifyPropertyChanged code into properties.")]
[assembly: AssemblyVersion("1.50.0")]
[assembly: AssemblyFileVersion("1.50.0")]
| mit | C# |
33263037044829a4fcc64cacb94d4b1931d3ed91 | Fix reboot options (#256) | Eclo/nf-debugger,nanoframework/nf-debugger | nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/RebootOptions.cs | nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/RebootOptions.cs | //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
using System;
namespace nanoFramework.Tools.Debugger
{
/// <summary>
/// Reboot options for nanoFramework device.
/// </summary>
[Flags]
public enum RebootOptions
{
/// <summary>
/// Hard reboot CPU.
/// </summary>
#pragma warning disable S2346 // Need this to be 0 because of native implementation
NormalReboot = 0,
#pragma warning restore S2346 // Flags enumerations zero-value members should be named "None"
/// <summary>
/// Reboot and enter nanoBooter.
/// </summary>
EnterNanoBooter = 1,
/// <summary>
/// Reboot CLR only.
/// </summary>
ClrOnly = 2,
/// <summary>
/// Wait for debugger.
/// </summary>
WaitForDebugger = 4,
/// <summary>
/// Reboot and enter proprietary bootloader.
/// </summary>
EnterProprietaryBooter = 8,
};
}
| //
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation. All rights reserved.
// See LICENSE file in the project root for full license information.
//
namespace nanoFramework.Tools.Debugger
{
/// <summary>
/// Reboot options for nanoFramework device.
/// </summary>
public enum RebootOptions
{
/// <summary>
/// Hard reboot CPU.
/// </summary>
NormalReboot = 0,
/// <summary>
/// Reboot and enter nanoBooter.
/// </summary>
EnterNanoBooter = 1,
/// <summary>
/// Reboot CLR only.
/// </summary>
ClrOnly = 2,
/// <summary>
/// Wait for debugger.
/// </summary>
WaitForDebugger = 4,
/// <summary>
/// Reboot and enter proprietary bootloader.
/// </summary>
EnterProprietaryBooter = 5,
};
}
| apache-2.0 | C# |
7a839df4863e4d88ef45cb8d3d42fa91c0f3c901 | Remove FileVeresion attribute. | sullivac/handlers | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | // 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.*")]
using System.Reflection;
[assembly: AssemblyVersion("1.0.0.*")]
| // 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.*")]
using System.Reflection;
[assembly: AssemblyVersion("1.0.0.*")]
[assembly: AssemblyFileVersion("1.0.0.*")]
| mit | C# |
ee5b0e594506a518fc9b642dcf7080b4945c4658 | Make LocationChangedEventArgs readonly | EddieGarmon/GraduatedCylinder,EddieGarmon/GraduatedCylinder | Source/GraduatedCylinder.Geo/Shared/Geo/LocationChangedEventArgs.cs | Source/GraduatedCylinder.Geo/Shared/Geo/LocationChangedEventArgs.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace GraduatedCylinder.Geo
{
public class LocationChangedEventArgs
{
private readonly GeoPosition _position;
private readonly Heading _heading;
public LocationChangedEventArgs(GeoPosition position, Heading heading) {
_position = position;
_heading = heading;
}
public GeoPosition Position {
get { return _position; }
}
public Heading Heading {
get { return _heading; }
}
}
} | using System;
using System.Collections.Generic;
using System.Text;
namespace GraduatedCylinder.Geo
{
public class LocationChangedEventArgs
{
public LocationChangedEventArgs(GeoPosition position, Heading heading) {
Position = position;
Heading = heading;
}
public GeoPosition Position { get; set; }
public Heading Heading { get; set; }
}
}
| mit | C# |
0bd8ea6968155e7a43865413149ad13c40159873 | Add XML docs for DefaultSettingValueAttribute | NFig/NFig | NFig/DefaultValueAttribute.cs | NFig/DefaultValueAttribute.cs | using System;
namespace NFig
{
/// <summary>
/// This is the base class for all NFig attributes which specify default values, except for the <see cref="SettingAttribute"/> itself. This attribute is
/// abstract because you should provide the attributes which make sense for your individual setup. The subApp/tier/dataCenter parameters in inheriting
/// attributes should be strongly typed (rather than using "object"), and match the generic parameters used for the NFigStore and Settings object.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
/// <summary>
/// The value of the default being applied. This must be either a convertable string, or a literal value whose type matches that of the setting. For
/// encrypted settings, a default value must always be an encrypted string.
/// </summary>
public object DefaultValue { get; protected set; }
/// <summary>
/// The sub-app which the default is applicable to. If null or the zero-value, it is considered applicable to the "Global" app, as well as any sub-app
/// which does not have another default applied. If your application only uses the Global app (no sub-apps), then you should not include this parameter
/// in inheriting attributes.
/// </summary>
public object SubApp { get; protected set; }
/// <summary>
/// The deployment tier (e.g. local/dev/prod) which the default is applicable to. If null or the zero-value, the default is applicable to any tier.
/// </summary>
public object Tier { get; protected set; }
/// <summary>
/// The data center which the default is applicable to. If null or the zero-value, the default is applicable to any data center.
/// </summary>
public object DataCenter { get; protected set; }
/// <summary>
/// Specifies whether NFig should accept runtime overrides for this default. Note that this only applies to environments where this particular default
/// is the active default. For example, if you set an default for Tier=Prod/DataCenter=Any which DOES NOT allow defaults, and another default for
/// Tier=Prod/DataCenter=East which DOES allow overrides, then you will be able to set overrides in Prod/East, but you won't be able to set overrides
/// in any other data center.
/// </summary>
public bool AllowOverrides { get; protected set; } = true;
}
} | using System;
namespace NFig
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
public object DefaultValue { get; protected set; }
public object SubApp { get; protected set; }
public object Tier { get; protected set; }
public object DataCenter { get; protected set; }
public bool AllowOverrides { get; protected set; } = true;
}
} | mit | C# |
21b5f0afe07d6983d02ddc27c57595ed47671357 | Remove trace | davidebbo/WAWSDeploy,davidebbo/WAWSDeploy | WAWSDeploy/WebDeployHelper.cs | WAWSDeploy/WebDeployHelper.cs | using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Web.Deployment;
namespace WAWSDeploy
{
public class WebDeployHelper
{
public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile)
{
contentPath = Path.GetFullPath(contentPath);
var sourceBaseOptions = new DeploymentBaseOptions();
DeploymentBaseOptions destBaseOptions;
string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions);
// Publish the content to the remote site
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions))
{
// Note: would be nice to have an async flavor of this API...
return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions());
}
}
private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions)
{
var document = XDocument.Load(path);
var profile = document.Descendants("publishProfile").First();
string siteName = profile.Attribute("msdeploySite").Value;
deploymentBaseOptions = new DeploymentBaseOptions
{
ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName),
UserName = profile.Attribute("userName").Value,
Password = profile.Attribute("userPWD").Value,
AuthenticationType = "Basic"
};
return siteName;
}
}
}
| using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Web.Deployment;
namespace WAWSDeploy
{
public class WebDeployHelper
{
public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile)
{
contentPath = Path.GetFullPath(contentPath);
var sourceBaseOptions = new DeploymentBaseOptions();
DeploymentBaseOptions destBaseOptions;
string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions);
Trace.TraceInformation("Starting WebDeploy for {0}", Path.GetFileName(publishSettingsFile));
// Publish the content to the remote site
using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, contentPath, sourceBaseOptions))
{
// Note: would be nice to have an async flavor of this API...
return deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions());
}
}
private string ParsePublishSettings(string path, out DeploymentBaseOptions deploymentBaseOptions)
{
var document = XDocument.Load(path);
var profile = document.Descendants("publishProfile").First();
string siteName = profile.Attribute("msdeploySite").Value;
deploymentBaseOptions = new DeploymentBaseOptions
{
ComputerName = String.Format("https://{0}/msdeploy.axd?site={1}", profile.Attribute("publishUrl").Value, siteName),
UserName = profile.Attribute("userName").Value,
Password = profile.Attribute("userPWD").Value,
AuthenticationType = "Basic"
};
return siteName;
}
}
}
| apache-2.0 | C# |
1531682427bfa8d957664ab62b70bf87e0c0f687 | fix Game.cs | sfc-sdp/GameCanvas-Unity | Assets/Game.cs | Assets/Game.cs | using Sequence = System.Collections.IEnumerator;
/// <summary>
/// ゲームクラス。
/// 学生が編集すべきソースコードです。
/// </summary>
public sealed class Game : GameBase
{
// 変数の宣言
int sec = 0;
/// <summary>
/// 初期化処理
/// </summary>
public override void InitGame()
{
// キャンバスの大きさを設定します
gc.SetResolution(720, 1280);
}
/// <summary>
/// 動きなどの更新処理
/// </summary>
public override void UpdateGame()
{
// 起動からの経過時間を取得します
sec = (int)gc.TimeSinceStartup;
}
/// <summary>
/// 描画の処理
/// </summary>
public override void DrawGame()
{
// 画面を白で塗りつぶします
gc.ClearScreen();
// 0番の画像を描画します
gc.DrawImage(0, 0, 0);
// 黒の文字を描画します
gc.SetColor(0, 0, 0);
gc.SetFontSize(48);
gc.DrawString("この文字と青空の画像が", 40, 160);
gc.DrawString("見えていれば成功です", 40, 270);
gc.DrawRightString($"{sec}s", 630, 10);
}
}
|
using Sequence = System.Collections.IEnumerator;
/// <summary>
/// ゲームクラス。
/// 学生が編集すべきソースコードです。
/// </summary>
public sealed class Game : GameBase
{
// 変数の宣言
int sec = 0;
/// <summary>
/// 初期化処理
/// </summary>
public override void InitGame()
{
// キャンバスの大きさを設定します
gc.SetResolution(720, 1280);
}
/// <summary>
/// 動きなどの更新処理
/// </summary>
public override void UpdateGame()
{
// 起動からの経過時間を取得します
sec = (int)gc.TimeSinceStartup;
}
/// <summary>
/// 描画の処理
/// </summary>
public override void DrawGame()
{
// 画面を白で塗りつぶします
gc.ClearScreen();
// 0番の画像を描画します
gc.DrawImage(0, 0, 0);
// 黒の文字を描画します
gc.SetColor(0, 0, 0);
gc.SetFontSize(48);
gc.DrawString("この文字と青空の画像が", 40, 160);
gc.DrawString("見えていれば成功です", 40, 270);
gc.DrawRightString($"{sec}s", 630, 10);
}
}
| mit | C# |
4e2a81ac26ee88679c9693201c1352765383e745 | Make IAudioAdapter read-only | terrafx/terrafx | sources/Audio/IAudioAdapter.cs | sources/Audio/IAudioAdapter.cs | // Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
namespace TerraFX.Audio
{
/// <summary>An interface representing an audio adapter.</summary>
public interface IAudioAdapter
{
/// <summary>The type of device this adapter represents.</summary>
AudioDeviceType DeviceType { get; }
/// <summary>The name of the adapter.</summary>
string Name { get; }
/// <summary>The sample rate the adapter operates at.</summary>
int SampleRate { get; }
/// <summary>The number of bits in each sample this adapter operates at.</summary>
int BitDepth { get; }
/// <summary>The number of channels this adapter operates at.</summary>
int Channels { get; }
/// <summary>The endianness of the adapter.</summary>
/// <remarks>If the adapter operates in big endian mode (MSB first), this will be <c>true</c>; otherwise, it operates in little endian mode (LSB first) and will be <c>false</c>.</remarks>
bool IsBigEndian { get; }
}
}
| // Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
namespace TerraFX.Audio
{
/// <summary>An interface representing an audio adapter.</summary>
public interface IAudioAdapter
{
/// <summary>The type of device this adapter represents.</summary>
AudioDeviceType DeviceType { get; set; }
/// <summary>The name of the adapter.</summary>
string Name { get; set; }
/// <summary>The sample rate the adapter operates at.</summary>
int SampleRate { get; set; }
/// <summary>The number of bits in each sample this adapter operates at.</summary>
int BitDepth { get; set; }
/// <summary>The number of channels this adapter operates at.</summary>
int Channels { get; set; }
/// <summary>The endianness of the adapter.</summary>
/// <remarks>If the adapter operates in big endian mode (MSB first), this will be <c>true</c>; otherwise, it operates in little endian mode (LSB first) and will be <c>false</c>.</remarks>
bool IsBigEndian { get; set; }
}
}
| mit | C# |
1cd11ee00ea771b7da465eeab07cd7a889d7468f | Fix doc comments | tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Host/Security/IAuthenticationContextFactory.cs | src/Tgstation.Server.Host/Security/IAuthenticationContextFactory.cs | using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Security
{
/// <summary>
/// For creating and accessing authentication contexts
/// </summary>
public interface IAuthenticationContextFactory
{
/// <summary>
/// The <see cref="IAuthenticationContext"/> the <see cref="IAuthenticationContextFactory"/> created
/// </summary>
IAuthenticationContext CurrentAuthenticationContext { get; }
/// <summary>
/// Create an <see cref="IAuthenticationContext"/> to populate <see cref="CurrentAuthenticationContext"/>
/// </summary>
/// <param name="userId">The <see cref="Api.Models.Internal.User.Id"/> of the <see cref="IAuthenticationContext.User"/></param>
/// <param name="instanceId">The <see cref="Api.Models.Instance.Id"/> of the operation</param>
/// <param name="validAfter">The <see cref="DateTimeOffset"/> the resulting <see cref="IAuthenticationContext.User"/>'s password must be valid after</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
/// <returns>A <see cref="Task"/> representing the running operation</returns>
Task CreateAuthenticationContext(long userId, long? instanceId, DateTimeOffset validAfter, CancellationToken cancellationToken);
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
namespace Tgstation.Server.Host.Security
{
/// <summary>
/// For creating and accessing authentication contexts
/// </summary>
public interface IAuthenticationContextFactory
{
/// <summary>
/// The <see cref="IAuthenticationContext"/> the <see cref="IAuthenticationContextFactory"/> created
/// </summary>
IAuthenticationContext CurrentAuthenticationContext { get; }
/// <summary>
/// Create an <see cref="IAuthenticationContext"/> to populate <see cref="CurrentAuthenticationContext"/>
/// </summary>
/// <param name="userId">The <see cref="Api.Models.Internal.User.Id"/> of the <see cref="IAuthenticationContext.User"/></param>
/// <param name="instanceId">The <see cref="Api.Models.Instance.Id"/> of the operation</param>
/// <param name="validAfter">The <see cref="DateTimeOffset"/> the resulting <see cref="IAuthenticationContext.User"/>'s password must be valid after</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the operation</param>
/// <returns>A <see cref="Task"/> representing the running operation</returns>
Task CreateAuthenticationContext(long userId, long? instanceId, DateTimeOffset validBefore, CancellationToken cancellationToken);
}
}
| agpl-3.0 | C# |
994c10ce0626b1b13a7c6391874733a83d8c6358 | Update SampleConfiguration.cs | PanagiotisDrakatos/Universal-Encryption-Channel,PanagiotisDrakatos/Universal-Encryption-Channel | SecureUWPChannel/SecureUWPChannel/Configuration/SampleConfiguration.cs | SecureUWPChannel/SecureUWPChannel/Configuration/SampleConfiguration.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
namespace SecureUWPChannel.Prooperties
{
public class SampleConfiguration
{
//socket properties
public static String ConnectionPort = "5555";
public static int MaxConnections = 100;
public static int timeout = 4000;
public static String Host = "localhost";
//encryption properties
public static String strSecret = "PutAStrongPassword";
public static String MacAlg = MacAlgorithmNames.HmacSha256;
//Put your Message to send to server
public static String Messages = "Hello Server :D";
//for more info check https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
//g^x mod p
//However, its very unlikely that anyone else listening on the channel
//can calculate the key, since the calculation of discrete logarithms under
//field arithmetic is very hard (see Galois Fields)
//Prime numbers machine generator
public static String exponent = "95632573769194905177488615436919317766582673020891665265323677789504596581977";
public static String modulus = "81554351438297688582888558141846154981885664956959015742153749206820791432251";
public const string SampleBackgroundTaskEntryPoint = "Tasks.SampleBackgroundTask";
public const string SampleBackgroundTaskName = "SampleBackgroundTask";
public static string SampleBackgroundTaskProgress = "";
public static bool SampleBackgroundTaskRegistered = false;
public const string TimeTriggeredTaskName = "TimeTriggeredTask";
public static string TimeTriggeredTaskProgress = "";
public static bool TimeTriggeredTaskRegistered = false;
public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";
public static string ApplicationTriggerTaskProgress = "";
public static string ApplicationTriggerTaskResult = "";
public static bool ApplicationTriggerTaskRegistered = false;
public static bool TaskRequiresBackgroundAccess(String name)
{
if ((name == TimeTriggeredTaskName) ||
(name == ApplicationTriggerTaskName))
{
return true;
}
else
{
return false;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
using Windows.Security.Cryptography.Core;
using Windows.Storage;
namespace SecureUWPChannel.Prooperties
{
public class SampleConfiguration
{
//socket properties
public static String ConnectionPort = "5555";
public static int MaxConnections = 100;
public static int timeout = 4000;
public static String Host = "localhost";
//encryption properties
public static String DefaultCAkey = "s/L6D2CgMQ+qDKCJ6FjZ/w==";//Certificate from Trusted ca
public static String strSecret = "PutAStrongPassword";
public static String MacAlg = MacAlgorithmNames.HmacSha256;
//Put your Message to send to server
public static String Messages = "Hello Server :D";
//for more info check https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange
//g^x mod p
//However, its very unlikely that anyone else listening on the channel
//can calculate the key, since the calculation of discrete logarithms under
//field arithmetic is very hard (see Galois Fields)
//Prime numbers machine generator
public static String exponent = "95632573769194905177488615436919317766582673020891665265323677789504596581977";
public static String modulus = "81554351438297688582888558141846154981885664956959015742153749206820791432251";
public const string SampleBackgroundTaskEntryPoint = "Tasks.SampleBackgroundTask";
public const string SampleBackgroundTaskName = "SampleBackgroundTask";
public static string SampleBackgroundTaskProgress = "";
public static bool SampleBackgroundTaskRegistered = false;
public const string TimeTriggeredTaskName = "TimeTriggeredTask";
public static string TimeTriggeredTaskProgress = "";
public static bool TimeTriggeredTaskRegistered = false;
public const string ApplicationTriggerTaskName = "ApplicationTriggerTask";
public static string ApplicationTriggerTaskProgress = "";
public static string ApplicationTriggerTaskResult = "";
public static bool ApplicationTriggerTaskRegistered = false;
public static bool TaskRequiresBackgroundAccess(String name)
{
if ((name == TimeTriggeredTaskName) ||
(name == ApplicationTriggerTaskName))
{
return true;
}
else
{
return false;
}
}
}
}
| mit | C# |
f41e51024e5021505335652bab6ee2b665ecc6da | Document the purpose of [ExternalEndpoint] (#1197) | mgmccarthy/allReady,anobleperson/allReady,gitChuckD/allReady,timstarbuck/allReady,stevejgordon/allReady,pranap/allReady,VishalMadhvani/allReady,colhountech/allReady,dpaquette/allReady,GProulx/allReady,forestcheng/allReady,HamidMosalla/allReady,HamidMosalla/allReady,GProulx/allReady,chinwobble/allReady,jonatwabash/allReady,MisterJames/allReady,VishalMadhvani/allReady,bcbeatty/allReady,jonatwabash/allReady,forestcheng/allReady,binaryjanitor/allReady,enderdickerson/allReady,dpaquette/allReady,HTBox/allReady,shanecharles/allReady,binaryjanitor/allReady,anobleperson/allReady,arst/allReady,MisterJames/allReady,timstarbuck/allReady,bcbeatty/allReady,c0g1t8/allReady,stevejgordon/allReady,forestcheng/allReady,c0g1t8/allReady,JowenMei/allReady,mipre100/allReady,pranap/allReady,mipre100/allReady,bcbeatty/allReady,gitChuckD/allReady,GProulx/allReady,colhountech/allReady,BillWagner/allReady,arst/allReady,VishalMadhvani/allReady,jonatwabash/allReady,VishalMadhvani/allReady,shanecharles/allReady,shanecharles/allReady,gitChuckD/allReady,binaryjanitor/allReady,JowenMei/allReady,HTBox/allReady,HTBox/allReady,pranap/allReady,colhountech/allReady,bcbeatty/allReady,mipre100/allReady,forestcheng/allReady,mgmccarthy/allReady,JowenMei/allReady,MisterJames/allReady,c0g1t8/allReady,colhountech/allReady,stevejgordon/allReady,stevejgordon/allReady,dpaquette/allReady,enderdickerson/allReady,dpaquette/allReady,timstarbuck/allReady,BillWagner/allReady,HamidMosalla/allReady,shanecharles/allReady,MisterJames/allReady,arst/allReady,enderdickerson/allReady,binaryjanitor/allReady,BillWagner/allReady,BillWagner/allReady,pranap/allReady,gitChuckD/allReady,mgmccarthy/allReady,chinwobble/allReady,mgmccarthy/allReady,timstarbuck/allReady,anobleperson/allReady,c0g1t8/allReady,arst/allReady,mipre100/allReady,enderdickerson/allReady,chinwobble/allReady,jonatwabash/allReady,JowenMei/allReady,HTBox/allReady,GProulx/allReady,chinwobble/allReady,anobleperson/allReady,HamidMosalla/allReady | AllReadyApp/Web-App/AllReady/Attributes/ExternalEndpointAttribute.cs | AllReadyApp/Web-App/AllReady/Attributes/ExternalEndpointAttribute.cs | using System;
namespace AllReady.Attributes
{
/// <summary>
/// This attribute tells the GlobalControllerTests that the method doesn't need a [ValidateAntiForgeryToken] attribute because the method is designed to be consumed by an external API such as the mobile app.
/// </summary>
public class ExternalEndpointAttribute : Attribute
{
}
}
| using System;
namespace AllReady.Attributes
{
public class ExternalEndpointAttribute : Attribute
{
}
} | mit | C# |
a989ce0db9fa86779b528d20230c5f1e69205d6f | test for where | christiandelbianco/monitor-table-change-with-sqltabledependency | TableDependency.Tests/TableDependency.DevelopmentTests/WhereTests.cs | TableDependency.Tests/TableDependency.DevelopmentTests/WhereTests.cs | using System;
using System.Linq.Expressions;
namespace ConsoleApplicationSqlServer
{
public partial class Program
{
public static void TestWhere()
{
//Expression<Func<Customers, bool>> query = u =>
// //u.CompanyName.EndsWith("a")
// u.CompanyName.Substring(1, 4).Trim().Length > 3
// //&& u.CompanyName.Trim() == "WW"
// //&& u.CompanyName.Length > 10
// //&& u.CompanyName == ""
// //&& u.CompanyName == string.Empty
// //&& u.CompanyName.Contains("WW")
// //&& u.Id > 10;
// ;
//var stringSql = new Where().Translate(query);
//Console.WriteLine(stringSql);
//Console.ReadKey();
}
}
}
| using System;
using System.Linq.Expressions;
using TableDependency.SqlClient.Where;
namespace ConsoleApplicationSqlServer
{
public partial class Program
{
public static void TestWhere()
{
Expression<Func<Customers, bool>> query = u =>
//u.CompanyName.EndsWith("a")
u.CompanyName.Substring(1, 4).Trim().Length > 3
//&& u.CompanyName.Trim() == "WW"
//&& u.CompanyName.Length > 10
//&& u.CompanyName == ""
//&& u.CompanyName == string.Empty
//&& u.CompanyName.Contains("WW")
//&& u.Id > 10;
;
var stringSql = new Where().Translate(query);
Console.WriteLine(stringSql);
Console.ReadKey();
}
}
}
| mit | C# |
c12c7de949d6b7cd680ec3c75edc4b2b6e410fae | Check for specific bit now to check if a game is downloaded at the moment | akorb/SteamShutdown | SteamShutdown/App.cs | SteamShutdown/App.cs | namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public bool IsDownloading => CheckDownloading(State);
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public static bool CheckDownloading(int appState)
{
// The second bit defines if anything for the app needs to be downloaded
// Doesn't matter if queued, download running and so on
return IsBitSet(appState, 1);
}
public override string ToString()
{
return Name;
}
private static bool IsBitSet(int b, int pos)
{
return (b & (1 << pos)) != 0;
}
}
}
| using System;
namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
public bool IsDownloading
{
get { return CheckDownloading(State); }
}
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
/// <param name="appState"></param>
/// <returns></returns>
public static bool CheckDownloading(int appState)
{
// 6: In queue for update
// 1026: In queue
// 1042: download running
return appState == 6 || appState == 1026 || appState == 1042 || appState == 1062 || appState == 1030;
}
public override string ToString()
{
return Name;
}
}
}
| mit | C# |
3bae24ce80b2b70ac766f111167591ca22c75e07 | Update version number | yas-mnkornym/TaihaToolkit | source/TaihaToolkit.Core/Properties/AssemblyInfo.cs | source/TaihaToolkit.Core/Properties/AssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TaihaToolkit.Core")]
[assembly: AssemblyDescription("大破してすまない")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("スタジオ大破")]
[assembly: AssemblyProduct("TaihaToolkit.Core")]
[assembly: AssemblyCopyright("Copyright (C) Studiotaiha 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("ja")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.30.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("TaihaToolkit.Core")]
[assembly: AssemblyDescription("大破してすまない")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("スタジオ大破")]
[assembly: AssemblyProduct("TaihaToolkit.Core")]
[assembly: AssemblyCopyright("Copyright (C) Studiotaiha 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("ja")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// リビジョン
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.19.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
079302a1233d64ee4f738ea6aac464ffa1ef7a7b | Fix bug in AnimatorKeyFrame.ValueProperty registration. | wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex | src/Avalonia.Animation/AnimatorKeyFrame.cs | src/Avalonia.Animation/AnimatorKeyFrame.cs | using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Avalonia.Metadata;
using Avalonia.Collections;
using Avalonia.Data;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
/// <summary>
/// Defines a KeyFrame that is used for
/// <see cref="Animator{T}"/> objects.
/// </summary>
public class AnimatorKeyFrame : AvaloniaObject
{
public static readonly DirectProperty<AnimatorKeyFrame, object> ValueProperty =
AvaloniaProperty.RegisterDirect<AnimatorKeyFrame, object>(nameof(Value), k => k.Value, (k, v) => k.Value = v);
public AnimatorKeyFrame()
{
}
public AnimatorKeyFrame(Type animatorType, Cue cue)
{
AnimatorType = animatorType;
Cue = cue;
}
public Type AnimatorType { get; }
public Cue Cue { get; }
public AvaloniaProperty Property { get; private set; }
private object _value;
public object Value
{
get => _value;
set => SetAndRaise(ValueProperty, ref _value, value);
}
public IDisposable BindSetter(IAnimationSetter setter, Animatable targetControl)
{
Property = setter.Property;
var value = setter.Value;
if (value is IBinding binding)
{
return this.Bind(ValueProperty, binding, targetControl);
}
else
{
return this.Bind(ValueProperty, ObservableEx.SingleValue(value).ToBinding(), targetControl);
}
}
public T GetTypedValue<T>()
{
var typeConv = TypeDescriptor.GetConverter(typeof(T));
if (Value == null)
{
throw new ArgumentNullException($"KeyFrame value can't be null.");
}
if (!typeConv.CanConvertTo(Value.GetType()))
{
throw new InvalidCastException($"KeyFrame value doesnt match property type.");
}
return (T)typeConv.ConvertTo(Value, typeof(T));
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using Avalonia.Metadata;
using Avalonia.Collections;
using Avalonia.Data;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
/// <summary>
/// Defines a KeyFrame that is used for
/// <see cref="Animator{T}"/> objects.
/// </summary>
public class AnimatorKeyFrame : AvaloniaObject
{
public static readonly DirectProperty<AnimatorKeyFrame, object> ValueProperty =
AvaloniaProperty.RegisterDirect<AnimatorKeyFrame, object>(nameof(Value), k => k._value, (k, v) => k._value = v);
public AnimatorKeyFrame()
{
}
public AnimatorKeyFrame(Type animatorType, Cue cue)
{
AnimatorType = animatorType;
Cue = cue;
}
public Type AnimatorType { get; }
public Cue Cue { get; }
public AvaloniaProperty Property { get; private set; }
private object _value;
public object Value
{
get => _value;
set => SetAndRaise(ValueProperty, ref _value, value);
}
public IDisposable BindSetter(IAnimationSetter setter, Animatable targetControl)
{
Property = setter.Property;
var value = setter.Value;
if (value is IBinding binding)
{
return this.Bind(ValueProperty, binding, targetControl);
}
else
{
return this.Bind(ValueProperty, ObservableEx.SingleValue(value).ToBinding(), targetControl);
}
}
public T GetTypedValue<T>()
{
var typeConv = TypeDescriptor.GetConverter(typeof(T));
if (Value == null)
{
throw new ArgumentNullException($"KeyFrame value can't be null.");
}
if (!typeConv.CanConvertTo(Value.GetType()))
{
throw new InvalidCastException($"KeyFrame value doesnt match property type.");
}
return (T)typeConv.ConvertTo(Value, typeof(T));
}
}
}
| mit | C# |
17aec4aaaf8dc3e4cd4fa5a7b298ce315018f6b1 | Implement the GetRecordMutations method for SQL Server | openchain/openchain | src/Openchain.SqlServer/SqlServerLedger.cs | src/Openchain.SqlServer/SqlServerLedger.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;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Openchain.Ledger;
namespace Openchain.SqlServer
{
public class SqlServerLedger : SqlServerStorageEngine, ILedgerQueries, ILedgerIndexes
{
private readonly int instanceId;
public SqlServerLedger(string connectionString, int instanceId, TimeSpan commandTimeout)
: base(connectionString, instanceId, commandTimeout)
{
this.instanceId = instanceId;
}
public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
{
return await ExecuteQuery<Record>(
"EXEC [Openchain].[GetRecordsFromKeyPrefix] @instance, @prefix;",
reader => new Record(new ByteString((byte[])reader[0]), new ByteString((byte[])reader[1]), new ByteString((byte[])reader[2])),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["prefix"] = prefix.ToByteArray()
});
}
public async Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
{
return await ExecuteQuery<ByteString>(
"EXEC [Openchain].[GetRecordMutations] @instance, @recordKey;",
reader => new ByteString((byte[])reader[0]),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["recordKey"] = recordKey.ToByteArray()
});
}
public Task<ByteString> GetTransaction(ByteString mutationHash)
{
throw new NotImplementedException();
}
public Task<IReadOnlyList<Record>> GetAllRecords(RecordType type, string name)
{
throw new NotImplementedException();
}
}
}
| // 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;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Openchain.Ledger;
namespace Openchain.SqlServer
{
public class SqlServerLedger : SqlServerStorageEngine, ILedgerQueries, ILedgerIndexes
{
private readonly int instanceId;
public SqlServerLedger(string connectionString, int instanceId, TimeSpan commandTimeout)
: base(connectionString, instanceId, commandTimeout)
{
this.instanceId = instanceId;
}
public async Task<IReadOnlyList<Record>> GetKeyStartingFrom(ByteString prefix)
{
return await ExecuteQuery<Record>(
"EXEC [Openchain].[GetRecordsFromKeyPrefix] @instance, @prefix;",
reader => new Record(new ByteString((byte[])reader[0]), new ByteString((byte[])reader[1]), new ByteString((byte[])reader[2])),
new Dictionary<string, object>()
{
["instance"] = this.instanceId,
["prefix"] = prefix.ToByteArray()
});
}
public Task<IReadOnlyList<ByteString>> GetRecordMutations(ByteString recordKey)
{
throw new NotImplementedException();
}
public Task<ByteString> GetTransaction(ByteString mutationHash)
{
throw new NotImplementedException();
}
public Task<IReadOnlyList<Record>> GetAllRecords(RecordType type, string name)
{
throw new NotImplementedException();
}
}
}
| apache-2.0 | C# |
538b084b6f4da33c56c4da4e7589e2c0272f58f4 | Comment for dev | Nick-Lucas/EntryPoint,Nick-Lucas/EntryPoint,Nick-Lucas/EntryPoint | src/EntryPoint/Internals/ArgumentArrayExtensions.cs | src/EntryPoint/Internals/ArgumentArrayExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint.Internals {
internal static class ArgumentArrayExtensions {
// Determines if a given arg array element is a - option
public static bool IsSingleDash(this string arg) {
return arg.StartsWith(EntryPointApi.DASH_SINGLE)
&& !arg.StartsWith(EntryPointApi.DASH_DOUBLE);
}
// Returns the array index of a given - option, or -1
public static int SingleDashIndex(this string[] args, char argName) {
return Array.FindIndex(args, s =>
s.IsSingleDash()
&& s.Contains(argName));
}
// Returns the array index of a given -- option, or -1
public static int DoubleDashIndex(this string[] args, string argName) {
return Array.FindIndex(args, s =>
s.StartsWith(EntryPointApi.DASH_DOUBLE + argName, StringComparison.CurrentCultureIgnoreCase));
}
// Determines if an option is used at all in the arguments list
public static bool OptionExists(this string[] args, BaseOptionAttribute option) {
return option.SingleDashIndex(args) >= 0
|| option.DoubleDashIndex(args) >= 0;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EntryPoint.Internals {
internal static class ArgumentArrayExtensions {
// Determines if a given arg array element is a - option
public static bool IsSingleDash(this string arg) {
return arg.StartsWith(EntryPointApi.DASH_SINGLE)
&& !arg.StartsWith(EntryPointApi.DASH_DOUBLE);
}
// Returns the array index of a given - option, or -1
public static int SingleDashIndex(this string[] args, char argName) {
return Array.FindIndex(args, s =>
s.IsSingleDash()
&& s.Contains(argName));
}
// Returns the array index of a given -- option, or -1
public static int DoubleDashIndex(this string[] args, string argName) {
return Array.FindIndex(args, s =>
s.StartsWith(EntryPointApi.DASH_DOUBLE + argName, StringComparison.CurrentCultureIgnoreCase));
}
public static bool OptionExists(this string[] args, BaseOptionAttribute option) {
return option.SingleDashIndex(args) >= 0
|| option.DoubleDashIndex(args) >= 0;
}
}
}
| mit | C# |
23c0aa2b183c8902e1ccde2fae9730006e8c701a | Make RemoveSession virtual. | yungtechboy1/MiNET,InPvP/MiNET,MiPE-JP/RaNET | src/MiNET/MiNET/SessionManager.cs | src/MiNET/MiNET/SessionManager.cs | using System.Collections.Concurrent;
using System.Collections.Generic;
using MiNET.Net;
namespace MiNET
{
public class SessionManager
{
private ConcurrentDictionary<UUID, Session> _sessions = new ConcurrentDictionary<UUID, Session>();
public virtual Session FindSession(Player player)
{
Session session;
_sessions.TryGetValue(player.ClientUuid, out session);
return session;
}
public virtual Session CreateSession(Player player)
{
_sessions.TryAdd(player.ClientUuid, new Session(player));
return FindSession(player);
}
public virtual void SaveSession(Session session)
{
}
public virtual void RemoveSession(Session session)
{
if (session.Player == null) return;
if (session.Player.ClientUuid == null) return;
_sessions.TryRemove(session.Player.ClientUuid, out session);
}
}
public class Session : Dictionary<string, object>
{
public Player Player { get; set; }
public Session(Player player)
{
Player = player;
}
}
} | using System.Collections.Concurrent;
using System.Collections.Generic;
using MiNET.Net;
namespace MiNET
{
public class SessionManager
{
private ConcurrentDictionary<UUID, Session> _sessions = new ConcurrentDictionary<UUID, Session>();
public virtual Session FindSession(Player player)
{
Session session;
_sessions.TryGetValue(player.ClientUuid, out session);
return session;
}
public virtual Session CreateSession(Player player)
{
_sessions.TryAdd(player.ClientUuid, new Session(player));
return FindSession(player);
}
public virtual void SaveSession(Session session)
{
}
public void RemoveSession(Session session)
{
if (session.Player == null) return;
if (session.Player.ClientUuid == null) return;
_sessions.TryRemove(session.Player.ClientUuid, out session);
}
}
public class Session : Dictionary<string, object>
{
public Player Player { get; set; }
public Session(Player player)
{
Player = player;
}
}
} | mpl-2.0 | C# |
2a35aec7a66d63c3298d2d89304148b8c8b9b5dc | Fix a bug where it didn't read .binlog files correctly. | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogger/BinaryLog.cs | src/StructuredLogger/BinaryLog.cs | using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
structuredLogger.Shutdown();
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
| using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
| mit | C# |
8db9c9714facaba021d5e2c3126cef7566fcfad0 | Append IIS queues with worker PID. | WaveServiceBus/WaveServiceBus | src/Wave.ServiceHosting.IIS/IISQueueNameResolver.cs | src/Wave.ServiceHosting.IIS/IISQueueNameResolver.cs | /* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}_{2}",
base.GetPrimaryQueueName(),
Environment.MachineName,
Process.GetCurrentProcess().Id
);
}
}
}
| /* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}",
base.GetPrimaryQueueName(),
Environment.MachineName);
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.