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 |
|---|---|---|---|---|---|---|---|---|
1653d236a6b6e13a430b4c5b4dad5034e0c0e051 | improve tests not found error message | TryItOnline/TioTests | Program.cs | Program.cs | using System;
using System.IO;
using Newtonsoft.Json;
namespace TioTests
{
public class Program
{
public static void Main(string[] args)
{
try
{
Execute(args);
}
catch (Exception e)
{
Logger.LogLine("Unexpected error: " + e);
Environment.Exit(-1);
}
}
private static void Execute(string[] args)
{
string configPath = "config.json";
Config config = File.Exists(configPath) ?
JsonConvert.DeserializeObject<Config>(File.ReadAllText(configPath)) :
new Config { TrimWhitespacesFromResults = true, DisplayDebugInfoOnError = true, UseConsoleCodes = true };
CommandLine.ApplyCommandLineArguments(args, config);
if (Directory.Exists(config.Test))
{
string[] files = Directory.GetFiles(config.Test, "*.json");
Array.Sort(files);
int counter = 0;
foreach (string file in files)
{
//Logger.Log($"[{++counter}/{files.Length}] ");
TestRunner.RunTest(file, config, $"[{++counter}/{files.Length}]");
}
}
else if (File.Exists(config.Test))
{
TestRunner.RunTest(config.Test, config,"[1/1]");
}
else if (File.Exists(config.Test + ".json"))
{
TestRunner.RunTest(config.Test + ".json", config,"1/1");
}
else
{
Logger.LogLine($"Tests '{config.Test}' not found");
}
}
}
}
| using System;
using System.IO;
using Newtonsoft.Json;
namespace TioTests
{
public class Program
{
public static void Main(string[] args)
{
try
{
Execute(args);
}
catch (Exception e)
{
Logger.LogLine("Unexpected error: " + e);
Environment.Exit(-1);
}
}
private static void Execute(string[] args)
{
string configPath = "config.json";
Config config = File.Exists(configPath) ?
JsonConvert.DeserializeObject<Config>(File.ReadAllText(configPath)) :
new Config { TrimWhitespacesFromResults = true, DisplayDebugInfoOnError = true, UseConsoleCodes = true };
CommandLine.ApplyCommandLineArguments(args, config);
if (Directory.Exists(config.Test))
{
string[] files = Directory.GetFiles(config.Test, "*.json");
Array.Sort(files);
int counter = 0;
foreach (string file in files)
{
//Logger.Log($"[{++counter}/{files.Length}] ");
TestRunner.RunTest(file, config, $"[{++counter}/{files.Length}]");
}
}
else if (File.Exists(config.Test))
{
TestRunner.RunTest(config.Test, config,"[1/1]");
}
else if (File.Exists(config.Test + ".json"))
{
TestRunner.RunTest(config.Test + ".json", config,"1/1");
}
else
{
Logger.LogLine($"{config.Test} not found");
}
}
}
}
| mit | C# |
3c05b20dc815dc7d986645c75818f33611825709 | make non-async | jonsequitur/PocketLogger | Pocket.Logger/For.Xunit/Tests/WhatIsLogged.cs | Pocket.Logger/For.Xunit/Tests/WhatIsLogged.cs | using FluentAssertions;
using System.Linq;
using Xunit;
namespace Pocket.For.Xunit.Tests
{
public class WhatIsLogged
{
[Fact]
public void Start_events_are_logged_for_each_test()
{
var attribute = new LogToPocketLoggerAttribute();
var methodInfo = GetType().GetMethod(nameof(Start_events_are_logged_for_each_test));
attribute.Before(methodInfo);
var log = TestLog.Current.Text;
attribute.After(methodInfo);
log.First()
.Should()
.Contain($"[{GetType().Name}.{nameof(Start_events_are_logged_for_each_test)}] ▶");
}
[Fact]
public void Stop_events_are_logged_for_each_test()
{
var attribute = new LogToPocketLoggerAttribute();
var methodInfo = GetType().GetMethod(nameof(Stop_events_are_logged_for_each_test));
attribute.Before(methodInfo);
var log = TestLog.Current;
attribute.After(methodInfo);
log.Text
.Last()
.Should()
.Match($"*[{GetType().Name}.{nameof(Stop_events_are_logged_for_each_test)}] ⏹ (*ms)*");
}
}
}
| using System.Reflection;
using FluentAssertions;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace Pocket.For.Xunit.Tests
{
public class WhatIsLogged
{
[Fact]
public void Start_events_are_logged_for_each_test()
{
var attribute = new LogToPocketLoggerAttribute();
var methodInfo = GetType().GetMethod(nameof(Start_events_are_logged_for_each_test));
attribute.Before(methodInfo);
var log = TestLog.Current.Text;
attribute.After(methodInfo);
log.First()
.Should()
.Contain($"[{GetType().Name}.{nameof(Start_events_are_logged_for_each_test)}] ▶");
}
[Fact]
public async Task Stop_events_are_logged_for_each_test()
{
var attribute = new LogToPocketLoggerAttribute();
var methodInfo = GetType().GetMethod(nameof(Stop_events_are_logged_for_each_test));
attribute.Before(methodInfo);
var log = TestLog.Current;
attribute.After(methodInfo);
log.Text
.Last()
.Should()
.Match($"*[{GetType().Name}.{nameof(Stop_events_are_logged_for_each_test)}] ⏹ (*ms)*");
}
}
}
| mit | C# |
ebc588a0e01779778e8f0a2b8184cfe44651e6c0 | improve netherlands provider | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Nager.Date/PublicHolidays/NetherlandsProvider.cs | Nager.Date/PublicHolidays/NetherlandsProvider.cs | using Nager.Date.Contract;
using Nager.Date.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Nager.Date.PublicHolidays
{
public class NetherlandsProvider : IPublicHolidayProvider
{
public IEnumerable<PublicHoliday> Get(DateTime easterSunday, int year)
{
//Netherlands
//https://en.wikipedia.org/wiki/Public_holidays_in_the_Netherlands
var countryCode = CountryCode.NL;
#region King's Day is Sunday fallback
var kingsDay = 27;
var kingsDate = new DateTime(year, 4, kingsDay);
if (kingsDate.DayOfWeek == DayOfWeek.Sunday)
{
kingsDay = 26;
}
#endregion
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(1, 1, year, "Nieuwjaarsdag", "New Year's Day", countryCode, 1967));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Goede Vrijdag", "Good Friday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), " Pasen", "Easter Monday", countryCode, 1642));
items.Add(new PublicHoliday(kingsDay, 4, year, "Koningsdag", "King's Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(39), "Hemelvaartsdag", "Ascension Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(50), "Pinksteren", "Whit Monday", countryCode));
items.Add(new PublicHoliday(25, 12, year, "Eerste kerstdag", "Christmas Day", countryCode));
items.Add(new PublicHoliday(26, 12, year, "Tweede kerstdag", "Christmas Day", countryCode));
#region Liberation Day
var liberationDay = new PublicHoliday(5, 5, year, "Bevrijdingsdag", "Liberation Day", countryCode, 1945);
if (year >= 1990)
{
//in 1990, the day was declared to be a national holiday
items.Add(liberationDay);
}
else if (year >= 1945)
{
if (year % 5 == 0)
{
items.Add(liberationDay);
}
}
#endregion
return items.OrderBy(o => o.Date);
}
}
}
| using Nager.Date.Contract;
using Nager.Date.Model;
using System;
using System.Collections.Generic;
namespace Nager.Date.PublicHolidays
{
public class NetherlandsProvider : IPublicHolidayProvider
{
public IEnumerable<PublicHoliday> Get(DateTime easterSunday, int year)
{
//Netherlands
var countryCode = CountryCode.NL;
var items = new List<PublicHoliday>();
items.Add(new PublicHoliday(1, 1, year, "Nieuwjaarsdag", "New Year's Day", countryCode, 1967));
items.Add(new PublicHoliday(easterSunday.AddDays(-2), "Goede Vrijdag", "Good Friday", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(1), " Pasen", "Easter Monday", countryCode, 1642));
items.Add(new PublicHoliday(27, 4, year, "Koningsdag", "King's Day", countryCode));
items.Add(new PublicHoliday(5, 5, year, "Bevrijdingsdag", "Liberation Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(39), "Hemelvaartsdag", "Ascension Day", countryCode));
items.Add(new PublicHoliday(easterSunday.AddDays(50), "Pinksteren", "Whit Monday", countryCode));
items.Add(new PublicHoliday(25, 12, year, "Weihnachten", "Christmas Day", countryCode));
items.Add(new PublicHoliday(26, 12, year, "TweedeKerstdag", "Boxing Day", countryCode));
return items;
}
}
}
| mit | C# |
ab0c9710574b84c7372440e1ef33c25aaeaf93a0 | Make sealed. | gafter/roslyn,DustinCampbell/roslyn,sharwell/roslyn,physhi/roslyn,genlu/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,gafter/roslyn,nguerrera/roslyn,xasx/roslyn,tmat/roslyn,aelij/roslyn,dpoeschl/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,xasx/roslyn,reaction1989/roslyn,nguerrera/roslyn,mavasani/roslyn,aelij/roslyn,abock/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,shyamnamboodiripad/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,davkean/roslyn,tmat/roslyn,xasx/roslyn,jmarolf/roslyn,physhi/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,davkean/roslyn,AlekseyTs/roslyn,sharwell/roslyn,jcouv/roslyn,genlu/roslyn,jcouv/roslyn,mavasani/roslyn,abock/roslyn,stephentoub/roslyn,jmarolf/roslyn,eriawan/roslyn,aelij/roslyn,bartdesmet/roslyn,gafter/roslyn,MichalStrehovsky/roslyn,mgoertz-msft/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,stephentoub/roslyn,dotnet/roslyn,diryboy/roslyn,KevinRansom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,agocke/roslyn,shyamnamboodiripad/roslyn,dpoeschl/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,brettfo/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,agocke/roslyn,wvdd007/roslyn,brettfo/roslyn,physhi/roslyn,agocke/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,genlu/roslyn,stephentoub/roslyn,heejaechang/roslyn,DustinCampbell/roslyn,davkean/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,heejaechang/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,tannergooding/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,abock/roslyn,panopticoncentral/roslyn,tmat/roslyn,dotnet/roslyn,eriawan/roslyn,diryboy/roslyn,VSadov/roslyn,panopticoncentral/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,eriawan/roslyn,brettfo/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,tannergooding/roslyn | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedLanguage.cs | src/Workspaces/Core/Portable/EmbeddedLanguages/RegularExpressions/LanguageServices/RegexEmbeddedLanguage.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices
{
internal sealed class RegexEmbeddedLanguage : IEmbeddedLanguage
{
public int StringLiteralKind { get; }
public ISyntaxFactsService SyntaxFacts { get; }
public ISemanticFactsService SemanticFacts { get; }
public IVirtualCharService VirtualCharService { get; }
public RegexEmbeddedLanguage(
int stringLiteralKind,
ISyntaxFactsService syntaxFacts,
ISemanticFactsService semanticFacts,
IVirtualCharService virtualCharService)
{
StringLiteralKind = stringLiteralKind;
SyntaxFacts = syntaxFacts;
SemanticFacts = semanticFacts;
VirtualCharService = virtualCharService;
BraceMatcher = new RegexEmbeddedBraceMatcher(this);
Classifier = new RegexEmbeddedClassifier(this);
Highlighter = new RegexEmbeddedHighlighter(this);
DiagnosticAnalyzer = new RegexDiagnosticAnalyzer(this);
}
public IEmbeddedBraceMatcher BraceMatcher { get; }
public IEmbeddedClassifier Classifier { get; }
public IEmbeddedHighlighter Highlighter { get; }
public IEmbeddedDiagnosticAnalyzer DiagnosticAnalyzer { get; }
public IEmbeddedCodeFixProvider CodeFixProvider { get; }
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.EmbeddedLanguages.LanguageServices;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
using Microsoft.CodeAnalysis.LanguageServices;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions.LanguageServices
{
internal class RegexEmbeddedLanguage : IEmbeddedLanguage
{
public int StringLiteralKind { get; }
public ISyntaxFactsService SyntaxFacts { get; }
public ISemanticFactsService SemanticFacts { get; }
public IVirtualCharService VirtualCharService { get; }
public RegexEmbeddedLanguage(
int stringLiteralKind,
ISyntaxFactsService syntaxFacts,
ISemanticFactsService semanticFacts,
IVirtualCharService virtualCharService)
{
StringLiteralKind = stringLiteralKind;
SyntaxFacts = syntaxFacts;
SemanticFacts = semanticFacts;
VirtualCharService = virtualCharService;
BraceMatcher = new RegexEmbeddedBraceMatcher(this);
Classifier = new RegexEmbeddedClassifier(this);
Highlighter = new RegexEmbeddedHighlighter(this);
DiagnosticAnalyzer = new RegexDiagnosticAnalyzer(this);
}
public IEmbeddedBraceMatcher BraceMatcher { get; }
public IEmbeddedClassifier Classifier { get; }
public IEmbeddedHighlighter Highlighter { get; }
public IEmbeddedDiagnosticAnalyzer DiagnosticAnalyzer { get; }
public IEmbeddedCodeFixProvider CodeFixProvider { get; }
}
}
| mit | C# |
e498be24e1deedab2d3c7be2519a8fdb7676dee8 | Fix random IP NRE | Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder | PathfinderAPI/BaseGameFixes/RandomIPNoRepeats.cs | PathfinderAPI/BaseGameFixes/RandomIPNoRepeats.cs | using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes
{
[HarmonyPatch]
internal static class RandomIPNoRepeats
{
[HarmonyPrefix]
[HarmonyPatch(typeof(NetworkMap), nameof(NetworkMap.generateRandomIP))]
internal static bool GenerateRandomIPReplacement(out string __result)
{
while (true)
{
var ip = Utils.random.Next(254) + 1 + "." + (Utils.random.Next(254) + 1) + "." + (Utils.random.Next(254) + 1) + "." + (Utils.random.Next(254) + 1);
if (ComputerLookup.FindByIp(ip, false) == null)
{
__result = ip;
return false;
}
}
}
}
}
| using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes
{
[HarmonyPatch]
internal static class RandomIPNoRepeats
{
[HarmonyPrefix]
[HarmonyPatch(typeof(NetworkMap), nameof(NetworkMap.generateRandomIP))]
internal static bool GenerateRandomIPReplacement(out string __result)
{
while (true)
{
var ip = Utils.random.Next(254) + 1 + "." + (Utils.random.Next(254) + 1) + "." + (Utils.random.Next(254) + 1) + "." + (Utils.random.Next(254) + 1);
if (ComputerLookup.FindByIp(ip) == null)
{
__result = ip;
return false;
}
}
}
}
}
| mit | C# |
709b103e7c2e2b400a2ff224bb2bf2529ec91fa8 | Fix Login VM | drasticactions/Pureisuteshon-App,drasticactions/PlayStation-App,drasticactions/PlayStation-App,drasticactions/Pureisuteshon-App | PlayStation-App/ViewModels/LoginPageViewModel.cs | PlayStation-App/ViewModels/LoginPageViewModel.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlayStation_App.Common;
using PlayStation_App.Core.Entities;
using PlayStation_App.Core.Exceptions;
using PlayStation_App.Core.Managers;
namespace PlayStation_App.ViewModels
{
public class LoginPageViewModel : NotifierBase
{
private readonly AuthenticationManager _authManager = new AuthenticationManager();
private string _password;
private string _userName;
public LoginPageViewModel()
{
ClickLoginButtonCommand = new AsyncDelegateCommand(async o => { await ClickLoginButton(); },
o => CanClickLoginButton);
}
public bool CanClickLoginButton => !string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password);
public string UserName
{
get { return _userName; }
set
{
if (_userName == value) return;
_userName = value;
OnPropertyChanged();
ClickLoginButtonCommand.RaiseCanExecuteChanged();
}
}
public string Password
{
get { return _password; }
set
{
if (_password == value) return;
_password = value;
OnPropertyChanged();
ClickLoginButtonCommand.RaiseCanExecuteChanged();
}
}
public AsyncDelegateCommand ClickLoginButtonCommand { get; private set; }
public event EventHandler<EventArgs> LoginSuccessful;
public event EventHandler<EventArgs> LoginFailed;
public async Task ClickLoginButton()
{
var loginResult = new UserAccountEntity();
IsLoading = true;
try
{
loginResult = await _authManager.Authenticate(UserName, Password);
}
catch (Exception ex)
{
}
IsLoading = false;
base.RaiseEvent(loginResult != null ? LoginSuccessful : LoginFailed, EventArgs.Empty);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PlayStation_App.Common;
using PlayStation_App.Core.Entities;
using PlayStation_App.Core.Exceptions;
using PlayStation_App.Core.Managers;
namespace PlayStation_App.ViewModels
{
public class LoginPageViewModel : NotifierBase
{
private readonly AuthenticationManager _authManager = new AuthenticationManager();
private string _password;
private string _userName;
public LoginPageViewModel()
{
ClickLoginButtonCommand = new AsyncDelegateCommand(async o => { await ClickLoginButton(); },
o => CanClickLoginButton);
}
public bool CanClickLoginButton => !string.IsNullOrWhiteSpace(UserName) && !string.IsNullOrWhiteSpace(Password);
public string UserName
{
get { return _userName; }
set
{
if (_userName == value) return;
_userName = value;
OnPropertyChanged();
ClickLoginButtonCommand.RaiseCanExecuteChanged();
}
}
public string Password
{
get { return _password; }
set
{
if (_password == value) return;
_password = value;
OnPropertyChanged();
ClickLoginButtonCommand.RaiseCanExecuteChanged();
}
}
public AsyncDelegateCommand ClickLoginButtonCommand { get; private set; }
public event EventHandler<EventArgs> LoginSuccessful;
public event EventHandler<EventArgs> LoginFailed;
public async Task ClickLoginButton()
{
var loginResult = new UserAccountEntity();
IsLoading = true;
try
{
loginResult = await _authManager.Authenticate(UserName, Password);
}
catch (LoginFailedException ex)
{
}
IsLoading = false;
base.RaiseEvent(loginResult != null ? LoginSuccessful : LoginFailed, EventArgs.Empty);
}
}
}
| mit | C# |
676634e8b6e1deed93f6d2b5f473ee78c6c45e90 | test names to have RecoveryServices | tonytang-microsoft-com/azure-powershell,stankovski/azure-powershell,praveennet/azure-powershell,zaevans/azure-powershell,hungmai-msft/azure-powershell,zhencui/azure-powershell,TaraMeyer/azure-powershell,hallihan/azure-powershell,praveennet/azure-powershell,yoavrubin/azure-powershell,zaevans/azure-powershell,jasper-schneider/azure-powershell,pelagos/azure-powershell,alfantp/azure-powershell,ankurchoubeymsft/azure-powershell,alfantp/azure-powershell,AzureAutomationTeam/azure-powershell,seanbamsft/azure-powershell,dulems/azure-powershell,enavro/azure-powershell,TaraMeyer/azure-powershell,yadavbdev/azure-powershell,yantang-msft/azure-powershell,pomortaz/azure-powershell,zhencui/azure-powershell,yadavbdev/azure-powershell,rohmano/azure-powershell,hallihan/azure-powershell,AzureRT/azure-powershell,haocs/azure-powershell,arcadiahlyy/azure-powershell,rohmano/azure-powershell,zaevans/azure-powershell,AzureAutomationTeam/azure-powershell,hungmai-msft/azure-powershell,hovsepm/azure-powershell,rohmano/azure-powershell,naveedaz/azure-powershell,tonytang-microsoft-com/azure-powershell,pankajsn/azure-powershell,kagamsft/azure-powershell,hallihan/azure-powershell,hungmai-msft/azure-powershell,krkhan/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,rhencke/azure-powershell,rhencke/azure-powershell,jasper-schneider/azure-powershell,SarahRogers/azure-powershell,haocs/azure-powershell,praveennet/azure-powershell,rohmano/azure-powershell,oaastest/azure-powershell,shuagarw/azure-powershell,TaraMeyer/azure-powershell,Matt-Westphal/azure-powershell,PashaPash/azure-powershell,nickheppleston/azure-powershell,shuagarw/azure-powershell,devigned/azure-powershell,atpham256/azure-powershell,oaastest/azure-powershell,shuagarw/azure-powershell,shuagarw/azure-powershell,bgold09/azure-powershell,nickheppleston/azure-powershell,jasper-schneider/azure-powershell,devigned/azure-powershell,jianghaolu/azure-powershell,ailn/azure-powershell,nemanja88/azure-powershell,oaastest/azure-powershell,chef-partners/azure-powershell,PashaPash/azure-powershell,stankovski/azure-powershell,enavro/azure-powershell,krkhan/azure-powershell,yantang-msft/azure-powershell,CamSoper/azure-powershell,juvchan/azure-powershell,krkhan/azure-powershell,dominiqa/azure-powershell,stankovski/azure-powershell,nickheppleston/azure-powershell,hungmai-msft/azure-powershell,jianghaolu/azure-powershell,chef-partners/azure-powershell,juvchan/azure-powershell,ankurchoubeymsft/azure-powershell,AzureRT/azure-powershell,SarahRogers/azure-powershell,zhencui/azure-powershell,bgold09/azure-powershell,yadavbdev/azure-powershell,pelagos/azure-powershell,pankajsn/azure-powershell,zhencui/azure-powershell,AzureAutomationTeam/azure-powershell,DeepakRajendranMsft/azure-powershell,rohmano/azure-powershell,hungmai-msft/azure-powershell,arcadiahlyy/azure-powershell,alfantp/azure-powershell,ailn/azure-powershell,pomortaz/azure-powershell,pankajsn/azure-powershell,yoavrubin/azure-powershell,dominiqa/azure-powershell,enavro/azure-powershell,ailn/azure-powershell,haocs/azure-powershell,dulems/azure-powershell,rhencke/azure-powershell,ailn/azure-powershell,atpham256/azure-powershell,tonytang-microsoft-com/azure-powershell,akurmi/azure-powershell,PashaPash/azure-powershell,CamSoper/azure-powershell,dominiqa/azure-powershell,atpham256/azure-powershell,AzureAutomationTeam/azure-powershell,CamSoper/azure-powershell,jtlibing/azure-powershell,dulems/azure-powershell,pankajsn/azure-powershell,hallihan/azure-powershell,Matt-Westphal/azure-powershell,jtlibing/azure-powershell,nemanja88/azure-powershell,atpham256/azure-powershell,hovsepm/azure-powershell,seanbamsft/azure-powershell,alfantp/azure-powershell,yantang-msft/azure-powershell,shuagarw/azure-powershell,ankurchoubeymsft/azure-powershell,mayurid/azure-powershell,yantang-msft/azure-powershell,mayurid/azure-powershell,enavro/azure-powershell,pomortaz/azure-powershell,jtlibing/azure-powershell,akurmi/azure-powershell,mayurid/azure-powershell,devigned/azure-powershell,CamSoper/azure-powershell,TaraMeyer/azure-powershell,jianghaolu/azure-powershell,devigned/azure-powershell,stankovski/azure-powershell,rohmano/azure-powershell,nemanja88/azure-powershell,akurmi/azure-powershell,Matt-Westphal/azure-powershell,SarahRogers/azure-powershell,nickheppleston/azure-powershell,ClogenyTechnologies/azure-powershell,zhencui/azure-powershell,chef-partners/azure-powershell,TaraMeyer/azure-powershell,zaevans/azure-powershell,SarahRogers/azure-powershell,yadavbdev/azure-powershell,ankurchoubeymsft/azure-powershell,alfantp/azure-powershell,naveedaz/azure-powershell,zhencui/azure-powershell,DeepakRajendranMsft/azure-powershell,devigned/azure-powershell,seanbamsft/azure-powershell,CamSoper/azure-powershell,PashaPash/azure-powershell,stankovski/azure-powershell,chef-partners/azure-powershell,AzureRT/azure-powershell,yantang-msft/azure-powershell,hallihan/azure-powershell,ClogenyTechnologies/azure-powershell,yoavrubin/azure-powershell,DeepakRajendranMsft/azure-powershell,DeepakRajendranMsft/azure-powershell,nemanja88/azure-powershell,tonytang-microsoft-com/azure-powershell,naveedaz/azure-powershell,bgold09/azure-powershell,yoavrubin/azure-powershell,jtlibing/azure-powershell,pomortaz/azure-powershell,chef-partners/azure-powershell,AzureRT/azure-powershell,arcadiahlyy/azure-powershell,pomortaz/azure-powershell,enavro/azure-powershell,mayurid/azure-powershell,yoavrubin/azure-powershell,PashaPash/azure-powershell,rhencke/azure-powershell,juvchan/azure-powershell,yantang-msft/azure-powershell,dulems/azure-powershell,yadavbdev/azure-powershell,pankajsn/azure-powershell,pelagos/azure-powershell,AzureRT/azure-powershell,nickheppleston/azure-powershell,pelagos/azure-powershell,naveedaz/azure-powershell,Matt-Westphal/azure-powershell,kagamsft/azure-powershell,praveennet/azure-powershell,SarahRogers/azure-powershell,oaastest/azure-powershell,arcadiahlyy/azure-powershell,AzureAutomationTeam/azure-powershell,kagamsft/azure-powershell,bgold09/azure-powershell,krkhan/azure-powershell,jianghaolu/azure-powershell,kagamsft/azure-powershell,pelagos/azure-powershell,hungmai-msft/azure-powershell,seanbamsft/azure-powershell,seanbamsft/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,naveedaz/azure-powershell,AzureAutomationTeam/azure-powershell,praveennet/azure-powershell,nemanja88/azure-powershell,devigned/azure-powershell,ailn/azure-powershell,ankurchoubeymsft/azure-powershell,akurmi/azure-powershell,naveedaz/azure-powershell,ClogenyTechnologies/azure-powershell,arcadiahlyy/azure-powershell,akurmi/azure-powershell,rhencke/azure-powershell,jianghaolu/azure-powershell,oaastest/azure-powershell,kagamsft/azure-powershell,AzureRT/azure-powershell,bgold09/azure-powershell,dominiqa/azure-powershell,hovsepm/azure-powershell,hovsepm/azure-powershell,juvchan/azure-powershell,dominiqa/azure-powershell,juvchan/azure-powershell,haocs/azure-powershell,seanbamsft/azure-powershell,zaevans/azure-powershell,jasper-schneider/azure-powershell,krkhan/azure-powershell,DeepakRajendranMsft/azure-powershell,ClogenyTechnologies/azure-powershell,Matt-Westphal/azure-powershell,jtlibing/azure-powershell,mayurid/azure-powershell,dulems/azure-powershell,pankajsn/azure-powershell,haocs/azure-powershell,ClogenyTechnologies/azure-powershell,tonytang-microsoft-com/azure-powershell,jasper-schneider/azure-powershell | src/ServiceManagement/RecoveryServices/Commands.RecoveryServices.Test/ScenarioTests/RecoveryServicesTests.cs | src/ServiceManagement/RecoveryServices/Commands.RecoveryServices.Test/ScenarioTests/RecoveryServicesTests.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.RecoveryServices.Test.ScenarioTests
{
public class RecoveryServicesTests : RecoveryServicesTestsBase
{
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesEnumerationTests()
{
this.RunPowerShellTest("Test-RecoveryServicesEnumerationTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesProtectionTests()
{
this.RunPowerShellTest("Test-RecoveryServicesProtectionTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesStorageMappingTest()
{
this.RunPowerShellTest("Test-StorageMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesStorageUnMappingTest()
{
this.RunPowerShellTest("Test-StorageUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesNetworkMappingTest()
{
this.RunPowerShellTest("Test-NetworkMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesNetworkUnMappingTest()
{
this.RunPowerShellTest("Test-NetworkUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.WindowsAzure.Commands.ScenarioTest;
using Xunit;
namespace Microsoft.Azure.Commands.RecoveryServices.Test.ScenarioTests
{
public class RecoveryServicesTests : RecoveryServicesTestsBase
{
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesEnumerationTests()
{
this.RunPowerShellTest("Test-RecoveryServicesEnumerationTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void RecoveryServicesProtectionTests()
{
this.RunPowerShellTest("Test-RecoveryServicesProtectionTests -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestStorageMapping()
{
this.RunPowerShellTest("Test-StorageMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestStorageUnMapping()
{
this.RunPowerShellTest("Test-StorageUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNetworkMapping()
{
this.RunPowerShellTest("Test-NetworkMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
[Fact]
[Trait(Category.AcceptanceType, Category.CheckIn)]
public void TestNetworkUnMapping()
{
this.RunPowerShellTest("Test-NetworkUnMapping -vaultSettingsFilePath \"" + vaultSettingsFilePath + "\"");
}
}
}
| apache-2.0 | C# |
5b473a216bfbe6dfb5f4349d59daee611207b4b6 | Fix compilation error | wmaryszczak/anixe_atoms_date_range | src/Anixe.Atoms.DateRange.Test/DateRangeTest.cs | src/Anixe.Atoms.DateRange.Test/DateRangeTest.cs | using System;
using System.Globalization;
using Xunit;
namespace Anixe.Atoms.Test
{
public class DateRangeTest
{
[
Theory,
InlineData("20170101:20170110", "20170102", true),
InlineData("20170101:20170110", "20170111", false),
InlineData("20170101:20170110", "20161211", false),
InlineData("20170101:20170110", "20170101", true),
InlineData("20170101:20170110", "20170110", true),
InlineData("20170110:20170101", "20170110", true),
InlineData("20170101+", "20170111", true),
InlineData("20170101", "20170101", true),
InlineData("20170101", "20170102", false),
]
public void Should_Include_Date(string dateRange, string input, bool expected)
{
var dr = DateRangeExtensions.FromString(dateRange);
var inputDate = DateTime.ParseExact(input, "yyyyMMdd", CultureInfo.InvariantCulture);
Assert.Equal(expected, dr.Includes(inputDate));
}
[
Theory,
InlineData("20170101:20170110", "20170101:20170110", true),
InlineData("20170101:20170110", "20170102:20170109", true),
InlineData("20170101:20170110", "20170102:20170111", false),
InlineData("20170101:20170110", "20161230:20170109", false),
]
public void Should_Include_DateRange(string dateRange, string input, bool expected)
{
var dr = DateRangeExtensions.FromString(dateRange);
var inputRange = DateRangeExtensions.FromString(input);
Assert.Equal(expected, dr.Includes(inputRange));
}
[Fact]
public void Undefined_DateRange_Should_Be_Empty()
{
var dr = new DateRange();
Assert.Equal(DateRange.Empty, dr);
}
}
} | using System;
using System.Globalization;
using Xunit;
namespace Anixe.Atoms.Test
{
public class DateRangeTest
{
[
Theory
InlineData("20170101:20170110", "20170102", true)
InlineData("20170101:20170110", "20170111", false)
InlineData("20170101:20170110", "20161211", false)
InlineData("20170101:20170110", "20170101", true)
InlineData("20170101:20170110", "20170110", true)
InlineData("20170110:20170101", "20170110", true)
InlineData("20170101+", "20170111", true)
InlineData("20170101", "20170101", true)
InlineData("20170101", "20170102", false)
]
public void Should_Include_Date(string dateRange, string input, bool expected)
{
var dr = DateRangeExtensions.FromString(dateRange);
var inputDate = DateTime.ParseExact(input, "yyyyMMdd", CultureInfo.InvariantCulture);
Assert.Equal(expected, dr.Includes(inputDate));
}
[
Theory
InlineData("20170101:20170110", "20170101:20170110", true)
InlineData("20170101:20170110", "20170102:20170109", true)
InlineData("20170101:20170110", "20170102:20170111", false)
InlineData("20170101:20170110", "20161230:20170109", false)
]
public void Should_Include_DateRange(string dateRange, string input, bool expected)
{
var dr = DateRangeExtensions.FromString(dateRange);
var inputRange = DateRangeExtensions.FromString(input);
Assert.Equal(expected, dr.Includes(inputRange));
}
[Fact]
public void Undefined_DateRange_Should_Be_Empty()
{
var dr = new DateRange();
Assert.Equal(DateRange.Empty, dr);
}
}
} | mit | C# |
73cf24612a9e89bb281a8b440e8920c19dd8de0b | Fix GetAllCategories | notdev/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI,xobed/RohlikAPI | RohlikAPI/Categories.cs | RohlikAPI/Categories.cs | using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
namespace RohlikAPI
{
internal class Categories
{
private readonly PersistentSessionHttpClient httpClient;
internal Categories(PersistentSessionHttpClient httpClient)
{
this.httpClient = httpClient;
}
public IEnumerable<string> GetAllCategories()
{
var rohlikFrontString = httpClient.Get("https://www.rohlik.cz/");
var rohlikFrontDocument = new HtmlDocument();
rohlikFrontDocument.LoadHtml(rohlikFrontString);
var categoryNodes = rohlikFrontDocument.DocumentNode.SelectNodes("//div[contains(@id,'rootcat')]/div/a");
var categoryHrefs = categoryNodes.Select(c => c.Attributes["href"].Value);
return categoryHrefs.Select(c => c.Substring(1));
}
}
} | using System.Collections.Generic;
using System.Linq;
using HtmlAgilityPack;
namespace RohlikAPI
{
internal class Categories
{
private readonly PersistentSessionHttpClient httpClient;
internal Categories(PersistentSessionHttpClient httpClient)
{
this.httpClient = httpClient;
}
public IEnumerable<string> GetAllCategories()
{
var rohlikFrontString = httpClient.Get("https://www.rohlik.cz/");
var rohlikFrontDocument = new HtmlDocument();
rohlikFrontDocument.LoadHtml(rohlikFrontString);
var categories = rohlikFrontDocument.DocumentNode.SelectNodes("//div[contains(@id,'rootcat')]/div/a");
return categories.Select(c => c.Attributes["href"].Value.Substring(1));
}
}
} | mit | C# |
55dc699ec0296b75b3181ecd088603b05757b333 | resolve null pointer exception when search returns no results | Kentico/Mvc,Kentico/Mvc,Kentico/Mvc | src/DancingGoat/Controllers/SearchController.cs | src/DancingGoat/Controllers/SearchController.cs | using System.Collections.Generic;
using System.Web.Mvc;
using PagedList;
using DancingGoat.Models.Search;
using Kentico.Search;
namespace DancingGoat.Controllers
{
public class SearchController : Controller
{
private readonly SearchService mService;
private const int PAGE_SIZE = 5;
public SearchController(SearchService searchService)
{
mService = searchService;
}
// GET: Search
[ValidateInput(false)]
public ActionResult Index(string searchText, int? page)
{
int totalItemsCount;
var pageIndex = (page ?? 1);
var searchResults = mService.Search(searchText, pageIndex, PAGE_SIZE, out totalItemsCount);
var model = new SearchResultsModel
{
Items = new StaticPagedList<SearchResultItem>(searchResults ?? new List<SearchResultItem>(), pageIndex, PAGE_SIZE, totalItemsCount),
Query = searchText
};
return View(model);
}
}
} | using System.Web.Mvc;
using PagedList;
using DancingGoat.Models.Search;
using Kentico.Search;
namespace DancingGoat.Controllers
{
public class SearchController : Controller
{
private readonly SearchService mService;
private const int PAGE_SIZE = 5;
public SearchController(SearchService searchService)
{
mService = searchService;
}
// GET: Search
[ValidateInput(false)]
public ActionResult Index(string searchText, int? page)
{
int totalItemsCount;
var pageIndex = (page ?? 1);
var searchResults = mService.Search(searchText, pageIndex, PAGE_SIZE, out totalItemsCount);
var model = new SearchResultsModel
{
Items = new StaticPagedList<SearchResultItem>(searchResults, pageIndex, PAGE_SIZE, totalItemsCount),
Query = searchText
};
return View(model);
}
}
} | mit | C# |
de59652255d6cbc6b63bf80f495b5fdd34f576d6 | Fix ModifyGuildMemberParameters serializing full role objects | BundledSticksInkorperated/Discore | src/Discore/Http/ModifyGuildMemberParameters.cs | src/Discore/Http/ModifyGuildMemberParameters.cs | using System.Collections.Generic;
namespace Discore.Http
{
/// <summary>
/// An optional set of parameters to change the attributes of a guild member.
/// </summary>
public class ModifyGuildMemberParameters
{
/// <summary>
/// The users nickname for the guild.
/// </summary>
public string Nickname { get; set; }
/// <summary>
/// A list of roles IDs the member is assigned to.
/// </summary>
public IEnumerable<Snowflake> RoleIds { get; set; }
/// <summary>
/// Whether the user is server muted.
/// </summary>
public bool? IsServerMute { get; set; }
/// <summary>
/// Whether the user is deafened.
/// </summary>
public bool? IsServerDeaf { get; set; }
/// <summary>
/// ID of the voice channel to move the user to (if they are currently connected to voice).
/// </summary>
public Snowflake? ChannelId { get; set; }
internal DiscordApiData Build()
{
DiscordApiData data = new DiscordApiData(DiscordApiDataType.Container);
data.Set("nick", Nickname);
data.Set("mute", IsServerMute);
data.Set("deaf", IsServerDeaf);
data.Set("channel_id", ChannelId);
if (RoleIds != null)
{
DiscordApiData rolesArray = new DiscordApiData(DiscordApiDataType.Array);
foreach (Snowflake roleId in RoleIds)
rolesArray.Values.Add(new DiscordApiData(roleId));
data.Set("roles", rolesArray);
}
return data;
}
}
}
| using System.Collections.Generic;
namespace Discore.Http
{
/// <summary>
/// An optional set of parameters to change the attributes of a guild member.
/// </summary>
public class ModifyGuildMemberParameters
{
/// <summary>
/// The users nickname for the guild.
/// </summary>
public string Nickname { get; set; }
/// <summary>
/// A list of roles the member is assigned to.
/// </summary>
public IEnumerable<DiscordRole> Roles { get; set; }
/// <summary>
/// Whether the user is server muted.
/// </summary>
public bool? IsServerMute { get; set; }
/// <summary>
/// Whether the user is deafened.
/// </summary>
public bool? IsServerDeaf { get; set; }
/// <summary>
/// ID of the voice channel to move the user to (if they are currently connected to voice).
/// </summary>
public Snowflake? ChannelId { get; set; }
internal DiscordApiData Build()
{
DiscordApiData data = new DiscordApiData(DiscordApiDataType.Container);
data.Set("nick", Nickname);
data.Set("mute", IsServerMute);
data.Set("deaf", IsServerDeaf);
data.Set("channel_id", ChannelId);
if (Roles != null)
{
DiscordApiData rolesArray = new DiscordApiData(DiscordApiDataType.Array);
foreach (DiscordRole role in Roles)
rolesArray.Values.Add(role.Serialize());
data.Set("roles", rolesArray);
}
return data;
}
}
}
| mit | C# |
47e00887a29a2a468cd920c1e548e00cbc6cf468 | Remove some spurious Console.WriteLine() calls from a test. | BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,nodatime/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime | src/NodaTime.Test/Annotations/MutabilityTest.cs | src/NodaTime.Test/Annotations/MutabilityTest.cs | // Copyright 2013 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 System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
| // Copyright 2013 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 System.Linq;
using NodaTime.Annotations;
using NUnit.Framework;
namespace NodaTime.Test.Annotations
{
[TestFixture]
public class MutabilityTest
{
[Test]
public void AllPublicClassesAreMutableOrImmutable()
{
var unannotatedClasses = typeof(Instant).Assembly
.GetTypes()
.Concat(new[] { typeof(ZonedDateTime.Comparer) })
.Where(t => t.IsClass && t.IsPublic && t.BaseType != typeof(MulticastDelegate))
.Where(t => !(t.IsAbstract && t.IsSealed)) // Ignore static classes
.OrderBy(t => t.Name)
.Where(t => !t.IsDefined(typeof(ImmutableAttribute), false) &&
!t.IsDefined(typeof(MutableAttribute), false))
.ToList();
var type = typeof (ZonedDateTime.Comparer);
Console.WriteLine(type.IsClass && type.IsPublic && type.BaseType != typeof (MulticastDelegate));
Console.WriteLine(!(type.IsAbstract && type.IsSealed));
Assert.IsEmpty(unannotatedClasses, "Unannotated classes: " + string.Join(", ", unannotatedClasses.Select(c => c.Name)));
}
}
}
| apache-2.0 | C# |
0b4a36b6a62eaa5435ddb949e864025e32d9cce8 | Fix warning about empty constructor | amweiss/WeatherLink | src/Services/HourlyAndMinutelyDarkSkyService.cs | src/Services/HourlyAndMinutelyDarkSkyService.cs | using DarkSky.Models;
using DarkSky.Services;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
using WeatherLink.Models;
namespace WeatherLink.Services
{
/// <summary>
/// A service to get a Dark Sky forecast for a latitude and longitude.
/// </summary>
public class HourlyAndMinutelyDarkSkyService : IDarkSkyService
{
private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } };
private readonly DarkSkyService _darkSkyService;
/// <summary>
/// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data.
/// </summary>
/// <param name="optionsAccessor"></param>
public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor)
{
_darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey);
}
/// <summary>
/// Make a request to get forecast data.
/// </summary>
/// <param name="latitude">Latitude to request data for in decimal degrees.</param>
/// <param name="longitude">Longitude to request data for in decimal degrees.</param>
/// <returns>A DarkSkyResponse with the API headers and data.</returns>
public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude)
{
return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters);
}
}
} | using DarkSky.Models;
using DarkSky.Services;
using Microsoft.Extensions.Options;
using System.Collections.Generic;
using System.Threading.Tasks;
using WeatherLink.Models;
namespace WeatherLink.Services
{
/// <summary>
/// A service to get a Dark Sky forecast for a latitude and longitude.
/// </summary>
public class HourlyAndMinutelyDarkSkyService : IDarkSkyService
{
private readonly DarkSkyService.OptionalParameters _darkSkyParameters = new DarkSkyService.OptionalParameters() { DataBlocksToExclude = new List<string> { "daily", "alerts", "flags" } };
private readonly DarkSkyService _darkSkyService;
/// <summary>
/// An implementation of IDarkSkyService that exlcudes daily data, alert data, and flags data.
/// </summary>
/// <param name="optionsAccessor"></param>
public HourlyAndMinutelyDarkSkyService(IOptions<WeatherLinkSettings> optionsAccessor)
{
_darkSkyService = new DarkSkyService(optionsAccessor.Value.DarkSkyApiKey);
}
/// <summary>
/// Make a request to get forecast data.
/// </summary>
/// <param name="latitude">Latitude to request data for in decimal degrees.</param>
/// <param name="longitude">Longitude to request data for in decimal degrees.</param>
/// <returns>A DarkSkyResponse with the API headers and data.</returns>
public async Task<DarkSkyResponse> GetForecast(double latitude, double longitude)
{
return await _darkSkyService.GetForecast(latitude, longitude, _darkSkyParameters);
}
}
} | mit | C# |
3e9f23df8e72c8c547e37798db9fb5a3ac68bb1d | Rewrite of the Time Parsing code | stoye/LiveSplit,Dalet/LiveSplit,zoton2/LiveSplit,CryZe/LiveSplit,Jiiks/LiveSplit,kugelrund/LiveSplit,drtchops/LiveSplit,Dalet/LiveSplit,PackSciences/LiveSplit,glasnonck/LiveSplit,Fluzzarn/LiveSplit,Seldszar/LiveSplit,glasnonck/LiveSplit,chloe747/LiveSplit,drtchops/LiveSplit,stoye/LiveSplit,kugelrund/LiveSplit,CryZe/LiveSplit,chloe747/LiveSplit,Jiiks/LiveSplit,kugelrund/LiveSplit,PackSciences/LiveSplit,PackSciences/LiveSplit,glasnonck/LiveSplit,madzinah/LiveSplit,ROMaster2/LiveSplit,ROMaster2/LiveSplit,Fluzzarn/LiveSplit,ROMaster2/LiveSplit,chloe747/LiveSplit,madzinah/LiveSplit,stoye/LiveSplit,madzinah/LiveSplit,Seldszar/LiveSplit,zoton2/LiveSplit,CryZe/LiveSplit,Fluzzarn/LiveSplit,zoton2/LiveSplit,Glurmo/LiveSplit,drtchops/LiveSplit,Glurmo/LiveSplit,Seldszar/LiveSplit,Glurmo/LiveSplit,Jiiks/LiveSplit,Dalet/LiveSplit,LiveSplit/LiveSplit | LiveSplit/LiveSplit.Core/Model/TimeSpanParser.cs | LiveSplit/LiveSplit.Core/Model/TimeSpanParser.cs | using System;
using System.Linq;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
var seconds = timeString
.Split(':')
.Select(x => Double.Parse(x, NumberStyles.Float, CultureInfo.InvariantCulture))
.Aggregate(0.0, (a, b) => 60 * a + b);
return TimeSpan.FromSeconds(factor * seconds);
}
}
}
| using System;
using System.Globalization;
namespace LiveSplit.Model
{
public static class TimeSpanParser
{
public static TimeSpan? ParseNullable(String timeString)
{
if (String.IsNullOrEmpty(timeString))
return null;
return Parse(timeString);
}
public static TimeSpan Parse(String timeString)
{
double num = 0.0;
var factor = 1;
if (timeString.StartsWith("-"))
{
factor = -1;
timeString = timeString.Substring(1);
}
string[] array = timeString.Split(':');
foreach (string s in array)
{
double num2;
if (double.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out num2))
{
num = num * 60.0 + num2;
}
else
{
throw new Exception();
}
}
if (factor * num > 864000)
throw new Exception();
return new TimeSpan((long)(factor * num * 10000000));
}
}
}
| mit | C# |
d12e4928e62023e26aa90ce32bbf84f087886e7d | Increase editor verify settings width to give more breathing space | ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu | osu.Game/Screens/Edit/Verify/VerifyScreen.cs | osu.Game/Screens/Edit/Verify/VerifyScreen.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 225),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
[Cached]
public class VerifyScreen : EditorScreen
{
public readonly Bindable<Issue> SelectedIssue = new Bindable<Issue>();
public readonly Bindable<DifficultyRating> InterpretedDifficulty = new Bindable<DifficultyRating>();
public readonly BindableList<IssueType> HiddenIssueTypes = new BindableList<IssueType> { IssueType.Negligible };
public IssueList IssueList { get; private set; }
public VerifyScreen()
: base(EditorScreenMode.Verify)
{
}
[BackgroundDependencyLoader]
private void load()
{
InterpretedDifficulty.Default = BeatmapDifficultyCache.GetDifficultyRating(EditorBeatmap.BeatmapInfo.StarRating);
InterpretedDifficulty.SetDefault();
Child = new Container
{
RelativeSizeAxes = Axes.Both,
Child = new GridContainer
{
RelativeSizeAxes = Axes.Both,
ColumnDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.Absolute, 200),
},
Content = new[]
{
new Drawable[]
{
IssueList = new IssueList(),
new IssueSettings(),
},
}
}
};
}
}
}
| mit | C# |
a33efa9bde170f6a9e77175a76f8547d85b7dea9 | Include watermark for flv containers | taliesins/talifun-commander,taliesins/talifun-commander | Talifun.Commander.Command.Video/FLVCommand.cs | Talifun.Commander.Command.Video/FLVCommand.cs | using System;
using System.Configuration;
using System.IO;
using Talifun.Commander.Command.Video.AudioFormats;
using Talifun.Commander.Command.Video.Configuration;
using Talifun.Commander.Command.Video.Containers;
using Talifun.Commander.Command.Video.VideoFormats;
using Talifun.Commander.Executor.CommandLine;
using Talifun.Commander.Executor.FFMpeg;
namespace Talifun.Commander.Command.Video
{
public class FlvCommand : ICommand<IContainerSettings>
{
#region ICommand<FLVCommand,FLVSettings> Members
public bool Run(IContainerSettings settings, AppSettingsSection appSettings, FileInfo inputFilePath, DirectoryInfo outputDirectoryPath, out FileInfo outPutFilePath, out string output)
{
var fileName = Path.GetFileNameWithoutExtension(inputFilePath.Name) + "." + settings.FileNameExtension;
outPutFilePath = new FileInfo(Path.Combine(outputDirectoryPath.FullName, fileName));
if (outPutFilePath.Exists)
{
outPutFilePath.Delete();
}
var fFMpegCommandArguments = string.Format("-i \"{0}\" {1} {2} {3} \"{4}\"", inputFilePath.FullName, settings.Video.GetOptionsForFirstPass(), settings.Audio.GetOptions(), settings.Watermark.GetOptions(), outPutFilePath.FullName);
var flvTool2CommandArguments = string.Format("-U \"{0}\"", outPutFilePath.FullName);
var workingDirectory = outputDirectoryPath.FullName;
var fFMpegCommandPath = appSettings.Settings[VideoConversionConfiguration.Instance.FFMpegPathSettingName].Value;
var flvTool2CommandPath = appSettings.Settings[VideoConversionConfiguration.Instance.FlvTool2PathSettingName].Value;
var result = false;
var encodeOutput = string.Empty;
var metaDataOutput = string.Empty;
var ffmpegHelper = new FfMpegCommandLineExecutor();
result = ffmpegHelper.Execute(workingDirectory, fFMpegCommandPath, fFMpegCommandArguments, out encodeOutput);
output = encodeOutput;
if (result)
{
var commandLineExecutor = new CommandLineExecutor();
result = commandLineExecutor.Execute(workingDirectory, flvTool2CommandPath, flvTool2CommandArguments, out metaDataOutput);
output += Environment.NewLine + metaDataOutput;
}
return result;
}
#endregion
}
}
| using System;
using System.Configuration;
using System.IO;
using Talifun.Commander.Command.Video.AudioFormats;
using Talifun.Commander.Command.Video.Configuration;
using Talifun.Commander.Command.Video.Containers;
using Talifun.Commander.Command.Video.VideoFormats;
using Talifun.Commander.Executor.CommandLine;
using Talifun.Commander.Executor.FFMpeg;
namespace Talifun.Commander.Command.Video
{
public class FlvCommand : ICommand<IContainerSettings>
{
#region ICommand<FLVCommand,FLVSettings> Members
public bool Run(IContainerSettings settings, AppSettingsSection appSettings, FileInfo inputFilePath, DirectoryInfo outputDirectoryPath, out FileInfo outPutFilePath, out string output)
{
var fileName = Path.GetFileNameWithoutExtension(inputFilePath.Name) + "." + settings.FileNameExtension;
outPutFilePath = new FileInfo(Path.Combine(outputDirectoryPath.FullName, fileName));
if (outPutFilePath.Exists)
{
outPutFilePath.Delete();
}
var fFMpegCommandArguments = string.Format("-i \"{0}\" {1} {2} \"{3}\"", inputFilePath.FullName, settings.Video.GetOptionsForFirstPass(), settings.Audio.GetOptions(), outPutFilePath.FullName);
var flvTool2CommandArguments = string.Format("-U \"{0}\"", outPutFilePath.FullName);
var workingDirectory = outputDirectoryPath.FullName;
var fFMpegCommandPath = appSettings.Settings[VideoConversionConfiguration.Instance.FFMpegPathSettingName].Value;
var flvTool2CommandPath = appSettings.Settings[VideoConversionConfiguration.Instance.FlvTool2PathSettingName].Value;
var result = false;
var encodeOutput = string.Empty;
var metaDataOutput = string.Empty;
var ffmpegHelper = new FfMpegCommandLineExecutor();
result = ffmpegHelper.Execute(workingDirectory, fFMpegCommandPath, fFMpegCommandArguments, out encodeOutput);
output = encodeOutput;
if (result)
{
var commandLineExecutor = new CommandLineExecutor();
result = commandLineExecutor.Execute(workingDirectory, flvTool2CommandPath, flvTool2CommandArguments, out metaDataOutput);
output += Environment.NewLine + metaDataOutput;
}
return result;
}
#endregion
}
}
| apache-2.0 | C# |
386d9b28cf8b77b370f244f7978c2134019af028 | Update MinValueInSortedArrayWithDuplicates.cs | shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank | interim/MinValueInSortedArrayWithDuplicates.cs | interim/MinValueInSortedArrayWithDuplicates.cs | public class Solution {
private int minVal;
public int FindMin(int[] nums) {
if(nums.Length==0)
return -1;
if(nums.Length==1)
return nums[0];
if(nums.Length==2)
return Math.Min(nums[0],nums[1]);
int? x = modifiedBinarySearch(nums, 0, (nums.Length-1)/2, nums.Length-1);
if(x==null)
return nums[0];
else
return Math.Min((int)x,minVal);
}
private int? modifiedBinarySearch(int []nums, int low, int mid, int high){
if(nums.Length==0)
return null;
minVal = Math.Min(minVal, nums[0]);
if(nums[0]<nums[nums.Length-1]){//array not rotated
return nums[0];
}
if(low > mid){
minVal = mid;
return modifiedBinarySearch(nums, low, (low+mid)/2, mid);
}
else if(low<mid){
minVal = low;
return modifiedBinarySearch(nums, mid, (mid+high)/2, high);
}
else{//low = mid
if(mid==high){
minVal = nums[0];
return null;
}
else{
return modifiedBinarySearch(nums, mid, (mid+high)/2,high);
}
}
}
}
| public class MinValueInSortedArrayWithDuplicates {
private int minVal;
public int FindMin(int[] nums) {
return modifiedBinarySearch(nums, low, mid, high);
}
private int modifiedBinarySearch(int []nums, int low, int mid, int high){
if(nums.Length==0)
return;
minVal = nums[0];
if(nums[0]<nums[nums.Length-1]){//array not rotated
return nums[0];
}
if(nums[low]>nums[low+1]){
minVal = nums[low+1];
return;
}
int low = 0;
int high = nums.Length-1;
int mid = (low+high)/2;
/* l m h
567801234 */
if(low<mid){
if(mid>high){
modifiedBinarySearch(nums, mid, (mid+high)/2, high);
}
else{
modifiedBinarySearch(nums, low, (low+mid)/2, mid);
}
}
else{
}
}
}
| mit | C# |
3b10811e61ed71ec331dd606b0234c7cb934f2bb | Set compatibility version to 2.2 in hello world sample project | ExplicitlyImplicit/AspNetCore.Mvc.FluentActions,ExplicitlyImplicit/AspNetCore.Mvc.FluentActions | samples/HelloWorld/Startup.cs | samples/HelloWorld/Startup.cs | using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services
.AddMvc()
.AddFluentActions()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
| using ExplicitlyImpl.AspNetCore.Mvc.FluentActions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
namespace HelloWorld
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().AddFluentActions();
}
public void Configure(IApplicationBuilder app)
{
app.UseFluentActions(actions =>
{
actions.RouteGet("/").To(() => "Hello World!");
});
app.UseMvc();
}
}
}
| mit | C# |
ab42b2db338427d010e9107c44f1975eeba3a084 | Add code documentation to the StringPalmValue | haefele/PalmDB | src/PalmDB/Serialization/StringPalmValue.cs | src/PalmDB/Serialization/StringPalmValue.cs | using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
/// <summary>
/// Represents a <see cref="string"/> value inside a palm database.
/// </summary>
internal class StringPalmValue : IPalmValue<string>
{
/// <summary>
/// Gets the length of this string block.
/// </summary>
public int Length { get; }
/// <summary>
/// Gets the encoding used to encode and decode the string.
/// </summary>
public Encoding Encoding { get; }
/// <summary>
/// Gets a value indicating whether the string is terminated with a zero-byte.
/// </summary>
public bool ZeroTerminated { get; }
/// <summary>
/// Initializes a new instance of the <see cref="StringPalmValue"/> class.
/// </summary>
/// <param name="length">The length of the string block.</param>
/// <param name="encoding">The encoding used to encode and decode the string.</param>
/// <param name="zeroTerminated">Whether the string is terminated with a zero-byte.</param>
public StringPalmValue(int length, Encoding encoding, bool zeroTerminated)
{
Guard.NotNegative(length, nameof(length));
Guard.NotNull(encoding, nameof(encoding));
this.Length = length;
this.Encoding = encoding;
this.ZeroTerminated = zeroTerminated;
}
/// <summary>
/// Reads the <see cref="string"/> using the specified <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The reader.</param>
public async Task<string> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
if (this.ZeroTerminated)
{
data = data
.TakeWhile(f => f != 0)
.ToArray();
}
return this.Encoding.GetString(data);
}
/// <summary>
/// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">The value.</param>
public Task WriteValueAsync(AsyncBinaryWriter writer, string value)
{
Guard.NotNull(writer, nameof(writer));
Guard.NotNull(value, nameof(value));
var data = this.Encoding.GetBytes(value);
//Ensure data has right length
Array.Resize(ref data, this.Length);
if (this.ZeroTerminated)
{
//Ensure last byte is 0
data[this.Length - 1] = 0;
}
return writer.WriteAsync(data);
}
}
} | using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
internal class StringPalmValue : IPalmValue<string>
{
public int Length { get; }
public Encoding Encoding { get; }
public bool ZeroTerminated { get; }
public StringPalmValue(int length, Encoding encoding, bool zeroTerminated)
{
Guard.NotNegative(length, nameof(length));
Guard.NotNull(encoding, nameof(encoding));
this.Length = length;
this.Encoding = encoding;
this.ZeroTerminated = zeroTerminated;
}
public async Task<string> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
if (this.ZeroTerminated)
{
data = data
.TakeWhile(f => f != 0)
.ToArray();
}
return this.Encoding.GetString(data);
}
public Task WriteValueAsync(AsyncBinaryWriter writer, string value)
{
Guard.NotNull(writer, nameof(writer));
Guard.NotNull(value, nameof(value));
var data = this.Encoding.GetBytes(value);
//Ensure data has right length
Array.Resize(ref data, this.Length);
if (this.ZeroTerminated)
{
//Ensure last byte is 0
data[this.Length - 1] = 0;
}
return writer.WriteAsync(data);
}
}
} | mit | C# |
003570c03ba11cecf1cfa500ba79414602adce4a | remove the notifications node - it was dependent on OWIN | alexrster/SAML2,elerch/SAML2 | src/SAML2.Core/Config/Saml2Configuration.cs | src/SAML2.Core/Config/Saml2Configuration.cs | using System.Collections.Generic;
using System.Configuration;
namespace SAML2.Config
{
/// <summary>
/// SAML2 Configuration Section.
/// </summary>
public class Saml2Configuration
{
/// <summary>
/// Gets the section name.
/// </summary>
public static string Name { get { return "saml2"; } }
/// <summary>
/// Gets or sets the allowed audience uris.
/// </summary>
/// <value>The allowed audience uris.</value>
public List<System.Uri> AllowedAudienceUris { get; set; }
/// <summary>
/// Gets or sets the assertion profile.
/// </summary>
/// <value>The assertion profile configuration.</value>
public string AssertionProfileValidator { get; set; }
/// <summary>
/// Gets or sets the common domain cookie configuration.
/// </summary>
/// <value>The common domain cookie configuration.</value>
public CommonDomainCookie CommonDomainCookie { get; set; }
/// <summary>
/// Gets or sets the identity providers.
/// </summary>
/// <value>The identity providers.</value>
public IdentityProviders IdentityProviders { get; set; }
/// <summary>
/// Gets or sets the logging configuration.
/// </summary>
/// <value>The logging configuration.</value>
public string LoggingFactoryType { get; set; }
/// <summary>
/// Gets or sets the metadata.
/// </summary>
/// <value>The metadata.</value>
public Metadata Metadata { get; set; }
/// <summary>
/// Gets or sets the service provider.
/// </summary>
/// <value>The service provider.</value>
public ServiceProvider ServiceProvider { get; set; }
}
}
| using System.Collections.Generic;
using System.Configuration;
namespace SAML2.Config
{
/// <summary>
/// SAML2 Configuration Section.
/// </summary>
public class Saml2Configuration
{
/// <summary>
/// Gets the section name.
/// </summary>
public static string Name { get { return "saml2"; } }
/// <summary>
/// Gets or sets the allowed audience uris.
/// </summary>
/// <value>The allowed audience uris.</value>
public List<System.Uri> AllowedAudienceUris { get; set; }
/// <summary>
/// Gets or sets the assertion profile.
/// </summary>
/// <value>The assertion profile configuration.</value>
public string AssertionProfileValidator { get; set; }
/// <summary>
/// Gets or sets the common domain cookie configuration.
/// </summary>
/// <value>The common domain cookie configuration.</value>
public CommonDomainCookie CommonDomainCookie { get; set; }
/// <summary>
/// Gets or sets the identity providers.
/// </summary>
/// <value>The identity providers.</value>
public IdentityProviders IdentityProviders { get; set; }
/// <summary>
/// Gets or sets the logging configuration.
/// </summary>
/// <value>The logging configuration.</value>
public string LoggingFactoryType { get; set; }
/// <summary>
/// Gets or sets the metadata.
/// </summary>
/// <value>The metadata.</value>
public Metadata Metadata { get; set; }
/// <summary>
/// Gets or sets the service provider.
/// </summary>
/// <value>The service provider.</value>
public ServiceProvider ServiceProvider { get; set; }
/// <summary>
/// Gets or sets the <see cref="SamlAuthenticationNotifications"/> to call when processing Saml messages.
/// </summary>
public SamlAuthenticationNotifications Notifications { get; set; }
}
}
| mpl-2.0 | C# |
f28dcd8d0c37eb63b1eefb9ca1cf17d3dd92f63b | Add extension method to set bitmap for all keys (+Xml documentation) | OpenStreamDeck/StreamDeckSharp | src/StreamDeckSharp/StreamDeckExtensions.cs | src/StreamDeckSharp/StreamDeckExtensions.cs | using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StreamDeckSharp
{
/// <summary>
/// </summary>
/// <remarks>
/// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation.
/// This extension class adds some commonly used functions to make things simpler.
/// </remarks>
public static class StreamDeckExtensions
{
/// <summary>
/// Sets a background image for a given key
/// </summary>
/// <param name="deck"></param>
/// <param name="keyId"></param>
/// <param name="bitmap"></param>
public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap)
{
deck.SetKeyBitmap(keyId, bitmap.rawBitmapData);
}
/// <summary>
/// Sets a background image for all keys
/// </summary>
/// <param name="deck"></param>
/// <param name="bitmap"></param>
public static void SetKeyBitmap(this IStreamDeck deck, StreamDeckKeyBitmap bitmap)
{
for (int i = 0; i < StreamDeckHID.numOfKeys; i++)
deck.SetKeyBitmap(i, bitmap.rawBitmapData);
}
/// <summary>
/// Sets background to black for a given key
/// </summary>
/// <param name="deck"></param>
/// <param name="keyId"></param>
public static void ClearKey(this IStreamDeck deck, int keyId)
{
deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black);
}
/// <summary>
/// Sets background to black for all given keys
/// </summary>
/// <param name="deck"></param>
public static void ClearKeys(this IStreamDeck deck)
{
deck.SetKeyBitmap(StreamDeckKeyBitmap.Black);
}
}
}
| using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StreamDeckSharp
{
/// <summary>
/// </summary>
/// <remarks>
/// The <see cref="IStreamDeck"/> interface is pretty basic to simplify implementation.
/// This extension class adds some commonly used functions to make things simpler.
/// </remarks>
public static class StreamDeckExtensions
{
public static void SetKeyBitmap(this IStreamDeck deck, int keyId, StreamDeckKeyBitmap bitmap)
{
deck.SetKeyBitmap(keyId, bitmap.rawBitmapData);
}
public static void ClearKey(this IStreamDeck deck, int keyId)
{
deck.SetKeyBitmap(keyId, StreamDeckKeyBitmap.Black);
}
public static void ClearKeys(this IStreamDeck deck)
{
for (int i = 0; i < StreamDeckHID.numOfKeys; i++)
deck.SetKeyBitmap(i, StreamDeckKeyBitmap.Black);
}
}
}
| mit | C# |
df562ee967d1e059fe62096443f67f599e04b68b | Fix semantic errors not showing error message. | mrward/typescript-addin,chrisber/typescript-addin,chrisber/typescript-addin,mrward/typescript-addin | src/TypeScriptBinding/Hosting/Diagnostic.cs | src/TypeScriptBinding/Hosting/Diagnostic.cs | //
// Diagnostic.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2014 Matthew Ward
//
// 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;
namespace ICSharpCode.TypeScriptBinding.Hosting
{
public class Diagnostic
{
public int start { get; set; }
public int length { get; set; }
public string message { get; set; }
public DiagnosticCategory category { get; set; }
public int code { get; set; }
public string GetDiagnosticMessage()
{
if (!String.IsNullOrEmpty(message)) {
return message;
}
return String.Format("{0}", code);
}
public override string ToString()
{
return GetDiagnosticMessage();
}
}
}
| //
// Diagnostic.cs
//
// Author:
// Matt Ward <ward.matt@gmail.com>
//
// Copyright (C) 2014 Matthew Ward
//
// 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;
namespace ICSharpCode.TypeScriptBinding.Hosting
{
public class Diagnostic
{
public int start { get; set; }
public int length { get; set; }
public string messageText { get; set; }
public DiagnosticCategory category { get; set; }
public int code { get; set; }
public string GetDiagnosticMessage()
{
if (!String.IsNullOrEmpty(messageText)) {
return messageText;
}
return String.Format("{0}", code);
}
public override string ToString()
{
return GetDiagnosticMessage();
}
}
}
| mit | C# |
5b87638c8bde92509aa19ccc405bf3f54ce78a82 | Replace MSBuild with DotNetBuild | syedhassaanahmed/aspnet-core-crud-demo,syedhassaanahmed/aspnet-core-crud-demo,syedhassaanahmed/aspnet-core-crud-demo | build.cake | build.cake | #tool "nuget:?package=GitVersion.CommandLine"
var target = Argument("target", "Default");
var outputDir = "./artifacts/";
var artifactName = "artifact.zip";
var solutionPath = "./AspNetCore.CrudDemo.sln";
var projectPath = "./AspNetCore.CrudDemo";
var projectJsonPath = projectPath + "/project.json";
var buildConfig = "Release";
Task("Clean")
.Does(() =>
{
if (DirectoryExists(outputDir))
DeleteDirectory(outputDir, recursive:true);
CreateDirectory(outputDir);
});
Task("Restore")
.Does(() => DotNetCoreRestore());
Task("Version")
.Does(() =>
{
GitVersion(new GitVersionSettings
{
UpdateAssemblyInfo = true,
OutputType = GitVersionOutput.BuildServer
});
var versionInfo = GitVersion(new GitVersionSettings{ OutputType = GitVersionOutput.Json });
var updatedProjectJson = System.IO.File.ReadAllText(projectJsonPath)
.Replace("1.0.0-*", versionInfo.NuGetVersion);
System.IO.File.WriteAllText(projectJsonPath, updatedProjectJson);
});
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Version")
.IsDependentOn("Restore")
.Does(() =>
{
DotNetBuild(solutionPath, settings => settings
.SetConfiguration(buildConfig)
.SetVerbosity(Core.Diagnostics.Verbosity.Minimal)
.WithTarget("Build"));
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./AspNetCore.CrudDemo.Controllers.Tests");
// Because DocumentDB emulator is not yet supported on CI
if (BuildSystem.IsLocalBuild)
DotNetCoreTest("./AspNetCore.CrudDemo.Services.Tests");
});
Task("Publish")
.IsDependentOn("Test")
.Does(() =>
{
var settings = new DotNetCorePublishSettings
{
Configuration = buildConfig,
OutputDirectory = outputDir
};
DotNetCorePublish(projectPath, settings);
Zip(outputDir, artifactName);
if (BuildSystem.IsRunningOnAppVeyor)
{
var files = GetFiles(artifactName);
foreach(var file in files)
AppVeyor.UploadArtifact(file.FullPath);
}
});
Task("Default")
.IsDependentOn("Publish");
RunTarget(target); | #tool "nuget:?package=GitVersion.CommandLine"
var target = Argument("target", "Default");
var outputDir = "./artifacts/";
var artifactName = "artifact.zip";
var solutionPath = "./AspNetCore.CrudDemo.sln";
var projectPath = "./AspNetCore.CrudDemo";
var projectJsonPath = projectPath + "/project.json";
var buildConfig = "Release";
Task("Clean")
.Does(() =>
{
if (DirectoryExists(outputDir))
DeleteDirectory(outputDir, recursive:true);
CreateDirectory(outputDir);
});
Task("Restore")
.Does(() => DotNetCoreRestore());
Task("Version")
.Does(() =>
{
GitVersion(new GitVersionSettings
{
UpdateAssemblyInfo = true,
OutputType = GitVersionOutput.BuildServer
});
var versionInfo = GitVersion(new GitVersionSettings{ OutputType = GitVersionOutput.Json });
var updatedProjectJson = System.IO.File.ReadAllText(projectJsonPath)
.Replace("1.0.0-*", versionInfo.NuGetVersion);
System.IO.File.WriteAllText(projectJsonPath, updatedProjectJson);
});
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Version")
.IsDependentOn("Restore")
.Does(() =>
{
MSBuild(solutionPath, new MSBuildSettings
{
Verbosity = Verbosity.Minimal,
ToolVersion = MSBuildToolVersion.VS2015,
Configuration = buildConfig,
PlatformTarget = PlatformTarget.MSIL
});
});
Task("Test")
.IsDependentOn("Build")
.Does(() =>
{
DotNetCoreTest("./AspNetCore.CrudDemo.Controllers.Tests");
// Because DocumentDB emulator is not yet supported on CI
if (BuildSystem.IsLocalBuild)
DotNetCoreTest("./AspNetCore.CrudDemo.Services.Tests");
});
Task("Publish")
.IsDependentOn("Test")
.Does(() =>
{
var settings = new DotNetCorePublishSettings
{
Configuration = buildConfig,
OutputDirectory = outputDir
};
DotNetCorePublish(projectPath, settings);
Zip(outputDir, artifactName);
if (BuildSystem.IsRunningOnAppVeyor)
{
var files = GetFiles(artifactName);
foreach(var file in files)
AppVeyor.UploadArtifact(file.FullPath);
}
});
Task("Default")
.IsDependentOn("Publish");
RunTarget(target); | mit | C# |
d8b07d2a36baf95bbb92ba7935067f9cc2f79730 | Change type of child order id | kiyoaki/bitflyer-api-dotnet-client | src/BitFlyer.Apis/ResponseData/ChildOrder.cs | src/BitFlyer.Apis/ResponseData/ChildOrder.cs | using System.Runtime.Serialization;
using System.Text;
using Utf8Json;
namespace BitFlyer.Apis
{
public class ChildOrder
{
[DataMember(Name = "id")]
public long Id { get; set; }
[DataMember(Name = "child_order_id")]
public string ChildOrderId { get; set; }
[DataMember(Name = "product_code")]
public string ProductCode { get; set; }
[DataMember(Name = "side")]
public Side Side { get; set; }
[DataMember(Name = "child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[DataMember(Name = "price")]
public double Price { get; set; }
[DataMember(Name = "average_price")]
public double AveragePrice { get; set; }
[DataMember(Name = "size")]
public double Size { get; set; }
[DataMember(Name = "child_order_state")]
public ChildOrderState ChildOrderState { get; set; }
[DataMember(Name = "expire_date")]
public string ExpireDate { get; set; }
[DataMember(Name = "child_order_date")]
public string ChildOrderDate { get; set; }
[DataMember(Name = "child_order_acceptance_id")]
public string ChildOrderAcceptanceId { get; set; }
[DataMember(Name = "outstanding_size")]
public double OutstandingSize { get; set; }
[DataMember(Name = "cancel_size")]
public double CancelSize { get; set; }
[DataMember(Name = "executed_size")]
public double ExecutedSize { get; set; }
[DataMember(Name = "total_commission")]
public double TotalCommission { get; set; }
public override string ToString()
{
return Encoding.UTF8.GetString(JsonSerializer.Serialize(this));
}
}
}
| using System.Runtime.Serialization;
using System.Text;
using Utf8Json;
namespace BitFlyer.Apis
{
public class ChildOrder
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "child_order_id")]
public string ChildOrderId { get; set; }
[DataMember(Name = "product_code")]
public string ProductCode { get; set; }
[DataMember(Name = "side")]
public Side Side { get; set; }
[DataMember(Name = "child_order_type")]
public ChildOrderType ChildOrderType { get; set; }
[DataMember(Name = "price")]
public double Price { get; set; }
[DataMember(Name = "average_price")]
public double AveragePrice { get; set; }
[DataMember(Name = "size")]
public double Size { get; set; }
[DataMember(Name = "child_order_state")]
public ChildOrderState ChildOrderState { get; set; }
[DataMember(Name = "expire_date")]
public string ExpireDate { get; set; }
[DataMember(Name = "child_order_date")]
public string ChildOrderDate { get; set; }
[DataMember(Name = "child_order_acceptance_id")]
public string ChildOrderAcceptanceId { get; set; }
[DataMember(Name = "outstanding_size")]
public double OutstandingSize { get; set; }
[DataMember(Name = "cancel_size")]
public double CancelSize { get; set; }
[DataMember(Name = "executed_size")]
public double ExecutedSize { get; set; }
[DataMember(Name = "total_commission")]
public double TotalCommission { get; set; }
public override string ToString()
{
return Encoding.UTF8.GetString(JsonSerializer.Serialize(this));
}
}
}
| mit | C# |
080b8cd367c5277c4cb0f43093e763b325bba51c | Update Views to be a catalogItem | smithab/azure-sdk-for-net,djyou/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,begoldsm/azure-sdk-for-net,peshen/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,djyou/azure-sdk-for-net,pankajsn/azure-sdk-for-net,nathannfan/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,markcowl/azure-sdk-for-net,begoldsm/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,hyonholee/azure-sdk-for-net,r22016/azure-sdk-for-net,mihymel/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,hyonholee/azure-sdk-for-net,shutchings/azure-sdk-for-net,mihymel/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,samtoubia/azure-sdk-for-net,AzCiS/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pilor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,AzCiS/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,pilor/azure-sdk-for-net,atpham256/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,smithab/azure-sdk-for-net,samtoubia/azure-sdk-for-net,olydis/azure-sdk-for-net,btasdoven/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,shutchings/azure-sdk-for-net,smithab/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,r22016/azure-sdk-for-net,peshen/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,atpham256/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,stankovski/azure-sdk-for-net,samtoubia/azure-sdk-for-net,hyonholee/azure-sdk-for-net,pankajsn/azure-sdk-for-net,mihymel/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,r22016/azure-sdk-for-net,nathannfan/azure-sdk-for-net,peshen/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,djyou/azure-sdk-for-net,begoldsm/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jamestao/azure-sdk-for-net,atpham256/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,olydis/azure-sdk-for-net,samtoubia/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,jamestao/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,pilor/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,pankajsn/azure-sdk-for-net,btasdoven/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,btasdoven/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,stankovski/azure-sdk-for-net,shutchings/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,hyonholee/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jamestao/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,nathannfan/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AzCiS/azure-sdk-for-net,olydis/azure-sdk-for-net,jamestao/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net | src/ResourceManagement/DataLake.Analytics/Microsoft.Azure.Management.DataLake.Analytics/Generated/Models/USqlView.cs | src/ResourceManagement/DataLake.Analytics/Microsoft.Azure.Management.DataLake.Analytics/Generated/Models/USqlView.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// A Data Lake Analytics catalog U-SQL view item.
/// </summary>
public partial class USqlView : CatalogItem
{
/// <summary>
/// Initializes a new instance of the USqlView class.
/// </summary>
public USqlView() { }
/// <summary>
/// Initializes a new instance of the USqlView class.
/// </summary>
public USqlView(string computeAccountName = default(string), string version = default(string), string databaseName = default(string), string schemaName = default(string), string viewName = default(string), string definition = default(string))
: base(computeAccountName, version)
{
DatabaseName = databaseName;
SchemaName = schemaName;
ViewName = viewName;
Definition = definition;
}
/// <summary>
/// Gets or sets the name of the database.
/// </summary>
[JsonProperty(PropertyName = "databaseName")]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the schema associated with this view and
/// database.
/// </summary>
[JsonProperty(PropertyName = "schemaName")]
public string SchemaName { get; set; }
/// <summary>
/// Gets or sets the name of the view.
/// </summary>
[JsonProperty(PropertyName = "viewName")]
public string ViewName { get; set; }
/// <summary>
/// Gets or sets the defined query of the view.
/// </summary>
[JsonProperty(PropertyName = "definition")]
public string Definition { get; set; }
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
using System;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Microsoft.Rest.Azure;
/// <summary>
/// A Data Lake Analytics catalog U-SQL view item.
/// </summary>
public partial class USqlView
{
/// <summary>
/// Initializes a new instance of the USqlView class.
/// </summary>
public USqlView() { }
/// <summary>
/// Initializes a new instance of the USqlView class.
/// </summary>
public USqlView(string databaseName = default(string), string schemaName = default(string), string viewName = default(string), string definition = default(string))
{
DatabaseName = databaseName;
SchemaName = schemaName;
ViewName = viewName;
Definition = definition;
}
/// <summary>
/// Gets or sets the name of the database.
/// </summary>
[JsonProperty(PropertyName = "databaseName")]
public string DatabaseName { get; set; }
/// <summary>
/// Gets or sets the name of the schema associated with this view and
/// database.
/// </summary>
[JsonProperty(PropertyName = "schemaName")]
public string SchemaName { get; set; }
/// <summary>
/// Gets or sets the name of the view.
/// </summary>
[JsonProperty(PropertyName = "viewName")]
public string ViewName { get; set; }
/// <summary>
/// Gets or sets the defined query of the view.
/// </summary>
[JsonProperty(PropertyName = "definition")]
public string Definition { get; set; }
}
}
| mit | C# |
fbcab418b5bb3b8da7cbe4c62c1c0b3166970c9b | Fix unlock user (#9701) | xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Users/Views/UserButtons.cshtml | src/OrchardCore.Modules/OrchardCore.Users/Views/UserButtons.cshtml | @model SummaryAdminUserViewModel
@using OrchardCore.Entities
@using OrchardCore.Users.Models
@using Microsoft.AspNetCore.Identity
@using OrchardCore.Users
@inject UserManager<IUser> UserManager
@inject IAuthorizationService AuthorizationService
@{
var user = Model.User as User;
var currentUser = user.UserName == User.Identity.Name;
var hasManageUser = await AuthorizationService.AuthorizeAsync(User, Permissions.ManageUsers, user);
var isLockedOut = await UserManager.IsLockedOutAsync(user);
}
<a asp-action="Edit" asp-route-id="@user.UserId" class="btn btn-primary btn-sm">@T["Edit"]</a>
@if (hasManageUser)
{
if (!currentUser)
{
<a class="btn btn-danger btn-sm" asp-action="Delete" asp-route-id="@user.UserId" data-url-af="RemoveUrl UnsafeUrl" >@T["Delete"]</a>
}
<a asp-action="EditPassword" asp-route-id="@user.UserId" class="btn btn-secondary btn-sm">@T["Edit Password"]</a>
if (isLockedOut)
{
<a asp-action="Unlock" asp-route-id="@user.UserId" class="btn btn-danger btn-sm" data-url-af="RemoveUrl UnsafeUrl" data-title="@T["Unlock user"]" data-message="@T["Are you sure you want to unlock this user?"]">@T["Unlock"]</a>
}
}
@if (!user.EmailConfirmed && Site.As<RegistrationSettings>().UsersMustValidateEmail && hasManageUser)
{
<form method="post" class="d-inline-block">
<input name="id" type="hidden" value="@user.UserId" />
<button asp-action="SendVerificationEmail" asp-controller="Registration" class="btn btn-info btn-sm">@T["Send verification email"]</button>
</form>
}
| @model SummaryAdminUserViewModel
@using OrchardCore.Entities
@using OrchardCore.Users.Models
@using Microsoft.AspNetCore.Identity
@using OrchardCore.Users
@inject UserManager<IUser> UserManager
@inject IAuthorizationService AuthorizationService
@{
var user = Model.User as User;
var currentUser = user.UserName == User.Identity.Name;
var hasManageUser = await AuthorizationService.AuthorizeAsync(User, Permissions.ManageUsers, user);
var isLockedOut = await UserManager.IsLockedOutAsync(user);
}
<a asp-action="Edit" asp-route-id="@user.UserId" class="btn btn-primary btn-sm">@T["Edit"]</a>
@if (hasManageUser)
{
if (!currentUser)
{
<a class="btn btn-danger btn-sm" asp-action="Delete" asp-route-id="@user.UserId" data-url-af="RemoveUrl UnsafeUrl" >@T["Delete"]</a>
}
<a asp-action="EditPassword" asp-route-id="@user.UserId" class="btn btn-secondary btn-sm">@T["Edit Password"]</a>
if (isLockedOut)
{
<a asp-action="Unlock" asp-route-id="@user.Id" class="btn btn-danger btn-sm" data-url-af="RemoveUrl UnsafeUrl" data-title="@T["Unlock user"]" data-message="@T["Are you sure you want to unlock this user?"]">@T["Unlock"]</a>
}
}
@if (!user.EmailConfirmed && Site.As<RegistrationSettings>().UsersMustValidateEmail && hasManageUser)
{
<form method="post" class="d-inline-block">
<input name="id" type="hidden" value="@user.UserId" />
<button asp-action="SendVerificationEmail" asp-controller="Registration" class="btn btn-info btn-sm">@T["Send verification email"]</button>
</form>
}
| bsd-3-clause | C# |
0e9d0f037efe9d9017bbbedf7ac22f69688a1d2b | update version 1.3 => 1.3.1 | devmondo/HangFire.SimpleInjector | src/HangFire.SimpleInjector/Properties/AssemblyInfo.cs | src/HangFire.SimpleInjector/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("Hangfire.SimpleInjector")]
[assembly: AssemblyDescription("SimpleInjector IoC Hangfire Integration")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevMondo")]
[assembly: AssemblyProduct("Hangfire.SimpleInjector")]
[assembly: AssemblyCopyright("Copyright © DevMondo 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9157e269-315d-4de0-ac0d-1dad63eee2e2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.1.0")]
[assembly: AssemblyFileVersion("1.3.1.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("Hangfire.SimpleInjector")]
[assembly: AssemblyDescription("SimpleInjector IoC Hangfire Integration")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("DevMondo")]
[assembly: AssemblyProduct("Hangfire.SimpleInjector")]
[assembly: AssemblyCopyright("Copyright © DevMondo 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9157e269-315d-4de0-ac0d-1dad63eee2e2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| mit | C# |
76d15ba83ee82bf52627d78b45998139ef772124 | Fix LanguageString (#3196) | ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE | Source/ACE.DatLoader/FileTypes/LanguageString.cs | Source/ACE.DatLoader/FileTypes/LanguageString.cs | using System.IO;
namespace ACE.DatLoader.FileTypes
{
/// <summary>
/// These are client_portal.dat files starting with 0x31.
/// This is called a "String" in the client; It has been renamed to avoid conflicts with the generic "String" class.
/// </summary>
[DatFileType(DatFileType.String)]
public class LanguageString : FileType
{
public string CharBuffer;
public override void Unpack(BinaryReader reader)
{
Id = reader.ReadUInt32();
uint strLen = reader.ReadCompressedUInt32();
if (strLen > 0)
{
byte[] thestring = reader.ReadBytes((int)strLen);
CharBuffer = System.Text.Encoding.Default.GetString(thestring);
}
}
}
}
| using System.IO;
namespace ACE.DatLoader.FileTypes
{
/// <summary>
/// These are client_portal.dat files starting with 0x31.
/// This is called a "String" in the client; It has been renamed to avoid conflicts with the generic "String" class.
/// </summary>
[DatFileType(DatFileType.String)]
public class LanguageString : FileType
{
public string CharBuffer;
public override void Unpack(BinaryReader reader)
{
Id = reader.ReadUInt32();
uint strLen = reader.ReadCompressedUInt32();
if (strLen > 0)
CharBuffer = reader.ReadPString(strLen);
}
}
}
| agpl-3.0 | C# |
81e5d852c6e277535f1268e5225bbdf7afedb288 | Fix ReturnsDefaultRepresenationCurrentCulture test for all cultures | omar/ByteSize | src/ByteSizeLib.Tests/Binary/ToBinaryStringMethod.cs | src/ByteSizeLib.Tests/Binary/ToBinaryStringMethod.cs | using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
| using System.Globalization;
using Xunit;
namespace ByteSizeLib.Tests.BinaryByteSizeTests
{
public class ToBinaryStringMethod
{
[Fact]
public void ReturnsDefaultRepresenation()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
// Act
var result = b.ToBinaryString(CultureInfo.InvariantCulture);
// Assert
Assert.Equal("9.77 KiB", result);
}
[Fact]
public void ReturnsDefaultRepresenationCurrentCulture()
{
// Arrange
var b = ByteSize.FromKiloBytes(10);
var s = CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator;
// Act
var result = b.ToBinaryString(CultureInfo.CurrentCulture);
// Assert
Assert.Equal($"9{s}77 KiB", result);
}
}
}
| mit | C# |
d89d42cdc3df5561a0cdae38462de514a972da4a | Configure StartupExtensions to use our new services | denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs | src/Diploms.WebUI/Configuration/StartupExtensions.cs | src/Diploms.WebUI/Configuration/StartupExtensions.cs | using Diploms.Core;
using Diploms.DataLayer;
using Diploms.Services.Departments;
using Diploms.WebUI.Authentication;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection AddDepartments(this IServiceCollection services)
{
services.AddScoped<IRepository<Department>, RepositoryBase<Department>>();
services.AddScoped<DepartmentsService>();
return services;
}
public static IServiceCollection AddJWTTokens(this IServiceCollection services)
{
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<IUserRepository, UserRepository>();
return services;
}
}
} | using Diploms.Core;
using Diploms.DataLayer;
using Diploms.Services.Departments;
using Microsoft.Extensions.DependencyInjection;
namespace Diploms.WebUI.Configuration
{
public static class StartupExtensions
{
public static IServiceCollection AddDepartments(this IServiceCollection services)
{
services.AddScoped<IRepository<Department>, RepositoryBase<Department>>();
services.AddScoped<DepartmentsService>();
return services;
}
}
} | mit | C# |
330eb6e5ea01b02800b64f71257839d2fb2449b1 | bump version | Fody/Fielder | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Fielder")]
[assembly: AssemblyProduct("Fielder")]
[assembly: AssemblyVersion("1.1.6")] | using System.Reflection;
[assembly: AssemblyTitle("Fielder")]
[assembly: AssemblyProduct("Fielder")]
[assembly: AssemblyVersion("1.1.5")] | mit | C# |
6544b6308c9aca9ba34a040c9bb473c08cdbf8af | Make NSIndexSet an IEnumerable | cwensley/maccore,beni55/maccore,jorik041/maccore,mono/maccore | src/Foundation/NSIndexSet.cs | src/Foundation/NSIndexSet.cs | //
// Authors:
// James Clancey james.clancey@gmail.com>
//
// 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSIndexSet : IEnumerable, IEnumerable<uint> {
IEnumerator IEnumerable.GetEnumerator ()
{
for (uint i = this.FirstIndex; i <= this.LastIndex;) {
yield return i;
i = this.IndexGreaterThan (i);
}
}
public IEnumerator<uint> GetEnumerator ()
{
for (uint i = this.FirstIndex; i <= this.LastIndex;) {
yield return i;
i = this.IndexGreaterThan (i);
}
}
public uint[] ToArray ()
{
uint [] indexes = new uint [Count];
int j = 0;
for (uint i = this.FirstIndex; i <= this.LastIndex;) {
indexes [j++] = i;
i = this.IndexGreaterThan (i);
}
return indexes;
}
public static NSIndexSet FromArray (uint[] items)
{
if (items == null)
return new NSIndexSet ();
var indexSet = new NSMutableIndexSet();
foreach (var index in items)
indexSet.Add (index);
return indexSet;
}
}
}
| //
// Authors:
// James Clancey james.clancey@gmail.com>
//
// 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.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public partial class NSIndexSet {
public uint[] ToArray ()
{
uint [] indexes = new uint [Count];
int j = 0;
for (uint i = this.FirstIndex; i <= this.LastIndex;) {
indexes [j++] = i;
i = this.IndexGreaterThan (i);
}
return indexes;
}
public static NSIndexSet FromArray (uint[] items)
{
if (items == null)
return new NSIndexSet ();
var indexSet = new NSMutableIndexSet();
foreach (var index in items)
indexSet.Add (index);
return indexSet;
}
}
}
| apache-2.0 | C# |
e9d6292d04e32f776326645a7baccd7723d11a8e | Add newfile Droid/MainActivity.cs | ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl | Droid/MainActivity.cs | Droid/MainActivity.cs |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace userAuth.cpl.Droid
{
[Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
LoadApplication (new App ());
// Create your apponlication here
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace userAuth.cpl.Droid
{
[Activity (Label = "MainActivity")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Create your application here
}
}
}
| mit | C# |
9d71f68d59aab695fb22306998f76c7bc2a53c98 | Add Fields prop to EndpointBase | arthurrump/Zermelo.API | Zermelo/Zermelo.API/Endpoints/EndpointBase.cs | Zermelo/Zermelo.API/Endpoints/EndpointBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Endpoints
{
abstract internal class EndpointBase
{
protected IAuthentication _auth;
protected IUrlBuilder _urlBuilder;
protected IHttpService _httpService;
protected IJsonService _jsonService;
protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService)
{
_auth = auth;
_urlBuilder = urlBuilder;
_httpService = httpService;
_jsonService = jsonService;
}
/// <summary>
/// The list of fields to return. Set to <c>null</c> or an empty list for defaults.
/// </summary>
public List<string> Fields { get; set; } = null;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zermelo.API.Interfaces;
using Zermelo.API.Services.Interfaces;
namespace Zermelo.API.Endpoints
{
abstract internal class EndpointBase
{
protected IAuthentication _auth;
protected IUrlBuilder _urlBuilder;
protected IHttpService _httpService;
protected IJsonService _jsonService;
protected EndpointBase(IAuthentication auth, IUrlBuilder urlBuilder, IHttpService httpService, IJsonService jsonService)
{
_auth = auth;
_urlBuilder = urlBuilder;
_httpService = httpService;
_jsonService = jsonService;
}
}
}
| mit | C# |
16973e7db1fb7610e39a68976237b72fca28b1c5 | Use CssParser front-end as intended | Livven/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,Livven/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,Livven/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,zedr0n/AngleSharp.Local | AngleSharp.Performance.Css/AngleSharpParser.cs | AngleSharp.Performance.Css/AngleSharpParser.cs | namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
static readonly CssParserOptions options = new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
};
static readonly CssParser parser = new CssParser(options, configuration);
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
parser.ParseStylesheet(source);
}
}
}
| namespace AngleSharp.Performance.Css
{
using AngleSharp;
using AngleSharp.Parser.Css;
using System;
class AngleSharpParser : ITestee
{
static readonly IConfiguration configuration = new Configuration().WithCss();
public String Name
{
get { return "AngleSharp"; }
}
public Type Library
{
get { return typeof(CssParser); }
}
public void Run(String source)
{
var parser = new CssParser(source, configuration);
parser.Parse(new CssParserOptions
{
IsIncludingUnknownDeclarations = true,
IsIncludingUnknownRules = true,
IsToleratingInvalidConstraints = true,
IsToleratingInvalidValues = true
});
}
}
}
| mit | C# |
695d0589d8efd6fc55a908e4d7af4fd560ae64a5 | Update to AssemblyInfo | taiste/ImmutableClass.Fody | AssemblyToReference/Properties/AssemblyInfo.cs | AssemblyToReference/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("ImmutableClass")]
[assembly: AssemblyDescription("A Fody add-in that generates a fully usable immutable class from a stub")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Taiste Oy")]
[assembly: AssemblyProduct("ImmutableClass")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dc0aacb8-e1bc-4d27-b045-f1bdaf803fb8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| 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("ImmutableClass")]
[assembly: AssemblyDescription("A Fody add-in that generates a fully usable immutable class from a stub")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Taiste Oy")]
[assembly: AssemblyProduct("ImmutableClass")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("dc0aacb8-e1bc-4d27-b045-f1bdaf803fb8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
| mit | C# |
d0aa9665db1940104be6112cf9e73f8b616f5c59 | Remove debugging logs | allmonty/BrokenShield,allmonty/BrokenShield | Assets/Scripts/AI/Enemy/TargetSpot_Decision.cs | Assets/Scripts/AI/Enemy/TargetSpot_Decision.cs | using UnityEngine;
[CreateAssetMenu (menuName = "AI/Decisions/TargetSpot")]
public class TargetSpot_Decision : Decision {
[SerializeField] float lookRange;
[SerializeField] string targetTag;
public override bool Decide(StateController controller) {
return TargetInSight(controller);
}
private bool TargetInSight(StateController controller) {
Enemy_StateController control = controller as Enemy_StateController;
RaycastHit hit;
Debug.DrawRay(control.eyes.position, control.eyes.forward.normalized * lookRange, Color.green);
Vector3 origin = control.eyes.position;
Vector3 direction = control.eyes.forward;
if( Physics.Raycast(origin, direction, out hit) && hit.collider.CompareTag("Player") ) {
return true;
}
else {
return false;
}
}
} | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu (menuName = "AI/Decisions/TargetSpot")]
public class TargetSpot_Decision : Decision {
[SerializeField] float lookRange;
[SerializeField] string targetTag;
public override bool Decide(StateController controller) {
return TargetInSight(controller);
}
private bool TargetInSight(StateController controller) {
Enemy_StateController control = controller as Enemy_StateController;
RaycastHit hit;
Debug.DrawRay(control.eyes.position, control.eyes.forward.normalized * lookRange, Color.green);
Vector3 origin = control.eyes.position;
Vector3 direction = control.eyes.forward;
if( Physics.Raycast(origin, direction, out hit) && hit.collider.CompareTag("Player") ) {
Debug.Log(targetTag + " SPOTTED");
return true;
}
else {
Debug.Log("Searching for " + targetTag);
return false;
}
}
} | apache-2.0 | C# |
986af3dbec492f8c251846e2dfcca5ab9f32c513 | Update MinValueInSortedArrayWithDuplicates.cs | shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms,shreeharshas/Algorithms,shreeharshas/hackerrank,shreeharshas/Algorithms | interim/MinValueInSortedArrayWithDuplicates.cs | interim/MinValueInSortedArrayWithDuplicates.cs | public class Solution {
private int minVal;
public int FindMin(int[] nums) {
if(nums.Length==0)
return -1;
if(nums.Length==1)
return nums[0];
if(nums.Length==2)
return Math.Min(nums[0],nums[1]);
int? x = modifiedBinarySearch(nums, 0, (nums.Length-1)/2, nums.Length-1);
if(x==null)
return nums[0];
else
return Math.Min((int)x,minVal);
}
private int? modifiedBinarySearch(int []nums, int low, int mid, int high){
minVal = Math.Min(minVal, nums[0]);
if(nums[0]<nums[nums.Length-1]){//array not rotated
return nums[0];
}
if(low > mid){
minVal = mid;
return modifiedBinarySearch(nums, low, (low+mid)/2, mid);
}
else if(low<mid){
minVal = low;
return modifiedBinarySearch(nums, mid, (mid+high)/2, high);
}
else{//low = mid
if(mid==high){
minVal = nums[0];
return null;
}
else{
return modifiedBinarySearch(nums, mid, (mid+high)/2,high);
}
}
}
public static void Main(string []args){
Solution s = new Solution();
int[] nums = {5,6,7,8,9,0,1,2,3,4};
Console.WriteLine(s.FindMin(nums));
}
}
| public class Solution {
private int minVal;
public int FindMin(int[] nums) {
if(nums.Length==0)
return -1;
if(nums.Length==1)
return nums[0];
if(nums.Length==2)
return Math.Min(nums[0],nums[1]);
int? x = modifiedBinarySearch(nums, 0, (nums.Length-1)/2, nums.Length-1);
if(x==null)
return nums[0];
else
return Math.Min((int)x,minVal);
}
private int? modifiedBinarySearch(int []nums, int low, int mid, int high){
if(nums.Length==0)
return null;
minVal = Math.Min(minVal, nums[0]);
if(nums[0]<nums[nums.Length-1]){//array not rotated
return nums[0];
}
if(low > mid){
minVal = mid;
return modifiedBinarySearch(nums, low, (low+mid)/2, mid);
}
else if(low<mid){
minVal = low;
return modifiedBinarySearch(nums, mid, (mid+high)/2, high);
}
else{//low = mid
if(mid==high){
minVal = nums[0];
return null;
}
else{
return modifiedBinarySearch(nums, mid, (mid+high)/2,high);
}
}
}
}
| mit | C# |
1f1d5c3b18e20621a2f621d6ad3bbec038277d4b | add ModelBinderProvider tests | ssg/TurkishId | test/TurkishId.ModelBinderTest/TurkishIdModelBinderProviderTest.cs | test/TurkishId.ModelBinderTest/TurkishIdModelBinderProviderTest.cs | using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata;
using Moq;
using NUnit.Framework;
using TurkishId.ModelBinder;
namespace TurkishId.ModelBinderTest
{
[TestFixture]
public class TurkishIdModelBinderProviderTest
{
public abstract class FakeStringModelMetadata : ModelMetadata
{
public FakeStringModelMetadata()
: base(ModelMetadataIdentity.ForType(typeof(string)))
{
}
}
public abstract class FakeTurkishIdNumberModelMetadata : ModelMetadata
{
public FakeTurkishIdNumberModelMetadata()
: base(ModelMetadataIdentity.ForType(typeof(TurkishIdNumber)))
{
}
}
[Test]
public void GetBinder_ModelTypeIsTurkishIdNumber_ReturnsTurkishIdNumberModelBinder()
{
var metadataMock = new Mock<FakeTurkishIdNumberModelMetadata>();
var mock = new Mock<ModelBinderProviderContext>();
_ = mock.SetupGet(c => c.Metadata).Returns(metadataMock.Object);
var provider = new TurkishIdModelBinderProvider();
var result = provider.GetBinder(mock.Object);
Assert.That(result, Is.InstanceOf<TurkishIdModelBinder>());
}
[Test]
public void GetBinder_ModelTypeIsSomethingElse_ReturnsNull()
{
var metadataMock = new Mock<FakeStringModelMetadata>();
var mock = new Mock<ModelBinderProviderContext>();
_ = mock.SetupGet(c => c.Metadata).Returns(metadataMock.Object);
var provider = new TurkishIdModelBinderProvider();
var result = provider.GetBinder(mock.Object);
Assert.That(result, Is.Null);
}
}
}
| using System;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Moq;
using NUnit.Framework;
using TurkishId.ModelBinder;
namespace TurkishId.ModelBinderTest
{
[TestFixture]
public class TurkishIdModelBinderProviderTest
{
[Test]
public void GetBinder_ModelTypeIsTurkishIdNumber_ReturnsTurkishIdNumberModelBinder()
{
var mock = new Mock<ModelBinderProviderContext>();
_ = mock.Setup(c => c.Metadata.ModelType).Returns(typeof(TurkishIdNumber));
var provider = new TurkishIdModelBinderProvider();
var result = provider.GetBinder(mock.Object);
Assert.That(result, Is.InstanceOf<TurkishIdModelBinder>());
}
[Test]
public void GetBinder_ModelTypeIsSomethingElse_ReturnsNull()
{
var mock = new Mock<ModelBinderProviderContext>();
_ = mock.Setup(c => c.Metadata.ModelType).Returns(typeof(string));
var provider = new TurkishIdModelBinderProvider();
var result = provider.GetBinder(mock.Object);
Assert.That(result, Is.Null);
}
}
}
| apache-2.0 | C# |
5a3e55e820de1c94dfc23839b2169412743dafec | Remove trailing slash from safe dir | sschmid/Entitas-CSharp,sschmid/Entitas-CSharp | Addons/Entitas.CodeGeneration.Plugins/Plugins/PostProcessors/WriteToDiskPostProcessor.cs | Addons/Entitas.CodeGeneration.Plugins/Plugins/PostProcessors/WriteToDiskPostProcessor.cs | using System;
using System.IO;
namespace Entitas.CodeGenerator {
public class WriteToDiskPostProcessor : ICodeGenFilePostProcessor {
public string name { get { return "Write to disk"; } }
public int priority { get { return 100; } }
public bool isEnabledByDefault { get { return true; } }
public bool runInDryMode { get { return false; } }
readonly string _directory;
public WriteToDiskPostProcessor() : this(new CodeGeneratorConfig(Preferences.LoadConfig()).targetDirectory) {
}
public WriteToDiskPostProcessor(string directory) {
_directory = getSafeDir(directory);
}
public CodeGenFile[] PostProcess(CodeGenFile[] files) {
cleanDir();
foreach(var file in files) {
var fileName = _directory + "/" + file.fileName;
var targetDir = Path.GetDirectoryName(fileName);
if(!Directory.Exists(targetDir)) {
Directory.CreateDirectory(targetDir);
}
File.WriteAllText(fileName, file.fileContent);
}
return files;
}
static string getSafeDir(string directory) {
if(!directory.EndsWith("/", StringComparison.Ordinal)) {
directory += "/";
}
if(!directory.EndsWith("Generated/", StringComparison.Ordinal)) {
directory += "Generated";
}
return directory;
}
void cleanDir() {
if(Directory.Exists(_directory)) {
var files = new DirectoryInfo(_directory).GetFiles("*.cs", SearchOption.AllDirectories);
foreach(var file in files) {
try {
File.Delete(file.FullName);
} catch {
Console.WriteLine("Could not delete file " + file);
}
}
} else {
Directory.CreateDirectory(_directory);
}
}
}
}
| using System;
using System.IO;
namespace Entitas.CodeGenerator {
public class WriteToDiskPostProcessor : ICodeGenFilePostProcessor {
public string name { get { return "Write to disk"; } }
public int priority { get { return 100; } }
public bool isEnabledByDefault { get { return true; } }
public bool runInDryMode { get { return false; } }
readonly string _directory;
public WriteToDiskPostProcessor() : this(new CodeGeneratorConfig(Preferences.LoadConfig()).targetDirectory) {
}
public WriteToDiskPostProcessor(string directory) {
_directory = getSafeDir(directory);
}
public CodeGenFile[] PostProcess(CodeGenFile[] files) {
cleanDir();
foreach(var file in files) {
var fileName = _directory + file.fileName;
var targetDir = Path.GetDirectoryName(fileName);
if(!Directory.Exists(targetDir)) {
Directory.CreateDirectory(targetDir);
}
File.WriteAllText(fileName, file.fileContent);
}
return files;
}
static string getSafeDir(string directory) {
if(!directory.EndsWith("/", StringComparison.Ordinal)) {
directory += "/";
}
if(!directory.EndsWith("Generated/", StringComparison.Ordinal)) {
directory += "Generated/";
}
return directory;
}
void cleanDir() {
if(Directory.Exists(_directory)) {
var files = new DirectoryInfo(_directory).GetFiles("*.cs", SearchOption.AllDirectories);
foreach(var file in files) {
try {
File.Delete(file.FullName);
} catch {
Console.WriteLine("Could not delete file " + file);
}
}
} else {
Directory.CreateDirectory(_directory);
}
}
}
}
| mit | C# |
1674f6afc68a89a2570c35fd40a0f1d277f08ac5 | Add some more properties to hover info. | DartVS/DartVS,DartVS/DartVS,modulexcite/DartVS,modulexcite/DartVS,DartVS/DartVS,modulexcite/DartVS | DanTup.DartAnalysis/Commands/AnalysisGetHover.cs | DanTup.DartAnalysis/Commands/AnalysisGetHover.cs | using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
public string parameter;
public string propagatedType;
public string staticType;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
| using System.Threading.Tasks;
namespace DanTup.DartAnalysis
{
class AnalysisGetHoverRequest : Request<AnalysisGetHoverParams, Response<AnalysisGetHoverResponse>>
{
public string method = "analysis.getHover";
public AnalysisGetHoverRequest(string file, int offset)
{
this.@params = new AnalysisGetHoverParams(file, offset);
}
}
class AnalysisGetHoverParams
{
public string file;
public int offset;
public AnalysisGetHoverParams(string file, int offset)
{
this.file = file;
this.offset = offset;
}
}
class AnalysisGetHoverResponse
{
public AnalysisHoverItem[] hovers = null;
}
public class AnalysisHoverItem
{
public string containingLibraryPath;
public string containingLibraryName;
public string dartdoc;
public string elementDescription;
}
public static class AnalysisGetHoverImplementation
{
public static async Task<AnalysisHoverItem[]> GetHover(this DartAnalysisService service, string file, int offset)
{
var response = await service.Service.Send(new AnalysisGetHoverRequest(file, offset));
return response.result.hovers;
}
}
}
| mit | C# |
a24949f772acb37245578dfac48b51383beb6297 | fix locator url | agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov,agrc/api.mapserv.utah.gov | WebAPI.API/Commands/Geocode/GetAltNameLocatorsForLocationCommand.cs | WebAPI.API/Commands/Geocode/GetAltNameLocatorsForLocationCommand.cs | using System.Configuration;
using WebAPI.Common.Abstractions;
using WebAPI.Domain;
using WebAPI.Domain.ArcServerResponse.Geolocator;
namespace WebAPI.API.Commands.Geocode
{
public class GetAltNameLocatorsForLocationCommand : Command<LocatorDetails>
{
public GetAltNameLocatorsForLocationCommand(Location location)
{
Location = location;
Host = ConfigurationManager.AppSettings["gis_server_host"];
}
public Location Location { get; set; }
public string Host { get; set; }
public override string ToString()
{
return string.Format("{0}, Location: {1}, Host: {2}", "GetAltNameLocatorsForLocationCommand", Location, Host);
}
protected override void Execute()
{
Result =
new LocatorDetails
{
Url =
string.Format("http://{0}", Host) +
"/arcgis/rest/services/Geolocators/Roads_AddressSystem_STREET/GeocodeServer/reverseGeocode?location={0},{1}&distance={2}&outSR={3}&f=json",
Name = "Centerlines.StatewideRoads"
};
}
}
} | using System.Configuration;
using WebAPI.Common.Abstractions;
using WebAPI.Domain;
using WebAPI.Domain.ArcServerResponse.Geolocator;
namespace WebAPI.API.Commands.Geocode
{
public class GetAltNameLocatorsForLocationCommand : Command<LocatorDetails>
{
public GetAltNameLocatorsForLocationCommand(Location location)
{
Location = location;
Host = ConfigurationManager.AppSettings["gis_server_host"];
}
public Location Location { get; set; }
public string Host { get; set; }
public override string ToString()
{
return string.Format("{0}, Location: {1}, Host: {2}", "GetAltNameLocatorsForLocationCommand", Location, Host);
}
protected override void Execute()
{
Result =
new LocatorDetails
{
Url =
string.Format("http://{0}", Host) +
"/arcgis/rest/services/Geolocators/Roads_AddressSystem/GeocodeServer/reverseGeocode?location={0},{1}&distance={2}&outSR={3}&f=json",
Name = "Centerlines.StatewideRoads"
};
}
}
} | mit | C# |
6382df06d25699c285f0fc313dd6bcccfe2c260e | Implement the second overload of Select | BillWagner/MVA-LINQ,sushantgoel/MVA-LINQ | CodePlayground/Program.cs | CodePlayground/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, int, TResult> transform)
{
int index = 0;
foreach (TSource item in inputSequence)
yield return transform(item, index++);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select((item, index) =>
new { index, item }))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodePlayground
{
public static class MyLinqMethods
{
public static IEnumerable<T> Where<T>(
this IEnumerable<T> inputSequence,
Func<T, bool> predicate)
{
foreach (T item in inputSequence)
if (predicate(item))
yield return item;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> inputSequence,
Func<TSource, TResult> transform)
{
foreach (TSource item in inputSequence)
yield return transform(item);
}
}
class Program
{
static void Main(string[] args)
{
// Generate items using a factory:
var items = GenerateSequence(i => i.ToString());
foreach (var item in items.Where(item => item.Length < 2))
Console.WriteLine(item);
foreach (var item in items.Select(item =>
new string(item.PadRight(9).Reverse().ToArray())))
Console.WriteLine(item);
return;
var moreItems = GenerateSequence(i => i);
foreach (var item in moreItems)
Console.WriteLine(item);
}
// Core syntax for an enumerable:
private static IEnumerable<T> GenerateSequence<T>(Func<int, T> factory)
{
var i = 0;
while (i++ < 100)
yield return factory(i);
}
}
}
| apache-2.0 | C# |
a7fef9d2b4d16e88e6f5a896e8572bc1b53e5f5b | Initialize wrapped SmtpClient | InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET | IntegrationEngine.Core/Mail/SmtpClientAdapter.cs | IntegrationEngine.Core/Mail/SmtpClientAdapter.cs | using System;
using System.Net.Mail;
namespace IntegrationEngine.Core
{
public class SmtpClientAdapter : ISmtpClient
{
public SmtpClient SmtpClient { get; set; }
public string Host { get { return SmtpClient.Host; } set { SmtpClient.Host = value; } }
public int Port { get { return SmtpClient.Port; } set { SmtpClient.Port = value; } }
public SmtpClientAdapter()
{
SmtpClient = new SmtpClient();
}
public virtual void Send(MailMessage mailMessage)
{
SmtpClient.Send(mailMessage);
}
}
}
| using System;
using System.Net.Mail;
namespace IntegrationEngine.Core
{
public class SmtpClientAdapter : ISmtpClient
{
public SmtpClient SmtpClient { get; set; }
public string Host { get { return SmtpClient.Host; } set { SmtpClient.Host = value; } }
public int Port { get { return SmtpClient.Port; } set { SmtpClient.Port = value; } }
public SmtpClientAdapter()
{
}
public virtual void Send(MailMessage mailMessage)
{
SmtpClient.Send(mailMessage);
}
}
}
| mit | C# |
1747535d0604db376786e186d7cdd8f2de7bd231 | Remove double licence header and add comment about Video vs VideoSprite | peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework/Graphics/Video/VideoSprite.cs | osu.Framework/Graphics/Video/VideoSprite.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework.Graphics.Video
{
/// <summary>
/// A sprite which holds a video with a custom conversion matrix. Use <see cref="Video"/> for loading and displaying a video.
/// </summary>
public class VideoSprite : Sprite
{
public VideoDecoder Decoder;
[BackgroundDependencyLoader]
private void load(GameHost gameHost, ShaderManager shaders)
{
TextureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.VIDEO);
RoundedTextureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.VIDEO_ROUNDED);
}
/// <summary>
/// YUV->RGB conversion matrix based on the video colorspace
/// </summary>
public Matrix3 ConversionMatrix => Decoder.GetConversionMatrix();
protected override DrawNode CreateDrawNode() => new VideoSpriteDrawNode(this);
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics.Shaders;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework.Graphics.Video
{
/// <summary>
/// A sprite which holds a video with a custom conversion matrix.
/// </summary>
public class VideoSprite : Sprite
{
public VideoDecoder Decoder;
[BackgroundDependencyLoader]
private void load(GameHost gameHost, ShaderManager shaders)
{
TextureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.VIDEO);
RoundedTextureShader = shaders.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.VIDEO_ROUNDED);
}
/// <summary>
/// YUV->RGB conversion matrix based on the video colorspace
/// </summary>
public Matrix3 ConversionMatrix => Decoder.GetConversionMatrix();
protected override DrawNode CreateDrawNode() => new VideoSpriteDrawNode(this);
}
}
| mit | C# |
1a9790fb35b56ef49073fd1478ebacf12b7623ec | Increment Version Number | mj1856/TimeZoneNames | SharedAssemblyInfo.cs | SharedAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")]
[assembly: AssemblyVersion("1.2.0.*")]
[assembly: AssemblyInformationalVersion("1.2.0")]
| using System.Reflection;
[assembly: AssemblyCompany("Matt Johnson")]
[assembly: AssemblyProduct("Time Zone Names")]
[assembly: AssemblyCopyright("Copyright © 2014 Matt Johnson")]
[assembly: AssemblyVersion("1.1.1.*")]
[assembly: AssemblyInformationalVersion("1.1.1")]
| mit | C# |
b03af4a7f5b36160b20db51afc32bd3f9331273d | 修改 HelloWorld Index view. | NemoChenTW/MvcMovie,NemoChenTW/MvcMovie,NemoChenTW/MvcMovie | src/MvcMovie/Views/HelloWorld/Index.cshtml | src/MvcMovie/Views/HelloWorld/Index.cshtml | @{
ViewData["Title"] = "Movie List";
}
<h2>My Movie List</h2>
<p>Hello from our View Template!</p> | @{
ViewData["Title"] = "Index";
}
<h2>Index</h2>
<p>Hello from our View Template!</p> | apache-2.0 | C# |
3cc87f8a68c1b339f68a34ed2c235fc0f093b4b0 | remove apikey for now | myty/muse,myty/muse,myty/muse | src/MyTy.Blog.Web/Modules/SiteMapModule.cs | src/MyTy.Blog.Web/Modules/SiteMapModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using MyTy.Blog.Web.Models;
using MyTy.Blog.Web.ViewModels;
using Nancy;
namespace MyTy.Blog.Web.Modules
{
public class SiteMapModule : NancyModule
{
public SiteMapModule(BlogDB db, IApplicationConfiguration config)
{
Get["/sitemap.xml"] = parameters => {
var apikey = Request.Query["key"];
//if (config.CanRefresh(apikey)) {
//}
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
var homepage = new XElement[] {
new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl)
)
};
var pages = db.Pages.Select(p => new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl + p.Href)
));
var posts = db.Posts.Select(p => new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl + p.Href)
));
return Response.AsXml(homepage.Concat(pages).Concat(posts));
};
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using MyTy.Blog.Web.Models;
using MyTy.Blog.Web.ViewModels;
using Nancy;
namespace MyTy.Blog.Web.Modules
{
public class SiteMapModule : NancyModule
{
public SiteMapModule(BlogDB db, IApplicationConfiguration config)
{
Get["/sitemap.xml"] = parameters => {
if (config.CanRefresh(Request.Query["key"])) {
}
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
var homepage = new XElement[] {
new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl)
)
};
var pages = db.Pages.Select(p => new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl + p.Href)
));
var posts = db.Posts.Select(p => new XElement(ns + "url",
new XElement(ns + "loc", config.BaseUrl + p.Href)
));
return Response.AsXml(homepage.Concat(pages).Concat(posts));
};
}
}
} | mit | C# |
fb07c9b87cee9de45df57196481401eff74dc28c | Improve test drive program. | jsakamoto/nupkg-selenium-webdriver-chromedriver | TestDrives/Program.cs | TestDrives/Program.cs | using System;
namespace TestDrive
{
class Program
{
static void Main(string[] args)
{
using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver())
{
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3);
driver.Navigate().GoToUrl("https://www.bing.com/");
driver.FindElementById("sb_form_q").SendKeys("Selenium WebDriver");
driver.FindElementByClassName("search").Click();
Console.WriteLine("OK");
Console.ReadKey(intercept: true);
}
}
}
}
| using System;
namespace TestDrive
{
class Program
{
static void Main(string[] args)
{
using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver())
{
driver.Navigate().GoToUrl("https://www.bing.com/");
driver.FindElementById("sb_form_q").SendKeys("Selenium WebDriver");
driver.FindElementById("sb_form_go").Click();
Console.WriteLine("OK");
Console.ReadKey(intercept: true);
}
}
}
}
| unlicense | C# |
d16066f9e84b1257969201efa3b0d01aed8a0caf | Fix `IBindableWithCurrent` using wrong constructor signature | ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework | osu.Framework/Bindables/IBindableWithCurrent.cs | osu.Framework/Bindables/IBindableWithCurrent.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Utils;
namespace osu.Framework.Bindables
{
public interface IBindableWithCurrent<T> : IBindable<T>, IHasCurrentValue<T>
{
/// <summary>
/// Creates a new <see cref="IBindableWithCurrent{T}"/> according to the specified value type.
/// If the value type is one supported by the <see cref="BindableNumber{T}"/>, an instance of <see cref="BindableNumberWithCurrent{T}"/> will be returned.
/// Otherwise an instance of <see cref="BindableWithCurrent{T}"/> will be returned instead.
/// </summary>
public static IBindableWithCurrent<T> Create()
{
if (Validation.IsSupportedBindableNumberType<T>())
return (IBindableWithCurrent<T>)Activator.CreateInstance(typeof(BindableNumberWithCurrent<>).MakeGenericType(typeof(T)), default(T));
return new BindableWithCurrent<T>();
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.UserInterface;
using osu.Framework.Utils;
namespace osu.Framework.Bindables
{
public interface IBindableWithCurrent<T> : IBindable<T>, IHasCurrentValue<T>
{
/// <summary>
/// Creates a new <see cref="IBindableWithCurrent{T}"/> according to the specified value type.
/// If the value type is one supported by the <see cref="BindableNumber{T}"/>, an instance of <see cref="BindableNumberWithCurrent{T}"/> will be returned.
/// Otherwise an instance of <see cref="BindableWithCurrent{T}"/> will be returned instead.
/// </summary>
public static IBindableWithCurrent<T> Create()
{
if (Validation.IsSupportedBindableNumberType<T>())
return (IBindableWithCurrent<T>)Activator.CreateInstance(typeof(BindableNumberWithCurrent<>).MakeGenericType(typeof(T)));
return new BindableWithCurrent<T>();
}
}
}
| mit | C# |
71fb51ad8900ed83b7c88bef137fff2feef39ac8 | Update IScriptRunner.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D | src/Core2D/Model/Interfaces/IScriptRunner.cs | src/Core2D/Model/Interfaces/IScriptRunner.cs | using System.Threading.Tasks;
namespace Core2D.Interfaces
{
/// <summary>
/// Executes code scripts.
/// </summary>
public interface IScriptRunner
{
/// <summary>
/// Executes code script and return current script state.
/// </summary>
/// <param name="code">The script code.</param>
/// <param name="state">The script state to continue execution from a previous state.</param>
/// <returns>The next script state.</returns>
Task<object> Execute(string code, object state);
}
}
| using System.Threading.Tasks;
namespace Core2D.Interfaces
{
/// <summary>
/// Executes code scripts.
/// </summary>
public interface IScriptRunner
{
/// <summary>
/// Executes code script.
/// </summary>
/// <param name="code">The script code.</param>
Task<object> Execute(string code);
/// <summary>
/// Executes code script and return current script state.
/// </summary>
/// <param name="code">The script code.</param>
/// <param name="state">The script state to continue execution from a previous state.</param>
/// <returns>The next script state.</returns>
Task<object> Execute(string code, object state);
}
}
| mit | C# |
f539fd1a26c1e1cda3ca81dbce57586f27a824a5 | add default timeout configuration for kafka client. | dotnetcore/CAP,ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP | src/DotNetCore.CAP.Kafka/CAP.KafkaOptions.cs | src/DotNetCore.CAP.Kafka/CAP.KafkaOptions.cs | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
/// <summary>
/// Provides programmatic configuration for the CAP kafka project.
/// </summary>
public class KafkaOptions
{
/// <summary>
/// librdkafka configuration parameters (refer to https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
/// <para>
/// Topic configuration parameters are specified via the "default.topic.config" sub-dictionary config parameter.
/// </para>
/// </summary>
public readonly ConcurrentDictionary<string, object> MainConfig;
private IEnumerable<KeyValuePair<string, object>> _kafkaConfig;
public KafkaOptions()
{
MainConfig = new ConcurrentDictionary<string, object>();
}
/// <summary>
/// Producer connection pool size, default is 10
/// </summary>
public int ConnectionPoolSize { get; set; } = 10;
/// <summary>
/// The `bootstrap.servers` item config of <see cref="MainConfig" />.
/// <para>
/// Initial list of brokers as a CSV list of broker host or host:port.
/// </para>
/// </summary>
public string Servers { get; set; }
internal IEnumerable<KeyValuePair<string, object>> AsKafkaConfig()
{
if (_kafkaConfig == null)
{
if (string.IsNullOrWhiteSpace(Servers))
{
throw new ArgumentNullException(nameof(Servers));
}
MainConfig["bootstrap.servers"] = Servers;
MainConfig["queue.buffering.max.ms"] = "10";
MainConfig["socket.blocking.max.ms"] = "10";
MainConfig["enable.auto.commit"] = "false";
MainConfig["log.connection.close"] = "false";
MainConfig["request.timeout.ms"] = "3000";
MainConfig["message.timeout.ms"] = "5000";
_kafkaConfig = MainConfig.AsEnumerable();
}
return _kafkaConfig;
}
}
} | // Copyright (c) .NET Core Community. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
namespace DotNetCore.CAP
{
/// <summary>
/// Provides programmatic configuration for the CAP kafka project.
/// </summary>
public class KafkaOptions
{
/// <summary>
/// librdkafka configuration parameters (refer to https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md).
/// <para>
/// Topic configuration parameters are specified via the "default.topic.config" sub-dictionary config parameter.
/// </para>
/// </summary>
public readonly ConcurrentDictionary<string, object> MainConfig;
private IEnumerable<KeyValuePair<string, object>> _kafkaConfig;
public KafkaOptions()
{
MainConfig = new ConcurrentDictionary<string, object>();
}
/// <summary>
/// Producer connection pool size, default is 10
/// </summary>
public int ConnectionPoolSize { get; set; } = 10;
/// <summary>
/// The `bootstrap.servers` item config of <see cref="MainConfig" />.
/// <para>
/// Initial list of brokers as a CSV list of broker host or host:port.
/// </para>
/// </summary>
public string Servers { get; set; }
internal IEnumerable<KeyValuePair<string, object>> AsKafkaConfig()
{
if (_kafkaConfig == null)
{
if (string.IsNullOrWhiteSpace(Servers))
{
throw new ArgumentNullException(nameof(Servers));
}
MainConfig["bootstrap.servers"] = Servers;
MainConfig["queue.buffering.max.ms"] = "10";
MainConfig["socket.blocking.max.ms"] = "10";
MainConfig["enable.auto.commit"] = "false";
MainConfig["log.connection.close"] = "false";
_kafkaConfig = MainConfig.AsEnumerable();
}
return _kafkaConfig;
}
}
} | mit | C# |
d999bb22462c7f4ebf585e9921444f47186dac73 | Remove unused namespaces | extremecodetv/SocksSharp | src/SocksSharp/Proxy/IProxySettingsFluent.cs | src/SocksSharp/Proxy/IProxySettingsFluent.cs | using System.Net;
namespace SocksSharp.Proxy
{
public interface IProxySettingsFluent
{
IProxySettingsFluent SetHost(string host);
IProxySettingsFluent SetPort(int port);
IProxySettingsFluent SetConnectionTimeout(int connectionTimeout);
IProxySettingsFluent SetReadWriteTimeout(int readwriteTimeout);
IProxySettingsFluent SetCredential(NetworkCredential credential);
IProxySettingsFluent SetCredential(string username, string password);
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace SocksSharp.Proxy
{
public interface IProxySettingsFluent
{
IProxySettingsFluent SetHost(string host);
IProxySettingsFluent SetPort(int port);
IProxySettingsFluent SetConnectionTimeout(int connectionTimeout);
IProxySettingsFluent SetReadWriteTimeout(int readwriteTimeout);
IProxySettingsFluent SetCredential(NetworkCredential credential);
IProxySettingsFluent SetCredential(string username, string password);
}
}
| mit | C# |
5da502ec8fb2362bbaf2f45be4eadd02b1373a0a | fix build | solomobro/Instagram,solomobro/Instagram,solomobro/Instagram | src/Solomobro.Instagram/Models/Pagination.cs | src/Solomobro.Instagram/Models/Pagination.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Solomobro.Instagram.Models
{
[DataContract]
public class Pagination
{
internal Pagination() {}
public Uri NextUrl => new Uri(NextUrlInternal);
[DataMember(Name = "next_url")]
internal string NextUrlInternal;
[DataMember(Name = "next_max_id")]
public string NextMaxId { get; internal set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Solomobro.Instagram.Models
{
[DataContract]
public class Pagination
{
internal Pagination() {};
public Uri NextUrl => new Uri(NextUrlInternal);
[DataMember(Name = "next_url")]
internal string NextUrlInternal;
[DataMember(Name = "next_max_id")]
public string NextMaxId { get; internal set; }
}
}
| apache-2.0 | C# |
714720b9aa80b63403551d88f5a7e1fbf35b00ea | Update sql commands and use the new method | Mimalef/repop | src/CustomerListEquip.aspx.cs | src/CustomerListEquip.aspx.cs | using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
fillTable(sql, ref TableEquipments);
}
}
| using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class CustomerListEquip : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
string sql = @"
SELECT *
FROM equipments
WHERE customer = '{0}'";
sql = string.Format(
sql,
Session["customer"]);
DataTable table = doQuery(sql);
foreach(DataRow row in table.Rows)
{
TableRow trow = new TableRow();
for (int i = 0; i < table.Columns.Count; i++)
{
if (table.Columns[i].ColumnName == "customer") continue;
if (table.Columns[i].ColumnName == "id") continue;
TableCell cell = new TableCell();
cell.Text = row[i].ToString();
trow.Cells.Add(cell);
}
TableEquipments.Rows.Add(trow);
}
}
}
| mit | C# |
a02eaf0e94ad08817eb70e16899918109e499f53 | Use StageDefinition to determine special column in ManiaReplayFrame | Frontear/osuKyzer,UselessToucan/osu,ppy/osu,DrabWeb/osu,peppy/osu,smoogipooo/osu,Nabile-Rahmani/osu,johnneijzen/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,NeoAdonis/osu,naoey/osu,DrabWeb/osu,smoogipoo/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,naoey/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,ZLima12/osu,johnneijzen/osu,naoey/osu,UselessToucan/osu,NeoAdonis/osu,2yangk23/osu,ZLima12/osu | osu.Game.Rulesets.Mania/Replays/ManiaReplayFrame.cs | osu.Game.Rulesets.Mania/Replays/ManiaReplayFrame.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Legacy;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Replays
{
public class ManiaReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public List<ManiaAction> Actions = new List<ManiaAction>();
public ManiaReplayFrame(double time, params ManiaAction[] actions)
: base(time)
{
Actions.AddRange(actions);
}
public void ConvertFrom(LegacyReplayFrame legacyFrame, Score score, Beatmap beatmap)
{
// We don't need to fully convert, just create the converter
var converter = new ManiaBeatmapConverter(beatmap.BeatmapInfo.Ruleset.Equals(score.Ruleset), beatmap);
// Todo: Apply mods to converter
// NB: Via co-op mod, osu-stable can have two stages with floor(col/2) and ceil(col/2) columns. This will need special handling
// elsewhere in the game if we do choose to support the old co-op mod anyway. For now, assume that there is only one stage.
var stage = new StageDefinition { Columns = converter.TargetColumns };
var normalAction = ManiaAction.Key1;
var specialAction = ManiaAction.Special1;
int activeColumns = (int)(legacyFrame.MouseX ?? 0);
int counter = 0;
while (activeColumns > 0)
{
Actions.Add((activeColumns & 1) > 0 ? specialAction : normalAction);
if (stage.IsSpecialColumn(counter))
normalAction++;
else
specialAction++;
counter++;
activeColumns >>= 1;
}
}
}
}
| // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System.Collections.Generic;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Mania.Beatmaps;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Replays.Legacy;
using osu.Game.Rulesets.Replays.Types;
using osu.Game.Rulesets.Scoring;
namespace osu.Game.Rulesets.Mania.Replays
{
public class ManiaReplayFrame : ReplayFrame, IConvertibleReplayFrame
{
public List<ManiaAction> Actions = new List<ManiaAction>();
public ManiaReplayFrame(double time, params ManiaAction[] actions)
: base(time)
{
Actions.AddRange(actions);
}
public void ConvertFrom(LegacyReplayFrame legacyFrame, Score score, Beatmap beatmap)
{
// We don't need to fully convert, just create the converter
var converter = new ManiaBeatmapConverter(beatmap.BeatmapInfo.Ruleset.Equals(score.Ruleset), beatmap);
// Todo: Apply mods to converter
// NB: Via co-op mod, osu-stable can have two stages with floor(col/2) and ceil(col/2) columns. This will need special handling
// elsewhere in the game if we do choose to support the old co-op mod anyway. For now, assume that there is only one stage.
bool isSpecialColumn(int column) => converter.TargetColumns % 2 == 1 && column == converter.TargetColumns / 2;
var normalAction = ManiaAction.Key1;
var specialAction = ManiaAction.Special1;
int activeColumns = (int)(legacyFrame.MouseX ?? 0);
int counter = 0;
while (activeColumns > 0)
{
Actions.Add((activeColumns & 1) > 0 ? specialAction : normalAction);
if (isSpecialColumn(counter))
normalAction++;
else
specialAction++;
counter++;
activeColumns >>= 1;
}
}
}
}
| mit | C# |
b2af0ea3bf4fe525e1dfa7d3f515738bd923aea3 | Clean usings. | OmniSharp/omnisharp-roslyn,OmniSharp/omnisharp-roslyn | tests/OmniSharp.MSBuild.Tests/MSBuildContextTests.cs | tests/OmniSharp.MSBuild.Tests/MSBuildContextTests.cs | using OmniSharp.MSBuild.ProjectFile;
using Xunit;
namespace OmniSharp.Tests
{
public class MSBuildContextTests
{
[Fact]
public void Project_path_is_case_insensitive()
{
var projectPath = @"c:\projects\project1\project.csproj";
var searchProjectPath = @"c:\Projects\Project1\Project.csproj";
var collection = new ProjectFileInfoCollection();
collection.Add(ProjectFileInfo.CreateEmpty(projectPath));
Assert.True(collection.TryGetValue(searchProjectPath, out var outInfo));
Assert.NotNull(outInfo);
}
}
}
| using System.Linq;
using System.Threading.Tasks;
using OmniSharp.MSBuild.ProjectFile;
using OmniSharp.MSBuild.Tests;
using TestUtility;
using Xunit;
namespace OmniSharp.Tests
{
public class MSBuildContextTests
{
[Fact]
public void Project_path_is_case_insensitive()
{
var projectPath = @"c:\projects\project1\project.csproj";
var searchProjectPath = @"c:\Projects\Project1\Project.csproj";
var collection = new ProjectFileInfoCollection();
collection.Add(ProjectFileInfo.CreateEmpty(projectPath));
Assert.True(collection.TryGetValue(searchProjectPath, out var outInfo));
Assert.NotNull(outInfo);
}
}
}
| mit | C# |
fdf93bcd764078b086816d9de4dbf6aad908beec | Make sure not to parse non-command arguments | appharbor/appharbor-cli | src/AppHarbor/CommandDispatcher.cs | src/AppHarbor/CommandDispatcher.cs | using System;
using System.IO;
using System.Linq;
using Castle.MicroKernel;
namespace AppHarbor
{
public class CommandDispatcher
{
private readonly IAliasMatcher _aliasMatcher;
private readonly ITypeNameMatcher _typeNameMatcher;
private readonly IKernel _kernel;
public CommandDispatcher(IAliasMatcher aliasMatcher, ITypeNameMatcher typeNameMatcher, IKernel kernel)
{
_aliasMatcher = aliasMatcher;
_typeNameMatcher = typeNameMatcher;
_kernel = kernel;
}
public void Dispatch(string[] args)
{
var commandArguments = args.TakeWhile(x => !x.StartsWith("-"));
var commandString = commandArguments.Any() ? string.Concat(commandArguments.Skip(1).FirstOrDefault(), args[0]) : "help";
Type matchingType = null;
int argsToSkip = 0;
if (_typeNameMatcher.IsSatisfiedBy(commandString))
{
matchingType = _typeNameMatcher.GetMatchedType(commandString);
argsToSkip = 2;
}
else if (_aliasMatcher.IsSatisfiedBy(args[0]))
{
matchingType = _aliasMatcher.GetMatchedType(args[0]);
argsToSkip = 1;
}
else
{
throw new DispatchException(string.Format("The command \"{0}\" doesn't match a command name or alias", string.Join(" ", args)));
}
var command = (Command)_kernel.Resolve(matchingType);
try
{
command.Execute(args.Skip(argsToSkip).ToArray());
}
catch (ApiException exception)
{
throw new DispatchException(string.Format("An error occured while connecting to the API. {0}", exception.Message));
}
catch (CommandException exception)
{
command.WriteUsage(invokedWith: string.Join(" ", commandArguments),
writer: _kernel.Resolve<TextWriter>());
if (!(exception is HelpException))
{
throw new DispatchException(exception.Message);
}
}
}
}
}
| using System;
using System.IO;
using System.Linq;
using Castle.MicroKernel;
namespace AppHarbor
{
public class CommandDispatcher
{
private readonly IAliasMatcher _aliasMatcher;
private readonly ITypeNameMatcher _typeNameMatcher;
private readonly IKernel _kernel;
public CommandDispatcher(IAliasMatcher aliasMatcher, ITypeNameMatcher typeNameMatcher, IKernel kernel)
{
_aliasMatcher = aliasMatcher;
_typeNameMatcher = typeNameMatcher;
_kernel = kernel;
}
public void Dispatch(string[] args)
{
var commandArgument = args.Any() ? string.Concat(args.Skip(1).FirstOrDefault(), args[0]) : "help";
Type matchingType = null;
int argsToSkip = 0;
if (_typeNameMatcher.IsSatisfiedBy(commandArgument))
{
matchingType = _typeNameMatcher.GetMatchedType(commandArgument);
argsToSkip = 2;
}
else if (_aliasMatcher.IsSatisfiedBy(args[0]))
{
matchingType = _aliasMatcher.GetMatchedType(args[0]);
argsToSkip = 1;
}
else
{
throw new DispatchException(string.Format("The command \"{0}\" doesn't match a command name or alias", string.Join(" ", args)));
}
var command = (Command)_kernel.Resolve(matchingType);
try
{
command.Execute(args.Skip(argsToSkip).ToArray());
}
catch (ApiException exception)
{
throw new DispatchException(string.Format("An error occured while connecting to the API. {0}", exception.Message));
}
catch (CommandException exception)
{
command.WriteUsage(invokedWith: string.Join(" ", args.TakeWhile(x => !x.StartsWith("-"))),
writer: _kernel.Resolve<TextWriter>());
if (!(exception is HelpException))
{
throw new DispatchException(exception.Message);
}
}
}
}
}
| mit | C# |
ee5037d63411916e2c71357030ff4e1b79f43aeb | Add touch and mouse support | danvy/win10demo | src/Win10Demo/InkView.xaml.cs | src/Win10Demo/InkView.xaml.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Core;
using Windows.UI.Input.Inking;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Win10Demo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class InkView : Page
{
private MemoryStream inkStream;
private InkManager inkManager;
public InkView()
{
this.InitializeComponent();
inkStream = new MemoryStream();
inkManager = new InkManager();
Ink.InkPresenter.IsInputEnabled = true;
Ink.InkPresenter.InputDeviceTypes = CoreInputDeviceTypes.Mouse | CoreInputDeviceTypes.Pen | CoreInputDeviceTypes.Touch;
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
await inkManager.SaveAsync(inkStream.AsOutputStream());
}
private async void LoadButton_Click(object sender, RoutedEventArgs e)
{
if ((inkStream != null) && (inkStream.Length > 0))
{
inkStream.Position = 0;
await inkManager.LoadAsync(inkStream.AsInputStream());
}
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
var strokes = inkManager.GetStrokes();
foreach (var stroke in strokes)
{
stroke.Selected = true;
}
inkManager.DeleteSelected();
}
private void RecognizeButton_Click(object sender, RoutedEventArgs e)
{
var sb = new StringBuilder();
var results = inkManager.GetRecognitionResults();
foreach (var result in results)
{
sb.AppendLine(result.GetTextCandidates().FirstOrDefault());
}
RecognitionText.Text = sb.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Input.Inking;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Win10Demo
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class InkView : Page
{
private MemoryStream inkStream;
private InkManager inkManager;
public InkView()
{
this.InitializeComponent();
inkStream = new MemoryStream();
inkManager = new InkManager();
Ink.InkPresenter.IsInputEnabled = true;
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
await inkManager.SaveAsync(inkStream.AsOutputStream());
}
private async void LoadButton_Click(object sender, RoutedEventArgs e)
{
if ((inkStream != null) && (inkStream.Length > 0))
{
inkStream.Position = 0;
await inkManager.LoadAsync(inkStream.AsInputStream());
}
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
var strokes = inkManager.GetStrokes();
foreach (var stroke in strokes)
{
stroke.Selected = true;
}
inkManager.DeleteSelected();
}
private void RecognizeButton_Click(object sender, RoutedEventArgs e)
{
var sb = new StringBuilder();
var results = inkManager.GetRecognitionResults();
foreach (var result in results)
{
sb.AppendLine(result.GetTextCandidates().FirstOrDefault());
}
RecognitionText.Text = sb.ToString();
}
}
}
| apache-2.0 | C# |
6fd5c94c661f159aadc61d12f06c2ee739bf0b13 | update client | shakuu/Parser,shakuu/Parser,shakuu/Parser | Parser/Clients/Parser.ConsoleClient/Program.cs | Parser/Clients/Parser.ConsoleClient/Program.cs | using System.Threading;
using Ninject;
using Parser.ConsoleClient.NinjectModules;
using Parser.FileReader.Contracts;
namespace Parser.ConsoleClient
{
public class Program
{
private const string MorninWoodDummyParse = @"../../../../../SampleLogs/combat_2017-02-22_22_30_37_978667.txt";
public static void Main()
{
var engine = NinjectStandardKernelProvider.Kernel.Get<IFileReaderEngine>();
engine.StartAsync(Program.MorninWoodDummyParse);
Thread.Sleep(100);
engine.Stop();
}
}
}
| using System.Threading;
using System.Threading.Tasks;
using Ninject;
using Parser.ConsoleClient.NinjectModules;
using Parser.FileReader.Contracts;
namespace Parser.ConsoleClient
{
public class Program
{
private const string MorninWoodDummyParse = @"../../../../../SampleLogs/combat_2017-02-22_22_30_37_978667.txt";
public static void Main()
{
var engine = NinjectStandardKernelProvider.Kernel.Get<IFileReaderEngine>();
Task.Run(() => engine.Start(Program.MorninWoodDummyParse));
Thread.Sleep(100);
engine.Stop();
}
}
}
| mit | C# |
6336cf03a2dd912f02865e1b4bb1a9674c57f820 | test the clearMetadata | mono/exiv2-sharp,mono/exiv2-sharp,mono/exiv2-sharp,mono/exiv2-sharp | samples/ImageInfo.cs | samples/ImageInfo.cs | /*
* ImageInfo.cs: get the image level info
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details
*/
using System;
using Exiv2;
namespace Sample
{
public class ImageInfo
{
static void Main (string [] args)
{
GLib.GType.Init ();
try {
if (args.Length != 1) {
Console.WriteLine ("Usage: ExifPrint.exe file");
System.Environment.Exit (1);
}
Exiv2.Image image = Exiv2.ImageFactory.Open (args [0]);
if (!image.Good)
return;
image.ReadMetadata ();
Console.WriteLine ("Mime type: {0}", image.MimeType);
Console.WriteLine ("pixel width: {0}", image.PixelWidth);
Console.WriteLine ("pixel height: {0}", image.PixelHeight);
Console.WriteLine ("comment: {0}", image.Comment);
image.Comment = "new comment";
//image.ClearMetadata ();
image.WriteMetadata ();
} catch (GLib.GException e) {
Console.WriteLine ("Exiv2.Exception caught {0}", e);
}
}
}
}
| /*
* ImageInfo.cs: get the image level info
*
* Author(s):
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details
*/
using System;
using Exiv2;
namespace Sample
{
public class ImageInfo
{
static void Main (string [] args)
{
GLib.GType.Init ();
try {
if (args.Length != 1) {
Console.WriteLine ("Usage: ExifPrint.exe file");
System.Environment.Exit (1);
}
Exiv2.Image image = Exiv2.ImageFactory.Open (args [0]);
if (!image.Good)
return;
image.ReadMetadata ();
Console.WriteLine ("Mime type: {0}", image.MimeType);
Console.WriteLine ("pixel width: {0}", image.PixelWidth);
Console.WriteLine ("pixel height: {0}", image.PixelHeight);
Console.WriteLine ("comment: {0}", image.Comment);
image.Comment = "new comment";
image.WriteMetadata ();
} catch (GLib.GException e) {
Console.WriteLine ("Exiv2.Exception caught {0}", e);
}
}
}
}
| mit | C# |
6d2acbdcbf75bf0dd90ad7e74e4c8ea108e5786d | Add Launchpad Mini support | DarthAffe/RGB.NET,DarthAffe/RGB.NET | RGB.NET.Devices.Novation/Enum/NovationDevices.cs | RGB.NET.Devices.Novation/Enum/NovationDevices.cs | #pragma warning disable 1591
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
using RGB.NET.Devices.Novation.Attributes;
namespace RGB.NET.Devices.Novation
{
/// <summary>
/// Represents a specific novation device.
/// </summary>
public enum NovationDevices
{
[DeviceId("Launchpad S")]
[ColorCapability(NovationColorCapabilities.LimitedRG)]
LaunchpadS,
[DeviceId("Launchpad Mini")]
[ColorCapability(NovationColorCapabilities.LimitedRG)]
LaunchpadMini
}
}
| #pragma warning disable 1591
// ReSharper disable InconsistentNaming
// ReSharper disable UnusedMember.Global
using RGB.NET.Devices.Novation.Attributes;
namespace RGB.NET.Devices.Novation
{
/// <summary>
/// Represents a specific novation device.
/// </summary>
public enum NovationDevices
{
[DeviceId("Launchpad S")]
[ColorCapability(NovationColorCapabilities.LimitedRG)]
LaunchpadS
}
}
| lgpl-2.1 | C# |
01961a2cfdfe3635bca0419d315f63672ebfc14e | Fix tests - all green | sheix/GameEngine,sheix/GameEngine,sheix/GameEngine | EngineTest/ActorShould.cs | EngineTest/ActorShould.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
private Mock<IAct> act;
[SetUp()]
public void SetUp()
{
act = new Mock<IAct>();
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(act.Object);
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{act.Object});
}
[Test()]
public void ActOnScene()
{
//arrange
//act
actor.Act(scene.Object);
//assert
act.Verify(m => m.Do(scene.Object));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Moq;
using Engine;
namespace EngineTest
{
[TestFixture()]
public class ActorShould
{
Mock<IScene> scene;
Actor actor;
Mock<IStrategy> strategy;
[SetUp()]
public void SetUp()
{
strategy = new Mock<IStrategy>();
actor = new Actor(strategy.Object);
scene = new Mock<IScene>();
strategy.Setup(mn => mn.SelectAction(It.IsAny<List<IAct>>(),It.IsAny<IScene>())).Returns(new Act("Act 1",actor,null ));
scene.Setup(mn => mn.GetPossibleActions(It.IsAny<IActor>())).Returns(new List<IAct>{new Act("Act 1",actor,null ),new Act("Act 2", actor,null)});
}
[Test()]
public void GetPossibleActionsFromScene()
{
//arrange
//act
actor.Act(scene.Object);
var actions = actor.AllActions;
//assert
Assert.AreNotEqual(0, actions.Count);
}
}
}
| mit | C# |
dc2465cec2e087bcf793cd752d6ce4f23f672bd4 | Remove using | roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University | R7.University/Models/UniversityCrudProvider.cs | R7.University/Models/UniversityCrudProvider.cs | //
// UniversityCrudProvider.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2018 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using R7.Dnn.Extensions.Models;
namespace R7.University.Models
{
public class UniversityCrudProvider<TItem>: ICrudProvider<TItem> where TItem: class
{
protected readonly IModelContext ModelContext;
public UniversityCrudProvider (IModelContext modelContext)
{
ModelContext = modelContext;
}
public TItem Get<TKey> (TKey itemId)
{
return ModelContext.Get<TItem, TKey> (itemId);
}
public void Add (TItem item)
{
ModelContext.Add (item);
ModelContext.SaveChanges ();
}
public void Delete (TItem item)
{
ModelContext.Remove (item);
ModelContext.SaveChanges ();
}
public void Update (TItem item)
{
ModelContext.Update (item);
ModelContext.SaveChanges ();
}
}
}
| //
// UniversityCrudProvider.cs
//
// Author:
// Roman M. Yagodin <roman.yagodin@gmail.com>
//
// Copyright (c) 2018 Roman M. Yagodin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using R7.Dnn.Extensions.Data;
using R7.Dnn.Extensions.Models;
namespace R7.University.Models
{
public class UniversityCrudProvider<TItem>: ICrudProvider<TItem> where TItem: class
{
protected readonly IModelContext ModelContext;
public UniversityCrudProvider (IModelContext modelContext)
{
ModelContext = modelContext;
}
public TItem Get<TKey> (TKey itemId)
{
return ModelContext.Get<TItem, TKey> (itemId);
}
public void Add (TItem item)
{
ModelContext.Add (item);
ModelContext.SaveChanges ();
}
public void Delete (TItem item)
{
ModelContext.Remove (item);
ModelContext.SaveChanges ();
}
public void Update (TItem item)
{
ModelContext.Update (item);
ModelContext.SaveChanges ();
}
}
}
| agpl-3.0 | C# |
c3af1fedc868de1fa0f7b371601851c61a508860 | make /event work | prozum/solitude | Solitude.Server/Controllers/EventController.cs | Solitude.Server/Controllers/EventController.cs | using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Collections.Generic;
using Model;
namespace Solitude.Server
{
[RoutePrefix("api/event")]
public class EventController : SolitudeController
{
[Authorize]
public async Task<IHttpActionResult> Get()
{
var events = await DB.GetAttendingEvents(User.Identity.GetUserId());
return Ok(events);
}
[Authorize]
public IHttpActionResult Get(int id)
{
List<Event> OrderList = new List<Event>
{
new Event {Title = "Julefrokost", Id = 0, Address = "Everywhere", Description = "Julefrokost", Date = "21-12-12" },
new Event {Title = "I-dag", Id = 1, Address = "DE-club", Description = "DE-club", Date = "Thursday" },
new Event {Title = "FLAN", Id = 2, Address = "Cassiopeia", Description = "Cassiopeia", Date = "00-00-99" },
new Event {Title = "J-dag", Id = 3, Address = "D-building", Description = "J-dag", Date = "05-11-15"},
new Event {Title = "ØL", Id = 4, Address = "Cantina", Description = "Free beer", Date = "Always tomorrow"}
};
return Ok(OrderList[id]);
}
[Authorize]
[Route("add")]
public async Task<IHttpActionResult> Add(Event e)
{
e.UserId = User.Identity.GetUserId();
await DB.AddEvent(e);
return Ok(new { Id = e.Id});
}
[Authorize]
[Route("delete")]
public async Task<IHttpActionResult> Delete(int eventId)
{
await DB.DeleteEvent(eventId);
return Ok();
}
[Authorize]
[Route("update")]
public async Task<IHttpActionResult> Update(Event e)
{
await DB.UpdateEvent(e);
return Ok();
}
}
} | using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using System.Collections.Generic;
using Model;
namespace Solitude.Server
{
[RoutePrefix("api/event")]
public class EventController : SolitudeController
{
[Authorize]
public async Task<IHttpActionResult> Get()
{
var offers = await DB.GetEvents(User.Identity.GetUserId());
return Ok(offers);
}
[Authorize]
public IHttpActionResult Get(int id)
{
List<Event> OrderList = new List<Event>
{
new Event {Title = "Julefrokost", Id = 0, Address = "Everywhere", Description = "Julefrokost", Date = "21-12-12" },
new Event {Title = "I-dag", Id = 1, Address = "DE-club", Description = "DE-club", Date = "Thursday" },
new Event {Title = "FLAN", Id = 2, Address = "Cassiopeia", Description = "Cassiopeia", Date = "00-00-99" },
new Event {Title = "J-dag", Id = 3, Address = "D-building", Description = "J-dag", Date = "05-11-15"},
new Event {Title = "ØL", Id = 4, Address = "Cantina", Description = "Free beer", Date = "Always tomorrow"}
};
return Ok(OrderList[id]);
}
[Authorize]
[Route("add")]
public async Task<IHttpActionResult> Add(Event e)
{
e.UserId = User.Identity.GetUserId();
await DB.AddEvent(e);
return Ok(new { Id = e.Id});
}
[Authorize]
[Route("delete")]
public async Task<IHttpActionResult> Delete(int eventId)
{
await DB.DeleteEvent(eventId);
return Ok();
}
[Authorize]
[Route("update")]
public async Task<IHttpActionResult> Update(Event e)
{
await DB.UpdateEvent(e);
return Ok();
}
}
} | mit | C# |
ae7f4087cd0a91b686276fe5b019ef89c9b8aff8 | fix for MyGravityProviderComponent | Souper07/Autopilot,Rynchodon/ARMS,Rynchodon/Autopilot,Souper07/Autopilot,Rynchodon/ARMS,Rynchodon/Autopilot | Scripts/Utility/Extensions/MyPlanetExtensions.cs | Scripts/Utility/Extensions/MyPlanetExtensions.cs | using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using VRage.ModAPI;
using VRageMath;
namespace Rynchodon
{
public static class MyPlanetExtensions
{
public static MyPlanet GetClosestPlanet(Vector3D position)
{
double distSquared;
return GetClosestPlanet(position, out distSquared);
}
public static MyPlanet GetClosestPlanet(Vector3D position, out double distSquared)
{
IMyVoxelBase closest = null;
double bestDistance = double.MaxValue;
MyAPIGateway.Session.VoxelMaps.GetInstances_Safe(null, voxel => {
if (voxel is MyPlanet)
{
double distance = Vector3D.DistanceSquared(position, voxel.GetCentre());
if (distance < bestDistance)
{
bestDistance = distance;
closest = voxel;
}
}
return false;
});
distSquared = bestDistance;
return (MyPlanet)closest;
}
public static bool IsPositionInGravityWell(this MyPlanet planet, ref Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().IsPositionInRange(worldPosition);
}
public static bool IsPositionInGravityWell(this MyPlanet planet, Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().IsPositionInRange(worldPosition);
}
public static Vector3D GetWorldGravityNormalized(this MyPlanet planet, ref Vector3D worldPosition)
{
return Vector3D.Normalize(planet.WorldMatrix.Translation - worldPosition);
}
public static Vector3D GetWorldGravityNormalized(this MyPlanet planet, Vector3D worldPosition)
{
return Vector3D.Normalize(planet.WorldMatrix.Translation - worldPosition);
}
public static float GetGravityMultiplier(this MyPlanet planet, ref Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().GetGravityMultiplier(worldPosition);
}
public static float GetGravityMultiplier(this MyPlanet planet, Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().GetGravityMultiplier(worldPosition);
}
public static Vector3D GetWorldGravity(this MyPlanet planet, ref Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().GetWorldGravity(worldPosition);
}
public static Vector3D GetWorldGravity(this MyPlanet planet, Vector3D worldPosition)
{
return planet.Components.Get<MyGravityProviderComponent>().GetWorldGravity(worldPosition);
}
}
}
| using Sandbox.Game.Entities;
using Sandbox.ModAPI;
using VRage.ModAPI;
using VRageMath;
namespace Rynchodon
{
public static class MyPlanetExtensions
{
public static MyPlanet GetClosestPlanet(Vector3D position)
{
double distSquared;
return GetClosestPlanet(position, out distSquared);
}
public static MyPlanet GetClosestPlanet(Vector3D position, out double distSquared)
{
IMyVoxelBase closest = null;
double bestDistance = double.MaxValue;
MyAPIGateway.Session.VoxelMaps.GetInstances_Safe(null, voxel => {
if (voxel is MyPlanet)
{
double distance = Vector3D.DistanceSquared(position, voxel.GetCentre());
if (distance < bestDistance)
{
bestDistance = distance;
closest = voxel;
}
}
return false;
});
distSquared = bestDistance;
return (MyPlanet)closest;
}
//private static Logger s_logger = new Logger("MyPlanetExtensions");
//private static FastResourceLock lock_getSurfPoint = new FastResourceLock("lock_getSurfPoint");
//static MyPlanetExtensions()
//{
// MyAPIGateway.Entities.OnCloseAll += Entities_OnCloseAll;
//}
//private static void Entities_OnCloseAll()
//{
// MyAPIGateway.Entities.OnCloseAll -= Entities_OnCloseAll;
// s_logger = null;
// lock_getSurfPoint = null;
//}
//public static bool Intersects(this MyPlanet planet, ref BoundingSphereD sphere)
//{
// Vector3D sphereCentre = sphere.Center;
// Vector3D planetCentre = planet.GetCentre();
// double distSq_sphereToPlanetCentre = Vector3D.DistanceSquared(sphereCentre, planetCentre);
// double everest = planet.MaximumRadius + sphere.Radius; everest *= everest;
// if (distSq_sphereToPlanetCentre > everest)
// return false;
// return true;
// Vector3D closestPoint = GetClosestSurfacePointGlobal_Safeish(planet, sphereCentre);
// double minDistance = sphere.Radius * sphere.Radius;
// if (Vector3D.DistanceSquared(sphereCentre, closestPoint) <= minDistance)
// return true;
// return distSq_sphereToPlanetCentre < Vector3D.DistanceSquared(planetCentre, closestPoint);
//}
//public static Vector3D GetClosestSurfacePointGlobal_Safeish(this MyPlanet planet, Vector3D worldPoint)
//{
// bool except = false;
// Vector3D surface = Vector3D.Zero;
// MainLock.UsingShared(() => except = GetClosestSurfacePointGlobal_Sub_Safeish(planet, worldPoint, out surface));
// if (except)
// return GetClosestSurfacePointGlobal_Safeish(planet, worldPoint);
// return surface;
//}
//[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
//private static bool GetClosestSurfacePointGlobal_Sub_Safeish(this MyPlanet planet, Vector3D worldPoint, out Vector3D closestPoint)
//{
// using (lock_getSurfPoint.AcquireExclusiveUsing())
// try
// {
// closestPoint = planet.GetClosestSurfacePointGlobal(ref worldPoint);
// return false;
// }
// catch (AccessViolationException ex)
// {
// s_logger.debugLog("Caught Exception: " + ex, "GetClosestSurfacePointGlobal_Sub_Safeish()", Logger.severity.DEBUG);
// closestPoint = Vector3D.Zero;
// return true;
// }
//}
}
}
| cc0-1.0 | C# |
06242559492710e6b62773e7510086d5d3dd1626 | Fix inner exception message assertion | edpollitt/Nerdle.AutoConfig | Nerdle.AutoConfig.Tests.Unit/Mapping/MappingFromAttributeTests/When_mapping_a_property.cs | Nerdle.AutoConfig.Tests.Unit/Mapping/MappingFromAttributeTests/When_mapping_a_property.cs | using System;
using System.Reflection;
using System.Xml.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Exceptions;
using Nerdle.AutoConfig.Mapping;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Unit.Mapping.MappingFromAttributeTests
{
[TestFixture]
public class When_mapping_a_property
{
readonly PropertyInfo _propertyInfo = typeof(Foo).GetProperty("Bar");
[Test]
public void The_property_is_set_using_an_internal_conversion()
{
var xAttribute = new XAttribute("whatever", "42");
var sut = new MappingFromAttribute(xAttribute, _propertyInfo);
var instance = new Foo();
sut.Apply(instance);
instance.Bar.Should().Be(42);
}
[Test]
public void A_mapping_exception_is_thrown_if_the_conversion_throws()
{
var xAttribute = new XAttribute("theAttributeName", "theInvalidValue");
var sut = new MappingFromAttribute(xAttribute, _propertyInfo);
var instance = new Foo();
Action mapping = () => sut.Apply(instance);
var exception = mapping.Should().ThrowExactly<AutoConfigMappingException>().Which;
exception.Message.Should().Contain("theAttributeName")
.And.Subject.Should().Contain("theInvalidValue")
.And.Subject.Should().Contain(_propertyInfo.Name)
.And.Subject.Should().Contain(typeof(Foo).Name);
exception.InnerException.Message.Should().Contain("theInvalidValue is not a valid value for Int32.");
}
}
class Foo
{
public int Bar { get; set; }
}
}
| using System;
using System.Reflection;
using System.Xml.Linq;
using FluentAssertions;
using Nerdle.AutoConfig.Exceptions;
using Nerdle.AutoConfig.Mapping;
using NUnit.Framework;
namespace Nerdle.AutoConfig.Tests.Unit.Mapping.MappingFromAttributeTests
{
[TestFixture]
public class When_mapping_a_property
{
readonly PropertyInfo _propertyInfo = typeof(Foo).GetProperty("Bar");
[Test]
public void The_property_is_set_using_an_internal_conversion()
{
var xAttribute = new XAttribute("whatever", "42");
var sut = new MappingFromAttribute(xAttribute, _propertyInfo);
var instance = new Foo();
sut.Apply(instance);
instance.Bar.Should().Be(42);
}
[Test]
public void A_mapping_exception_is_thrown_if_the_conversion_throws()
{
var xAttribute = new XAttribute("theAttributeName", "theInvalidValue");
var sut = new MappingFromAttribute(xAttribute, _propertyInfo);
var instance = new Foo();
Action mapping = () => sut.Apply(instance);
mapping.Should().ThrowExactly<AutoConfigMappingException>()
.Where(m => m.Message.Contains("theAttributeName")
&& m.Message.Contains("theInvalidValue")
&& m.Message.Contains(_propertyInfo.Name)
&& m.Message.Contains(typeof(Foo).Name)
&& m.InnerException.Message == "theInvalidValue is not a valid value for Int32.");
}
}
class Foo
{
public int Bar { get; set; }
}
}
| mit | C# |
9c87bdbcc62f04a709eb11036d7f637a1ffc7724 | Update HttpStringDecodeFilter.cs | CypressNorth/.NET-WebApi-HttpStringDecodeFilter | HttpStringDecodeFilter.cs | HttpStringDecodeFilter.cs | using System;
using System.Net;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace CN.WebApi.Filters
{
public class DecodeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
// If the request is either a PUT or POST, attempt to decode all strings
if (actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Post
|| actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Put)
{
// For each of the items in the PUT/POST
foreach (var item in actionContext.ActionArguments.Values)
{
try {
// Get the type of the object
Type type = item.GetType();
// For each property of this object, html decode it if it is of type string
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
var prop = propertyInfo.GetValue(item);
if (prop != null && prop.GetType() == typeof(string))
{
propertyInfo.SetValue(item, WebUtility.HtmlDecode((string)prop));
}
}
} catch {}
}
}
}
}
}
| using System;
using System.Net;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace CN.WebApi.Filters
{
public class DecodeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
// If the request is either a PUT or POST, attempt to decode all strings
if (actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Post
|| actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Put)
{
// For each of the items in the PUT/POST
foreach (var item in actionContext.ActionArguments.Values)
{
// Get the type of the object
Type type = item.GetType();
// For each property of this object, html decode it if it is of type string
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
var prop = propertyInfo.GetValue(item);
if (prop != null && prop.GetType() == typeof(string))
{
propertyInfo.SetValue(item, WebUtility.HtmlDecode((string)prop));
}
}
}
}
}
}
}
| mit | C# |
56d2afabe55562282e79a3d9f7fbe986ddebcedd | Remove unnecessary else statement. Remove unnecessary return statement. | kreynes/TeleBot | TeleBot/API/Extensions/ParseModeEnumConverter.cs | TeleBot/API/Extensions/ParseModeEnumConverter.cs | using System;
using Newtonsoft.Json;
using TeleBot.API.Enums;
namespace TeleBot.API.Extensions
{
public class ParseModeEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var enumString = (string)reader.Value;
return Enum.Parse(typeof(ParseMode), enumString, true);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!value.Equals(ParseMode.Default))
{
var type = (ParseMode)value;
writer.WriteValue(type.ToString());
}
}
}
}
| using System;
using Newtonsoft.Json;
using TeleBot.API.Enums;
namespace TeleBot.API.Extensions
{
public class ParseModeEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var enumString = (string)reader.Value;
return Enum.Parse(typeof(ParseMode), enumString, true);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (!value.Equals(ParseMode.Default))
{
var type = (ParseMode)value;
writer.WriteValue(type.ToString());
}
else return;
}
}
}
| mit | C# |
888f050b86fc092fce2c4706ad91bfd2b6ea6f20 | add reference type restriction to generic param | NebulousConcept/b2-csharp-client | b2-csharp-client/B2.Client/ValidationUtils.cs | b2-csharp-client/B2.Client/ValidationUtils.cs | using System;
namespace B2.Client
{
/// <summary>
/// Extension methods for doing common method parameter validation.
/// </summary>
public static class ValidationUtils
{
/// <summary>
/// Validate that a value is non-null. This method is intended for simple parameter validation in method calls.
/// </summary>
/// <example>
/// This sample shows the expected usage of this method.
/// <code>
/// public void DoStuff(string value)
/// {
/// var safeValue = value.ThrowIfNull(nameof(value));
/// //...
/// }
/// </code>
/// </example>
/// <param name="input">The value to assert non-nullity on.</param>
/// <param name="name">The name of the input value.</param>
/// <typeparam name="T">The type of the input value.</typeparam>
/// <returns>The input value, if it is non-null.</returns>
/// <exception cref="ArgumentNullException">If the input is null.</exception>
public static T ThrowIfNull<T>(this T input, string name)
where T : class
{
if (input == null) {
throw new ArgumentNullException(name);
}
return input;
}
}
} | using System;
namespace B2.Client
{
/// <summary>
/// Extension methods for doing common method parameter validation.
/// </summary>
public static class ValidationUtils
{
/// <summary>
/// Validate that a value is non-null. This method is intended for simple parameter validation in method calls.
/// </summary>
/// <example>
/// This sample shows the expected usage of this method.
/// <code>
/// public void DoStuff(string value)
/// {
/// var safeValue = value.ThrowIfNull(nameof(value));
/// //...
/// }
/// </code>
/// </example>
/// <param name="input">The value to assert non-nullity on.</param>
/// <param name="name">The name of the input value.</param>
/// <typeparam name="T">The type of the input value.</typeparam>
/// <returns>The input value, if it is non-null.</returns>
/// <exception cref="ArgumentNullException">If the input is null.</exception>
public static T ThrowIfNull<T>(this T input, string name)
{
if (input == null) {
throw new ArgumentNullException(name);
}
return input;
}
}
} | mit | C# |
76bb320f08e0a686e4c7383b2edcf2c69caa0d3b | Fix hash calculation | SteamDatabase/ValveResourceFormat | ValveResourceFormat/Utils/EntityLumpKeyLookup.cs | ValveResourceFormat/Utils/EntityLumpKeyLookup.cs | using System.Collections.Generic;
using ValveResourceFormat.ThirdParty;
namespace ValveResourceFormat.Utils
{
public static class EntityLumpKeyLookup
{
public const uint MURMUR2SEED = 0x31415926; // It's pi!
private static Dictionary<string, uint> Lookup = new Dictionary<string, uint>();
public static uint Get(string key)
{
if (Lookup.ContainsKey(key))
{
return Lookup[key];
}
var hash = MurmurHash2.Hash(key, MURMUR2SEED);
Lookup[key] = hash;
return hash;
}
}
}
| using System.Collections.Generic;
using ValveResourceFormat.ThirdParty;
namespace ValveResourceFormat.Utils
{
public static class EntityLumpKeyLookup
{
public const uint MURMUR2SEED = 0x31415926; // It's pi!
private static Dictionary<string, uint> Lookup = new Dictionary<string, uint>();
public static uint Get(string key)
{
if (Lookup.ContainsKey(key))
{
return Lookup[key];
}
var hash = MurmurHash2.Hash("origin", MURMUR2SEED);
Lookup[key] = hash;
return hash;
}
}
}
| mit | C# |
93d44d29d2ec933fbf7af6649e7a28e8b0bc66e2 | Remove IPlayerEvent | Yonom/BotBits,EEJesse/BotBits,Tunous/BotBits | BotBits/Packages/MessageHandler/Events/PlayerEvent.cs | BotBits/Packages/MessageHandler/Events/PlayerEvent.cs | using PlayerIOClient;
namespace BotBits.Events
{
internal interface ICancellable
{
bool Cancelled { get; }
}
public abstract class PlayerEvent<T> : ReceiveEvent<T>, ICancellable where T : PlayerEvent<T>
{
private readonly Player _player;
internal PlayerEvent(BotBitsClient client, Message message, uint userId = 0, bool create = false)
: base(client, message)
{
if (message.Count > userId)
{
if (create)
{
this._player = Players.Of(client).TryAddPlayer(message.GetInt(userId));
}
else
{
Players.Of(client).TryGetPlayer(message.GetInt(userId), out this._player);
}
}
else
{
this._player = Player.Nobody;
}
}
public Player Player
{
get { return this._player; }
}
public bool Cancelled
{
get { return this.Player == null; }
}
}
}
| using System;
using System.Collections.Generic;
using PlayerIOClient;
namespace BotBits.Events
{
internal interface ICancellable
{
bool Cancelled { get; }
}
public interface IPlayerEvent
{
Player Player { get; }
}
public abstract class PlayerEvent<T> : ReceiveEvent<T>, IPlayerEvent, ICancellable where T : PlayerEvent<T>
{
private readonly Player _player;
internal PlayerEvent(BotBitsClient client, Message message, uint userId = 0, bool create = false)
: base(client, message)
{
if (message.Count > userId)
{
if (create)
{
this._player = Players.Of(client).TryAddPlayer(message.GetInt(userId));
}
else
{
Players.Of(client).TryGetPlayer(message.GetInt(userId), out this._player);
}
}
else
{
this._player = Player.Nobody;
}
}
public Player Player
{
get { return this._player; }
}
public bool Cancelled
{
get { return this.Player == null; }
}
}
}
| mit | C# |
0f945ac2b1f13a7530be767bad5490bbcb8781a5 | Update VM.cs | zxfishhack/KafkaSniffer | VM.cs | VM.cs | using System.Collections.ObjectModel;
namespace KafkaSniffer
{
internal class Vm
{
public BrokerInfo BrokerInfo { get; } = BrokerInfo.Instance;
public ObservableCollection<Consumer> ConsumerList { get; } = new ObservableCollection<Consumer>();
public ObservableCollection<Producer> ProducerList { get; } = new ObservableCollection<Producer>();
}
}
| using System.Collections.Generic;
namespace KafkaSniffer
{
internal class Vm
{
public BrokerInfo BrokerInfo { get; } = BrokerInfo.Instance;
public List<Consumer> ConsumerList { get; } = new List<Consumer>();
public List<Producer> ProducerList { get; } = new List<Producer>();
}
}
| apache-2.0 | C# |
02d242a71c9fe959f6726862804d600080490f4e | split out the variable | wangkanai/Detection | test/Hosting/PageRouteModelConventionTest.cs | test/Hosting/PageRouteModelConventionTest.cs | using System.Linq;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging.Abstractions;
using Wangkanai.Detection.Mocks;
using Xunit;
namespace Wangkanai.Detection.Hosting
{
public class PageRouteModelConventionTest
{
[Fact]
public void Apply_Null()
{
var relativePath = "";
var viewEnginePath = "";
var areaName = "";
var model = new PageRouteModel(relativePath, viewEnginePath, areaName);
var convention = new ResponsivePageRouteModelConvention();
convention.Apply(model);
Assert.Same("", model.Selectors.Single().AttributeRouteModel.Template);
}
[Theory]
[InlineData("Admin", "Admin/Index", "/Areas/Admin/Pages/Index.mobile.cshtml", "/Index.mobile")]
[InlineData("Admin", "Admin/Index", "/Areas/Admin/Pages/Index.tablet.cshtml", "/Index.tablet")]
[InlineData(null, "About/Index", "/Pages/About/Index.mobile.cshtml", "/About/Index.mobile")]
[InlineData(null, "About/Index", "/Pages/About/Index.tablet.cshtml", "/About/Index.tablet")]
[InlineData(null, "Index", "/Pages/Index.mobile.cshtml", "/Index.mobile")]
[InlineData(null, "Index", "/Pages/Index.tablet.cshtml", "/Index.tablet")]
[InlineData(null, "Privacy", "/Pages/Privacy.mobile.cshtml", "/Privacy.mobile")]
[InlineData(null, "Privacy", "/Pages/Privacy.tablet.cshtml", "/Privacy.tablet")]
public void Apply_Area(string areaName, string template, string relativePath, string viewEnginePath)
{
var options = new RazorPagesOptions();
var factory = new MockPageRouteModel(options);
var model = factory.CreateAreaRouteModel(relativePath, template);
var convention = new ResponsivePageRouteModelConvention();
convention.Apply(model);
Assert.Equal(template, model.Selectors.Single().AttributeRouteModel.Template);
}
[Fact]
public void Apply_Index()
{
var relativePath = "/Pages/Index.mobile.cshtml";
var routeTemplate = "/Index.mobile";
var template = "Index";
var options = new RazorPagesOptions();
var factory = new MockPageRouteModel(options);
var model = factory.CreateRouteModel(relativePath, routeTemplate);
var convention = new ResponsivePageRouteModelConvention();
convention.Apply(model);
Assert.Equal(2, model.Selectors.Count);
var selector = model.Selectors.Single();
Assert.Equal(template, selector.AttributeRouteModel.Template);
}
}
} | using System.Linq;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging.Abstractions;
using Wangkanai.Detection.Mocks;
using Xunit;
namespace Wangkanai.Detection.Hosting
{
public class PageRouteModelConventionTest
{
[Fact]
public void Apply_Null()
{
var relativePath = "";
var viewEnginePath = "";
var areaName = "";
var model = new PageRouteModel(relativePath, viewEnginePath, areaName);
var convention = new ResponsivePageRouteModelConvention();
convention.Apply(model);
Assert.Same("", model.Selectors.Single().AttributeRouteModel.Template);
}
[Theory]
[InlineData("Admin", "Admin/Index", "/Areas/Admin/Pages/Index.mobile.cshtml", "/Index.mobile")]
[InlineData("Admin", "Admin/Index", "/Areas/Admin/Pages/Index.tablet.cshtml", "/Index.tablet")]
[InlineData(null, "About/Index", "/Pages/About/Index.mobile.cshtml", "/About/Index.mobile")]
[InlineData(null, "About/Index", "/Pages/About/Index.tablet.cshtml", "/About/Index.tablet")]
[InlineData(null, "Index", "/Pages/Index.mobile.cshtml", "/Index.mobile")]
[InlineData(null, "Index", "/Pages/Index.tablet.cshtml", "/Index.tablet")]
[InlineData(null, "Privacy", "/Pages/Privacy.mobile.cshtml", "/Privacy.mobile")]
[InlineData(null, "Privacy", "/Pages/Privacy.tablet.cshtml", "/Privacy.tablet")]
public void Apply_Area(string areaName, string template, string relativePath, string viewEnginePath)
{
var options = new RazorPagesOptions();
var factory = new MockPageRouteModel(options);
var model = factory.CreateAreaRouteModel(relativePath, template);
var convention = new ResponsivePageRouteModelConvention();
convention.Apply(model);
Assert.Equal(template, model.Selectors.Single().AttributeRouteModel.Template);
}
}
} | apache-2.0 | C# |
86a1403d4846bd0ae37df0baf68e077477c54615 | Update layout | tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller,tuelsch/schreinerei-gfeller | schreinerei-gfeller/Views/Shared/_Layout.cshtml | schreinerei-gfeller/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Schreinerei Gfeller</title>
@* CSS *@
<link href="~/res/16x16/favicon.png" rel="icon" type="image/png">
<link href="~/Assets/css/main.css" rel="stylesheet" type="text/css"/>
@RenderSection("css", required:false)
</head>
<body>
<div id="wrapper">
@Html.Partial("~/Views/Shared/_Header.cshtml")
<main>
@RenderBody()
</main>
@Html.Partial("~/Views/Shared/_Footer.cshtml")
</div>
@* JS *@
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="/Assets/js/app.js"></script>
@RenderSection("js", required:false)
</body>
</html>
| <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Meine ASP.NET-Anwendung</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
@Html.ActionLink("Anwendungsname", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Startseite", "Index", "Home")</li>
<li>@Html.ActionLink("Info", "About", "Home")</li>
<li>@Html.ActionLink("Kontakt", "Contact", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Meine ASP.NET-Anwendung</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
0f2e4c47c695686ef42d36c144887de28113caa3 | Revert "Added edit method into UserRepository" | BikeMates/bike-mates,BikeMates/bike-mates,BikeMates/bike-mates | BikeMates/BikeMates.Contracts/IUserRepository.cs | BikeMates/BikeMates.Contracts/IUserRepository.cs | using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
| using BikeMates.DataAccess.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BikeMates.Contracts
{
//TODO: Create folder Repositories and move this interface into it
//TODO: Create a base IRepository interface
public interface IUserRepository
{
void Add(ApplicationUser entity);
void Delete(ApplicationUser entity);
IEnumerable<ApplicationUser> GetAll();
ApplicationUser Get(string id);
void Edit(ApplicationUser entity);
void SaveChanges(); //TODO: Remove this method. Use it inside each methods like Add, Delete, etc.
}
}
| mit | C# |
d385b53f81339208a8b6274bac73f206f39f1b56 | Fix #7: Remove empty groups | tom-englert/ProjectConfigurationManager | ProjectConfigurationManager.Model/ExtensionMethods.cs | ProjectConfigurationManager.Model/ExtensionMethods.cs | namespace tomenglertde.ProjectConfigurationManager.Model
{
using System.Diagnostics.Contracts;
using System.Xml.Linq;
public static class ExtensionMethods
{
public static void RemoveSelfAndWhitespace(this XElement element)
{
Contract.Requires(element != null);
while (true)
{
var previous = element.PreviousNode as XText;
if ((previous != null) && string.IsNullOrWhiteSpace(previous.Value))
{
previous.Remove();
}
var parent = element.Parent;
element.Remove();
if ((parent == null) || parent.HasElements)
return;
element = parent;
}
}
}
} | namespace tomenglertde.ProjectConfigurationManager.Model
{
using System.Diagnostics.Contracts;
using System.Xml.Linq;
public static class ExtensionMethods
{
public static void RemoveSelfAndWhitespace(this XElement element)
{
Contract.Requires(element != null);
var previous = element.PreviousNode as XText;
if ((previous != null) && string.IsNullOrWhiteSpace(previous.Value))
{
previous.Remove();
}
element.Remove();
}
}
} | mit | C# |
af160fea3e814cec388976a54914d9694148e873 | correct sheard to shared | mschray/CalendarHelper | shared/LogHelper.csx | shared/LogHelper.csx | public static class LogHelper
{
private static TraceWriter logger;
public static void Initialize(TraceWriter log)
{
if (!logger) logger = log;
}
public static void Info(TraceWriter log, string logtext)
{
logger.Info(logtext);
}
public static void Error(TraceWriter log, string logtext)
{
logger.Error(logtext);
}
} | public static class LogHelper
{
private static TraceWriter logger;
public static void Initialize(TraceWriter log)
{
if (!logger) logger = log;
}
public static void Info(TraceWriter log, string logtext)
{
logger.Info(logtext);
}
public static void Error(TraceWriter log, string logtext)
{
logger.Error(logtext);
}
} | mit | C# |
7e484d5c4eeda9a0a8b4d852c242054e9e4f4f16 | Add StdToText and StdToJson | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Tooling/ProcessExtensions.cs | source/Nuke.Common/Tooling/ProcessExtensions.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Newtonsoft.Json.Linq;
using Nuke.Common.IO;
using Nuke.Common.Utilities;
namespace Nuke.Common.Tooling
{
[PublicAPI]
[DebuggerStepThrough]
[DebuggerNonUserCode]
public static class ProcessExtensions
{
[AssertionMethod]
public static IProcess AssertWaitForExit(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
return process;
}
[AssertionMethod]
public static IProcess AssertZeroExitCode(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
process.AssertWaitForExit();
if (process.ExitCode != 0)
throw new ProcessException(process);
return process;
}
public static IReadOnlyCollection<Output> EnsureOnlyStd(this IReadOnlyCollection<Output> output)
{
foreach (var o in output)
ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
return output;
}
public static string StdToText(this IEnumerable<Output> output)
{
return output.Where(x => x.Type == OutputType.Std)
.Select(x => x.Text)
.JoinNewLine();
}
public static T StdToJson<T>(this IEnumerable<Output> output)
{
return SerializationTasks.JsonDeserialize<T>(output.StdToText());
}
public static JObject StdToJson(this IEnumerable<Output> output)
{
return output.StdToJson<JObject>();
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
namespace Nuke.Common.Tooling
{
[PublicAPI]
[DebuggerStepThrough]
[DebuggerNonUserCode]
public static class ProcessExtensions
{
[AssertionMethod]
public static IProcess AssertWaitForExit(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()");
return process;
}
[AssertionMethod]
public static IProcess AssertZeroExitCode(
[AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull]
this IProcess process)
{
process.AssertWaitForExit();
if (process.ExitCode != 0)
throw new ProcessException(process);
return process;
}
public static IReadOnlyCollection<Output> EnsureOnlyStd(this IReadOnlyCollection<Output> output)
{
foreach (var o in output)
ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std");
return output;
}
}
}
| mit | C# |
50a02b23f904abd5b65e654b561fb38587c5b35c | Add xml comments to IExecutionStrategy (#1539) | graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet | src/GraphQL/Execution/IExecutionStrategy.cs | src/GraphQL/Execution/IExecutionStrategy.cs | using System.Threading.Tasks;
namespace GraphQL.Execution
{
/// <summary>
/// Processes a parsed GraphQL request, resolving all the nodes and returning the result; exceptions
/// are unhandled. Should not run any <see cref="IDocumentExecutionListener">IDocumentExecutionListener</see>s except
/// for <see cref="IDocumentExecutionListener.BeforeExecutionStepAwaitedAsync(object, System.Threading.CancellationToken)">BeforeExecutionStepAwaitedAsync</see>.
/// </summary>
public interface IExecutionStrategy
{
/// <summary>
/// Executes a GraphQL request and returns the result
/// </summary>
/// <param name="context">The execution parameters</param>
Task<ExecutionResult> ExecuteAsync(ExecutionContext context);
}
}
| using System.Threading.Tasks;
namespace GraphQL.Execution
{
public interface IExecutionStrategy
{
Task<ExecutionResult> ExecuteAsync(ExecutionContext context);
}
}
| mit | C# |
a6648da511e2f5ebfcf43c204f9d0129d5e34b78 | fix namespace in FileSandboxFeature | ArtofQuality/F2F.Testing,ArtofQuality/F2F.Testing | src/F2F.Testing.Xunit.Sandbox/FileSandboxFeature.cs | src/F2F.Testing.Xunit.Sandbox/FileSandboxFeature.cs | using System;
using System.Collections.Generic;
using System.Text;
using F2F.Testing.Sandbox;
#if NUNIT
using NUnit.Framework;
namespace F2F.Testing.NUnit.Sandbox
#endif
#if XUNIT
namespace F2F.Testing.Xunit.Sandbox
#endif
#if MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace F2F.Testing.MSTest.Sandbox
#endif
{
/// <summary>
/// Provides a temporary file system (sandbox) for a test fixture.
/// </summary>
public class FileSandboxFeature : IDisposable
{
/// <summary>The file locator.</summary>
private readonly IFileLocator _fileLocator;
/// <summary>The disposed state.</summary>
private bool _disposed = false;
/// <summary>The sandbox.</summary>
private IFileSandbox _sandbox;
/// <summary>
/// Initializes the test fixture without a file locator.
/// </summary>
public FileSandboxFeature()
: this(new EmptyFileLocator())
{
}
/// <summary>
/// Initializes the test fixture with the given file locator.
/// </summary>
/// <param name="fileLocator">The file locator.</param>
public FileSandboxFeature(IFileLocator fileLocator)
{
_fileLocator = fileLocator;
#if XUNIT
SetUpSandbox();
#endif
}
/// <summary>Gets the sandbox.</summary>
/// <value>The sandbox.</value>
public IFileSandbox Sandbox
{
get { return _sandbox; }
}
#if NUNIT
/// <summary>Set up the sandbox.</summary>
[SetUp]
public void NUnit_SetUpSandbox()
{
SetUpSandbox();
}
/// <summary>Tear down the sandbox.</summary>
[TearDown]
public void NUnit_TearDownSandbox()
{
Dispose();
}
#endif
#if MSTEST
/// <summary>Set up the sandbox.</summary>
[TestInitialize]
public void MSTest_SetUpSandbox()
{
SetUpSandbox();
}
/// <summary>Tear down the sandbox.</summary>
[TestCleanup]
public void MSTest_TearDownSandbox()
{
Dispose();
}
#endif
private void SetUpSandbox()
{
_sandbox = new FileSandbox(_fileLocator);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged
/// resources.
/// </summary>
/// <seealso cref="M:System.IDisposable.Dispose()"/>
public void Dispose()
{
if (!_disposed)
{
_sandbox.Dispose();
_disposed = true;
}
}
}
} | using System;
using System.Collections.Generic;
using System.Text;
using F2F.Testing.Sandbox;
#if NUNIT
using NUnit.Framework;
namespace F2F.Testing.NUnit
#endif
#if XUNIT
namespace F2F.Testing.Xunit
#endif
#if MSTEST
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace F2F.Testing.MSTest
#endif
{
/// <summary>
/// Provides a temporary file system (sandbox) for a test fixture.
/// </summary>
public class FileSandboxFeature : IDisposable
{
/// <summary>The file locator.</summary>
private readonly IFileLocator _fileLocator;
/// <summary>The disposed state.</summary>
private bool _disposed = false;
/// <summary>The sandbox.</summary>
private IFileSandbox _sandbox;
/// <summary>
/// Initializes the test fixture without a file locator.
/// </summary>
public FileSandboxFeature()
: this(new EmptyFileLocator())
{
}
/// <summary>
/// Initializes the test fixture with the given file locator.
/// </summary>
/// <param name="fileLocator">The file locator.</param>
public FileSandboxFeature(IFileLocator fileLocator)
{
_fileLocator = fileLocator;
#if XUNIT
SetUpSandbox();
#endif
}
/// <summary>Gets the sandbox.</summary>
/// <value>The sandbox.</value>
public IFileSandbox Sandbox
{
get { return _sandbox; }
}
#if NUNIT
/// <summary>Set up the sandbox.</summary>
[SetUp]
public void NUnit_SetUpSandbox()
{
SetUpSandbox();
}
/// <summary>Tear down the sandbox.</summary>
[TearDown]
public void NUnit_TearDownSandbox()
{
Dispose();
}
#endif
#if MSTEST
/// <summary>Set up the sandbox.</summary>
[TestInitialize]
public void MSTest_SetUpSandbox()
{
SetUpSandbox();
}
/// <summary>Tear down the sandbox.</summary>
[TestCleanup]
public void MSTest_TearDownSandbox()
{
Dispose();
}
#endif
private void SetUpSandbox()
{
_sandbox = new FileSandbox(_fileLocator);
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged
/// resources.
/// </summary>
/// <seealso cref="M:System.IDisposable.Dispose()"/>
public void Dispose()
{
if (!_disposed)
{
_sandbox.Dispose();
_disposed = true;
}
}
}
} | mit | C# |
7072d089ef9671e5e42a05b687968c46cc566d4e | Remove heartbeat server property index name | sergezhigunov/Hangfire.EntityFramework | src/Hangfire.EntityFramework/HangfireServer.cs | src/Hangfire.EntityFramework/HangfireServer.cs | // Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
} | // Copyright (c) 2017 Sergey Zhigunov.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Hangfire.EntityFramework
{
internal class HangfireServer
{
[Key]
[MaxLength(100)]
public string Id { get; set; }
[ForeignKey(nameof(ServerHost))]
public Guid ServerHostId { get; set; }
public string Data { get; set; }
[Index("IX_HangfireServer_Heartbeat")]
[DateTimePrecision(7)]
public DateTime Heartbeat { get; set; }
public virtual HangfireServerHost ServerHost { get; set; }
}
} | mit | C# |
3d39cc02578e28899114ccf2d0bc1a03f7ef9b89 | Increase version to 1.3 before publication | fredatgithub/UsefulFunctions | CodeGenerationWinForm/Properties/AssemblyInfo.cs | CodeGenerationWinForm/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("CodeGenerationWinForm")]
[assembly: AssemblyDescription("This application creates code for unit tests for a series of numbers, a particular number or randomly")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Freddy Juhel")]
[assembly: AssemblyProduct("CodeGenerationWinForm")]
[assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("b492fe99-f506-48c7-8d6d-b35c2cdef668")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("CodeGenerationWinForm")]
[assembly: AssemblyDescription("This application creates code for unit tests for a series of numbers, a particular number or randomly")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Freddy Juhel")]
[assembly: AssemblyProduct("CodeGenerationWinForm")]
[assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("b492fe99-f506-48c7-8d6d-b35c2cdef668")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| mit | C# |
bdb07e5396562f1a1b4d2f01853df872ca8f3e83 | Add Fallback func | bunashibu/kikan | Assets/Scripts/Matching/TeamToggleManager.cs | Assets/Scripts/Matching/TeamToggleManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Hashtable = ExitGames.Client.Photon.Hashtable;
namespace Bunashibu.Kikan {
public class TeamToggleManager : Photon.MonoBehaviour {
void Start() {
SetHope(-1);
_redToggle.onValueChanged.AddListener((state) => {
Restrict(state, _blueToggle, 0);
Fallback();
});
_blueToggle.onValueChanged.AddListener((state) => {
Restrict(state, _redToggle, 1);
Fallback();
});
}
private void Restrict(bool state, Toggle target, int hopeTeam) {
if (state && target.isOn) {
target.isOn = false;
SetHope(hopeTeam);
}
}
private void Fallback() {
if (!_redToggle.isOn && !_blueToggle.isOn)
SetHope(-1);
}
private void SetHope(int hopeTeam) {
var props = new Hashtable() {{ "HopeTeam", hopeTeam }};
PhotonNetwork.player.SetCustomProperties(props);
}
[SerializeField] private Toggle _redToggle;
[SerializeField] private Toggle _blueToggle;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Hashtable = ExitGames.Client.Photon.Hashtable;
namespace Bunashibu.Kikan {
public class TeamToggleManager : Photon.MonoBehaviour {
void Start() {
_redToggle.onValueChanged.AddListener((state) => {
Restrict(state, _blueToggle);
SetHope(0);
});
_blueToggle.onValueChanged.AddListener((state) => {
Restrict(state, _redToggle);
SetHope(1);
});
}
private void Restrict(bool state, Toggle target) {
if (state && target.isOn)
target.isOn = false;
}
private void SetHope(int hopeTeam) {
var props = new Hashtable() {{ "HopeTeam", hopeTeam }};
PhotonNetwork.player.SetCustomProperties(props);
}
[SerializeField] private Toggle _redToggle;
[SerializeField] private Toggle _blueToggle;
}
}
| mit | C# |
fa9e7b7d85ba3eaae8758f182829ae65957b76c2 | Fix bug on zoom camera by mouse wheel | ReiiYuki/KU-Structure | Assets/Scripts/UtilityScript/CameraZoomer.cs | Assets/Scripts/UtilityScript/CameraZoomer.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoomer : MonoBehaviour {
public float perspectiveZoomSpeed = 0.5f; // The rate of change of the field of view in perspective mode.
public float orthoZoomSpeed = 0.5f; // The rate of change of the orthographic size in orthographic mode.
float cameraDistanceMax = 20f;
float cameraDistanceMin = 5f;
float cameraDistance = 10f;
float scrollSpeed = 3;
Camera camera;
void Start()
{
camera = Camera.main;
}
void Update()
{
// If there are two touches on the device...
if (Input.touchCount == 2)
{
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
// ... change the orthographic size based on the change in distance between the touches.
camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
// Make sure the orthographic size never drops below zero.
camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
}
if (Input.GetAxis("Mouse ScrollWheel") != 0)
{
cameraDistance += Input.GetAxis("Mouse ScrollWheel") * scrollSpeed;
cameraDistance = Mathf.Clamp(cameraDistance, cameraDistanceMin, cameraDistanceMax);
camera.orthographicSize = cameraDistance;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoomer : MonoBehaviour {
public float perspectiveZoomSpeed = 0.5f; // The rate of change of the field of view in perspective mode.
public float orthoZoomSpeed = 0.5f; // The rate of change of the orthographic size in orthographic mode.
Camera camera;
void Start()
{
camera = Camera.main;
}
void Update()
{
// If there are two touches on the device...
if (Input.touchCount == 2)
{
// Store both touches.
Touch touchZero = Input.GetTouch(0);
Touch touchOne = Input.GetTouch(1);
// Find the position in the previous frame of each touch.
Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
Vector2 touchOnePrevPos = touchOne.position - touchOne.deltaPosition;
// Find the magnitude of the vector (the distance) between the touches in each frame.
float prevTouchDeltaMag = (touchZeroPrevPos - touchOnePrevPos).magnitude;
float touchDeltaMag = (touchZero.position - touchOne.position).magnitude;
// Find the difference in the distances between each frame.
float deltaMagnitudeDiff = prevTouchDeltaMag - touchDeltaMag;
// ... change the orthographic size based on the change in distance between the touches.
camera.orthographicSize += deltaMagnitudeDiff * orthoZoomSpeed;
// Make sure the orthographic size never drops below zero.
camera.orthographicSize = Mathf.Max(camera.orthographicSize, 0.1f);
}
if (Input.GetAxis("Mouse ScrollWheel") > 0) // forward
{
Camera.main.orthographicSize = Mathf.Min(Camera.main.orthographicSize - 1, 6);
}
else if (Input.GetAxis("Mouse ScrollWheel") < 0) // back
{
Camera.main.orthographicSize = Mathf.Max(Camera.main.orthographicSize - 1, 1);
}
}
}
| mit | C# |
e5bf98f204470a02b95d7bee7373e7c42a3d04ab | Add ShowInExpenseClaims prop in Account model | jcvandan/XeroAPI.Net,TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net | source/XeroApi/Model/Account.cs | source/XeroApi/Model/Account.cs | using System;
namespace XeroApi.Model
{
public class Account : ModelBase
{
[ItemId]
public Guid AccountID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string TaxType { get; set; }
public string Description { get; set; }
public string Class { get; set; }
public string SystemAccount { get; set; }
public bool? EnablePaymentsToAccount { get; set; }
public string BankAccountNumber { get; set; }
public string CurrencyCode { get; set; }
public string ReportingCode { get; set; }
public string ReportingCodeName { get; set; }
// Added for v2.14
public bool ShowInExpenseClaims { get; set; }
}
public class Accounts : ModelList<Account>
{
}
} | using System;
namespace XeroApi.Model
{
public class Account : ModelBase
{
[ItemId]
public Guid AccountID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public string Type { get; set; }
public string TaxType { get; set; }
public string Description { get; set; }
public string Class { get; set; }
public string SystemAccount { get; set; }
public bool? EnablePaymentsToAccount { get; set; }
public string BankAccountNumber { get; set; }
public string CurrencyCode { get; set; }
public string ReportingCode { get; set; }
public string ReportingCodeName { get; set; }
}
public class Accounts : ModelList<Account>
{
}
} | mit | C# |
9cdb1c13d02b96fca2ac8d40e90670b61e597349 | Update CsiTests.cs to explicitly check for /i- in the generated build task response file contents. | tannergooding/roslyn,MichalStrehovsky/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,diryboy/roslyn,Giftednewt/roslyn,panopticoncentral/roslyn,antonssonj/roslyn,davkean/roslyn,MatthieuMEZIL/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,dpoeschl/roslyn,heejaechang/roslyn,amcasey/roslyn,dotnet/roslyn,vcsjones/roslyn,MattWindsor91/roslyn,DustinCampbell/roslyn,weltkante/roslyn,AmadeusW/roslyn,kelltrick/roslyn,Inverness/roslyn,AArnott/roslyn,aelij/roslyn,KiloBravoLima/roslyn,mmitche/roslyn,lorcanmooney/roslyn,eriawan/roslyn,jeffanders/roslyn,KevinH-MS/roslyn,mgoertz-msft/roslyn,managed-commons/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,abock/roslyn,srivatsn/roslyn,bkoelman/roslyn,budcribar/roslyn,ljw1004/roslyn,jmarolf/roslyn,zooba/roslyn,tmat/roslyn,xoofx/roslyn,abock/roslyn,jhendrixMSFT/roslyn,Maxwe11/roslyn,wvdd007/roslyn,KiloBravoLima/roslyn,amcasey/roslyn,mseamari/Stuff,jamesqo/roslyn,tannergooding/roslyn,natgla/roslyn,KevinH-MS/roslyn,jasonmalinowski/roslyn,paulvanbrenk/roslyn,tannergooding/roslyn,ValentinRueda/roslyn,drognanar/roslyn,moozzyk/roslyn,natgla/roslyn,pdelvo/roslyn,drognanar/roslyn,khyperia/roslyn,gafter/roslyn,reaction1989/roslyn,thomaslevesque/roslyn,a-ctor/roslyn,ericfe-ms/roslyn,budcribar/roslyn,xoofx/roslyn,managed-commons/roslyn,srivatsn/roslyn,wvdd007/roslyn,vslsnap/roslyn,jcouv/roslyn,nguerrera/roslyn,michalhosala/roslyn,vcsjones/roslyn,pdelvo/roslyn,basoundr/roslyn,Pvlerick/roslyn,CyrusNajmabadi/roslyn,lorcanmooney/roslyn,physhi/roslyn,agocke/roslyn,antonssonj/roslyn,dpoeschl/roslyn,yeaicc/roslyn,vslsnap/roslyn,ericfe-ms/roslyn,paulvanbrenk/roslyn,a-ctor/roslyn,danielcweber/roslyn,Shiney/roslyn,bbarry/roslyn,VPashkov/roslyn,Shiney/roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,shyamnamboodiripad/roslyn,jeffanders/roslyn,mgoertz-msft/roslyn,akrisiun/roslyn,tmeschter/roslyn,khellang/roslyn,orthoxerox/roslyn,tmat/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,vslsnap/roslyn,AArnott/roslyn,heejaechang/roslyn,natidea/roslyn,mmitche/roslyn,zooba/roslyn,abock/roslyn,michalhosala/roslyn,kelltrick/roslyn,Hosch250/roslyn,brettfo/roslyn,aelij/roslyn,oocx/roslyn,cston/roslyn,jamesqo/roslyn,jbhensley/roslyn,mattscheffer/roslyn,akrisiun/roslyn,jasonmalinowski/roslyn,Giftednewt/roslyn,Inverness/roslyn,balajikris/roslyn,AlekseyTs/roslyn,AnthonyDGreen/roslyn,cston/roslyn,tmeschter/roslyn,agocke/roslyn,rgani/roslyn,moozzyk/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,HellBrick/roslyn,aanshibudhiraja/Roslyn,SeriaWei/roslyn,mattwar/roslyn,KirillOsenkov/roslyn,natgla/roslyn,sharadagrawal/Roslyn,aelij/roslyn,sharwell/roslyn,basoundr/roslyn,eriawan/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,a-ctor/roslyn,stephentoub/roslyn,danielcweber/roslyn,TyOverby/roslyn,khyperia/roslyn,KirillOsenkov/roslyn,danielcweber/roslyn,diryboy/roslyn,mattwar/roslyn,bbarry/roslyn,basoundr/roslyn,natidea/roslyn,aanshibudhiraja/Roslyn,brettfo/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,Pvlerick/roslyn,tvand7093/roslyn,mgoertz-msft/roslyn,ValentinRueda/roslyn,sharadagrawal/Roslyn,gafter/roslyn,jhendrixMSFT/roslyn,jkotas/roslyn,jeffanders/roslyn,robinsedlaczek/roslyn,davkean/roslyn,MatthieuMEZIL/roslyn,nguerrera/roslyn,michalhosala/roslyn,Maxwe11/roslyn,xoofx/roslyn,wvdd007/roslyn,dotnet/roslyn,natidea/roslyn,stephentoub/roslyn,mavasani/roslyn,rgani/roslyn,mavasani/roslyn,budcribar/roslyn,khellang/roslyn,Maxwe11/roslyn,KevinRansom/roslyn,leppie/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,bartdesmet/roslyn,bkoelman/roslyn,mavasani/roslyn,orthoxerox/roslyn,KiloBravoLima/roslyn,MatthieuMEZIL/roslyn,drognanar/roslyn,aanshibudhiraja/Roslyn,genlu/roslyn,physhi/roslyn,sharwell/roslyn,MichalStrehovsky/roslyn,yeaicc/roslyn,ericfe-ms/roslyn,jhendrixMSFT/roslyn,kelltrick/roslyn,jkotas/roslyn,HellBrick/roslyn,panopticoncentral/roslyn,jaredpar/roslyn,orthoxerox/roslyn,weltkante/roslyn,khellang/roslyn,jkotas/roslyn,leppie/roslyn,TyOverby/roslyn,OmarTawfik/roslyn,ErikSchierboom/roslyn,CaptainHayashi/roslyn,TyOverby/roslyn,jbhensley/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,OmarTawfik/roslyn,jmarolf/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,tmeschter/roslyn,VSadov/roslyn,VPashkov/roslyn,diryboy/roslyn,sharwell/roslyn,robinsedlaczek/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,ljw1004/roslyn,lorcanmooney/roslyn,VSadov/roslyn,yeaicc/roslyn,oocx/roslyn,jaredpar/roslyn,jcouv/roslyn,sharadagrawal/Roslyn,tvand7093/roslyn,genlu/roslyn,robinsedlaczek/roslyn,Hosch250/roslyn,pdelvo/roslyn,cston/roslyn,MattWindsor91/roslyn,bartdesmet/roslyn,zooba/roslyn,jamesqo/roslyn,leppie/roslyn,mattwar/roslyn,CaptainHayashi/roslyn,mseamari/Stuff,KevinRansom/roslyn,antonssonj/roslyn,brettfo/roslyn,SeriaWei/roslyn,Inverness/roslyn,VPashkov/roslyn,AlekseyTs/roslyn,paulvanbrenk/roslyn,reaction1989/roslyn,bbarry/roslyn,jmarolf/roslyn,physhi/roslyn,mattscheffer/roslyn,managed-commons/roslyn,balajikris/roslyn,SeriaWei/roslyn,stephentoub/roslyn,swaroop-sridhar/roslyn,MattWindsor91/roslyn,jasonmalinowski/roslyn,tmat/roslyn,ErikSchierboom/roslyn,mseamari/Stuff,KevinH-MS/roslyn,AnthonyDGreen/roslyn,xasx/roslyn,jcouv/roslyn,genlu/roslyn,CaptainHayashi/roslyn,OmarTawfik/roslyn,akrisiun/roslyn,khyperia/roslyn,HellBrick/roslyn,moozzyk/roslyn,agocke/roslyn,jaredpar/roslyn,thomaslevesque/roslyn,vcsjones/roslyn,gafter/roslyn,ValentinRueda/roslyn,Pvlerick/roslyn,AArnott/roslyn,bkoelman/roslyn,nguerrera/roslyn,ErikSchierboom/roslyn,thomaslevesque/roslyn,VSadov/roslyn,oocx/roslyn,mattscheffer/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tvand7093/roslyn,dotnet/roslyn,Shiney/roslyn,eriawan/roslyn,srivatsn/roslyn,ljw1004/roslyn,rgani/roslyn,amcasey/roslyn,AmadeusW/roslyn,xasx/roslyn,xasx/roslyn,jbhensley/roslyn,AnthonyDGreen/roslyn,mmitche/roslyn,balajikris/roslyn,Giftednewt/roslyn | src/Compilers/Core/MSBuildTaskTests/CsiTests.cs | src/Compilers/Core/MSBuildTaskTests/CsiTests.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public sealed class CsiTests
{
[Fact]
public void SingleSource()
{
var csi = new Csi();
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents());
}
[Fact]
public void Features()
{
Action<string> test = (s) =>
{
var csi = new Csi();
csi.Features = s;
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("/i- /features:a /features:b test.csx", csi.GenerateResponseFileContents());
};
test("a;b");
test("a,b");
test("a b");
test(",a;b ");
test(";a;;b;");
test(",a,,b,");
}
[Fact]
public void FeaturesEmpty()
{
foreach (var cur in new[] { "", null })
{
var csi = new Csi();
csi.Features = cur;
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("/i- test.csx", csi.GenerateResponseFileContents());
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Xunit;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public sealed class CsiTests
{
[Fact]
public void SingleSource()
{
var csi = new Csi();
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("test.csx", csi.GenerateResponseFileContents());
}
[Fact]
public void Features()
{
Action<string> test = (s) =>
{
var csi = new Csi();
csi.Features = s;
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("/features:a /features:b test.csx", csi.GenerateResponseFileContents());
};
test("a;b");
test("a,b");
test("a b");
test(",a;b ");
test(";a;;b;");
test(",a,,b,");
}
[Fact]
public void FeaturesEmpty()
{
foreach (var cur in new[] { "", null })
{
var csi = new Csi();
csi.Features = cur;
csi.Source = MSBuildUtil.CreateTaskItem("test.csx");
Assert.Equal("test.csx", csi.GenerateResponseFileContents());
}
}
}
}
| mit | C# |
8395fd6f6e8f1bebfa3384ddece309a9200cfa68 | Fix validation error message, add working directory to failure message | eatdrinksleepcode/casper,eatdrinksleepcode/casper | Core/Exec.cs | Core/Exec.cs | using System.Diagnostics;
using System.Text;
using System;
using Casper.IO;
namespace Casper {
public class Exec : TaskBase {
public string WorkingDirectory { get; set; }
public string Executable { get; set; }
public string Arguments { get; set; }
public override void Execute(IFileSystem fileSystem) {
if (null == Executable) {
throw new CasperException(CasperException.EXIT_CODE_CONFIGURATION_ERROR, "Must set 'Executable'");
}
var processStartInfo = new ProcessStartInfo {
FileName = Executable,
Arguments = Arguments,
UseShellExecute = false,
WorkingDirectory = WorkingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
var process = Process.Start(processStartInfo);
var allOutput = new StringBuilder();
process.ErrorDataReceived += (sender, e) => { if(e.Data != null) allOutput.AppendLine(e.Data); };
process.OutputDataReceived += (sender, e) => { if(e.Data != null) allOutput.AppendLine(e.Data); };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
if (0 != process.ExitCode) {
Console.Error.WriteLine(allOutput.ToString());
throw new CasperException(CasperException.EXIT_CODE_TASK_FAILED, "Process '{0}{1}'{2} exited with code {3}", Executable, null == Arguments ? "" : " " + Arguments, null == WorkingDirectory ? "" : " in '" + WorkingDirectory + "'", process.ExitCode);
}
}
}
}
| using System.Diagnostics;
using System.Text;
using System;
using Casper.IO;
namespace Casper {
public class Exec : TaskBase {
public string WorkingDirectory { get; set; }
public string Executable { get; set; }
public string Arguments { get; set; }
public override void Execute(IFileSystem fileSystem) {
if (null == Executable) {
throw new CasperException(CasperException.EXIT_CODE_CONFIGURATION_ERROR, "Must set 'Source'");
}
var processStartInfo = new ProcessStartInfo {
FileName = Executable,
Arguments = Arguments,
UseShellExecute = false,
WorkingDirectory = WorkingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
};
var process = Process.Start(processStartInfo);
var allOutput = new StringBuilder();
process.ErrorDataReceived += (sender, e) => { if(e.Data != null) allOutput.AppendLine(e.Data); };
process.OutputDataReceived += (sender, e) => { if(e.Data != null) allOutput.AppendLine(e.Data); };
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
if (0 != process.ExitCode) {
Console.Error.WriteLine(allOutput.ToString());
throw new CasperException(CasperException.EXIT_CODE_TASK_FAILED, "Process '{0}{1}' exited with code {2}", Executable, null == Arguments ? "" : " " + Arguments, process.ExitCode);
}
}
}
}
| mit | C# |
53ee0902ae0941fae4f221ad9f505cb7df957db7 | Add warnings to ResultType | bazzilic/choco,harish123400/choco,jberezanski/choco,kouweizhong/choco,sideeffffect/choco,mwrock/choco,alephnaughty/choco,finchd/choco,harish123400/choco,raisercostin/choco,hagb4rd/choco,jamessingizi/choco,TheBigBear/choco,dshaneg/choco,TheBigBear/choco,mwrock/choco,ShwoognationHQ/choco,Apteryx0/choco,vcarrera/choco,hagb4rd/choco,jberezanski/choco,ewilde/choco,TheBigBear/choco,b1thunt3r/choco,bc3tech/choco,jberezanski/choco,Annih/choco,bazzilic/choco,ShwoognationHQ/choco,vcarrera/choco,darrelmiller/choco,b1thunt3r/choco,christianrondeau/choco,ewilde/choco,dtgm/choco,dtgm/choco,alephnaughty/choco,jamessingizi/choco,eeevans/choco,sideeffffect/choco,christianrondeau/choco,Apteryx0/choco,dshaneg/choco,raisercostin/choco,darrelmiller/choco,kouweizhong/choco,eeevans/choco,finchd/choco,Annih/choco,bc3tech/choco | src/chocolatey/infrastructure/results/ResultType.cs | src/chocolatey/infrastructure/results/ResultType.cs | namespace chocolatey.infrastructure.results
{
/// <summary>
/// When working with results, this identifies the type of result
/// </summary>
public enum ResultType
{
/// <summary>
/// The default result type.
/// </summary>
None,
/// <summary>
/// Debugging messages that may help the recipient determine items leading up to errors
/// </summary>
Debug,
/// <summary>
/// Verbose messages that may help the recipient determine items leading up to errors
/// </summary>
Verbose,
/// <summary>
/// These are notes to pass along with the result
/// </summary>
Note,
/// <summary>
/// There was no result.
/// </summary>
Inconclusive,
/// <summary>
/// These are warnings
/// </summary>
Warn,
/// <summary>
/// These are errors
/// </summary>
Error,
}
} | namespace chocolatey.infrastructure.results
{
/// <summary>
/// When working with results, this identifies the type of result
/// </summary>
public enum ResultType
{
/// <summary>
/// The default result type.
/// </summary>
None,
/// <summary>
/// Debugging messages that may help the recipient determine items leading up to errors
/// </summary>
Debug,
/// <summary>
/// Verbose messages that may help the recipient determine items leading up to errors
/// </summary>
Verbose,
/// <summary>
/// These are notes to pass along with the result
/// </summary>
Note,
/// <summary>
/// There was no result.
/// </summary>
Inconclusive,
/// <summary>
/// These are errors
/// </summary>
Error,
}
} | apache-2.0 | C# |
afdb5fcee54635c405bad7c35d331575350ffbdf | Fix identation | toddams/RazorLight,toddams/RazorLight | src/RazorLight/ITemplatePage.cs | src/RazorLight/ITemplatePage.cs | using Microsoft.AspNetCore.Html;
using RazorLight.Internal;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RazorLight
{
public interface ITemplatePage
{
void SetModel(object model);
/// <summary>
/// Gets or sets the view context of the rendering template.
/// </summary>
PageContext PageContext { get; set; }
/// <summary>
/// Gets or sets the body content.
/// </summary>
IHtmlContent BodyContent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether encoding is disabled for the entire template
/// </summary>
bool DisableEncoding { get; set; }
/// <summary>
/// Gets or sets the unique key of the current template
/// </summary>
string Key { get; set; }
/// <summary>
/// Gets or sets a flag that determines if the layout of this page is being rendered.
/// </summary>
/// <remarks>
/// Sections defined in a page are deferred and executed as part of the layout page.
/// When this flag is set, all write operations performed by the page are part of a
/// section being rendered.
/// </remarks>
bool IsLayoutBeingRendered { get; set; }
/// <summary>
/// Gets or sets the key of a layout page.
/// </summary>
string Layout { get; set; }
/// <summary>
/// Gets or sets the sections that can be rendered by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> PreviousSectionWriters { get; set; }
/// <summary>
/// Gets the sections that are defined by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> SectionWriters { get; }
/// <summary>
/// Renders the page and writes the output to the <see cref="IPageContext.Writer"/> />.
/// </summary>
/// <returns>A task representing the result of executing the page.</returns>
Task ExecuteAsync();
Func<string, object, Task> IncludeFunc { get; set; }
void EnsureRenderedBodyOrSections();
}
}
| using Microsoft.AspNetCore.Html;
using RazorLight.Internal;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace RazorLight
{
public interface ITemplatePage
{
void SetModel(object model);
/// <summary>
/// Gets or sets the view context of the rendering template.
/// </summary>
PageContext PageContext { get; set; }
/// <summary>
/// Gets or sets the body content.
/// </summary>
IHtmlContent BodyContent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether encoding is disabled for the entire template
/// </summary>
bool DisableEncoding { get; set; }
/// <summary>
/// Gets or sets the unique key of the current template
/// </summary>
string Key { get; set; }
/// <summary>
/// Gets or sets a flag that determines if the layout of this page is being rendered.
/// </summary>
/// <remarks>
/// Sections defined in a page are deferred and executed as part of the layout page.
/// When this flag is set, all write operations performed by the page are part of a
/// section being rendered.
/// </remarks>
bool IsLayoutBeingRendered { get; set; }
/// <summary>
/// Gets or sets the key of a layout page.
/// </summary>
string Layout { get; set; }
/// <summary>
/// Gets or sets the sections that can be rendered by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> PreviousSectionWriters { get; set; }
/// <summary>
/// Gets the sections that are defined by this page.
/// </summary>
IDictionary<string, RenderAsyncDelegate> SectionWriters { get; }
/// <summary>
/// Renders the page and writes the output to the <see cref="IPageContext.Writer"/> />.
/// </summary>
/// <returns>A task representing the result of executing the page.</returns>
Task ExecuteAsync();
Func<string, object, Task> IncludeFunc { get; set; }
void EnsureRenderedBodyOrSections();
}
}
| apache-2.0 | C# |
f25240cfe6a4b7f030b2dfd5db1365b4de44301d | Set current SynchronizationContext before the game loop starts | mcanders/godot,mcanders/godot,RandomShaper/godot,Paulloz/godot,RandomShaper/godot,Valentactive/godot,NateWardawg/godot,sanikoyes/godot,josempans/godot,firefly2442/godot,godotengine/godot,Valentactive/godot,BastiaanOlij/godot,NateWardawg/godot,Valentactive/godot,guilhermefelipecgs/godot,groud/godot,ZuBsPaCe/godot,firefly2442/godot,ZuBsPaCe/godot,MarianoGnu/godot,okamstudio/godot,honix/godot,BastiaanOlij/godot,vkbsb/godot,Paulloz/godot,ex/godot,Zylann/godot,sanikoyes/godot,NateWardawg/godot,RandomShaper/godot,vkbsb/godot,akien-mga/godot,akien-mga/godot,BastiaanOlij/godot,guilhermefelipecgs/godot,Zylann/godot,Faless/godot,ex/godot,Zylann/godot,MarianoGnu/godot,NateWardawg/godot,josempans/godot,pkowal1982/godot,RandomShaper/godot,MarianoGnu/godot,MarianoGnu/godot,RandomShaper/godot,akien-mga/godot,guilhermefelipecgs/godot,sanikoyes/godot,josempans/godot,okamstudio/godot,groud/godot,ex/godot,godotengine/godot,akien-mga/godot,josempans/godot,vnen/godot,akien-mga/godot,mcanders/godot,honix/godot,honix/godot,vnen/godot,vnen/godot,NateWardawg/godot,MarianoGnu/godot,RandomShaper/godot,groud/godot,guilhermefelipecgs/godot,firefly2442/godot,Faless/godot,pkowal1982/godot,groud/godot,groud/godot,guilhermefelipecgs/godot,Valentactive/godot,vnen/godot,firefly2442/godot,vkbsb/godot,mcanders/godot,Valentactive/godot,ex/godot,Zylann/godot,guilhermefelipecgs/godot,josempans/godot,akien-mga/godot,DmitriySalnikov/godot,vkbsb/godot,Paulloz/godot,RandomShaper/godot,firefly2442/godot,vnen/godot,Paulloz/godot,BastiaanOlij/godot,okamstudio/godot,akien-mga/godot,guilhermefelipecgs/godot,NateWardawg/godot,okamstudio/godot,okamstudio/godot,godotengine/godot,mcanders/godot,BastiaanOlij/godot,Faless/godot,Valentactive/godot,pkowal1982/godot,okamstudio/godot,okamstudio/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,MarianoGnu/godot,ex/godot,josempans/godot,okamstudio/godot,Shockblast/godot,Paulloz/godot,Shockblast/godot,sanikoyes/godot,Faless/godot,ex/godot,NateWardawg/godot,BastiaanOlij/godot,Zylann/godot,vkbsb/godot,BastiaanOlij/godot,Shockblast/godot,Valentactive/godot,godotengine/godot,honix/godot,Faless/godot,firefly2442/godot,pkowal1982/godot,vnen/godot,Faless/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,MarianoGnu/godot,Zylann/godot,vkbsb/godot,MarianoGnu/godot,josempans/godot,ex/godot,vkbsb/godot,DmitriySalnikov/godot,sanikoyes/godot,godotengine/godot,firefly2442/godot,Zylann/godot,Valentactive/godot,josempans/godot,sanikoyes/godot,Shockblast/godot,Shockblast/godot,vnen/godot,Faless/godot,ZuBsPaCe/godot,Paulloz/godot,honix/godot,Shockblast/godot,Zylann/godot,ZuBsPaCe/godot,vnen/godot,okamstudio/godot,DmitriySalnikov/godot,vkbsb/godot,Paulloz/godot,akien-mga/godot,pkowal1982/godot,groud/godot,ex/godot,godotengine/godot,BastiaanOlij/godot,Shockblast/godot,DmitriySalnikov/godot,firefly2442/godot,pkowal1982/godot,NateWardawg/godot,godotengine/godot,okamstudio/godot,ZuBsPaCe/godot,godotengine/godot,honix/godot,mcanders/godot,pkowal1982/godot,sanikoyes/godot,NateWardawg/godot,pkowal1982/godot,guilhermefelipecgs/godot,DmitriySalnikov/godot,ZuBsPaCe/godot,Shockblast/godot,Faless/godot,sanikoyes/godot | modules/mono/glue/cs_files/GodotTaskScheduler.cs | modules/mono/glue/cs_files/GodotTaskScheduler.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Godot
{
public class GodotTaskScheduler : TaskScheduler
{
private GodotSynchronizationContext Context { get; set; }
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
public GodotTaskScheduler()
{
Context = new GodotSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(Context);
}
protected sealed override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.AddLast(task);
}
}
protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (SynchronizationContext.Current != Context)
{
return false;
}
if (taskWasPreviouslyQueued)
{
TryDequeue(task);
}
return TryExecuteTask(task);
}
protected sealed override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
}
protected sealed override IEnumerable<Task> GetScheduledTasks()
{
lock (_tasks)
{
return _tasks.ToArray();
}
}
public void Activate()
{
ExecuteQueuedTasks();
Context.ExecutePendingContinuations();
}
private void ExecuteQueuedTasks()
{
while (true)
{
Task task;
lock (_tasks)
{
if (_tasks.Any())
{
task = _tasks.First.Value;
_tasks.RemoveFirst();
}
else
{
break;
}
}
if (task != null)
{
if (!TryExecuteTask(task))
{
throw new InvalidOperationException();
}
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Godot
{
public class GodotTaskScheduler : TaskScheduler
{
private GodotSynchronizationContext Context { get; set; }
private readonly LinkedList<Task> _tasks = new LinkedList<Task>();
public GodotTaskScheduler()
{
Context = new GodotSynchronizationContext();
}
protected sealed override void QueueTask(Task task)
{
lock (_tasks)
{
_tasks.AddLast(task);
}
}
protected sealed override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (SynchronizationContext.Current != Context)
{
return false;
}
if (taskWasPreviouslyQueued)
{
TryDequeue(task);
}
return TryExecuteTask(task);
}
protected sealed override bool TryDequeue(Task task)
{
lock (_tasks)
{
return _tasks.Remove(task);
}
}
protected sealed override IEnumerable<Task> GetScheduledTasks()
{
lock (_tasks)
{
return _tasks.ToArray();
}
}
public void Activate()
{
SynchronizationContext.SetSynchronizationContext(Context);
ExecuteQueuedTasks();
Context.ExecutePendingContinuations();
}
private void ExecuteQueuedTasks()
{
while (true)
{
Task task;
lock (_tasks)
{
if (_tasks.Any())
{
task = _tasks.First.Value;
_tasks.RemoveFirst();
}
else
{
break;
}
}
if (task != null)
{
if (!TryExecuteTask(task))
{
throw new InvalidOperationException();
}
}
}
}
}
}
| mit | C# |
40a28c08d92d98cf06af688a71b551e6a4ffd2e1 | fix specs that depend on version | jonnii/SpeakEasy | src/SpeakEasy.Specifications/UserAgentSpecs.cs | src/SpeakEasy.Specifications/UserAgentSpecs.cs | using Machine.Specifications;
namespace SpeakEasy.Specifications
{
[Subject(typeof(UserAgent))]
class UserAgentSpecs
{
class default_user_agent
{
It should_contain_app_version = () =>
UserAgent.SpeakEasy.Name.ShouldContain("SpeakEasy/1.");
}
}
}
| using Machine.Specifications;
namespace SpeakEasy.Specifications
{
[Subject(typeof(UserAgent))]
class UserAgentSpecs
{
class default_user_agent
{
It should_contain_app_version = () =>
UserAgent.SpeakEasy.Name.ShouldContain("SpeakEasy/1.0");
}
}
}
| apache-2.0 | C# |
d0c1245877064612cb78446d634b5a801802907d | Make ClientException fields public | tgstation/tgstation-server,tgstation/tgstation-server-tools,Cyberboss/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server | src/Tgstation.Server.Client/ClientException.cs | src/Tgstation.Server.Client/ClientException.cs | using System;
using System.Net;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client
{
/// <summary>
/// Exceptions thrown by <see cref="IServerClient"/>s
/// </summary>
public abstract class ClientException : Exception
{
/// <summary>
/// The <see cref="HttpStatusCode"/> of the <see cref="ClientException"/>
/// </summary>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// The <see cref="Version"/> of the server's API
/// </summary>
public Version ServerApiVersion { get; }
/// <summary>
/// Construct a <see cref="ClientException"/> using an <paramref name="errorMessage"/> and <paramref name="statusCode"/>
/// </summary>
/// <param name="errorMessage">The <see cref="ErrorMessage"/> associated with the <see cref="ClientException"/></param>
/// <param name="statusCode">The <see cref="HttpStatusCode"/> of the <see cref="ClientException"/></param>
protected ClientException(ErrorMessage errorMessage, HttpStatusCode statusCode) : base(errorMessage == null ? throw new ArgumentNullException(nameof(errorMessage)) : errorMessage.Message ?? "Unknown Error")
{
StatusCode = statusCode;
ServerApiVersion = errorMessage?.SeverApiVersion;
}
/// <summary>
/// Construct a <see cref="ClientException"/>
/// </summary>
protected ClientException() { }
/// <summary>
/// Construct a <see cref="ClientException"/> with a <paramref name="message"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
protected ClientException(string message) : base(message) { }
/// <summary>
/// Construct a <see cref="ClientException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
protected ClientException(string message, Exception innerException) : base(message, innerException) { }
}
}
| using System;
using System.Net;
using Tgstation.Server.Api.Models;
namespace Tgstation.Server.Client
{
/// <summary>
/// Exceptions thrown by <see cref="IServerClient"/>s
/// </summary>
public abstract class ClientException : Exception
{
/// <summary>
/// The <see cref="HttpStatusCode"/> of the <see cref="ClientException"/>
/// </summary>
HttpStatusCode StatusCode { get; }
Version ServerApiVersion { get; }
/// <summary>
/// Construct a <see cref="ClientException"/> using an <paramref name="errorMessage"/> and <paramref name="statusCode"/>
/// </summary>
/// <param name="errorMessage">The <see cref="ErrorMessage"/> associated with the <see cref="ClientException"/></param>
/// <param name="statusCode">The <see cref="HttpStatusCode"/> of the <see cref="ClientException"/></param>
protected ClientException(ErrorMessage errorMessage, HttpStatusCode statusCode) : base(errorMessage == null ? throw new ArgumentNullException(nameof(errorMessage)) : errorMessage.Message ?? "Unknown Error")
{
StatusCode = statusCode;
ServerApiVersion = errorMessage?.SeverApiVersion;
}
/// <summary>
/// Construct a <see cref="ClientException"/>
/// </summary>
protected ClientException() { }
/// <summary>
/// Construct a <see cref="ClientException"/> with a <paramref name="message"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
protected ClientException(string message) : base(message) { }
/// <summary>
/// Construct a <see cref="ClientException"/> with a <paramref name="message"/> and <paramref name="innerException"/>
/// </summary>
/// <param name="message">The message for the <see cref="Exception"/></param>
/// <param name="innerException">The inner <see cref="Exception"/> for the base <see cref="Exception"/></param>
protected ClientException(string message, Exception innerException) : base(message, innerException) { }
}
}
| agpl-3.0 | C# |
a0864fb41f959c81d52154f5cb0d15f12bf5104e | Update AssemblyInfo | Implem/Implem.Pleasanter,Implem/Implem.Pleasanter,Implem/Implem.Pleasanter | Implem.Pleasanter/Properties/AssemblyInfo.cs | Implem.Pleasanter/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Implem.Pleasanter")]
[assembly: AssemblyDescription("Business application platform")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Implem.Pleasanter")]
[assembly: AssemblyCopyright("Copyright © Implem Inc 2014 - 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ec0d3d5b-8879-462b-835f-ff1737a01543")]
[assembly: AssemblyVersion("0.50.252.*")] | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Implem.Pleasanter")]
[assembly: AssemblyDescription("Business application platform")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Implem.Pleasanter")]
[assembly: AssemblyCopyright("Copyright © Implem Inc 2014 - 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("ec0d3d5b-8879-462b-835f-ff1737a01543")]
[assembly: AssemblyVersion("0.50.251.*")] | agpl-3.0 | C# |
f6e38562ca963299ec18f590b33a3d01ac767168 | Handle null id for Cars/Details action | tipjung/tdd-carfuel,tipjung/tdd-carfuel,tipjung/tdd-carfuel | CarFuel/Controllers/CarsController.cs | CarFuel/Controllers/CarsController.cs | using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} | using CarFuel.DataAccess;
using CarFuel.Models;
using CarFuel.Services;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace CarFuel.Controllers
{
public class CarsController : Controller
{
private ICarDb db;
private CarService carService;
public CarsController()
{
db = new CarDb();
carService = new CarService(db);
}
[Authorize]
public ActionResult Index()
{
var userId = new Guid(User.Identity.GetUserId());
IEnumerable<Car> cars = carService.GetCarsByMember(userId);
return View(cars);
}
[Authorize]
public ActionResult Create()
{
return View();
}
[HttpPost]
[Authorize]
public ActionResult Create(Car item)
{
var userId = new Guid(User.Identity.GetUserId());
try
{
carService.AddCar(item, userId);
}
catch (OverQuotaException ex)
{
TempData["error"] = ex.Message;
}
return RedirectToAction("Index");
}
public ActionResult Details(Guid id)
{
var userId = new Guid(User.Identity.GetUserId());
var c = carService.GetCarsByMember(userId).SingleOrDefault(x => x.Id == id);
return View(c);
}
}
} | mit | C# |
65e7aa20fc4becf81d18a90ff7b07ff23a8b3b52 | Update version to 0.8 | Carbon/Css | Carbon.Css/Properties/AssemblyInfo.cs | Carbon.Css/Properties/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Carbon Css")]
[assembly: AssemblyProduct("Carbon")]
[assembly: AssemblyCopyright("© 2012-2014 Jason Nelson")]
[assembly: AssemblyVersion("0.0.8")]
/*
- CssPropertyInfo
IsStandard
Vendor
0.0.1 (2012-07-20)
-----------------------------------------------------
Initial
*/ | using System.Reflection;
[assembly: AssemblyTitle("Carbon Css")]
[assembly: AssemblyProduct("Carbon")]
[assembly: AssemblyCopyright("© 2012-2014 Jason Nelson")]
[assembly: AssemblyVersion("0.0.7")]
/*
- CssPropertyInfo
IsStandard
Vendor
0.0.1 (2012-07-20)
-----------------------------------------------------
Initial
*/ | mit | C# |
007d807efffbd5838392e85412a1adddc1f382c8 | Comment section updated | shahriarhossain/MailChimp.Api.Net | MailChimp.Api.Net/Services/Reports/MCReportsLocation.cs | MailChimp.Api.Net/Services/Reports/MCReportsLocation.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MailChimp.Api.Net.Domain.Reports;
using MailChimp.Api.Net.Enum;
using Newtonsoft.Json;
namespace MailChimp.Api.Net.Services.Reports
{
public class MCReportsLocation
{
/// <summary>
/// Return top open locations for a specific campaign.
/// <param name="campaignId">Unique id for the campaign</param>
/// </summary>
public async Task<RootLocation> GetTopLocation(string campaignId)
{
string endpoint = Authenticate.EndPoint(TargetTypes.reports, SubTargetType.locations, SubTargetType.not_applicable, campaignId);
string content;
using (var client = new HttpClient())
{
Authenticate.ClientAuthentication(client);
content = await client.GetStringAsync(endpoint);
}
return JsonConvert.DeserializeObject<RootLocation>(content);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using MailChimp.Api.Net.Domain.Reports;
using MailChimp.Api.Net.Enum;
using Newtonsoft.Json;
namespace MailChimp.Api.Net.Services.Reports
{
public class MCReportsLocation
{
/// <summary>
/// Return top open locations for a specific campaign.
/// <param name="campaignId">Campaign Id</param>
/// </summary>
public async Task<RootLocation> GetTopLocation(string campaignId)
{
string endpoint = Authenticate.EndPoint(TargetTypes.reports, SubTargetType.locations, SubTargetType.not_applicable, campaignId);
string content;
using (var client = new HttpClient())
{
Authenticate.ClientAuthentication(client);
content = await client.GetStringAsync(endpoint);
}
return JsonConvert.DeserializeObject<RootLocation>(content);
}
}
}
| mit | C# |
ee851cf3049d59f9ef6ab40949d41eb2db3b2729 | add test for missing x-upstream header | Pondidum/Jess,Pondidum/Jess | Jess.Tests/Acceptance/Hydration/WhenHydrating.cs | Jess.Tests/Acceptance/Hydration/WhenHydrating.cs | using System;
using System.Net;
using System.Net.Http;
using Jess.Tests.Util;
using Newtonsoft.Json;
using Shouldly;
using Xunit;
namespace Jess.Tests.Acceptance.Hydration
{
public class WhenHydrating : AcceptanceBase
{
public WhenHydrating()
{
Remote.RespondsTo(
"/candidate/ref/123",
request => new DehydratedResponse(Resource.PersonWithOneRef));
Remote.RespondsTo(
"/candidate/ref/456",
request => new JsonResponse(Resource.PersonWithOneRef));
}
[Fact]
public void Without_a_hydrate_header()
{
var response = Hydrator.MakeRequest("/candidate/ref/456", BuildMessage(new HttpRequestMessage()));
var body = response.Content.ReadAsStringAsync().Result;
body.ShouldNotBeEmpty();
body.ShouldBe(Resource.PersonWithOneRef);
}
[Fact]
public void When_the_request_has_no_upstream_header()
{
var response = Hydrator.MakeRequest("/candidate/ref/456", new HttpRequestMessage());
response.StatusCode.ShouldBe(HttpStatusCode.InternalServerError);
//in-memory doesnt give you the full exception back?
}
}
}
| using System.Net.Http;
using Jess.Tests.Util;
using Shouldly;
using Xunit;
namespace Jess.Tests.Acceptance.Hydration
{
public class WhenHydrating : AcceptanceBase
{
public WhenHydrating()
{
Remote.RespondsTo(
"/candidate/ref/123",
request => new DehydratedResponse(Resource.PersonWithOneRef));
Remote.RespondsTo(
"/candidate/ref/456",
request => new JsonResponse(Resource.PersonWithOneRef));
}
[Fact]
public void Without_a_hydrate_header()
{
var response = Hydrator.MakeRequest("/candidate/ref/456", BuildMessage(new HttpRequestMessage()));
var body = response.Content.ReadAsStringAsync().Result;
body.ShouldNotBeEmpty();
body.ShouldBe(Resource.PersonWithOneRef);
}
}
}
| lgpl-2.1 | C# |
32f54484363662d973c5583522179fe46f439390 | Add NotOfType<T>() and FirstOfType<T>(). | PombeirP/LinqContrib | src/Linq.Contrib/LinqExtensions.cs | src/Linq.Contrib/LinqExtensions.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="LinqExtensions.cs" company="Developer In The Flow">
// © 2013 Pedro Pombeiro
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Linq.Contrib
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class LinqExtensions
{
#region Public Methods and Operators
public static bool AnyOfType<T>(this IEnumerable source)
{
return source.OfType<T>().Any();
}
public static T FirstOfType<T>(this IEnumerable source)
{
return source.OfType<T>().First();
}
public static T FirstOrDefaultOfType<T>(this IEnumerable source)
{
return source.OfType<T>().FirstOrDefault();
}
public static IEnumerable NotOfType<T>(this IEnumerable source)
{
return source.Cast<object>().Where(x => !(x is T));
}
public static IEnumerable<IEnumerable<T>> Segment<T>(this IEnumerable<T> source, int segmentSize)
{
var index = 0;
for (;;)
{
// ReSharper disable PossibleMultipleEnumeration
var sourceSegment = source.Skip(index++ * segmentSize)
.Take(segmentSize);
if (!sourceSegment.Any())
{
yield break;
}
yield return sourceSegment;
// ReSharper restore PossibleMultipleEnumeration
}
}
public static T SingleOfType<T>(this IEnumerable source)
{
return source.OfType<T>().Single();
}
public static T SingleOrDefaultOfType<T>(this IEnumerable source)
{
return source.OfType<T>().SingleOrDefault();
}
#endregion
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="LinqExtensions.cs" company="Developer In The Flow">
// © 2013 Pedro Pombeiro
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Linq.Contrib
{
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public static class LinqExtensions
{
#region Public Methods and Operators
public static bool AnyOfType<T>(this IEnumerable source)
{
return source.OfType<T>().Any();
}
public static IEnumerable<IEnumerable<T>> Segment<T>(this IEnumerable<T> source, int segmentSize)
{
var index = 0;
for (;;)
{
// ReSharper disable PossibleMultipleEnumeration
var sourceSegment = source.Skip(index++ * segmentSize)
.Take(segmentSize);
if (!sourceSegment.Any())
{
yield break;
}
yield return sourceSegment;
// ReSharper restore PossibleMultipleEnumeration
}
}
public static T SingleOfType<T>(this IEnumerable source)
{
return source.OfType<T>().Single();
}
public static T SingleOrDefaultOfType<T>(this IEnumerable source)
{
return source.OfType<T>().SingleOrDefault();
}
#endregion
}
} | mit | C# |
ede7d9b8e77d5b5c71f33af67676d58179863a74 | Update SkillsController - nou it is possible to remove skills from the database | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.WebApp/Controllers/SkillsController.cs | NinjaHive.WebApp/Controllers/SkillsController.cs | using System;
using System.Web.Mvc;
using NinjaHive.Contract.Commands;
using NinjaHive.Contract.DTOs;
using NinjaHive.Contract.Queries;
using NinjaHive.Core;
using NinjaHive.WebApp.Services;
namespace NinjaHive.WebApp.Controllers
{
public class SkillsController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<EditSkillCommand> editSkillCommandHandler;
private readonly ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler;
public SkillsController(
IQueryProcessor queryProcessor,
ICommandHandler<EditSkillCommand> editSkillCommandHandler,
ICommandHandler<DeleteSkillCommand> deleteSkillCommandHandler)
{
this.queryProcessor = queryProcessor;
this.editSkillCommandHandler = editSkillCommandHandler;
this.deleteSkillCommandHandler = deleteSkillCommandHandler;
}
// GET: Skills
public ActionResult Index()
{
var skills = this.queryProcessor.Execute(new GetAllSkillsQuery());
return View(skills);
}
public ActionResult Create()
{
return View();
}
public ActionResult Edit(Guid skillId)
{
var skill = this.queryProcessor.Execute(new GetEntityByIdQuery<Skill>(skillId));
return View(skill);
}
[HttpPost]
public ActionResult Create(Skill skill)
{
skill.Id = Guid.NewGuid();
var command = new EditSkillCommand(skill, createNew: true);
this.editSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
public ActionResult Delete(Skill skill)
{
var command = new DeleteSkillCommand()
{
Skill = skill
};
deleteSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
}
} | using System;
using System.Web.Mvc;
using NinjaHive.Contract.Commands;
using NinjaHive.Contract.DTOs;
using NinjaHive.Contract.Queries;
using NinjaHive.Core;
using NinjaHive.WebApp.Services;
namespace NinjaHive.WebApp.Controllers
{
public class SkillsController : Controller
{
private readonly IQueryProcessor queryProcessor;
private readonly ICommandHandler<EditSkillCommand> editSkillCommandHandler;
public SkillsController(
IQueryProcessor queryProcessor,
ICommandHandler<EditSkillCommand> editSkillCommandHandler)
{
this.queryProcessor = queryProcessor;
this.editSkillCommandHandler = editSkillCommandHandler;
}
// GET: Skills
public ActionResult Index()
{
var skills = this.queryProcessor.Execute(new GetAllSkillsQuery());
return View(skills);
}
public ActionResult Create()
{
return View();
}
public ActionResult Edit(Guid skillId)
{
var skill = this.queryProcessor.Execute(new GetEntityByIdQuery<Skill>(skillId));
return View(skill);
}
[HttpPost]
public ActionResult Create(Skill skill)
{
skill.Id = Guid.NewGuid();
var command = new EditSkillCommand(skill, createNew: true);
this.editSkillCommandHandler.Handle(command);
var redirectUri = UrlProvider<SkillsController>.GetRouteValues(c => c.Index());
return RedirectToRoute(redirectUri);
}
}
} | apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.