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 |
|---|---|---|---|---|---|---|---|---|
96ac13f3ea49e5c2286d44212e1290ed146b833a | fix coordinate mappa test/demo | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Classi/Condivise/Coordinate.cs | src/backend/SO115App.Models/Classi/Condivise/Coordinate.cs | //-----------------------------------------------------------------------
// <copyright file="Coordinate.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
using System.Text.Json.Serialization;
namespace SO115App.API.Models.Classi.Condivise
{
public class Coordinate
{
public Coordinate(double Latitudine = 0.0, double Longitudine = 0.0)
{
this.Latitudine = Latitudine;
this.Longitudine = Longitudine;
}
/// <summary>
/// Latitudine
/// </summary>
[JsonConverter(typeof(string))]
public double Latitudine { get; set; }
/// <summary>
/// Latitudine
/// </summary>
[JsonConverter(typeof(string))]
public double Longitudine { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="Coordinate.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
namespace SO115App.API.Models.Classi.Condivise
{
public class Coordinate
{
public Coordinate(double Latitudine = 0.0, double Longitudine = 0.0)
{
this.Latitudine = Latitudine;
this.Longitudine = Longitudine;
}
/// <summary>
/// Latitudine
/// </summary>
[BsonRepresentation(BsonType.String)]
public double Latitudine { get; set; }
/// <summary>
/// Latitudine
/// </summary>
[BsonRepresentation(BsonType.String)]
public double Longitudine { get; set; }
}
}
| agpl-3.0 | C# |
b34b6a095eafc1d85f110abf7b0dc4d36c25a785 | rename the test method. | jwChung/Experimentalism,jwChung/Experimentalism | test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs | test/Experiment.AutoFixtureUnitTest/AssemblyLevelTest.cs | using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
[Theory]
[InlineData("TheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesNugetTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
VerifyGeneratingFile(origin, destination);
}
[Conditional("CI")]
private static void VerifyGeneratingFile(string origin, string destination)
{
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
} | using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Extensions;
namespace Jwc.Experiment
{
public class AssemblyLevelTest
{
[Fact]
public void SutReferencesOnlySpecifiedAssemblies()
{
var sut = typeof(TheoremAttribute).Assembly;
var specifiedAssemblies = new []
{
"mscorlib",
"Jwc.Experiment",
"Ploeh.AutoFixture"
};
var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray();
Assert.Equal(specifiedAssemblies.Length, actual.Length);
Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty");
}
[Theory]
[InlineData("TheoremAttribute")]
[InlineData("TestFixtureAdapter")]
public void SutGeneratesNugetTransformFiles(string originName)
{
string directory = @"..\..\..\..\src\Experiment.AutoFixture\";
var origin = directory + originName + ".cs";
var destination = directory + originName + ".cs.pp";
Assert.True(File.Exists(origin), "exists.");
VerifyGenerateFile(origin, destination);
}
[Conditional("CI")]
private static void VerifyGenerateFile(string origin, string destination)
{
var content = File.ReadAllText(origin, Encoding.UTF8)
.Replace("namespace Jwc.Experiment", "namespace $rootnamespace$");
File.WriteAllText(destination, content, Encoding.UTF8);
Assert.True(File.Exists(destination), "exists.");
}
}
} | mit | C# |
483507429b7ba2ed60c93caeb54c6c0d44f7cc60 | Update verision. Publish new package | ihtfw/Megaplan.API | src/Megaplan.API/Megaplan.API/Properties/AssemblyInfo.cs | src/Megaplan.API/Megaplan.API/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("nMegaplan.API")]
[assembly: AssemblyDescription("nMegaplan.API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ihtfw")]
[assembly: AssemblyProduct("nMegaplan.API")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("93654457-8419-48b9-bc98-0e44e310b5ec")]
// 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.3")]
[assembly: AssemblyFileVersion("1.0.0.3")]
| 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("nMegaplan.API")]
[assembly: AssemblyDescription("nMegaplan.API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ihtfw")]
[assembly: AssemblyProduct("nMegaplan.API")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("93654457-8419-48b9-bc98-0e44e310b5ec")]
// 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.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
| mit | C# |
df725e612fbd9508eae520c3716c31d66b6278a3 | Fix build | jorik041/maccore,mono/maccore,cwensley/maccore | src/Foundation/NSAction.cs | src/Foundation/NSAction.cs | //
// Copyright 2009-2010, Novell, Inc.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Runtime.InteropServices;
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public delegate void NSAction ();
// Use this for synchronous operations
[Register ("__MonoMac_NSActionDispatcher")]
internal class NSActionDispatcher : NSObject {
public static Selector Selector = new Selector ("apply");
NSAction action;
public NSActionDispatcher (NSAction action)
{
this.action = action;
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
}
}
// Use this for asynchronous operations
[Register ("__MonoMac_NSAsyncActionDispatcher")]
internal class NSAsyncActionDispatcher : NSObject {
GCHandle gch;
NSAction action;
public NSAsyncActionDispatcher (NSAction action)
{
this.action = action;
gch = GCHandle.Alloc (this);
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
gch.Free ();
}
}
}
| //
// Copyright 2009-2010, Novell, Inc.
// Copyright 2012 Xamarin Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using MonoMac.ObjCRuntime;
namespace MonoMac.Foundation {
public delegate void NSAction ();
// Use this for synchronous operations
[Register ("__MonoMac_NSActionDispatcher")]
internal class NSActionDispatcher : NSObject {
public static Selector Selector = new Selector ("apply");
NSAction action;
public NSActionDispatcher (NSAction action)
{
this.action = action;
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
}
}
// Use this for asynchronous operations
[Register ("__MonoMac_NSAsyncActionDispatcher")]
internal class NSAsyncActionDispatcher : NSObject {
GCHandle gch;
NSAction action;
public NSActionDispatcher (NSAction action)
{
this.action = action;
gch = GCHandle.Alloc (this);
}
[Export ("apply")]
[Preserve (Conditional = true)]
public void Apply ()
{
action ();
gch.Free ();
}
}
}
| apache-2.0 | C# |
213be7fde765e0595700e9f1b92212e4cec124b7 | Generalize ParserQuery extension methods on item type. | plioi/parsley | src/Parsley/ParserQuery.cs | src/Parsley/ParserQuery.cs | using System.Diagnostics.CodeAnalysis;
namespace Parsley;
public static class ParserQuery
{
/// <summary>
/// Converts any value into a parser that always succeeds with the given value.
/// </summary>
/// <remarks>
/// In monadic terms, this is the 'Unit' function.
/// </remarks>
/// <typeparam name="TItem">The type of the items in the span being traversed.</typeparam>
/// <typeparam name="TValue">The type of the value to treat as a parse result.</typeparam>
/// <param name="value">The value to treat as a parse result.</param>
public static Parser<TItem, TValue> SucceedWithThisValue<TItem, TValue>(this TValue value)
{
return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out TValue? succeedingValue, [NotNullWhen(false)] out string? expectation) =>
{
expectation = null;
succeedingValue = value!;
return true;
};
}
/// <summary>
/// Allows LINQ syntax to construct a new parser from a simpler parser, using a single 'from' clause.
/// </summary>
public static Parser<TItem, U> Select<TItem, T, U>(this Parser<TItem, T> parser, Func<T, U> constructResult)
{
return parser.Bind(t => constructResult(t).SucceedWithThisValue<TItem, U>());
}
/// <summary>
/// Allows LINQ syntax to construct a new parser from an ordered sequence of simpler parsers, using multiple 'from' clauses.
/// </summary>
public static Parser<TItem, V> SelectMany<TItem, T, U, V>(this Parser<TItem, T> parser, Func<T, Parser<TItem, U>> k, Func<T, U, V> s)
{
return parser.Bind(x => k(x).Bind(y => s(x, y).SucceedWithThisValue<TItem, V>()));
}
/// <summary>
/// Extend a parser such that, after executing, the remaining input is processed by the next parser in the chain.
/// </summary>
/// <remarks>
/// In monadic terms, this is the 'Bind' function.
/// </remarks>
static Parser<TItem, U> Bind<TItem, T, U>(this Parser<TItem, T> parse, Func<T, Parser<TItem, U>> constructNextParser)
{
return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out U? uValue, [NotNullWhen(false)] out string? expectation) =>
{
if (parse(input, ref index, out var tValue, out expectation))
return constructNextParser(tValue)(input, ref index, out uValue, out expectation);
uValue = default;
return false;
};
}
}
| using System.Diagnostics.CodeAnalysis;
namespace Parsley;
public static class ParserQuery
{
/// <summary>
/// Converts any value into a parser that always succeeds with the given value.
/// </summary>
/// <remarks>
/// In monadic terms, this is the 'Unit' function.
/// </remarks>
/// <typeparam name="TItem">The type of the items in the span being traversed.</typeparam>
/// <typeparam name="TValue">The type of the value to treat as a parse result.</typeparam>
/// <param name="value">The value to treat as a parse result.</param>
public static Parser<TItem, TValue> SucceedWithThisValue<TItem, TValue>(this TValue value)
{
return (ReadOnlySpan<TItem> input, ref int index, [NotNullWhen(true)] out TValue? succeedingValue, [NotNullWhen(false)] out string? expectation) =>
{
expectation = null;
succeedingValue = value!;
return true;
};
}
/// <summary>
/// Allows LINQ syntax to construct a new parser from a simpler parser, using a single 'from' clause.
/// </summary>
public static Parser<char, U> Select<T, U>(this Parser<char, T> parser, Func<T, U> constructResult)
{
return parser.Bind(t => constructResult(t).SucceedWithThisValue<char, U>());
}
/// <summary>
/// Allows LINQ syntax to construct a new parser from an ordered sequence of simpler parsers, using multiple 'from' clauses.
/// </summary>
public static Parser<char, V> SelectMany<T, U, V>(this Parser<char, T> parser, Func<T, Parser<char, U>> k, Func<T, U, V> s)
{
return parser.Bind(x => k(x).Bind(y => s(x, y).SucceedWithThisValue<char, V>()));
}
/// <summary>
/// Extend a parser such that, after executing, the remaining input is processed by the next parser in the chain.
/// </summary>
/// <remarks>
/// In monadic terms, this is the 'Bind' function.
/// </remarks>
static Parser<char, U> Bind<T, U>(this Parser<char, T> parse, Func<T, Parser<char, U>> constructNextParser)
{
return (ReadOnlySpan<char> input, ref int index, [NotNullWhen(true)] out U? uValue, [NotNullWhen(false)] out string? expectation) =>
{
if (parse(input, ref index, out var tValue, out expectation))
return constructNextParser(tValue)(input, ref index, out uValue, out expectation);
uValue = default;
return false;
};
}
}
| mit | C# |
3681c157c3c44d214b73bc319c759b146f3c6f53 | Fix up auth for user api tests | ankodu/nether,ankodu/nether,brentstineman/nether,vflorusso/nether,navalev/nether,stuartleeks/nether,brentstineman/nether,stuartleeks/nether,ankodu/nether,stuartleeks/nether,vflorusso/nether,vflorusso/nether,oliviak/nether,navalev/nether,stuartleeks/nether,krist00fer/nether,MicrosoftDX/nether,stuartleeks/nether,vflorusso/nether,ankodu/nether,brentstineman/nether,navalev/nether,brentstineman/nether,brentstineman/nether,navalev/nether,vflorusso/nether | tests/Nether.Web.IntegrationTests/Identity/UserApiTests.cs | tests/Nether.Web.IntegrationTests/Identity/UserApiTests.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Web.IntegrationTests.Identity
{
public class UserApiTests : WebTestBase
{
private HttpClient _client;
[Fact]
public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
{
await AsPlayerAsync();
await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.Forbidden);
}
[Fact]
public async Task As_a_player_I_get_Forbidden_response_calling_GetUser()
{
await AsPlayerAsync();
await ResponseForGetAsync("/api/identity/users/123", hasStatusCode: HttpStatusCode.Forbidden);
}
// ... should we fill out the other requests to check permissions, or not?
[Fact]
public async Task As_an_admin_I_can_list_users()
{
await AsAdminAsync();
var response = await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.OK);
dynamic responseContent = await response.Content.ReadAsAsync<dynamic>();
var users = ((IEnumerable<dynamic>)responseContent.users).ToList();
Assert.NotNull(users);
Assert.True(users.Count > 0);
dynamic user = users[0];
Assert.NotNull(user.userId);
Assert.NotNull(user.role);
Assert.NotNull(user._link);
}
private async Task AsPlayerAsync()
{
_client = await GetClientAsync(username: "testuser", setPlayerGamertag: true);
}
private async Task AsAdminAsync()
{
_client = await GetClientAsync(username: "devadmin", setPlayerGamertag: false);
}
private async Task<HttpResponseMessage> ResponseForGetAsync(string path, HttpStatusCode hasStatusCode)
{
var response = await _client.GetAsync(path);
Assert.Equal(hasStatusCode, response.StatusCode);
return response;
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
namespace Nether.Web.IntegrationTests.Identity
{
public class UserApiTests : WebTestBase
{
private HttpClient _client;
[Fact]
public async Task As_a_player_I_get_Forbidden_response_calling_GetUsers()
{
await AsPlayerAsync();
await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.Forbidden);
}
[Fact]
public async Task As_a_player_I_get_Forbidden_response_calling_GetUser()
{
await AsPlayerAsync();
await ResponseForGetAsync("/api/identity/users/123", hasStatusCode: HttpStatusCode.Forbidden);
}
// ... should we fill out the other requests to check permissions, or not?
[Fact]
public async Task As_an_admin_I_can_list_users()
{
await AsPlayerAsync();
var response = await ResponseForGetAsync("/api/identity/users", hasStatusCode: HttpStatusCode.OK);
dynamic responseContent = response.Content.ReadAsAsync<dynamic>();
var users = ((IEnumerable<dynamic>)responseContent.users).ToList();
Assert.NotNull(users);
Assert.True(users.Count > 0);
dynamic user = users[0];
Assert.NotNull(user.userId);
Assert.NotNull(user.role);
Assert.NotNull(user._link);
}
private async Task<HttpResponseMessage> ResponseForGetAsync(string path, HttpStatusCode hasStatusCode)
{
var response = await _client.GetAsync(path);
Assert.Equal(hasStatusCode, response.StatusCode);
return response;
}
private async Task AsPlayerAsync()
{
_client = await GetClientAsync(username: "testuser", setPlayerGamertag: true);
}
}
}
| mit | C# |
fb0be60029ba0fcda8b56543bde49e12e0b85b72 | Update src/Avalonia.Controls/Notifications/Notification.cs | AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex | src/Avalonia.Controls/Notifications/Notification.cs | src/Avalonia.Controls/Notifications/Notification.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// Implements the INotification interfaces.
/// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/>
/// </summary>
/// <remarks>
/// This notification content type is compatible with native notifications.
/// </remarks>
public class Notification : INotification
{
/// <summary>
/// Initializes a new instance of the <see cref="Notification"/> class.
/// </summary>
/// <param name="title">The title of the notification.</param>
/// <param name="message">The message to be displayed in the notification.</param>
/// <param name="type">The <see cref="NotificationType"/> of the notification.</param>
/// <param name="expiration">The expiry time at which the notification will close.
/// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param>
/// <param name="onClick">The Action to call when the notification is clicked.</param>
/// <param name="onClose">The Action to call when the notification is closed.</param>
public Notification(string title,
string message,
NotificationType type = NotificationType.Information,
TimeSpan? expiration = null,
Action onClick = null,
Action onClose = null)
{
Title = title;
Message = message;
Type = type;
Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5);
OnClick = onClick;
OnClose = onClose;
}
/// <inheritdoc/>
public string Title { get; private set; }
/// <inheritdoc/>
public string Message { get; private set; }
/// <inheritdoc/>
public NotificationType Type { get; private set; }
/// <inheritdoc/>
public TimeSpan Expiration { get; private set; }
/// <inheritdoc/>
public Action OnClick { get; private set; }
/// <inheritdoc/>
public Action OnClose { get; private set; }
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using System;
namespace Avalonia.Controls.Notifications
{
/// <summary>
/// Implements the INotification interfaces.
/// Can be displayed by both <see cref="INotificationManager"/> and <see cref="IManagedNotificationManager"/>
/// </summary>
/// <remarks>
/// This notification content type is compatible with native notifications.
/// </remarks>
public class Notification : INotification
{
/// <summary>
/// Instantiates an instance of <see cref="Notification"/>
/// </summary>
/// <param name="title">The title of the notification.</param>
/// <param name="message">The message to be displayed in the notification.</param>
/// <param name="type">The <see cref="NotificationType"/> of the notification.</param>
/// <param name="expiration">The expiry time at which the notification will close.
/// Use <see cref="TimeSpan.Zero"/> for notifications that will remain open.</param>
/// <param name="onClick">The Action to call when the notification is clicked.</param>
/// <param name="onClose">The Action to call when the notification is closed.</param>
public Notification(string title,
string message,
NotificationType type = NotificationType.Information,
TimeSpan? expiration = null,
Action onClick = null,
Action onClose = null)
{
Title = title;
Message = message;
Type = type;
Expiration = expiration.HasValue ? expiration.Value : TimeSpan.FromSeconds(5);
OnClick = onClick;
OnClose = onClose;
}
/// <inheritdoc/>
public string Title { get; private set; }
/// <inheritdoc/>
public string Message { get; private set; }
/// <inheritdoc/>
public NotificationType Type { get; private set; }
/// <inheritdoc/>
public TimeSpan Expiration { get; private set; }
/// <inheritdoc/>
public Action OnClick { get; private set; }
/// <inheritdoc/>
public Action OnClose { get; private set; }
}
}
| mit | C# |
fb3d7b09f0853e74d4436aba676b4b56076e1ae5 | Call UseReactiveUI in BuildAvaloniaApp. | AvaloniaUI/PerspexVS | templates/AvaloniaMvvmApplicationTemplate/Program.cs | templates/AvaloniaMvvmApplicationTemplate/Program.cs | using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug()
.UseReactiveUI();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
app.Run(window);
}
}
}
| using System;
using Avalonia;
using Avalonia.Logging.Serilog;
using $safeprojectname$.ViewModels;
using $safeprojectname$.Views;
namespace $safeprojectname$
{
class Program
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
public static void Main(string[] args) => BuildAvaloniaApp().Start(AppMain, args);
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
=> AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToDebug();
// Your application's entry point. Here you can initialize your MVVM framework, DI
// container, etc.
private static void AppMain(Application app, string[] args)
{
var window = new MainWindow
{
DataContext = new MainWindowViewModel(),
};
app.Run(window);
}
}
}
| mit | C# |
4f907da4f912627c10a2911c0e8e798d008e487e | Update the Dematt.Airy.Identity Assembly Information. | MatthewRudolph/Airy | src/Dematt.Airy.Identity/Properties/AssemblyInfo.cs | src/Dematt.Airy.Identity/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Dematt.Airy.Identity")]
[assembly: AssemblyDescription("Identity entity classes for NHibernate implementation of ASP Net Identity.")]
[assembly: AssemblyCompany("Matthew Rudolph")]
[assembly: AssemblyProduct("Dematt.Airy.Identity")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if (DEBUG)
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
// 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("f2ea6e56-bcf2-4901-831e-026f9302390d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0 Build")]
| 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("Dematt.Airy.Identity")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Dematt.Airy.Identity")]
[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("f2ea6e56-bcf2-4901-831e-026f9302390d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
6951e7bb654a26234f74325a8b962a80ac00f09c | Call the disposeEmitter action on dispose | influxdata/influxdb-csharp,michael-wolfenden/influxdb-lineprotocol,nblumhardt/influxdb-lineprotocol | src/InfluxDB.LineProtocol/CollectorConfiguration.cs | src/InfluxDB.LineProtocol/CollectorConfiguration.cs | using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeEmitter();
});
}
}
}
| using InfluxDB.LineProtocol.Collector;
using System;
namespace InfluxDB.LineProtocol
{
public class CollectorConfiguration
{
readonly IPointEmitter _parent;
readonly PipelinedCollectorTagConfiguration _tag;
readonly PipelinedCollectorEmitConfiguration _emitter;
readonly PipelinedCollectorBatchConfiguration _batcher;
public CollectorConfiguration()
: this(null)
{
}
internal CollectorConfiguration(IPointEmitter parent = null)
{
_parent = parent;
_tag = new PipelinedCollectorTagConfiguration(this);
_emitter = new PipelinedCollectorEmitConfiguration(this);
_batcher = new PipelinedCollectorBatchConfiguration(this);
}
public CollectorTagConfiguration Tag
{
get { return _tag; }
}
public CollectorEmitConfiguration WriteTo
{
get { return _emitter; }
}
public CollectorBatchConfiguration Batch
{
get { return _batcher; }
}
public MetricsCollector CreateCollector()
{
Action disposeEmitter;
Action disposeBatcher;
var emitter = _parent;
emitter = _emitter.CreateEmitter(emitter, out disposeEmitter);
emitter = _batcher.CreateEmitter(emitter, out disposeBatcher);
return new PipelinedMetricsCollector(emitter, _tag.CreateEnricher(), () =>
{
if (disposeBatcher != null)
disposeBatcher();
if (disposeEmitter != null)
disposeBatcher();
});
}
}
}
| apache-2.0 | C# |
adbf5c07cc8318b7c8722a622a1f3c7947d2dc78 | Make scripts razor section lowercase | amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre,amoerie/teamcity-theatre | src/TeamCityTheatre.Web/Views/Shared/_Layout.cshtml | src/TeamCityTheatre.Web/Views/Shared/_Layout.cshtml | @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>TeamCity Theatre</title>
<base href="@Url.Content("~")"/>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css"/>
<link rel="stylesheet" href="~/css/site.css"/>
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"/>
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/>
</environment>
@Html.Raw(JavaScriptSnippet.FullScript)
</head>
<body>
<div id="mainnav" data-ng-include="'app/mainnav/mainnav.html'"></div>
<div id="body" class="container-fluid">
@RenderBody()
</div>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
@RenderSection("scripts", required: false)
</body>
</html> | @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>TeamCity Theatre</title>
<base href="@Url.Content("~")"/>
<environment names="Development">
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.css"/>
<link rel="stylesheet" href="~/css/site.css"/>
</environment>
<environment names="Staging,Production">
<link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/dist/css/bootstrap.min.css"
asp-fallback-test-class="sr-only" asp-fallback-test-property="position" asp-fallback-test-value="absolute"/>
<link rel="stylesheet" href="~/css/site.min.css" asp-append-version="true"/>
</environment>
@Html.Raw(JavaScriptSnippet.FullScript)
</head>
<body>
<div id="mainnav" data-ng-include="'app/mainnav/mainnav.html'"></div>
<div id="body" class="container-fluid">
@RenderBody()
</div>
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous"
integrity="sha384-K+ctZQ+LL8q6tP7I94W+qzQsfRV2a+AfHIi9k8z8l9ggpc8X+Ytst4yBo/hH+8Fk">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
@RenderSection("Scripts", required: false)
</body>
</html> | mit | C# |
21b916f43617ec2c711428c06ca0c285e5ba50cc | Add test for x-github-request-id | github/VisualStudio,github/VisualStudio,github/VisualStudio | test/GitHub.Exports.UnitTests/ApiExceptionExtensionsTests.cs | test/GitHub.Exports.UnitTests/ApiExceptionExtensionsTests.cs | using System.Collections.Generic;
using System.Collections.Immutable;
using Octokit;
using NSubstitute;
using NUnit.Framework;
using GitHub.Extensions;
public class ApiExceptionExtensionsTests
{
public class TheIsGitHubApiExceptionMethod
{
[TestCase("Not-GitHub-Request-Id", false)]
[TestCase("X-GitHub-Request-Id", true)]
[TestCase("x-github-request-id", true)]
public void NoGitHubRequestId(string key, bool expect)
{
var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } });
var result = ApiExceptionExtensions.IsGitHubApiException(ex);
Assert.That(result, Is.EqualTo(expect));
}
static ApiException CreateApiException(Dictionary<string, string> headers)
{
var response = Substitute.For<IResponse>();
response.Headers.Returns(headers.ToImmutableDictionary());
var ex = new ApiException(response);
return ex;
}
}
}
| using System.Collections.Generic;
using System.Collections.Immutable;
using Octokit;
using NSubstitute;
using NUnit.Framework;
using GitHub.Extensions;
public class ApiExceptionExtensionsTests
{
public class TheIsGitHubApiExceptionMethod
{
[TestCase("Not-GitHub-Request-Id", false)]
[TestCase("X-GitHub-Request-Id", true)]
public void NoGitHubRequestId(string key, bool expect)
{
var ex = CreateApiException(new Dictionary<string, string> { { key, "ANYTHING" } });
var result = ApiExceptionExtensions.IsGitHubApiException(ex);
Assert.That(result, Is.EqualTo(expect));
}
static ApiException CreateApiException(Dictionary<string, string> headers)
{
var response = Substitute.For<IResponse>();
response.Headers.Returns(headers.ToImmutableDictionary());
var ex = new ApiException(response);
return ex;
}
}
}
| mit | C# |
7c58e5780df98cea98ea625b075afe4a7ad946c2 | Rename Byte to ByteField | laicasaane/VFW | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Bytes.cs | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Bytes.cs | using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public byte ByteField(byte value)
{
return ByteField(string.Empty, value);
}
public byte ByteField(string label, byte value)
{
return ByteField(label, value, null);
}
public byte ByteField(string label, string tooltip, byte value)
{
return ByteField(label, tooltip, value, null);
}
public byte ByteField(string label, byte value, Layout option)
{
return ByteField(label, string.Empty, value, option);
}
public byte ByteField(string label, string tooltip, byte value, Layout option)
{
return ByteField(GetContent(label, tooltip), value, option);
}
public abstract byte ByteField(GUIContent content, byte value, Layout option);
}
}
| using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public byte Byte(byte value)
{
return Byte(string.Empty, value);
}
public byte Byte(string label, byte value)
{
return Byte(label, value, null);
}
public byte Byte(string label, string tooltip, byte value)
{
return Byte(label, tooltip, value, null);
}
public byte Byte(string label, byte value, Layout option)
{
return Byte(label, string.Empty, value, option);
}
public byte Byte(string label, string tooltip, byte value, Layout option)
{
return Byte(GetContent(label, tooltip), value, option);
}
public abstract byte Byte(GUIContent content, byte value, Layout option);
}
}
| mit | C# |
07b95838e948a573ae63efd486e84fd049c54d13 | 添加MD5时间性能 | zbw911/Dev.All,zbw911/Dev.All,zbw911/Dev.All,zbw911/Dev.All | DevLibs/Framework/Comm/Dev.Comm.Test/Core/FileUtilTest.cs | DevLibs/Framework/Comm/Dev.Comm.Test/Core/FileUtilTest.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dev.Comm.Test.Core
{
[TestClass]
public class FileUtilTest
{
[TestMethod]
public void TestMethod1()
{
}
[TestMethod]
public void Md5File()
{
var filepath = @"E:\AutoDesk\Revit\Autodesk Revit2014完美完整包(族库、样板、注册机、序列号密、匙、安装视频及说明).zip";
var key1 = FileUtil.MD5File(filepath);
var key2 = FileUtil.MD5Stream(filepath);
Console.WriteLine(key1);
Assert.AreEqual(key1, key2);
}
[TestMethod]
public void Md5File2()
{
var filepath = @"C:\Users\Administrator\Desktop\changelog.txt";
var filepath2 = @"C:\Users\Administrator\Desktop\changelog.txt";
var key1 = FileUtil.MD5File(filepath);
var key2 = FileUtil.MD5Stream(filepath2);
Console.WriteLine(key1);
Assert.AreEqual(key1, key2);
}
[TestMethod]
public void MyTestMethod()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
var filepath = @"E:\AutoDesk\Revit\Autodesk Revit2014完美完整包(族库、样板、注册机、序列号密、匙、安装视频及说明).zip";
var key1 = FileUtil.MD5File(filepath);
//var key2 = FileUtil.MD5Stream(filepath);
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
[TestMethod]
public void MyTestMethod2()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();
var filepath = @"E:\AutoDesk\Revit\Autodesk Revit2014完美完整包(族库、样板、注册机、序列号密、匙、安装视频及说明).zip";
//var key1 = FileUtil.MD5File(filepath);
var key2 = FileUtil.MD5Stream(filepath);
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Dev.Comm.Test.Core
{
[TestClass]
public class FileUtilTest
{
[TestMethod]
public void TestMethod1()
{
}
[TestMethod]
public void Md5File()
{
var filepath = @"E:\AutoDesk\Revit\Autodesk Revit2014完美完整包(族库、样板、注册机、序列号密、匙、安装视频及说明).zip";
var key1 = FileUtil.MD5File(filepath);
var key2 = FileUtil.MD5Stream(filepath);
Console.WriteLine(key1);
Assert.AreEqual(key1, key2);
}
[TestMethod]
public void Md5File2()
{
var filepath = @"C:\Users\Administrator\Desktop\changelog.txt";
var filepath2 = @"C:\Users\Administrator\Desktop\changelog1.txt";
var key1 = FileUtil.MD5File(filepath);
var key2 = FileUtil.MD5Stream(filepath2);
Console.WriteLine(key1);
Assert.AreEqual(key1, key2);
}
}
}
| apache-2.0 | C# |
ce9c489ae2e14933d26527b8e07642bebde84593 | Fix ApplicationEventHandler order | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.Owin/Hosting/OwinHostingServiceFactory.cs | InfinniPlatform.Owin/Hosting/OwinHostingServiceFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using InfinniPlatform.Core.Factories;
using InfinniPlatform.Core.Hosting;
using InfinniPlatform.Owin.Modules;
using InfinniPlatform.Sdk.Hosting;
namespace InfinniPlatform.Owin.Hosting
{
/// <summary>
/// Фабрика для создания сервиса хостинга приложения на базе OWIN.
/// </summary>
public sealed class OwinHostingServiceFactory : IHostingServiceFactory
{
public OwinHostingServiceFactory(IOwinHostingContext hostingContext)
{
// Создание сервиса хостинга приложения на базе OWIN
var hostingService = new OwinHostingService(hostingContext);
// Получение списка обработчиков событий приложения
var appEventHandlers = hostingContext.ContainerResolver.Resolve<IEnumerable<IApplicationEventHandler>>();
if (appEventHandlers != null)
{
hostingService.OnBeforeStart += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnBeforeStart());
hostingService.OnAfterStart += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnAfterStart());
hostingService.OnBeforeStop += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnBeforeStop());
hostingService.OnAfterStop += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnAfterStop());
}
_hostingService = hostingService;
}
private readonly OwinHostingService _hostingService;
/// <summary>
/// Создать сервис хостинга.
/// </summary>
public IHostingService CreateHostingService()
{
return _hostingService;
}
private static void InvokeAppHandlers(IEnumerable<IApplicationEventHandler> handlers, Action<IApplicationEventHandler> handle)
{
foreach (var handler in handlers.OrderBy(i => i.Order))
{
handle(handler);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using InfinniPlatform.Core.Factories;
using InfinniPlatform.Core.Hosting;
using InfinniPlatform.Owin.Modules;
using InfinniPlatform.Sdk.Hosting;
namespace InfinniPlatform.Owin.Hosting
{
/// <summary>
/// Фабрика для создания сервиса хостинга приложения на базе OWIN.
/// </summary>
public sealed class OwinHostingServiceFactory : IHostingServiceFactory
{
public OwinHostingServiceFactory(IOwinHostingContext hostingContext)
{
// Создание сервиса хостинга приложения на базе OWIN
var hostingService = new OwinHostingService(hostingContext);
// Получение списка обработчиков событий приложения
var appEventHandlers = hostingContext.ContainerResolver.Resolve<IEnumerable<IApplicationEventHandler>>();
if (appEventHandlers != null)
{
hostingService.OnBeforeStart += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnBeforeStart());
hostingService.OnAfterStart += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnAfterStart());
hostingService.OnBeforeStop += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnBeforeStop());
hostingService.OnAfterStop += (s, e) => InvokeAppHandlers(appEventHandlers, h => h.OnAfterStop());
}
_hostingService = hostingService;
}
private readonly OwinHostingService _hostingService;
/// <summary>
/// Создать сервис хостинга.
/// </summary>
public IHostingService CreateHostingService()
{
return _hostingService;
}
private static void InvokeAppHandlers(IEnumerable<IApplicationEventHandler> handlers, Action<IApplicationEventHandler> handle)
{
foreach (var handler in handlers.OrderByDescending(i => i.Order))
{
handle(handler);
}
}
}
} | agpl-3.0 | C# |
1f57f5a7f4a5f6b8550b3deb5f19d4af258587dc | Remove ability to upload assembly & xml for now, will require a large development effort to realize and is not without issues. | LBiNetherlands/LBi.LostDoc,LBiNetherlands/LBi.LostDoc | LBi.LostDoc.Repository.Web.Host/Areas/Administration/Views/Repository/Index.cshtml | LBi.LostDoc.Repository.Web.Host/Areas/Administration/Views/Repository/Index.cshtml | @*
* Copyright 2013 LBi Netherlands B.V.
*
* 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 LBi.LostDoc.Repository.Web.Areas.Administration.Models
@model LBi.LostDoc.Repository.Web.Host.Areas.Administration.Models.ContentRepositoryModel
<h1>Content repository</h1>
<h2>Available files</h2>
@Html.Partial("_ContentRepository")
@if (Model.Assemblies.Length == 0)
{
<p>There are no LostDoc files in the repository, you can upload some:</p>
}
<h2>Upload LostDoc file</h2>
<form action="@Url.Action("Upload")" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required="required" />
<input type="submit" name="upload" value="Upload" />
</form>
| @*
* Copyright 2013 LBi Netherlands B.V.
*
* 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 LBi.LostDoc.Repository.Web.Areas.Administration.Models
@model LBi.LostDoc.Repository.Web.Host.Areas.Administration.Models.ContentRepositoryModel
<h1>Content repository</h1>
<h2>Available files</h2>
@Html.Partial("_ContentRepository")
@if (Model.Assemblies.Length == 0)
{
<p>There are no LostDoc files in the repository, you can upload some:</p>
}
<h2>Upload LostDoc file</h2>
<form action="@Url.Action("Upload")" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required="required" />
<input type="submit" name="upload" value="Upload" />
</form>
<h2>Upload Assembly & Xml documentation file</h2>
<form action="@Url.Action("Upload")" method="POST" enctype="multipart/form-data">
<h3>
<label for="assembly">Assembly (dll or exe)</label></h3>
<input type="file" name="assembly" required="required" />
<h3>
<label for="xmldocumentation">Xml documentation file (optional)</label></h3>
<input type="file" name="xmldocumentation" />
<div>
<input type="submit" name="upload" value="Upload" />
</div>
</form>
| apache-2.0 | C# |
c6a0a0e910a6fdfbb6b7cc7a9c2e3c5aad36afb6 | Update ManagingDocumentProperties.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Files/Utility/ManagingDocumentProperties.cs | Examples/CSharp/Files/Utility/ManagingDocumentProperties.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Files.Utility
{
public class ManagingDocumentProperties
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a Workbook object
//Open an Excel file
Workbook workbook = new Workbook(dataDir + "Book1.xls");
//Retrieve a list of all custom document properties of the Excel file
Aspose.Cells.Properties.DocumentPropertyCollection customProperties = workbook.Worksheets.CustomDocumentProperties;
//Accessing a custom document property by using the property index
Aspose.Cells.Properties.DocumentProperty customProperty1 = customProperties[3];
//Accessing a custom document property by using the property name
Aspose.Cells.Properties.DocumentProperty customProperty2 = customProperties["Owner"];
System.Console.WriteLine(customProperty1.Name + " -> " + customProperty1.Value);
System.Console.WriteLine(customProperty2.Name + " -> " + customProperty2.Value);
//Retrieve a list of all custom document properties of the Excel file
Aspose.Cells.Properties.CustomDocumentPropertyCollection customPropertiesCollection = workbook.Worksheets.CustomDocumentProperties;
//Adding a custom document property to the Excel file
Aspose.Cells.Properties.DocumentProperty publisher = customPropertiesCollection.Add("Publisher", "Aspose");
//Add link to content.
customPropertiesCollection.AddLinkToContent("Owner", "MyRange");
//Accessing the custom document property by using the property name
Aspose.Cells.Properties.DocumentProperty customProperty3 = customPropertiesCollection["Owner"];
//Check whether the property is lined to content
bool islinkedtocontent = customProperty3.IsLinkedToContent;
//Get the source for the property
string source = customProperty3.Source;
//Save the file with added properties
workbook.Save(dataDir + "Test_Workbook.out.xls");
//Removing a custom document property
customProperties.Remove("Publisher");
//Save the file with added properties
workbook.Save(dataDir + "Test_Workbook_RemovedProperty.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Files.Utility
{
public class ManagingDocumentProperties
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Instantiate a Workbook object
//Open an Excel file
Workbook workbook = new Workbook(dataDir + "Book1.xls");
//Retrieve a list of all custom document properties of the Excel file
Aspose.Cells.Properties.DocumentPropertyCollection customProperties = workbook.Worksheets.CustomDocumentProperties;
//Accessing a custom document property by using the property index
Aspose.Cells.Properties.DocumentProperty customProperty1 = customProperties[3];
//Accessing a custom document property by using the property name
Aspose.Cells.Properties.DocumentProperty customProperty2 = customProperties["Owner"];
System.Console.WriteLine(customProperty1.Name + " -> " + customProperty1.Value);
System.Console.WriteLine(customProperty2.Name + " -> " + customProperty2.Value);
//Retrieve a list of all custom document properties of the Excel file
Aspose.Cells.Properties.CustomDocumentPropertyCollection customPropertiesCollection = workbook.Worksheets.CustomDocumentProperties;
//Adding a custom document property to the Excel file
Aspose.Cells.Properties.DocumentProperty publisher = customPropertiesCollection.Add("Publisher", "Aspose");
//Add link to content.
customPropertiesCollection.AddLinkToContent("Owner", "MyRange");
//Accessing the custom document property by using the property name
Aspose.Cells.Properties.DocumentProperty customProperty3 = customPropertiesCollection["Owner"];
//Check whether the property is lined to content
bool islinkedtocontent = customProperty3.IsLinkedToContent;
//Get the source for the property
string source = customProperty3.Source;
//Save the file with added properties
workbook.Save(dataDir + "Test_Workbook.out.xls");
//Removing a custom document property
customProperties.Remove("Publisher");
//Save the file with added properties
workbook.Save(dataDir + "Test_Workbook_RemovedProperty.out.xls");
}
}
} | mit | C# |
4f2a13c40a8d55fa003d8da8df247499f43f2df9 | Add the ~/ to the css relative paths, because VS likes that. | bigfont/sweet-water-revolver | mvcWebApp/Views/Home/Index.cshtml | mvcWebApp/Views/Home/Index.cshtml | @{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sweet Water Revolver</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="~/assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="~/assets/site/css/bigfont.css" rel="stylesheet" media="screen" />
<link href="~/assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" media="screen" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-46462947-1', 'sweetwaterrevolver.com');
ga('send', 'pageview');
</script>
</head>
<body>
<a id="top" style="position:absolute; top:-100px;"></a>
<article>
@Html.Partial("_Header")
@*@Html.Partial("_Jumbotron")*@
@Html.Partial("_Carousel")
@Html.Partial("_ExternalLinks")
@Html.Partial("_Images")
@Html.Partial("_Footer")
</article>
<img id="under-construction" src="~/Images/utility-under-construction-v1.png" style="position:absolute;top:0;right:0;z-index:10000;width:400px;" />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="~/assets/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
});
</script>
</body>
</html>
| @{
Layout = null;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sweet Water Revolver</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="assets/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="assets/site/css/bigfont.css" rel="stylesheet" media="screen" />
<link href="~/assets/font-awesome/css/font-awesome.min.css" rel="stylesheet" media="screen" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-46462947-1', 'sweetwaterrevolver.com');
ga('send', 'pageview');
</script>
</head>
<body>
<a id="top" style="position:absolute; top:-100px;"></a>
<article>
@Html.Partial("_Header")
@*@Html.Partial("_Jumbotron")*@
@Html.Partial("_Carousel")
@Html.Partial("_ExternalLinks")
@Html.Partial("_Images")
@Html.Partial("_Footer")
</article>
<img id="under-construction" src="~/Images/utility-under-construction-v1.png" style="position:absolute;top:0;right:0;z-index:10000;width:400px;" />
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="assets/bootstrap/dist/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
});
</script>
</body>
</html>
| mit | C# |
5e0842f6a76dfb72f427e24db5042470dd3ce04c | Fix broken unit test | jquintus/TrelloWorld,jquintus/TrelloWorld | TrelloWorld/TrelloWorld.Server/Services/SettingsLoader.cs | TrelloWorld/TrelloWorld.Server/Services/SettingsLoader.cs | namespace TrelloWorld.Server.Services
{
using System.Web;
using System.Web.Configuration;
using TrelloWorld.Server.Config;
public class SettingsLoader : ISettingsLoader<Settings>
{
public Settings Load()
{
string root = HttpContext.Current == null
? string.Empty
: HttpContext.Current.Server.MapPath("~/MarkdownViews");
return new Settings()
{
Key = WebConfigurationManager.AppSettings["Trello.Key"],
Token = WebConfigurationManager.AppSettings["Trello.Token"],
MarkdownRootPath = root,
};
}
}
} | namespace TrelloWorld.Server.Services
{
using System.Web;
using System.Web.Configuration;
using TrelloWorld.Server.Config;
public class SettingsLoader : ISettingsLoader<Settings>
{
public Settings Load()
{
return new Settings()
{
Key = WebConfigurationManager.AppSettings["Trello.Key"],
Token = WebConfigurationManager.AppSettings["Trello.Token"],
MarkdownRootPath = HttpContext.Current.Server.MapPath("~/MarkdownViews"),
};
}
}
} | mit | C# |
0f60acedf1981a26a8331158a379e8540fb3c1c8 | Fix version | pauljz/pvc-azureblob | src/Properties/AssemblyInfo.cs | src/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("Pvc.AzureBlob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Paul Zumbrun")]
[assembly: AssemblyProduct("Pvc.AzureBlob")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("Paul Zumbrun")]
[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("f88715ee-4c54-454f-b0a6-c8909e2ef353")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.0.1.0")]
[assembly: AssemblyFileVersion("0.0.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("Pvc.AzureBlob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Paul Zumbrun")]
[assembly: AssemblyProduct("Pvc.AzureBlob")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("Paul Zumbrun")]
[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("f88715ee-4c54-454f-b0a6-c8909e2ef353")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
ed24e61de38aaaacbd947f66a47c344ac4347aa5 | Make constructor argument optional for PaymentClient. | jjeffery/SecurePay | src/SecurePay/PaymentClient.cs | src/SecurePay/PaymentClient.cs | using System;
using System.Threading.Tasks;
using SecurePay.Messages;
using SecurePay.Model;
using SecurePay.Runtime;
namespace SecurePay
{
public class PaymentClient : WebServiceClient, ISecurePayPayment
{
public PaymentClient(ClientConfig config = null) : base(config, "xml-4.2")
{
}
public async Task<StandardPaymentResponse> StandardPaymentAsync(StandardPaymentRequest request)
{
var requestMessage = new PaymentRequestMessage();
var transaction = requestMessage.Payment.PaymentList.Transaction;
transaction.TransactionType = PaymentTransactionType.StandardPayment;
transaction.TransactionSource = PaymentTransactionSource.Xml;
transaction.PurchaseOrderNumber = request.PurchaseOrder;
transaction.Amount = request.Amount;
transaction.Currency = request.Currency;
transaction.CreditCardInfo = new CreditCardInfo {
CardNumber = request.CreditCard.CardNumber,
Cvv = request.CreditCard.Cvv,
ExpiryDate = request.CreditCard.Expires.ToSecurePayString(),
};
var responseMessage = await PostAsync<PaymentRequestMessage, PaymentResponseMessage>(requestMessage);
transaction = responseMessage.Payment.PaymentList.Transaction;
var response = new StandardPaymentResponse {
Approved = transaction.Approved == "Yes",
PurchaseOrder = transaction.PurchaseOrderNumber,
ResponseCode = transaction.ResponseCode,
ResponseText = transaction.ReponseText,
Amount = transaction.Amount,
Currency = transaction.Currency,
TransactionId = transaction.TransactionId,
SettlementDate = DateUtils.ParseYyyymmdd(transaction.SettlementDate),
};
if (transaction.CreditCardInfo != null)
{
response.CreditCard = new CreditCardResponse {
Expires = new YearMonth(transaction.CreditCardInfo.ExpiryDate),
TruncatedCardNumber = transaction.CreditCardInfo.TruncatedCreditCardNumber,
CardDescription = transaction.CreditCardInfo.CardDescription,
};
}
return response;
}
protected override Uri GetServiceUrl()
{
var baseUrl = new Uri(Config.Url);
return new Uri(baseUrl, "/xmlapi/payment");
}
}
}
| using System;
using System.Threading.Tasks;
using SecurePay.Messages;
using SecurePay.Model;
using SecurePay.Runtime;
namespace SecurePay
{
public class PaymentClient : WebServiceClient, ISecurePayPayment
{
public PaymentClient(ClientConfig config) : base(config, "xml-4.2")
{
}
public async Task<StandardPaymentResponse> StandardPaymentAsync(StandardPaymentRequest request)
{
var requestMessage = new PaymentRequestMessage();
var transaction = requestMessage.Payment.PaymentList.Transaction;
transaction.TransactionType = PaymentTransactionType.StandardPayment;
transaction.TransactionSource = PaymentTransactionSource.Xml;
transaction.PurchaseOrderNumber = request.PurchaseOrder;
transaction.Amount = request.Amount;
transaction.Currency = request.Currency;
transaction.CreditCardInfo = new CreditCardInfo {
CardNumber = request.CreditCard.CardNumber,
Cvv = request.CreditCard.Cvv,
ExpiryDate = request.CreditCard.Expires.ToSecurePayString(),
};
var responseMessage = await PostAsync<PaymentRequestMessage, PaymentResponseMessage>(requestMessage);
transaction = responseMessage.Payment.PaymentList.Transaction;
var response = new StandardPaymentResponse {
Approved = transaction.Approved == "Yes",
PurchaseOrder = transaction.PurchaseOrderNumber,
ResponseCode = transaction.ResponseCode,
ResponseText = transaction.ReponseText,
Amount = transaction.Amount,
Currency = transaction.Currency,
TransactionId = transaction.TransactionId,
SettlementDate = DateUtils.ParseYyyymmdd(transaction.SettlementDate),
};
if (transaction.CreditCardInfo != null)
{
response.CreditCard = new CreditCardResponse {
Expires = new YearMonth(transaction.CreditCardInfo.ExpiryDate),
TruncatedCardNumber = transaction.CreditCardInfo.TruncatedCreditCardNumber,
CardDescription = transaction.CreditCardInfo.CardDescription,
};
}
return response;
}
protected override Uri GetServiceUrl()
{
var baseUrl = new Uri(Config.Url);
return new Uri(baseUrl, "/xmlapi/payment");
}
}
}
| mit | C# |
97f75642d5eeb06fa637798ecc22a215ce391264 | Update some comments in data-binder to doxygen standard. | ryanwang/LeapMotionCoreAssets,Amarcolina/LeapMotionCoreAssets | Assets/LeapMotion/Widgets/Scripts/Interfaces/DataBinder.cs | Assets/LeapMotion/Widgets/Scripts/Interfaces/DataBinder.cs | using UnityEngine;
using System;
using System.Collections.Generic;
namespace LMWidgets {
// Interface to define an object that can be a data provider to a widget.
public abstract class DataBinder<WidgetType, PayloadType> : MonoBehaviour where WidgetType : IDataBoundWidget<WidgetType, PayloadType> {
[SerializeField]
private List<WidgetType> m_widgets;
private PayloadType m_lastDataValue;
// Fires when the data is updated with the most recent data as the payload
public event EventHandler<EventArg<PayloadType>> DataChangedHandler;
/// <summary>
/// Returns the current system value of the data.
/// </summary>
/// <remarks>
/// In the default implementation of the data-binder this is called every frame (in Update) so it's best to keep
/// this implementation light weight.
/// </remarks>
abstract public PayloadType GetCurrentData();
/// <summary>
/// Set the current system value of the data.
/// </summary>
abstract protected void setDataModel(PayloadType value);
// Directly set the current value of the data-model and send out the relevant updates.
public void SetCurrentData(PayloadType value) {
setDataModel (value);
updateLinkedWidgets ();
fireDataChangedEvent (GetCurrentData ());
m_lastDataValue = GetCurrentData ();
}
// Itterate through the linked widgets and update their values.
private void updateLinkedWidgets() {
foreach(WidgetType widget in m_widgets) {
widget.SetWidgetValue(GetCurrentData());
}
}
// Register all assigned widgets with the data-binder.
virtual protected void Awake() {
foreach (WidgetType widget in m_widgets) {
widget.RegisterDataBinder(this);
}
}
// Grab the inital value for GetCurrentData
virtual protected void Start() {
m_lastDataValue = GetCurrentData();
}
// Checks for change in data.
// We need this in addition to SetCurrentData as the data we're linked to
// could be modified by an external source.
void Update() {
PayloadType currentData = GetCurrentData();
if (!compare (m_lastDataValue, currentData)) {
updateLinkedWidgets ();
fireDataChangedEvent (currentData);
}
m_lastDataValue = currentData;
}
// Fire the data changed event.
// Wrapping this in a function allows child classes to call it and fire the event.
protected void fireDataChangedEvent(PayloadType currentData) {
EventHandler<EventArg<PayloadType>> handler = DataChangedHandler;
if ( handler != null ) { handler(this, new EventArg<PayloadType>(currentData)); }
}
// Handles proper comparison of generic types.
private bool compare(PayloadType x, PayloadType y)
{
return EqualityComparer<PayloadType>.Default.Equals(x, y);
}
}
public abstract class DataBinderSlider : DataBinder<SliderBase, float> {};
public abstract class DataBinderToggle : DataBinder<ButtonToggleBase, bool> {};
public abstract class DataBinderDial : DataBinder<DialGraphics, string> {};
} | using UnityEngine;
using System;
using System.Collections.Generic;
namespace LMWidgets {
// Interface to define an object that can be a data provider to a widget.
public abstract class DataBinder<WidgetType, PayloadType> : MonoBehaviour where WidgetType : IDataBoundWidget<WidgetType, PayloadType> {
[SerializeField]
private List<WidgetType> m_widgets;
private PayloadType m_lastDataValue;
// Fires when the data is updated with the most recent data as the payload
public event EventHandler<EventArg<PayloadType>> DataChangedHandler;
// Returns the current system value of the data.
// In the default implementation of the data-binder this is called every frame (in Update) so it's best to keep
// this implementation light weight.
abstract public PayloadType GetCurrentData();
// Set the current system value of the data.
abstract protected void setDataModel(PayloadType value);
// Directly set the current value of the data-model and send out the relevant updates.
public void SetCurrentData(PayloadType value) {
setDataModel (value);
updateLinkedWidgets ();
fireDataChangedEvent (GetCurrentData ());
m_lastDataValue = GetCurrentData ();
}
// Itterate through the linked widgets and update their values.
private void updateLinkedWidgets() {
foreach(WidgetType widget in m_widgets) {
widget.SetWidgetValue(GetCurrentData());
}
}
// Register all assigned widgets with the data-binder.
virtual protected void Awake() {
foreach (WidgetType widget in m_widgets) {
widget.RegisterDataBinder(this);
}
}
// Grab the inital value for GetCurrentData
virtual protected void Start() {
m_lastDataValue = GetCurrentData();
}
// Checks for change in data.
// We need this in addition to SetCurrentData as the data we're linked to
// could be modified by an external source.
void Update() {
PayloadType currentData = GetCurrentData();
if (!compare (m_lastDataValue, currentData)) {
updateLinkedWidgets ();
fireDataChangedEvent (currentData);
}
m_lastDataValue = currentData;
}
// Fire the data changed event.
// Wrapping this in a function allows child classes to call it and fire the event.
protected void fireDataChangedEvent(PayloadType currentData) {
EventHandler<EventArg<PayloadType>> handler = DataChangedHandler;
if ( handler != null ) { handler(this, new EventArg<PayloadType>(currentData)); }
}
// Handles proper comparison of generic types.
private bool compare(PayloadType x, PayloadType y)
{
return EqualityComparer<PayloadType>.Default.Equals(x, y);
}
}
public abstract class DataBinderSlider : DataBinder<SliderBase, float> {};
public abstract class DataBinderToggle : DataBinder<ButtonToggleBase, bool> {};
public abstract class DataBinderDial : DataBinder<DialGraphics, string> {};
} | apache-2.0 | C# |
f0260ec5554d24d04e2c0557241107942f5cc8cf | Update UrlReWrite.cs | xuqingkai/UrlReWrite.cs | App_Code/UrlReWrite.cs | App_Code/UrlReWrite.cs | //https://github.com/xuqingkai/UrlReWrite.cs
using System;
namespace SH
{
/// <summary>
/// 伪静态,URL重写
/// </summary>
public class UrlReWrite : System.Web.IHttpModule
{
/// <summary>
/// 伪静态配置文件路径
/// </summary>
public static string FilePath = "";
public void Init(System.Web.HttpApplication context) { context.BeginRequest += new System.EventHandler(BeginRequest); }
public void Dispose() { }
private void BeginRequest(object sender, System.EventArgs e)
{
System.Web.HttpContext context = ((System.Web.HttpApplication)sender).Context;
string filePath = FilePath;
if (filePath.Length == 0) { filePath = System.Configuration.ConfigurationManager.AppSettings["SH.UrlReWrite.FilePath"] + ""; }
if (filePath.Length == 0) { filePath = "/" + this.GetType().Name + ".txt"; }
if (!filePath.StartsWith("/")) { filePath = "/" + filePath; }
filePath = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
//用空格分开,前面是重写规则,后面是原始文件地址
if (System.IO.File.Exists(filePath))
{
string url = context.Request.RawUrl; string[] urlArr = url.Split('?');
url = System.Web.HttpUtility.UrlEncode(urlArr[0]).Replace("%2f", "/").Replace("%2F", "/") + (urlArr.Length > 1 ? "?" + urlArr[1] : "");
string strTxt = System.IO.File.ReadAllText(filePath);
foreach (string strRole in strTxt.Split('\r'))
{
if (strRole.IndexOf(" ") > 0)
{
string role = strRole.Trim(); if (role.IndexOf("//") > 0) { role = role.Substring(0, role.IndexOf("//")); }
role = role.Trim(); string path = role.Substring(0, role.Trim().IndexOf(" ")).Replace("数", "(\\d+)").Replace("字", "(.+)");
if (path.Length > 0) { path = "^" + (path.Substring(0, 1) == "/" ? "" : "/") + path; }
string file = role.Substring(role.Trim().IndexOf(" ") + 1).Trim();
if (System.Text.RegularExpressions.Regex.IsMatch(@url, @path, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
context.RewritePath(System.Text.RegularExpressions.Regex.Replace(@url, @path, file, System.Text.RegularExpressions.RegexOptions.IgnoreCase), true);
break;
}
}
}
}
}
}
}
| using System;
namespace SH
{
/// <summary>
/// 伪静态,URL重写
/// </summary>
public class UrlReWrite : System.Web.IHttpModule
{
/// <summary>
/// 伪静态配置文件路径
/// </summary>
public static string FilePath = "";
public void Init(System.Web.HttpApplication context) { context.BeginRequest += new System.EventHandler(BeginRequest); }
public void Dispose() { }
private void BeginRequest(object sender, System.EventArgs e)
{
System.Web.HttpContext context = ((System.Web.HttpApplication)sender).Context;
string filePath = FilePath;
if (filePath.Length == 0) { filePath = System.Configuration.ConfigurationManager.AppSettings["SH.UrlReWrite.FilePath"] + ""; }
if (filePath.Length == 0) { filePath = "/" + this.GetType().Name + ".txt"; }
if (!filePath.StartsWith("/")) { filePath = "/" + filePath; }
filePath = System.Web.Hosting.HostingEnvironment.MapPath(filePath);
//用空格分开,前面是重写规则,后面是原始文件地址
if (System.IO.File.Exists(filePath))
{
string url = context.Request.RawUrl; string[] urlArr = url.Split('?');
url = System.Web.HttpUtility.UrlEncode(urlArr[0]).Replace("%2f", "/").Replace("%2F", "/") + (urlArr.Length > 1 ? "?" + urlArr[1] : "");
string strTxt = System.IO.File.ReadAllText(filePath);
foreach (string strRole in strTxt.Split('\r'))
{
if (strRole.IndexOf(" ") > 0)
{
string role = strRole.Trim(); if (role.IndexOf("//") > 0) { role = role.Substring(0, role.IndexOf("//")); }
role = role.Trim(); string path = role.Substring(0, role.Trim().IndexOf(" ")).Replace("数", "(\\d+)").Replace("字", "(.+)");
if (path.Length > 0) { path = "^" + (path.Substring(0, 1) == "/" ? "" : "/") + path; }
string file = role.Substring(role.Trim().IndexOf(" ") + 1).Trim();
if (System.Text.RegularExpressions.Regex.IsMatch(@url, @path, System.Text.RegularExpressions.RegexOptions.IgnoreCase))
{
context.RewritePath(System.Text.RegularExpressions.Regex.Replace(@url, @path, file, System.Text.RegularExpressions.RegexOptions.IgnoreCase), true);
break;
}
}
}
}
}
}
} | mit | C# |
af1dfc866dad0beeaa0e97be9cb2407a30f9d037 | Add retry test for ArrayExtensionsShuffle | klmcwhirter/puzzle-service,klmcwhirter/puzzle-service | puzzles.Tests/Utils/ArrayExtensionsShuffleTests.cs | puzzles.Tests/Utils/ArrayExtensionsShuffleTests.cs | using System.Linq;
using Xunit;
using puzzles.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace puzzles.Tests
{
public partial class ArrayExtensionsTests
{
public class ArrayParameter
{
public object[] Array { get; set; }
public string Expected { get; set; }
}
static readonly ArrayParameter IntArray = new ArrayParameter
{
Array = new object[] { 1, 3, 4, 9 },
Expected = "[ \"1\", \"3\", \"4\", \"9\" ]"
};
static readonly ArrayParameter StringArray = new ArrayParameter
{
Array = new object[] { "hello", "world", "this", "array" },
Expected = "[ \"hello\", \"world\", \"this\", \"array\" ]"
};
public static IEnumerable<object> ArraysMemberDataSource()
{
yield return new object[] { IntArray };
yield return new object[] { StringArray };
}
[Theory]
[MemberData(nameof(ArraysMemberDataSource))]
public void ShuffleIntArrayShouldShuffle(object orig)
{
var param = orig as ArrayParameter;
var origArr = (object[])param.Array;
//Given
var arr = (object[])origArr.Clone();
var retryCt = 0;
var diff = false;
do
{
//When
arr.Shuffle();
//Then
for (int i = 0; i < origArr.Length; i++)
{
if (((IComparable)origArr[i]).CompareTo(((IComparable)arr[i])) != 0)
{
diff = true;
}
}
// Retry a couple of times in case the random # generator just happened to shuffle them exactly like orig
} while (!diff && (retryCt++ < 2));
var origStr = origArr.ToMessageString();
var arrStr = arr.ToMessageString();
Assert.True(diff, $"arr should have been shuffled\norigArr = {origStr}\narr = {arrStr}");
}
}
}
| using System.Linq;
using Xunit;
using puzzles.Utils;
using System;
using System.Collections.Generic;
using System.Text;
namespace puzzles.Tests
{
public partial class ArrayExtensionsTests
{
public class ArrayParameter
{
public object[] Array { get; set; }
public string Expected { get; set; }
}
static readonly ArrayParameter IntArray = new ArrayParameter
{
Array = new object[] { 1, 3, 4, 9 },
Expected = "[ \"1\", \"3\", \"4\", \"9\" ]"
};
static readonly ArrayParameter StringArray = new ArrayParameter
{
Array = new object[] { "hello", "world", "this", "array" },
Expected = "[ \"hello\", \"world\", \"this\", \"array\" ]"
};
public static IEnumerable<object> ArraysMemberDataSource()
{
yield return new object[] { IntArray };
yield return new object[] { StringArray };
}
[Theory]
[MemberData(nameof(ArraysMemberDataSource))]
public void ShuffleIntArrayShouldShuffle(object orig)
{
var param = orig as ArrayParameter;
var origArr = (object[])param.Array;
//Given
var arr = (object[])origArr.Clone();
//When
arr.Shuffle();
//Then
var diff = false;
for (int i = 0; i < origArr.Length; i++)
{
if (((IComparable)origArr[i]).CompareTo(((IComparable)arr[i])) != 0)
{
diff = true;
}
}
var origStr = origArr.ToMessageString();
var arrStr = arr.ToMessageString();
Assert.True(diff, $"arr should have been shuffled\norigArr = {origStr}\narr = {arrStr}");
}
}
}
| mit | C# |
82ebb86d5808847fefcbe1affe24201ce4270ac2 | Replace proprietary file header with BSD one | ft-/opensim-optimizations-wip-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip-extras,TomDataworks/opensim,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,BogusCurry/arribasim-dev,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip-extras,RavenB/opensim,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,M-O-S-E-S/opensim,BogusCurry/arribasim-dev,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,OpenSimian/opensimulator,TomDataworks/opensim,OpenSimian/opensimulator,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-tests,TomDataworks/opensim,ft-/arribasim-dev-tests,OpenSimian/opensimulator,ft-/arribasim-dev-extras,QuillLittlefeather/opensim-1,Michelle-Argus/ArribasimExtract,M-O-S-E-S/opensim,ft-/arribasim-dev-extras,RavenB/opensim,ft-/arribasim-dev-tests,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,OpenSimian/opensimulator,TomDataworks/opensim,OpenSimian/opensimulator,RavenB/opensim,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,RavenB/opensim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip-tests,ft-/opensim-optimizations-wip,TomDataworks/opensim,ft-/arribasim-dev-extras,ft-/opensim-optimizations-wip-tests,ft-/arribasim-dev-tests,ft-/arribasim-dev-tests,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,BogusCurry/arribasim-dev,ft-/opensim-optimizations-wip-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,QuillLittlefeather/opensim-1,M-O-S-E-S/opensim,RavenB/opensim,ft-/opensim-optimizations-wip,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,OpenSimian/opensimulator,BogusCurry/arribasim-dev,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-extras | OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs | OpenSim/Region/Framework/Interfaces/IBakedTextureModule.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
| ////////////////////////////////////////////////////////////////
//
// (c) 2009, 2010 Careminster Limited and Melanie Thielker
//
// All rights reserved
//
using System;
using Nini.Config;
using OpenSim.Framework;
using OpenMetaverse;
namespace OpenSim.Services.Interfaces
{
public interface IBakedTextureModule
{
WearableCacheItem[] Get(UUID id);
void Store(UUID id, WearableCacheItem[] data);
}
}
| bsd-3-clause | C# |
43cfa41fc99272dc2b4e28c9c4ac4b402c4d5134 | Fix copyright date | github/VisualStudio,github/VisualStudio,github/VisualStudio | src/common/SolutionInfo.cs | src/common/SolutionInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub Extension for Visual Studio")]
[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.0.0")]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2014-2016")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "1.99.0.0";
}
}
| using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("GitHub Extension for Visual Studio")]
[assembly: AssemblyVersion("1.99.0.0")]
[assembly: AssemblyFileVersion("1.99.0.0")]
[assembly: ComVisible(false)]
[assembly: AssemblyCompany("GitHub, Inc.")]
[assembly: AssemblyCopyright("Copyright GitHub, Inc. 2014-2015")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en-US")]
namespace System
{
internal static class AssemblyVersionInformation {
internal const string Version = "1.99.0.0";
}
}
| mit | C# |
8c4d169951074b1e3b6410c26dd254791c407ee6 | test project did not compile anymore | AlexBoehm/Barebone.Routing,AlexBoehm/Barebone.Routing | src/Barebone.Router.Tests/ReadmeExamples.cs | src/Barebone.Router.Tests/ReadmeExamples.cs | using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace Barebone.Routing.Tests
{
using OwinEnv = IDictionary<string, object>;
public class SimpleExample{
public Task ProcessRequest(OwinEnv env){
var router = new Router();
var route = new Route("GET", "/products/{id}-{name}.html", InfoAppFunc);
router.AddRoute(route);
var result = router.Resolve(env);
if (result.Success) {
var id = result.Parameters["id"];
var name = result.Parameters["name"];
return result.Route.OwinAction(env); //Call the AppFunc
} else {
// Do something else
throw new Exception();
}
}
public void ParametersInRoutes(){
var route = new Route("GET", "/foo/{action}", App);
var router = new Router();
router.AddRoute(route);
var result = router.Resolve(FakeRequest.Get("/foo/test"));
}
public void StoringArbitraryData(OwinEnv owinEnironment){
var route = new Route("GET", "/customers/show/{id}", App);
route.Data["CacheOptions"] = new CacheOptions(/* options */);
var router = new Router();
router.AddRoute(route);
var result = router.Resolve(FakeRequest.Get("/customers/show/{id}"));
var cacheOptions = (CacheOptions)route.Data["CacheOptions"];
// Add Caching Options to HTTP-Header
result.Route.OwinAction.Invoke(owinEnironment);
}
private Task App (OwinEnv env){
// Don't do this in real code!
return Task.Factory.StartNew(() => {
// show info page
});
}
private Task InfoAppFunc(OwinEnv env){
// Don't do this in real code!
return Task.Factory.StartNew(() => {
// show info page
});
}
private class CacheOptions{
}
}
} | using System;
using Xunit;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
namespace Barebone.Routing.Tests
{
using OwinEnv = IDictionary<string, object>;
public class SimpleExample{
public Task ProcessRequest(OwinEnv env){
var router = new Router();
var route = new Route("GET", "/products/{id}-{name}.html", InfoAppFunc);
router.AddRoute(route);
var result = router.Resolve(env);
if (result.Success) {
var id = result.Parameters["id"];
var name = result.Parameters["name"];
return result.Route.OwinAction(env); //Call the AppFunc
} else {
// Do something else
throw new Exception();
}
}
public Task ParametersInRoutes(){
var route = new Route("GET", "/foo/{action}", App);
var router = new Router();
router.AddRoute(route);
var result = router.Resolve(FakeRequest.Get("/foo/test"));
}
public Task StoringArbitraryData(OwinEnv owinEnironment){
var route = new Route("GET", "/customers/show/{id}", App);
route.Data["CacheOptions"] = new CacheOptions(/* options */);
var router = new Router();
router.AddRoute(route);
var resolved = router.Resolve(FakeRequest.Get("/customers/show/{id}"));
var cacheOptions = (CacheOptions)route.Data["CacheOptions"];
// Add Caching Options to HTTP-Header
resolved.Route.OwinAction.Invoke(owinEnironment);
}
private Task App (OwinEnv env){
// Don't do this in real code!
return Task.Factory.StartNew(() => {
// show info page
});
}
private Task InfoAppFunc(OwinEnv env){
// Don't do this in real code!
return Task.Factory.StartNew(() => {
// show info page
});
}
private class CacheOptions{
}
}
} | mit | C# |
f86d643c68983f3106442b4fd3e7d1c07355c0d9 | Update GeoffreyHuntley.cs | beraybentesen/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,stvansolano/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,beraybentesen/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin | src/Firehose.Web/Authors/GeoffreyHuntley.cs | src/Firehose.Web/Authors/GeoffreyHuntley.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string Title => "aussie who likes both promite and vegemite";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/atom.xml"); } }
public DateTime FirstAwarded => new DateTime(2017, 1, 1);
public string GravatarHash => "";
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class GeoffreyHuntley : IAmAMicrosoftMVP
{
public string FirstName => "Geoffrey";
public string LastName => "Huntley";
public string Title => "Likes both promite and vegemite.";
public string StateOrRegion => "Sydney, Australia";
public string EmailAddress => "ghuntley@ghuntley.com";
public string TwitterHandle => "geoffreyhuntley";
public Uri WebSite => new Uri("https://ghuntley.com/");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://ghuntley.com/atom.xml"); } }
public DateTime FirstAwarded => new DateTime(2017, 1, 1);
public string GravatarHash => "";
}
} | mit | C# |
3969cba446daa51f0a926f1743fcf4c5df320916 | Allow additional paths to be appended when getting root path of test. | firegiant/AzureStorageBuildTasks | FireGiant.BuildTasks.AzureStorage.Test/TestHelpers.cs | FireGiant.BuildTasks.AzureStorage.Test/TestHelpers.cs | //---------------------------------------------------------------------------
// <copyright file="TestHelpers.cs" company="FireGiant">
// Copyright (c) 2014, FireGiant.
// This software is released under BSD License.
// The license and further copyright text can be found in the file
// LICENSE.txt at the root directory of the distribution.
// </copyright>
//---------------------------------------------------------------------------
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
namespace FireGiant.BuildTasks.AzureStorage.Test
{
public static class TestHelpers
{
public static string RootPath(string additional = null)
{
return Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring(8)), additional ?? String.Empty);
}
public static void EnsureNoContainers()
{
var account = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var client = account.CreateCloudBlobClient();
var deletes = client.ListContainers().Select(c => c.DeleteAsync()).ToArray();
Task.WaitAll(deletes);
}
public static void EnsureOneContainerAsManyBlobs(string containerName, params string[] blobNames)
{
var account = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var client = account.CreateCloudBlobClient();
var deletes = client.ListContainers().Select(c => c.DeleteAsync()).ToArray();
Task.WaitAll(deletes);
var container = client.GetContainerReference(containerName);
container.Create();
var uploads = blobNames.Select(n =>
{
var blob = container.GetBlockBlobReference(n);
return blob.UploadFromByteArrayAsync(new byte[] { 1, 2, 3, 4, }, 0, 4);
}).ToArray();
Task.WaitAll(uploads);
}
}
}
| //---------------------------------------------------------------------------
// <copyright file="TestHelpers.cs" company="FireGiant">
// Copyright (c) 2014, FireGiant.
// This software is released under BSD License.
// The license and further copyright text can be found in the file
// LICENSE.txt at the root directory of the distribution.
// </copyright>
//---------------------------------------------------------------------------
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage;
namespace FireGiant.BuildTasks.AzureStorage.Test
{
public static class TestHelpers
{
public static string RootPath()
{
return Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase.Substring(8));
}
public static void EnsureNoContainers()
{
var account = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var client = account.CreateCloudBlobClient();
var deletes = client.ListContainers().Select(c => c.DeleteAsync()).ToArray();
Task.WaitAll(deletes);
}
public static void EnsureOneContainerAsManyBlobs(string containerName, params string[] blobNames)
{
var account = CloudStorageAccount.Parse("UseDevelopmentStorage=true");
var client = account.CreateCloudBlobClient();
var deletes = client.ListContainers().Select(c => c.DeleteAsync()).ToArray();
Task.WaitAll(deletes);
var container = client.GetContainerReference(containerName);
container.Create();
var uploads = blobNames.Select(n =>
{
var blob = container.GetBlockBlobReference(n);
return blob.UploadFromByteArrayAsync(new byte[] { 1, 2, 3, 4, }, 0, 4);
}).ToArray();
Task.WaitAll(uploads);
}
}
}
| bsd-3-clause | C# |
aa97ad50dad7aa6f97c88ec2950589818aec5f42 | Revert "Add new add-in repository, replacing wonky old one" | Mailaender/Pinta,PintaProject/Pinta,jakeclawson/Pinta,jakeclawson/Pinta,PintaProject/Pinta,Fenex/Pinta,Mailaender/Pinta,Fenex/Pinta,PintaProject/Pinta | Pinta/AddinSetupService.cs | Pinta/AddinSetupService.cs | //
// AddinSetupService.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2011 Novell, Inc (http://www.novell.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 Mono.Addins;
using Mono.Addins.Setup;
using Pinta.Core;
using Mono.Unix;
namespace Pinta
{
public class AddinSetupService: SetupService
{
internal AddinSetupService (AddinRegistry r): base (r)
{
}
public bool AreRepositoriesRegistered ()
{
string url = GetPlatformRepositoryUrl ();
return Repositories.ContainsRepository (url);
}
public void RegisterRepositories (bool enable)
{
RegisterRepository (GetPlatformRepositoryUrl (),
Catalog.GetString ("Pinta Platform Dependent Add-in Repository"),
enable);
RegisterRepository (GetAllRepositoryUrl (),
Catalog.GetString ("Pinta Platform Independent Add-in Repository"),
enable);
}
private void RegisterRepository(string url, string name, bool enable)
{
if (!Repositories.ContainsRepository (url)) {
var rep = Repositories.RegisterRepository (null, url, false);
rep.Name = name;
// Although repositories are enabled by default, we should always call this method to ensure
// that the repository name from the previous line ends up being saved to disk.
Repositories.SetRepositoryEnabled (url, enable);
}
}
private string GetPlatformRepositoryUrl ()
{
string platform;
if (SystemManager.GetOperatingSystem () == OS.Windows)
platform = "Windows";
else if (SystemManager.GetOperatingSystem () == OS.Mac)
platform = "Mac";
else
platform = "Linux";
//TODO: Need to change version number here
return "http://178.79.177.109:8080/Stable/" + platform + "/" + PintaCore.ApplicationVersion + "/main.mrep";
}
private string GetAllRepositoryUrl ()
{
//TODO: Need to change version number here
return "http://178.79.177.109:8080/Stable/All/" + PintaCore.ApplicationVersion + "/main.mrep";
}
}
}
| //
// AddinSetupService.cs
//
// Author:
// Lluis Sanchez Gual <lluis@novell.com>
//
// Copyright (c) 2011 Novell, Inc (http://www.novell.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 Mono.Addins;
using Mono.Addins.Setup;
using Pinta.Core;
using Mono.Unix;
namespace Pinta
{
public class AddinSetupService: SetupService
{
static string repositoryUrl = "http://pintaproject.github.io/Pinta-Community-Addins/repository/main.mrep";
internal AddinSetupService (AddinRegistry r): base (r)
{
}
public bool AreRepositoriesRegistered ()
{
return Repositories.ContainsRepository (repositoryUrl);
}
public void RegisterRepositories (bool enable)
{
RegisterRepository (repositoryUrl,
Catalog.GetString ("Pinta Community Add-ins"),
enable);
}
private void RegisterRepository(string url, string name, bool enable)
{
if (!Repositories.ContainsRepository (url)) {
var rep = Repositories.RegisterRepository (null, url, false);
rep.Name = name;
// Although repositories are enabled by default, we should always call this method to ensure
// that the repository name from the previous line ends up being saved to disk.
Repositories.SetRepositoryEnabled (url, enable);
}
}
}
}
| mit | C# |
02b2493ae91433a4f96060a04badd95a7548c1b6 | Bump version | nixxquality/WebMConverter,o11c/WebMConverter,Yuisbean/WebMConverter | Properties/AssemblyInfo.cs | 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.13.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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.12.3")]
| mit | C# |
9f3a5618e383c80f201e44fc761ef003cd9f7486 | Ajuste da versão | damasio34/seedwork | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Damasio34.Seedwork")]
[assembly: AssemblyDescription("Projeto base damasio34")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Damasio34")]
[assembly: AssemblyProduct("Damasio34.Seedwork")]
[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("745fd7cf-4d71-48ad-a6ca-a26bad9d4b1f")]
// 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.7")]
[assembly: AssemblyFileVersion("1.0.0.7")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Damasio34.Seedwork")]
[assembly: AssemblyDescription("Projeto base damasio34")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Damasio34")]
[assembly: AssemblyProduct("Damasio34.Seedwork")]
[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("745fd7cf-4d71-48ad-a6ca-a26bad9d4b1f")]
// 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.6")]
[assembly: AssemblyFileVersion("1.0.0.6")] | mit | C# |
a14c722cd176293037ede6ad141ad9259ad8667e | Fix CF | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Tor/Socks5/Models/Messages/TorSocks5Request.cs | WalletWasabi/Tor/Socks5/Models/Messages/TorSocks5Request.cs | using System;
using WalletWasabi.Helpers;
using WalletWasabi.Tor.Socks5.Models.Bases;
using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields;
using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields;
namespace WalletWasabi.Tor.Socks5.Models.Messages
{
public class TorSocks5Request : ByteArraySerializableBase
{
public TorSocks5Request(CmdField cmd, AddrField dstAddr, PortField dstPort)
{
Cmd = Guard.NotNull(nameof(cmd), cmd);
DstAddr = Guard.NotNull(nameof(dstAddr), dstAddr);
DstPort = Guard.NotNull(nameof(dstPort), dstPort);
Ver = VerField.Socks5;
Rsv = RsvField.X00;
Atyp = dstAddr.Atyp;
}
public VerField Ver { get; }
public CmdField Cmd { get; }
public RsvField Rsv { get; }
public AtypField Atyp { get; }
public AddrField DstAddr { get; }
public PortField DstPort { get; }
public override byte[] ToBytes() => ByteHelpers.Combine(
new byte[]
{
Ver.ToByte(), Cmd.ToByte(), Rsv.ToByte(), Atyp.ToByte()
}
, DstAddr.ToBytes()
, DstPort.ToBytes());
}
}
| using System;
using WalletWasabi.Helpers;
using WalletWasabi.Tor.Socks5.Models.Bases;
using WalletWasabi.Tor.Socks5.Models.Fields.ByteArrayFields;
using WalletWasabi.Tor.Socks5.Models.Fields.OctetFields;
namespace WalletWasabi.Tor.Socks5.Models.Messages
{
public class TorSocks5Request : ByteArraySerializableBase
{
public TorSocks5Request(CmdField cmd, AddrField dstAddr, PortField dstPort)
{
Cmd = Guard.NotNull(nameof(cmd), cmd);
DstAddr = Guard.NotNull(nameof(dstAddr), dstAddr);
DstPort = Guard.NotNull(nameof(dstPort), dstPort);
Ver = VerField.Socks5;
Rsv = RsvField.X00;
Atyp = dstAddr.Atyp;
}
public VerField Ver { get; }
public CmdField Cmd { get; }
public RsvField Rsv { get; }
public AtypField Atyp { get; }
public AddrField DstAddr { get; }
public PortField DstPort { get; }
public override byte[] ToBytes() => ByteHelpers.Combine(new byte[] { Ver.ToByte(), Cmd.ToByte(), Rsv.ToByte(), Atyp.ToByte() }, DstAddr.ToBytes(), DstPort.ToBytes());
}
}
| mit | C# |
9dc1bb3416262a90f33cb0f9734b411d3e6040e7 | Switch Thumbnailer to BlockingCollection | antonio-bakula/simpleDLNA,bra1nb3am3r/simpleDLNA,itamar82/simpleDLNA,nmaier/simpleDLNA | fsserver/Thumbnailer.cs | fsserver/Thumbnailer.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace NMaier.SimpleDlna.FileMediaServer
{
internal sealed class Thumbnailer
{
private struct Item
{
public readonly WeakReference Store;
public readonly WeakReference File;
public Item(WeakReference store, WeakReference file)
{
Store = store;
File = file;
}
}
private static readonly BlockingCollection<Item> queue = CreateQueue();
private static BlockingCollection<Item> CreateQueue()
{
new Thread(Run)
{
IsBackground = true,
Priority = ThreadPriority.Lowest
}.Start();
return new BlockingCollection<Item>(new ConcurrentQueue<Item>());
}
private static void Run()
{
var logger = log4net.LogManager.GetLogger(typeof(Thumbnailer));
logger.Debug("Thumber started");
try {
for (; ; ) {
var item = queue.Take();
var store = item.Store.Target as FileStore;
var file = item.File.Target as BaseFile;
if (store == null || file == null) {
continue;
}
try {
if (store.HasCover(file)) {
continue;
}
logger.DebugFormat("Trying {0}", file.Item.FullName);
file.LoadCover();
using (var k = file.Cover.Content) {
k.ReadByte();
}
}
catch (Exception) {
// Already logged and don't care.
}
}
}
finally {
logger.Debug("Thumber stopped");
}
}
public static void AddFiles(FileStore store, IEnumerable<WeakReference> items)
{
var storeRef = new WeakReference(store);
foreach (var i in items) {
queue.Add(new Item(storeRef, i));
}
}
}
}
| using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace NMaier.SimpleDlna.FileMediaServer
{
internal sealed class Thumbnailer
{
private struct Item
{
public readonly WeakReference Store;
public readonly WeakReference File;
public Item(WeakReference store, WeakReference file)
{
Store = store;
File = file;
}
}
private static readonly ConcurrentQueue<Item> queue = CreateQueue();
private static readonly AutoResetEvent signal = new AutoResetEvent(false);
private static ConcurrentQueue<Item> CreateQueue()
{
new Thread(Run)
{
IsBackground = true,
Priority = ThreadPriority.Lowest
}.Start();
return new ConcurrentQueue<Item>();
}
private static void Run()
{
var logger = log4net.LogManager.GetLogger(typeof(Thumbnailer));
logger.Debug("thumber started");
while (signal.WaitOne()) {
Item item;
while (queue.TryDequeue(out item)) {
var store = item.Store.Target as FileStore;
var file = item.File.Target as BaseFile;
if (store == null || file == null) {
continue;
}
try {
if (store.HasCover(file)) {
continue;
}
logger.DebugFormat("Trying {0}", file.Item.FullName);
file.LoadCover();
using (var k = file.Cover.Content) {
k.ReadByte();
}
}
catch (Exception) {
// Already logged and don't care.
}
}
}
}
public static void AddFiles(FileStore store, IEnumerable<WeakReference> items)
{
var storeRef = new WeakReference(store);
foreach (var i in items) {
queue.Enqueue(new Item(storeRef, i));
}
signal.Set();
}
}
}
| bsd-2-clause | C# |
30003b83604dbd052af8c1e245506609a9073687 | fix version | Fody/Freezable | CommonAssemblyInfo.cs | CommonAssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("Freezable")]
[assembly: AssemblyProduct("Freezable")]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Freezable")]
[assembly: AssemblyProduct("Freezable")]
[assembly: ComVisible(false)]
[assembly: AssemblyVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
| mit | C# |
a34a511a01588f4e1267b9bca881ba0458bbe559 | Clean up | ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth | GalleryMVC_With_Auth/Controllers/ImagesController.cs | GalleryMVC_With_Auth/Controllers/ImagesController.cs | using System.Linq;
using System.Web.Mvc;
using GalleryMVC_With_Auth.CustomFilters;
using GalleryMVC_With_Auth.Domain.Abstract;
using GalleryMVC_With_Auth.Domain.Entities;
using GalleryMVC_With_Auth.Models;
using GalleryMVC_With_Auth.Resources;
using Microsoft.AspNet.Identity;
namespace GalleryMVC_With_Auth.Controllers
{
public class ImagesController : Controller
{
private readonly IPicturesRepository _repository;
public ImagesController(IPicturesRepository repository)
{
_repository = repository;
}
public ActionResult Universal(int Id)
{
return View(_repository.Pictures.Where(p => p.AlbumId == Id).ToList());
}
[AuthLog(Roles = Defines.UserRole + "," + Defines.AdminRole)]
public ActionResult Comments(int Id)
{
return View(_repository.Comments.Where(c => c.PictureID == Id).ToList());
}
[AuthLog(Roles = Defines.UserRole + "," + Defines.AdminRole)]
[HttpPost]
public ActionResult Comments(CommentModel comm, int Id)
{
if (!ModelState.IsValid) return View(_repository.Comments.Where(c => c.PictureID == Id).ToList());
_repository.SendComment(new Comment {PictureID = Id, UserId = User.Identity.GetUserId(), Text = comm.Text});
return View(_repository.Comments.Where(c => c.PictureID == Id).ToList());
}
}
} | using System.Data.Entity.Migrations;
using System.Linq;
using System.Web.Mvc;
using GalleryMVC_With_Auth.CustomFilters;
using GalleryMVC_With_Auth.Domain.Abstract;
using GalleryMVC_With_Auth.Domain.Entities;
using GalleryMVC_With_Auth.Models;
using GalleryMVC_With_Auth.Resources;
using Microsoft.AspNet.Identity;
namespace GalleryMVC_With_Auth.Controllers
{
public class ImagesController : Controller
{
private readonly IPicturesRepository _repository;
public ImagesController(IPicturesRepository repository)
{
_repository = repository;
}
public ActionResult Universal(int Id)
{
return View(_repository.Pictures.Where(p => p.AlbumId == Id).ToList());
}
[AuthLog(Roles = Defines.UserRole+","+ Defines.AdminRole)]
public ActionResult Comments(int Id)
{
return View(_repository.Comments.Where(c=>c.PictureID == Id).ToList());
}
[AuthLog(Roles = Defines.UserRole + "," + Defines.AdminRole)]
[HttpPost]
public ActionResult Comments(CommentModel comm,int Id)
{
if (!ModelState.IsValid) return View(_repository.Comments.Where(c => c.PictureID == Id).ToList());
_repository.SendComment(new Comment { PictureID = Id, UserId = User.Identity.GetUserId(), Text = comm.Text });
return View(_repository.Comments.Where(c => c.PictureID == Id).ToList());
}
}
} | apache-2.0 | C# |
60b66b1f623b36fbe77a86102de391e297d99c89 | Remove future features from UI | MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site,MelHarbour/HeadRaceTiming-Site | HeadRaceTiming-Site/Views/Competition/Details.cshtml | HeadRaceTiming-Site/Views/Competition/Details.cshtml | @model HeadRaceTimingSite.Models.Competition
@{
ViewData["Title"] = Model.Name;
}
<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>
@section titleBar{
<div main-title>@ViewData["Title"]</div>
} | @model HeadRaceTimingSite.Models.Competition
@{
ViewData["Title"] = Model.Name;
}
<results-list competition-id="@Model.CompetitionId" first-intermediate-name="Barnes" second-intermediate-name="Hammersmith" search-value="{{searchValue}}" show-first-intermediate show-second-intermediate></results-list>
@section titleBar{
<div main-title>@ViewData["Title"]</div>
<paper-icon-button icon="search" id="searchButton"></paper-icon-button>
<paper-icon-button icon="cloud-download" id="downloadButton"></paper-icon-button>
<paper-icon-button class="searchTools" icon="arrow-back" id="backButton"></paper-icon-button>
<paper-input class="searchTools" id="searchBox" value="{{searchValue}}" no-label-float="true"></paper-input>
}
@section scripts{
<script>
window.addEventListener('WebComponentsReady', function (e) {
document.querySelector("#searchButton").addEventListener("click", function (e) {
$("#searchButton").css("display", "none");
$("#downloadButton").css("display", "none");
$("#backButton").css("display", "block");
$("#searchBox").css("display", "block");
$("#searchBox").focus();
$("[main-title]").css("display", "none");
});
document.querySelector("#backButton").addEventListener("click", function (e) {
$("#searchButton").css("display", "inline-block");
$("#downloadButton").css("display", "inline-block");
$("#backButton").css("display", "none");
$("#searchBox").css("display", "none");
$("[main-title]").css("display", "block");
});
document.querySelector("#downloadButton").addEventListener("click", function (e) {
location.href = '/Competition/DetailsAsCsv/@Model.CompetitionId'
});
});
</script>
} | mit | C# |
ad9f1591fd3d04346e65eb84791f4f2f5202d72c | Update LdapAuthenticationSource.cs | EtwasGE/InformationPortal,EtwasGE/InformationPortal | Portal.Core/Authorization/LdapAuthenticationSource.cs | Portal.Core/Authorization/LdapAuthenticationSource.cs | using System.DirectoryServices.AccountManagement;
using Abp.Zero.Ldap.Authentication;
using Abp.Zero.Ldap.Configuration;
using Portal.Core.Authorization.Users;
using Portal.Core.MultiTenancy;
namespace Portal.Core.Authorization
{
public class LdapAuthenticationSource : LdapAuthenticationSource<Tenant, User>
{
public LdapAuthenticationSource(ILdapSettings settings, IAbpZeroLdapModuleConfig ldapModuleConfig)
: base(settings, ldapModuleConfig)
{
}
protected override void UpdateUserFromPrincipal(User user, UserPrincipal userPrincipal)
{
user.UserName = userPrincipal.SamAccountName;
user.Name = userPrincipal.GivenName;
user.Surname = userPrincipal.Surname;
user.EmailAddress = userPrincipal.EmailAddress ?? userPrincipal.UserPrincipalName;
if (string.IsNullOrEmpty(userPrincipal.MiddleName))
{
var names = userPrincipal.Name.Split(' ');
if (names.Length == 3)
{
user.MiddleName = names[2];
}
}
else
{
user.MiddleName = userPrincipal.MiddleName;
}
//TODO: Not working in IIS. Always return false.
//if (userPrincipal.Enabled.HasValue)
//{
// user.IsActive = userPrincipal.Enabled.Value;
//}
}
}
}
| using System.DirectoryServices.AccountManagement;
using Abp.Zero.Ldap.Authentication;
using Abp.Zero.Ldap.Configuration;
using Portal.Core.Authorization.Users;
using Portal.Core.MultiTenancy;
namespace Portal.Core.Authorization
{
public class LdapAuthenticationSource : LdapAuthenticationSource<Tenant, User>
{
public LdapAuthenticationSource(ILdapSettings settings, IAbpZeroLdapModuleConfig ldapModuleConfig)
: base(settings, ldapModuleConfig)
{
}
protected override void UpdateUserFromPrincipal(User user, UserPrincipal userPrincipal)
{
user.UserName = userPrincipal.SamAccountName;
user.Name = userPrincipal.GivenName;
user.Surname = userPrincipal.Surname;
user.EmailAddress = userPrincipal.EmailAddress ?? userPrincipal.UserPrincipalName;
if (string.IsNullOrEmpty(userPrincipal.MiddleName))
{
var names = userPrincipal.Name.Split(' ');
if (names.Length == 3)
{
user.MiddleName = names[2];
}
}
else
{
user.MiddleName = userPrincipal.MiddleName;
}
if (userPrincipal.Enabled.HasValue)
{
user.IsActive = userPrincipal.Enabled.Value;
}
}
}
}
| mit | C# |
f34342f2fd4920f73c96723acb96c2f95eda1035 | improve example program | nerai/CMenu | src/ConsoleMenu/Program.cs | src/ConsoleMenu/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleMenu
{
/// <summary>
/// Test program for CMenu.
/// </summary>
class Program
{
static CMenu menu;
static void Main (string[] args)
{
Basics ();
InputModification ();
CaseSensitivity ();
}
static void Basics ()
{
Console.WriteLine ("Simple CMenu demonstration");
Console.WriteLine ("Enter \"help\" for help.");
// Create menu
menu = new CMenu ();
// Add simple Hello World command
menu.Add ("hello", s => Console.WriteLine ("Hello world!"));
/*
* If the command happens to be more complex, you can just put it in a separate method.
*/
menu.Add ("len", s => PrintLen (s));
/*
* It is also possible to return an exit code to signal that processing should be stopped.
* By default, the command "quit" exists for this purpose. Let's add an alternative way to stop processing input.
*/
menu.Add ("exit", s => MenuResult.Quit);
/*
* To create a command with help text, simply add it during definition.
*/
menu.Add ("time",
s => Console.WriteLine (DateTime.UtcNow),
"Help for \"time\": Writes the current time");
/*
* You can also access individual commands to edit them later, though this is rarely required.
*/
((CMenuItem) menu["time"]).HelpText += " (UTC).";
// Run menu. The menu will run until quit by the user.
menu.Run ();
Console.WriteLine ("Finished!");
}
static void PrintLen (string s)
{
Console.WriteLine ("String \"" + s + "\" has length " + s.Length);
}
static void InputModification ()
{
/*
* It is also possible to modify the input queue.
* Check out how the "repeat" command adds its argument to the input queue two times.
*/
menu.Add ("repeat",
s => Repeat (s),
"Repeats a command two times.");
// Run menu. The menu will run until quit by the user.
Console.WriteLine ("New command available: repeat");
menu.Run ();
}
static void Repeat (string s)
{
menu.Input (s, true);
menu.Input (s, true);
}
static void CaseSensitivity ()
{
/*
* Commands are case *in*sensitive by default. This can be changed using the `StringComparison` property.
*/
menu.StringComparison = StringComparison.InvariantCulture;
menu.Add ("Hello", s => Console.WriteLine ("Hi!"));
Console.WriteLine ("The menu is now case sensitive.");
menu.Run ();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleMenu
{
/// <summary>
/// Test program for CMenu.
/// </summary>
class Program
{
static CMenu menu;
static void Main (string[] args)
{
Basics ();
InputModification ();
CaseSensitivity ();
}
static void Basics ()
{
Console.WriteLine ("Simple CMenu demonstration");
Console.WriteLine ("Enter \"help\" for help.");
// Create menu
menu = new CMenu ();
// Add simple Hello World command
menu.Add ("hello", s => Console.WriteLine ("Hello world!"));
/*
* If the command happens to be more complex, you can just put it in a separate method.
*/
menu.Add ("len", s => PrintLen (s));
/*
* It is also possible to return an exit code to signal that processing should be stopped.
* By default, the command "quit" exists for this purpose. Let's add an alternative way to stop processing input.
*/
menu.Add ("exit", s => MenuResult.Quit);
/*
* To create a command with help text, simply add it during definition.
*/
menu.Add ("time",
s => Console.WriteLine (DateTime.UtcNow),
"Help for \"time\": Writes the current time");
/*
* You can also access individual commands to edit them later, though this is rarely required.
*/
((CMenuItem) menu["time"]).HelpText += " (UTC).";
// Run menu. The menu will run until quit by the user.
menu.Run ();
Console.WriteLine ("Finished!");
}
static void PrintLen (string s)
{
Console.WriteLine ("String \"" + s + "\" has length " + s.Length);
}
static void Repeat (string s)
{
menu.Input (s, true);
menu.Input (s, true);
menu.Input (s, true);
}
static void InputModification ()
{
/*
* It is also possible to modify the input queue.
* Check out how the "repeat" command adds its argument to the input queue three times.
*/
menu.Add ("repeat",
s => Repeat (s),
"Repeats a command 3 times.");
// Run menu. The menu will run until quit by the user.
Console.WriteLine ("New command available: repeat");
menu.Run ();
}
static void CaseSensitivity ()
{
/*
* Commands are case *in*sensitive by default. This can be changed using the `StringComparison` property.
*/
menu.StringComparison = StringComparison.InvariantCulture;
menu.Add ("Hello", s => Console.WriteLine ("Hi!"));
Console.WriteLine ("The menu is now case sensitive.");
menu.Run ();
}
}
}
| mit | C# |
a9bc319a2939197a904c5bf4733be856d6fc7c12 | Add scope token | danielmarbach/service-fabric-webinar,danielmarbach/service-fabric-webinar | stateful-queues/Back_Stateful/Controllers/OrdersController.cs | stateful-queues/Back_Stateful/Controllers/OrdersController.cs | using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
namespace Back_Stateful.Controllers
{
[Route("api/[controller]")]
public class OrdersController : Controller
{
public OrdersController(IReliableStateManager stateManager, IApplicationLifetime applicationLifetime)
{
this.stateManager = stateManager;
this.applicationLifetime = applicationLifetime;
}
[HttpGet]
public async Task<IEnumerable<Order>> Orders()
{
var orders = new List<Order>();
var result = await stateManager.TryGetAsync<IReliableDictionary<int, Order>>(Order.OrdersDictionaryName).ConfigureAwait(false);
if (!result.HasValue)
{
return orders;
}
var dictionary = result.Value;
using (var transaction = stateManager.CreateTransaction())
{
var enumerable = await dictionary.CreateEnumerableAsync(transaction);
var enumerator = enumerable.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync(applicationLifetime.ApplicationStopping))
{
orders.Add(enumerator.Current.Value);
}
}
return orders;
}
readonly IReliableStateManager stateManager;
readonly IApplicationLifetime applicationLifetime;
}
}
| using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.ServiceFabric.Data;
using Microsoft.ServiceFabric.Data.Collections;
namespace Back_Stateful.Controllers
{
[Route("api/[controller]")]
public class OrdersController : Controller
{
public OrdersController(IReliableStateManager stateManager)
{
this.stateManager = stateManager;
}
[HttpGet]
public async Task<IEnumerable<Order>> Orders()
{
var orders = new List<Order>();
var result = await stateManager.TryGetAsync<IReliableDictionary<int, Order>>(Order.OrdersDictionaryName).ConfigureAwait(false);
if (!result.HasValue)
{
return orders;
}
var dictionary = result.Value;
using (var transaction = stateManager.CreateTransaction())
{
var enumerable = await dictionary.CreateEnumerableAsync(transaction);
var enumerator = enumerable.GetAsyncEnumerator();
while (await enumerator.MoveNextAsync(CancellationToken.None))
{
orders.Add(enumerator.Current.Value);
}
}
return orders;
}
readonly IReliableStateManager stateManager;
}
}
| apache-2.0 | C# |
e8007d96637cf2d636fa65b2c9b86ff52a685b0c | Make flaky tests a bit less flaky | rprouse/nunit-tests,rprouse/nunit-tests,rprouse/nunit-tests | nunit-v3/FlakyTest.cs | nunit-v3/FlakyTest.cs | using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int count2 = 0;
int FlakyAdd(int x, int y)
{
if(count2++ == 2)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
| using System;
using NUnit.Framework;
namespace nunit.v3
{
[TestFixture]
public class FlakyTest
{
[Test]
[Retry(5)]
public void TestFlakyMethod()
{
int result = 0;
try
{
result = FlakyAdd(2, 2);
}
catch(Exception ex)
{
Assert.Fail($"Test failed with unexpected exception, {ex.Message}");
}
Assert.That(result, Is.EqualTo(4));
}
int FlakyAdd(int x, int y)
{
var rand = new Random();
if (rand.NextDouble() > 0.5)
throw new ArgumentOutOfRangeException();
return x + y;
}
[Test]
[Retry(2)]
public void TestFlakySubtract()
{
Assert.That(FlakySubtract(4, 2), Is.EqualTo(2));
}
int count = 0;
int FlakySubtract(int x, int y)
{
count++;
return count == 1 ? 42 : x - y;
}
}
}
| mit | C# |
1e93b3cb8213d05b52d3d7db907df8f048f20ff0 | change ioc content | mengxinjinglong/Mermaid.Loft | Mermaid.Loft.Infrastructure.Ioc/RepositoryBuilder.cs | Mermaid.Loft.Infrastructure.Ioc/RepositoryBuilder.cs | using Autofac;
using Mermaid.Loft.Infrastructure.Ioc.Categories;
using Mermaid.Loft.Infrastructure.Ioc.Products;
using Mermaid.Loft.Infrastructure.Ioc.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mermaid.Loft.Infrastructure.Ioc
{
public class RepositoryBuilder : IRepositoryBuilder
{
private static readonly RepositoryBuilder _instance = new RepositoryBuilder();
private static readonly ContainerBuilder _container = new ContainerBuilder();
private RepositoryBuilder() { }
public static RepositoryBuilder Instance {
get { return _instance; }
}
public void RegisterType<T>() where T:class
{
_container.RegisterType<T>();
}
public void Initialize()
{
_container.RegisterType<CategoryRepositoryImpl>()
.As<ICategoryRepository>();
_container.RegisterType<ProductRepositoryImpl>()
.As<IProductRepository>();
_container.RegisterType<UserRepositoryImpl>()
.As<IUserRepository>();
}
}
}
| using Autofac;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mermaid.Loft.Infrastructure.Ioc
{
public class RepositoryBuilder : IRepositoryBuilder
{
private static readonly RepositoryBuilder _instance = new RepositoryBuilder();
private static readonly ContainerBuilder _container = new ContainerBuilder();
private RepositoryBuilder() { }
public static RepositoryBuilder Instance {
get { return _instance; }
}
public void RegisterType<T>() where T:class
{
_container.RegisterType<T>();
}
}
}
| apache-2.0 | C# |
d06e7e88e668995e5cb64fa05fa92e712154b9fe | Add methods to manipulate MediaStoreItems | SnowflakePowered/snowflake,faint32/snowflake-1,RonnChyran/snowflake,RonnChyran/snowflake,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,SnowflakePowered/snowflake | Snowflake.API/Information/MediaStore/MediaStoreSection.cs | Snowflake.API/Information/MediaStore/MediaStoreSection.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
this.MediaStoreItems = this.LoadMediaStore();
}
private Dictionary<string, string> LoadMediaStore()
{
try
{
return JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return new Dictionary<string, string>();
}
}
public void Add(string key, string fileName){
File.Copy(fileName, Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Add(key, Path.GetFileName(fileName));
this.UpdateMediaStoreRecord();
}
public void Remove(string key){
File.Delete(Path.Combine(this.mediaStoreRoot, Path.GetFileName(fileName));
this.MediaStoreItems.Remove(key);
this.UpdateMediaStoreRecord();
}
private void UpdateMediaStoreRecord(){
string record = JsonConvert.SerializeObject(this.MediaStoreItems);
File.WriteAllText(Path.Combine(mediaStoreRoot, ".mediastore"));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace Snowflake.Information.MediaStore
{
public class MediaStoreSection
{
public string SectionName { get; set; }
public Dictionary<string, string> MediaStoreItems;
private string mediaStoreRoot;
public MediaStoreSection(string sectionName, MediaStore mediaStore)
{
this.mediaStoreRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Snowflake", "mediastores", mediaStore.MediaStoreKey, sectionName);
this.SectionName = sectionName;
}
private void LoadMediaStore()
{
try
{
JsonConvert.DeserializeObject<Dictionary<string, string>>(File.ReadAllText(Path.Combine(mediaStoreRoot, ".mediastore")));
}
catch
{
return;
}
}
}
}
| mpl-2.0 | C# |
c380b6e442ddd0c8615d4c1f55e012208c20527f | Update Event SQL Writer (#3756) | LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,ACEmulator/ACE,LtRipley36706/ACE | Source/ACE.Database/SQLFormatters/World/EventSQLWriter.cs | Source/ACE.Database/SQLFormatters/World/EventSQLWriter.cs | using System;
using System.Globalization;
using System.IO;
using ACE.Database.Models.World;
using ACE.Entity.Enum;
namespace ACE.Database.SQLFormatters.World
{
public class EventSQLWriter : SQLWriter
{
/// <summary>
/// Default is formed from: input.name
/// </summary>
public string GetDefaultFileName(Event input)
{
string fileName = input.Name;
fileName = IllegalInFileName.Replace(fileName, "_");
fileName += ".sql";
return fileName;
}
public void CreateSQLDELETEStatement(Event input, StreamWriter writer)
{
writer.WriteLine($"DELETE FROM `event` WHERE `name` = {GetSQLString(input.Name)};");
}
public void CreateSQLINSERTStatement(Event input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `event` (`name`, `start_Time`, `end_Time`, `state`, `last_Modified`)");
var output = "VALUES (" +
$"{GetSQLString(input.Name)}, " +
$"{(input.StartTime == -1 ? $"{input.StartTime}" : $"{input.StartTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.StartTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{(input.EndTime == -1 ? $"{input.EndTime}" : $"{input.EndTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.EndTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{input.State} /* GameEventState.{(GameEventState)input.State} */, " +
$"'{input.LastModified:yyyy-MM-dd HH:mm:ss}'" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
}
}
}
| using System;
using System.Globalization;
using System.IO;
using ACE.Database.Models.World;
namespace ACE.Database.SQLFormatters.World
{
public class EventSQLWriter : SQLWriter
{
/// <summary>
/// Default is formed from: input.name
/// </summary>
public string GetDefaultFileName(Event input)
{
string fileName = input.Name;
fileName = IllegalInFileName.Replace(fileName, "_");
fileName += ".sql";
return fileName;
}
public void CreateSQLDELETEStatement(Event input, StreamWriter writer)
{
writer.WriteLine($"DELETE FROM `event` WHERE `name` = {GetSQLString(input.Name)};");
}
public void CreateSQLINSERTStatement(Event input, StreamWriter writer)
{
writer.WriteLine("INSERT INTO `event` (`name`, `start_Time`, `end_Time`, `state`, `last_Modified`)");
var output = "VALUES (" +
$"{GetSQLString(input.Name)}, " +
$"{(input.StartTime == -1 ? $"{input.StartTime}" : $"{input.StartTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.StartTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{(input.EndTime == -1 ? $"{input.EndTime}" : $"{input.EndTime} /* {DateTimeOffset.FromUnixTimeSeconds(input.EndTime).DateTime.ToUniversalTime().ToString(CultureInfo.InvariantCulture)} */")}, " +
$"{input.State}, " +
$"'{input.LastModified:yyyy-MM-dd HH:mm:ss}'" +
");";
output = FixNullFields(output);
writer.WriteLine(output);
}
}
}
| agpl-3.0 | C# |
4c31e6b3130501133d206822fe26b4d3cb55951d | Fix NLog orchard-tenant-name returns None. (#1974) | petedavis/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2 | src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs | src/OrchardCore/OrchardCore.Logging.NLog/TenantLayoutRenderer.cs | using System.Text;
using NLog;
using NLog.LayoutRenderers;
using NLog.Web.LayoutRenderers;
using OrchardCore.Hosting.ShellBuilders;
namespace OrchardCore.Logging
{
/// <summary>
/// Print the tenant name
/// </summary>
[LayoutRenderer(LayoutRendererName)]
public class TenantLayoutRenderer : AspNetLayoutRendererBase
{
public const string LayoutRendererName = "orchard-tenant-name";
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
// If there is no ShellContext in the Features then the log is rendered from the Host
var tenantName = context.Features.Get<ShellContext>()?.Settings?.Name ?? "None";
builder.Append(tenantName);
}
}
}
| using System.Text;
using NLog;
using NLog.LayoutRenderers;
using NLog.Web.LayoutRenderers;
using OrchardCore.Environment.Shell;
namespace OrchardCore.Logging
{
/// <summary>
/// Print the tenant name
/// </summary>
[LayoutRenderer(LayoutRendererName)]
public class TenantLayoutRenderer : AspNetLayoutRendererBase
{
public const string LayoutRendererName = "orchard-tenant-name";
protected override void DoAppend(StringBuilder builder, LogEventInfo logEvent)
{
var context = HttpContextAccessor.HttpContext;
// If there is no ShellSettings in the Features then the log is rendered from the Host
var tenantName = context.Features.Get<ShellSettings>()?.Name ?? "None";
builder.Append(tenantName);
}
}
}
| bsd-3-clause | C# |
e3d09614acc68f1e1a6a0ff7d13f216a1b2b4cb6 | correct hand merge error | Olorin71/RetreatCode,Olorin71/RetreatCode | c#/TexasHoldEmEngineSolution/TexasHoldEmEngine.Interfaces/IHandComparer.cs | c#/TexasHoldEmEngineSolution/TexasHoldEmEngine.Interfaces/IHandComparer.cs | using System;
using System.Collections.Generic;
namespace TexasHoldEmEngine.Interfaces
{
public interface IHandComparer
{
// ToDo: Wäre eine Liste von IPlayer zurück besser?
IList<Guid> FindRoundWinners(IDictionary<Guid, IPlayerHoleCards> players, IList<ICard> communityCards);
}
} | using System;
using System.Collections.Generic;
namespace TexasHoldEmEngine.Interfaces
{
public interface IHandComparer
{
// ToDo: Wäre eine Liste von IPlayer zurück besser?
IList<Guid> FindRoundWinners(IDictionary<Guid, IPlayer> players, IList<ICard> communityCards);
}
} | mit | C# |
892839c948a4c4288183c3c6bc901f7ee46327b6 | Add ProfilerInterceptor.GuardInternal() for public APIs even if they are hidden. | telerik/JustMockLite | Telerik.JustMock/Core/Context/AsyncContextResolver.cs | Telerik.JustMock/Core/Context/AsyncContextResolver.cs | /*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return ProfilerInterceptor.GuardInternal(() =>
resolver.GetContext()
);
}
public static void CaptureContext()
{
ProfilerInterceptor.GuardInternal(() =>
resolver.CaptureContext()
);
}
}
}
| /*
JustMock Lite
Copyright © 2019 Progress Software 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 System.ComponentModel;
using System.Reflection;
namespace Telerik.JustMock.Core.Context
{
[EditorBrowsable(EditorBrowsableState.Never)]
public static class AsyncContextResolver
{
#if NETCORE
static IAsyncContextResolver resolver = new AsyncLocalWrapper();
#else
static IAsyncContextResolver resolver = new CallContextWrapper();
#endif
public static MethodBase GetContext()
{
return resolver.GetContext();
}
public static void CaptureContext()
{
resolver.CaptureContext();
}
}
}
| apache-2.0 | C# |
5b453f45b922169797d7d768065017e6080e0145 | Add OicResourceType Attributes | NZSmartie/OICNet | OICNet/OicResource.cs | OICNet/OicResource.cs | using System;
using System.Linq;
using System.Reflection;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
namespace OICNet
{
public enum OicResourceInterface
{
[EnumMember(Value = "oic.if.baseline")]
Baseline,
[EnumMember(Value = "oic.if.ll")]
LinkLists,
[EnumMember(Value = "oic.if.b")]
Batch,
[EnumMember(Value = "oic.if.r")]
ReadOnly,
[EnumMember(Value = "oic.if.rw")]
ReadWrite,
[EnumMember(Value = "oic.if.a")]
Actuator,
[EnumMember(Value = "oic.if.s")]
Sensor,
}
[AttributeUsage(AttributeTargets.Class)]
public class OicResourceTypeAttribute : Attribute
{
public readonly string Id;
public OicResourceTypeAttribute(string id)
{
Id = id;
}
}
public static class OicResourceExtensions
{
public static string GetResourceTypeId(this OicCoreResource resource)
{
var info = resource.GetType()
.GetTypeInfo()
.GetCustomAttributes()
.FirstOrDefault(i => i is OicResourceTypeAttribute)
as OicResourceTypeAttribute;
return info.Id;
}
}
public class OicCoreResource
{
[JsonProperty("rt"), JsonRequired()]
[MinLength(1), StringLength(64)]
public List<string> ResourceTypes { get; set; }
[JsonProperty("if", ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter)), JsonRequired()]
public List<OicResourceInterface> Interfaces { get; set; }
[JsonProperty("n", NullValueHandling=NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
}
public class OicBaseResouece<VType> : OicCoreResource
{
[JsonProperty("value", Order = 5)]
public VType Value { get; set; }
}
public class OicIntResouece : OicBaseResouece<int>
{
[JsonProperty("range", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore, Order = 6)]
public List<int> Range { get; set; }
}
public class OicNumberResouece : OicBaseResouece<float>
{
[JsonProperty("range", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore, Order = 6)]
public List<float> Range { get; set; }
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json;
namespace OICNet
{
public enum OicResourceInterface
{
[EnumMember(Value = "oic.if.baseline")]
Baseline,
[EnumMember(Value = "oic.if.ll")]
LinkLists,
[EnumMember(Value = "oic.if.b")]
Batch,
[EnumMember(Value = "oic.if.r")]
ReadOnly,
[EnumMember(Value = "oic.if.rw")]
ReadWrite,
[EnumMember(Value = "oic.if.a")]
Actuator,
[EnumMember(Value = "oic.if.s")]
Sensor,
}
public class OicCoreResource
{
[JsonProperty("rt"), JsonRequired()]
[MinLength(1), StringLength(64)]
public List<string> ResourceTypes { get; set; }
[JsonProperty("if", ItemConverterType = typeof(Newtonsoft.Json.Converters.StringEnumConverter)), JsonRequired()]
public List<OicResourceInterface> Interfaces { get; set; }
[JsonProperty("n", NullValueHandling=NullValueHandling.Ignore)]
public string Name { get; set; }
[JsonProperty("id", NullValueHandling = NullValueHandling.Ignore)]
public string Id { get; set; }
}
public class OicBaseResouece<VType> : OicCoreResource
{
[JsonProperty("value", Order = 5)]
public VType Value { get; set; }
}
public class OicIntResouece : OicBaseResouece<int>
{
[JsonProperty("range", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore, Order = 6)]
public List<int> Range { get; set; }
}
public class OicNumberResouece : OicBaseResouece<float>
{
[JsonProperty("range", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore, Order = 6)]
public List<float> Range { get; set; }
}
}
| apache-2.0 | C# |
a8006699076910f38aaa3ff7ebb4a9d860a91268 | change buttonRatio from 90% to 95% | yasokada/unity-151117-linemonitor-UI | Assets/ScreenSizeKeeper.cs | Assets/ScreenSizeKeeper.cs | using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.2 2015/11/21
* - change myStandard from [Button] to [Text]
*/
public class ScreenSizeKeeper : MonoBehaviour {
public Text myStandard; // set component whose width is used as standard
bool isRunningOnAndroid() {
return (Application.platform == RuntimePlatform.Android);
}
void Start () {
if (isRunningOnAndroid () == false) {
return;
}
float aspect = (float)Screen.height / (float)Screen.width;
float buttonRatio = 0.95f; // 95%
int buttonWidth = (int)myStandard.GetComponent<RectTransform> ().rect.width;
float newWidth, newHeight;
newWidth = buttonWidth / buttonRatio;
newHeight = newWidth * aspect;
Screen.SetResolution ((int)newWidth, (int)newHeight, false);
}
}
| using UnityEngine;
using System.Collections;
using UnityEngine.UI;
/*
* v0.2 2015/11/21
* - change myStandard from [Button] to [Text]
*/
public class ScreenSizeKeeper : MonoBehaviour {
public Text myStandard; // set component whose width is used as standard
bool isRunningOnAndroid() {
return (Application.platform == RuntimePlatform.Android);
}
void Start () {
if (isRunningOnAndroid () == false) {
return;
}
float aspect = (float)Screen.height / (float)Screen.width;
float buttonRatio = 0.9f; // 90%
int buttonWidth = (int)myStandard.GetComponent<RectTransform> ().rect.width;
float newWidth, newHeight;
newWidth = buttonWidth / buttonRatio;
newHeight = newWidth * aspect;
Screen.SetResolution ((int)newWidth, (int)newHeight, false);
}
}
| mit | C# |
9adb1d45d14fa4a74609e59e3af10d055801cb2d | Update BoardCommentParams.cs | vknet/vk,vknet/vk | VkNet/Model/RequestParams/Board/BoardCommentParams.cs | VkNet/Model/RequestParams/Board/BoardCommentParams.cs | using System;
using Newtonsoft.Json;
using VkNet.Utils;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры метода wall.addComment
/// </summary>
[Serializable]
public class BoardCommentParams
{
/// <summary>
/// Идентификатор сообщества, в котором находится обсуждение. положительное число,
/// обязательный параметр
/// </summary>
[JsonProperty(propertyName: "group_id")]
public long GroupId { get; set; }
/// <summary>
/// Идентификатор обсуждения. положительное число,
/// обязательный параметр
/// </summary>
[JsonProperty(propertyName: "topic_id")]
public long TopicId { get; set; }
/// <summary>
/// Идентификатор комментария в обсуждении, обязательный параметр.
/// </summary>
[JsonProperty(propertyName: "comment_id")]
public long CommentId { get; set; }
/// <summary>
/// Идентификатор капчи
/// </summary>
[JsonProperty(propertyName: "captcha_sid")]
[Obsolete(ObsoleteText.CaptchaNeeded)]
public long? CaptchaSid { get; set; }
/// <summary>
/// Текст, который ввел пользователь
/// </summary>
[JsonProperty(propertyName: "captcha_key")]
[Obsolete(ObsoleteText.CaptchaNeeded)]
public string CaptchaKey { get; set; }
/// <summary>
/// Привести к типу VkParameters.
/// </summary>
/// <param name="p"> Параметры. </param>
/// <returns> </returns>
public static VkParameters ToVkParameters(BoardCommentParams p)
{
var parameters = new VkParameters
{
{ "group_id", p.GroupId },
{ "topic_id", p.TopicId },
{ "comment_id", p.CommentId },
{ "captcha_sid", p.CaptchaSid },
{ "captcha_key", p.CaptchaKey }
};
return parameters;
}
}
} | using System;
using Newtonsoft.Json;
using VkNet.Utils;
namespace VkNet.Model.RequestParams
{
/// <summary>
/// Параметры метода wall.addComment
/// </summary>
[Serializable]
public class BoardCommentParams
{
/// <summary>
/// Идентификатор сообщества, в котором находится обсуждение.положительное число,
/// обязательный параметр
/// </summary>
[JsonProperty(propertyName: "group_id")]
public long GroupId { get; set; }
/// <summary>
/// Идентификатор сообщества, в котором находится обсуждение.положительное число,
/// обязательный параметр
/// </summary>
[JsonProperty(propertyName: "topic_id")]
public long TopicId { get; set; }
/// <summary>
/// Идентификатор комментария в обсуждении, обязательный параметр.
/// </summary>
[JsonProperty(propertyName: "comment_id")]
public long CommentId { get; set; }
/// <summary>
/// Идентификатор капчи
/// </summary>
[JsonProperty(propertyName: "captcha_sid")]
[Obsolete(ObsoleteText.CaptchaNeeded)]
public long? CaptchaSid { get; set; }
/// <summary>
/// Текст, который ввел пользователь
/// </summary>
[JsonProperty(propertyName: "captcha_key")]
[Obsolete(ObsoleteText.CaptchaNeeded)]
public string CaptchaKey { get; set; }
/// <summary>
/// Привести к типу VkParameters.
/// </summary>
/// <param name="p"> Параметры. </param>
/// <returns> </returns>
public static VkParameters ToVkParameters(BoardCommentParams p)
{
var parameters = new VkParameters
{
{ "group_id", p.GroupId }
, { "topic_id", p.TopicId }
, { "comment_id", p.CommentId }
, { "captcha_sid", p.CaptchaSid }
, { "captcha_key", p.CaptchaKey }
};
return parameters;
}
}
} | mit | C# |
a618456f5ffa72a07782b96d80b69ae91e73e51f | Fix error message detection | richardlawley/stripe.net,stripe/stripe-dotnet | src/Stripe.net.Tests/plans/when_deleting_a_plan.cs | src/Stripe.net.Tests/plans/when_deleting_a_plan.cs | using Machine.Specifications;
namespace Stripe.Tests
{
public class when_deleting_a_plan
{
private static StripePlanCreateOptions _stripePlanCreateOptions;
private static StripePlanService _stripePlanService;
private static string _createdStripePlanId;
Establish context = () =>
{
_stripePlanService = new StripePlanService();
_stripePlanCreateOptions = test_data.stripe_plan_create_options.Valid();
var stripePlan = _stripePlanService.Create(_stripePlanCreateOptions);
_createdStripePlanId = stripePlan.Id;
};
Because of = () =>
_stripePlanService.Delete(_createdStripePlanId);
It should_throw_exception_when_getting = () =>
{
var exception = Catch.Exception(() => _stripePlanService.Get(_createdStripePlanId));
exception.Message.ShouldContain("No such ");
};
}
} | using Machine.Specifications;
namespace Stripe.Tests
{
public class when_deleting_a_plan
{
private static StripePlanCreateOptions _stripePlanCreateOptions;
private static StripePlanService _stripePlanService;
private static string _createdStripePlanId;
Establish context = () =>
{
_stripePlanService = new StripePlanService();
_stripePlanCreateOptions = test_data.stripe_plan_create_options.Valid();
var stripePlan = _stripePlanService.Create(_stripePlanCreateOptions);
_createdStripePlanId = stripePlan.Id;
};
Because of = () =>
_stripePlanService.Delete(_createdStripePlanId);
It should_throw_exception_when_getting = () =>
{
var exception = Catch.Exception(() => _stripePlanService.Get(_createdStripePlanId));
exception.Message.ShouldContain("No such plan");
};
}
} | apache-2.0 | C# |
f3c93261059230326e53ebb148931294b3a92305 | Convert MultilineStringField to UIField | larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,mmoening/MatterControl,mmoening/MatterControl,jlewin/MatterControl,mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl | SlicerConfiguration/UIFields/MultilineStringField.cs | SlicerConfiguration/UIFields/MultilineStringField.cs | /*
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using MatterHackers.Agg.UI;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class MultilineStringField : BasicField, IUIField
{
private readonly int multiLineEditHeight = (int)(120 * GuiWidget.DeviceScale + .5);
private MHTextEditWidget editWidget;
public void Initialize(int tabIndex)
{
editWidget = new MHTextEditWidget("", pixelWidth: 320, pixelHeight: multiLineEditHeight, multiLine: true, tabIndex: tabIndex, typeFace: ApplicationController.MonoSpacedTypeFace)
{
HAnchor = HAnchor.Stretch,
};
editWidget.DrawFromHintedCache();
editWidget.ActualTextEditWidget.EditComplete += (sender, e) =>
{
if (sender is TextEditWidget textEditWidget)
{
this.SetValue(
textEditWidget.Text.Replace("\n", "\\n"),
userInitiated: true);
}
};
this.Content = editWidget;
}
protected override void OnValueChanged(FieldChangedEventArgs fieldChangedEventArgs)
{
editWidget.Text = this.Value.Replace("\\n", "\n");
base.OnValueChanged(fieldChangedEventArgs);
}
}
}
| /*
Copyright (c) 2017, Lars Brubaker, John Lewin
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using MatterHackers.Agg.UI;
namespace MatterHackers.MatterControl.SlicerConfiguration
{
public class MultilineStringField : ISettingsField
{
private readonly int multiLineEditHeight = (int)(120 * GuiWidget.DeviceScale + .5);
private MHTextEditWidget editWidget;
public Action UpdateStyle { get; set; }
public string Value { get; set; }
public GuiWidget Create(SettingsContext settingsContext, SliceSettingData settingData, int tabIndex)
{
string convertedNewLines = this.Value.Replace("\\n", "\n");
editWidget = new MHTextEditWidget(convertedNewLines, pixelWidth: 320, pixelHeight: multiLineEditHeight, multiLine: true, tabIndex: tabIndex, typeFace: ApplicationController.MonoSpacedTypeFace)
{
HAnchor = HAnchor.Stretch,
};
editWidget.DrawFromHintedCache();
editWidget.ActualTextEditWidget.EditComplete += (sender, e) =>
{
settingsContext.SetValue(settingData.SlicerConfigName, ((TextEditWidget)sender).Text.Replace("\n", "\\n"));
this.UpdateStyle();
};
return editWidget;
}
public void OnValueChanged(string text)
{
editWidget.Text = text.Replace("\\n", "\n");
}
}
}
| bsd-2-clause | C# |
db7676ebd7247e456b5640109fd2e84e906d9fa4 | Change IDE diagnostic number. | aelij/roslyn,rgani/roslyn,basoundr/roslyn,KevinRansom/roslyn,balajikris/roslyn,sharadagrawal/Roslyn,bartdesmet/roslyn,natgla/roslyn,eriawan/roslyn,basoundr/roslyn,lorcanmooney/roslyn,jeffanders/roslyn,ErikSchierboom/roslyn,michalhosala/roslyn,amcasey/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,natidea/roslyn,DustinCampbell/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,dpoeschl/roslyn,AArnott/roslyn,abock/roslyn,reaction1989/roslyn,jkotas/roslyn,brettfo/roslyn,srivatsn/roslyn,nguerrera/roslyn,aelij/roslyn,tmeschter/roslyn,CyrusNajmabadi/roslyn,AnthonyDGreen/roslyn,wvdd007/roslyn,orthoxerox/roslyn,AlekseyTs/roslyn,CaptainHayashi/roslyn,balajikris/roslyn,swaroop-sridhar/roslyn,genlu/roslyn,jamesqo/roslyn,khyperia/roslyn,yeaicc/roslyn,weltkante/roslyn,ericfe-ms/roslyn,jmarolf/roslyn,sharwell/roslyn,Hosch250/roslyn,stephentoub/roslyn,robinsedlaczek/roslyn,physhi/roslyn,bartdesmet/roslyn,brettfo/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,OmarTawfik/roslyn,jaredpar/roslyn,reaction1989/roslyn,jcouv/roslyn,agocke/roslyn,rgani/roslyn,jcouv/roslyn,MatthieuMEZIL/roslyn,stephentoub/roslyn,drognanar/roslyn,MichalStrehovsky/roslyn,natidea/roslyn,yeaicc/roslyn,paulvanbrenk/roslyn,tvand7093/roslyn,kelltrick/roslyn,xasx/roslyn,mattscheffer/roslyn,ErikSchierboom/roslyn,gafter/roslyn,davkean/roslyn,gafter/roslyn,SeriaWei/roslyn,jhendrixMSFT/roslyn,sharadagrawal/Roslyn,jaredpar/roslyn,khellang/roslyn,bartdesmet/roslyn,ericfe-ms/roslyn,bbarry/roslyn,VSadov/roslyn,basoundr/roslyn,MattWindsor91/roslyn,jasonmalinowski/roslyn,Hosch250/roslyn,mavasani/roslyn,KevinH-MS/roslyn,Pvlerick/roslyn,cston/roslyn,kelltrick/roslyn,xoofx/roslyn,khellang/roslyn,cston/roslyn,ljw1004/roslyn,DustinCampbell/roslyn,TyOverby/roslyn,vslsnap/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,drognanar/roslyn,panopticoncentral/roslyn,AArnott/roslyn,abock/roslyn,akrisiun/roslyn,tmeschter/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,jhendrixMSFT/roslyn,Giftednewt/roslyn,KirillOsenkov/roslyn,jhendrixMSFT/roslyn,ljw1004/roslyn,pdelvo/roslyn,mgoertz-msft/roslyn,agocke/roslyn,tannergooding/roslyn,Shiney/roslyn,swaroop-sridhar/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,a-ctor/roslyn,vslsnap/roslyn,gafter/roslyn,leppie/roslyn,ericfe-ms/roslyn,budcribar/roslyn,SeriaWei/roslyn,lorcanmooney/roslyn,MattWindsor91/roslyn,MatthieuMEZIL/roslyn,zooba/roslyn,cston/roslyn,balajikris/roslyn,michalhosala/roslyn,bkoelman/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,dotnet/roslyn,panopticoncentral/roslyn,a-ctor/roslyn,tmeschter/roslyn,mattscheffer/roslyn,khellang/roslyn,VSadov/roslyn,jasonmalinowski/roslyn,jeffanders/roslyn,genlu/roslyn,drognanar/roslyn,paulvanbrenk/roslyn,MichalStrehovsky/roslyn,mattwar/roslyn,zooba/roslyn,heejaechang/roslyn,khyperia/roslyn,KirillOsenkov/roslyn,Shiney/roslyn,bbarry/roslyn,dpoeschl/roslyn,bbarry/roslyn,jkotas/roslyn,khyperia/roslyn,CaptainHayashi/roslyn,robinsedlaczek/roslyn,leppie/roslyn,MichalStrehovsky/roslyn,reaction1989/roslyn,michalhosala/roslyn,orthoxerox/roslyn,robinsedlaczek/roslyn,Shiney/roslyn,orthoxerox/roslyn,Giftednewt/roslyn,dotnet/roslyn,KiloBravoLima/roslyn,pdelvo/roslyn,mattwar/roslyn,KevinRansom/roslyn,swaroop-sridhar/roslyn,jcouv/roslyn,VSadov/roslyn,tannergooding/roslyn,agocke/roslyn,mattwar/roslyn,SeriaWei/roslyn,natidea/roslyn,akrisiun/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,jeffanders/roslyn,dotnet/roslyn,bkoelman/roslyn,CaptainHayashi/roslyn,AArnott/roslyn,AmadeusW/roslyn,eriawan/roslyn,xoofx/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,leppie/roslyn,xoofx/roslyn,physhi/roslyn,davkean/roslyn,a-ctor/roslyn,jamesqo/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,xasx/roslyn,ljw1004/roslyn,natgla/roslyn,tvand7093/roslyn,eriawan/roslyn,amcasey/roslyn,tvand7093/roslyn,wvdd007/roslyn,TyOverby/roslyn,kelltrick/roslyn,mmitche/roslyn,Giftednewt/roslyn,OmarTawfik/roslyn,jmarolf/roslyn,akrisiun/roslyn,sharwell/roslyn,vslsnap/roslyn,jkotas/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,wvdd007/roslyn,budcribar/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,OmarTawfik/roslyn,amcasey/roslyn,KevinH-MS/roslyn,AnthonyDGreen/roslyn,bkoelman/roslyn,rgani/roslyn,srivatsn/roslyn,weltkante/roslyn,natgla/roslyn,KevinH-MS/roslyn,heejaechang/roslyn,yeaicc/roslyn,Pvlerick/roslyn,jamesqo/roslyn,AmadeusW/roslyn,mmitche/roslyn,weltkante/roslyn,lorcanmooney/roslyn,Hosch250/roslyn,mattscheffer/roslyn,stephentoub/roslyn,tmat/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,genlu/roslyn,aelij/roslyn,MatthieuMEZIL/roslyn,MattWindsor91/roslyn,Pvlerick/roslyn,nguerrera/roslyn,budcribar/roslyn,pdelvo/roslyn,brettfo/roslyn,mavasani/roslyn,sharadagrawal/Roslyn,DustinCampbell/roslyn,srivatsn/roslyn,KiloBravoLima/roslyn,mavasani/roslyn,tmat/roslyn,diryboy/roslyn,KiloBravoLima/roslyn,dpoeschl/roslyn,xasx/roslyn,paulvanbrenk/roslyn,mmitche/roslyn,TyOverby/roslyn,jaredpar/roslyn,diryboy/roslyn,zooba/roslyn,physhi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008 | src/Features/Core/Portable/Diagnostics/Analyzers/IDEDiagnosticIds.cs | src/Features/Core/Portable/Diagnostics/Analyzers/IDEDiagnosticIds.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.
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class IDEDiagnosticIds
{
public const string SimplifyNamesDiagnosticId = "IDE0001";
public const string SimplifyMemberAccessDiagnosticId = "IDE0002";
public const string SimplifyThisOrMeDiagnosticId = "IDE0003";
public const string RemoveUnnecessaryCastDiagnosticId = "IDE0004";
public const string RemoveUnnecessaryImportsDiagnosticId = "IDE0005";
public const string IntellisenseBuildFailedDiagnosticId = "IDE0006";
public const string PopulateSwitchDiagnosticId = "IDE0010";
// Analyzer error Ids
public const string AnalyzerChangedId = "IDE1001";
public const string AnalyzerDependencyConflictId = "IDE1002";
public const string MissingAnalyzerReferenceId = "IDE1003";
public const string ErrorReadingRulesetId = "IDE1004";
public const string InvokeDelegateWithConditionalAccessId = "IDE1005";
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Diagnostics
{
internal static class IDEDiagnosticIds
{
public const string SimplifyNamesDiagnosticId = "IDE0001";
public const string SimplifyMemberAccessDiagnosticId = "IDE0002";
public const string SimplifyThisOrMeDiagnosticId = "IDE0003";
public const string RemoveUnnecessaryCastDiagnosticId = "IDE0004";
public const string RemoveUnnecessaryImportsDiagnosticId = "IDE0005";
public const string IntellisenseBuildFailedDiagnosticId = "IDE0006";
public const string PopulateSwitchDiagnosticId = "IDE0007";
// Analyzer error Ids
public const string AnalyzerChangedId = "IDE1001";
public const string AnalyzerDependencyConflictId = "IDE1002";
public const string MissingAnalyzerReferenceId = "IDE1003";
public const string ErrorReadingRulesetId = "IDE1004";
public const string InvokeDelegateWithConditionalAccessId = "IDE1005";
}
}
| mit | C# |
4fedad723131acfedf437808811e43455ea9a569 | Update CORS code | JasonBock/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla,rockfordlhotka/csla,MarimerLLC/csla,MarimerLLC/csla,MarimerLLC/csla,JasonBock/csla | Samples/ProjectTracker/ProjectTracker.AppServerCore/Startup.cs | Samples/ProjectTracker/ProjectTracker.AppServerCore/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Csla.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
namespace ProjectTracker.AppServerCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
private const string BlazorClientPolicy = "AllowAllOrigins";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(BlazorClientPolicy,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc((o) => o.EnableEndpointRouting = false);
// If using Kestrel:
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
// If using IIS:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
services.AddCsla();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCors(BlazorClientPolicy); // must be before app.UseMvc()
app.UseHttpsRedirection();
app.UseMvc();
app.UseCsla();
ConfigurationManager.AppSettings["DalManagerType"] =
"ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Csla.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Server.Kestrel.Core;
namespace ProjectTracker.AppServerCore
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddMvc((o) => o.EnableEndpointRouting = false);
// If using Kestrel:
services.Configure<KestrelServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
// If using IIS:
services.Configure<IISServerOptions>(options =>
{
options.AllowSynchronousIO = true;
});
services.AddCsla();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseCsla();
ConfigurationManager.AppSettings["DalManagerType"] =
"ProjectTracker.DalMock.DalManager,ProjectTracker.DalMock";
}
}
}
| mit | C# |
4c8d8741aa0bc081749dbaa664992bad5c13014d | fix vari | vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf | src/backend/SO115App.Models/Classi/Composizione/ComposizioneMezzi.cs | src/backend/SO115App.Models/Classi/Composizione/ComposizioneMezzi.cs | //-----------------------------------------------------------------------
// <copyright file="ComposizioneMezzi.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Condivise;
using SO115App.Models.Classi.Composizione;
using System;
using System.Collections.Generic;
namespace SO115App.API.Models.Classi.Composizione
{
public class ComposizioneMezzi
{
public string Id { get; set; }
public string IdMongo { get; set; }
public Mezzo Mezzo { get; set; }
/// <summary>
/// Squadre preaccoppiate
/// </summary>
public List<SquadraSemplice> SquadrePreaccoppiate { get; set; } = null;
/// <summary>
/// Squadre in rientro
/// </summary>
public List<SquadraSemplice> ListaSquadre { get; set; } = null;
/// <summary>
/// Rappresentato in KM
/// </summary>
public string Km { get; set; } = "0";
/// <summary>
/// Rappresentato in Minuti
/// </summary>
public string TempoPercorrenza { get; set; } = "0";
public DateTime? IstanteScadenzaSelezione { get; set; }
/// <summary>
/// Incide generato dinamicamente, cambia da richiesta a richiesta. Serve ad ordinare i
/// mezzi, dal più opportuno al meno opportuno nella composizione partenza
/// </summary>
public decimal IndiceOrdinamento { get; set; }
/// <summary>
/// Se un mezzo si trova sul posto indicare anche l'indirizzo dell'intervento
/// </summary>
public string IndirizzoIntervento { get; set; }
}
public class SquadraSemplice
{
public string Codice { get; set; }
public Sede Distaccamento { get; set; }
public string Nome { get; set; }
public StatoSquadraComposizione Stato { get; set; }
public char Turno { get; set; }
public List<Componente> Membri { get; set; }
}
}
| //-----------------------------------------------------------------------
// <copyright file="ComposizioneMezzi.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF 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.
//
// SOVVF 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/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.API.Models.Classi.Condivise;
using SO115App.Models.Classi.Composizione;
using System;
using System.Collections.Generic;
namespace SO115App.API.Models.Classi.Composizione
{
public class ComposizioneMezzi
{
public string Id { get; set; }
public string IdMongo { get; set; }
public Mezzo Mezzo { get; set; }
/// <summary>
/// Squadre preaccoppiate
/// </summary>
public List<SquadraSemplice> SquadrePreaccoppiate { get; set; } = null;
/// <summary>
/// Squadre in rientro
/// </summary>
public List<SquadraSemplice> ListaSquadre { get; set; } = null;
/// <summary>
/// Rappresentato in KM
/// </summary>
public string Km { get; set; }
/// <summary>
/// Rappresentato in Minuti
/// </summary>
public string TempoPercorrenza { get; set; }
public DateTime? IstanteScadenzaSelezione { get; set; }
/// <summary>
/// Incide generato dinamicamente, cambia da richiesta a richiesta. Serve ad ordinare i
/// mezzi, dal più opportuno al meno opportuno nella composizione partenza
/// </summary>
public decimal IndiceOrdinamento { get; set; }
/// <summary>
/// Se un mezzo si trova sul posto indicare anche l'indirizzo dell'intervento
/// </summary>
public string IndirizzoIntervento { get; set; }
}
public class SquadraSemplice
{
public string Codice { get; set; }
public Sede Distaccamento { get; set; }
public string Nome { get; set; }
public StatoSquadraComposizione Stato { get; set; }
public char Turno { get; set; }
public List<Componente> Membri { get; set; }
}
}
| agpl-3.0 | C# |
1d14ecb1a375fc6b345367d42542f50caf227fee | Use killer exception message as the UnexpectedElasticsearchClientException message | KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,cstlaurent/elasticsearch-net,azubanov/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,KodrAus/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,RossLieberman/NEST,RossLieberman/NEST,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net | src/Elasticsearch.Net/Exceptions/UnexpectedElasticsearchClientException.cs | src/Elasticsearch.Net/Exceptions/UnexpectedElasticsearchClientException.cs | using System;
using System.Collections.Generic;
namespace Elasticsearch.Net
{
public class UnexpectedElasticsearchClientException : ElasticsearchClientException
{
public List<PipelineException> SeenExceptions { get; set; }
public UnexpectedElasticsearchClientException(Exception killerException, List<PipelineException> seenExceptions)
: base(PipelineFailure.Unexpected, killerException?.Message ?? "An unexpected exception occured.", killerException)
{
this.SeenExceptions = seenExceptions;
}
}
}
| using System;
using System.Collections.Generic;
namespace Elasticsearch.Net
{
public class UnexpectedElasticsearchClientException : ElasticsearchClientException
{
public List<PipelineException> SeenExceptions { get; set; }
public UnexpectedElasticsearchClientException(Exception killerException, List<PipelineException> seenExceptions)
: base(Elasticsearch.Net.PipelineFailure.Unexpected,"An unexpected exception occured.", killerException)
{
this.SeenExceptions = seenExceptions;
}
}
}
| apache-2.0 | C# |
408c85d063491d7a68bd642d6d59847ce155f20c | Improve UoW integration creation from mock | generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/TestHelpers/CommonTestDataSetup.cs | src/Smooth.IoC.Dapper.Repository.UnitOfWork.Tests/TestHelpers/CommonTestDataSetup.cs | using System.Data;
using System.IO;
using FakeItEasy;
using FakeItEasy.Core;
using NUnit.Framework;
using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers.Migrations;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public abstract class CommonTestDataSetup
{
private static IMyDatabaseSettings _settings;
public static ITestSession Connection { get; private set; }
public static IDbFactory Factory { get; private set; }
[SetUp]
public static void TestSetup()
{
if (Connection != null) return;
Factory = A.Fake<IDbFactory>();
_settings = A.Fake<IMyDatabaseSettings>();
var path = $@"{TestContext.CurrentContext.TestDirectory}\RepoTests.db";
if (File.Exists(path))
{
File.Delete(path);
}
A.CallTo(() => _settings.ConnectionString).Returns($@"Data Source={path};Version=3;New=True;BinaryGUID=False;");
Connection = CreateSession(null);
A.CallTo(() => Factory.Create<IUnitOfWork>(A<IDbFactory>._, A<ISession>._, IsolationLevel.Serializable))
.ReturnsLazily(CreateUnitOrWork);
A.CallTo(() => Factory.Create<ITestSession>()).ReturnsLazily(CreateSession);
new MigrateDb(Connection);
}
private static ITestSession CreateSession(IFakeObjectCall arg)
{
return new TestSession(Factory, _settings);
}
private static IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory)arg.FakedObject, CreateSession(null));
}
}
}
| using System.Data;
using System.IO;
using FakeItEasy;
using FakeItEasy.Core;
using NUnit.Framework;
using Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers.Migrations;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.FastCRUD.Repository.UnitOfWork.Tests.TestHelpers
{
public abstract class CommonTestDataSetup
{
private static IMyDatabaseSettings _settings;
public static ITestSession Connection { get; private set; }
public static IDbFactory Factory { get; private set; }
[SetUp]
public static void TestSetup()
{
if (Connection != null) return;
Factory = A.Fake<IDbFactory>();
_settings = A.Fake<IMyDatabaseSettings>();
var path = $@"{TestContext.CurrentContext.TestDirectory}\RepoTests.db";
if (File.Exists(path))
{
File.Delete(path);
}
A.CallTo(() => _settings.ConnectionString).Returns($@"Data Source={path};Version=3;New=True;BinaryGUID=False;");
Connection = CreateSession(null);
A.CallTo(() => Factory.Create<IUnitOfWork>(A<IDbFactory>._, A<ISession>._, IsolationLevel.Serializable))
.ReturnsLazily(CreateUnitOrWork);
A.CallTo(() => Factory.Create<ITestSession>()).ReturnsLazily(CreateSession);
new MigrateDb(Connection);
}
private static ITestSession CreateSession(IFakeObjectCall arg)
{
return new TestSession(Factory, _settings);
}
private static IUnitOfWork CreateUnitOrWork(IFakeObjectCall arg)
{
return new Dapper.Repository.UnitOfWork.Data.UnitOfWork((IDbFactory)arg.FakedObject, Connection);
}
}
}
| mit | C# |
9031afc73d847a6b7a8795464977ed26e24b9572 | Fix method name | martincostello/project-euler | tests/ProjectEuler.Tests/Puzzles/Puzzle092Tests.cs | tests/ProjectEuler.Tests/Puzzles/Puzzle092Tests.cs | // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Puzzle092"/> class. This class cannot be inherited.
/// </summary>
public static class Puzzle092Tests
{
[Fact(Skip = "Too slow.")]
public static void Puzzle092_Returns_Correct_Solution()
{
// Arrange
int expected = 8581146;
// Act and Assert
Puzzles.AssertSolution<Puzzle092>(expected);
}
}
}
| // Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using Xunit;
/// <summary>
/// A class containing tests for the <see cref="Puzzle092"/> class. This class cannot be inherited.
/// </summary>
public static class Puzzle092Tests
{
[Fact(Skip = "Too slow.")]
public static void Puzzle052_Returns_Correct_Solution()
{
// Arrange
int expected = 8581146;
// Act and Assert
Puzzles.AssertSolution<Puzzle092>(expected);
}
}
}
| apache-2.0 | C# |
05fb15c44cd7997c80c6b502723df56f4f56f262 | Fix InitialEventEntityMatcher if DTEnd is null | aluxnimm/outlookcaldavsynchronizer | CalDavSynchronizer/Implementation/Events/InitialEventEntityMatcher.cs | CalDavSynchronizer/Implementation/Events/InitialEventEntityMatcher.cs | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// 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 System;
using System.Collections.Generic;
using CalDavSynchronizer.Implementation.ComWrappers;
using DDay.iCal;
using GenSync.InitialEntityMatching;
namespace CalDavSynchronizer.Implementation.Events
{
internal class InitialEventEntityMatcher : InitialEntityMatcherByPropertyGrouping<AppointmentItemWrapper, string, DateTime, string, IICalendar, Uri, string, string>
{
public InitialEventEntityMatcher (IEqualityComparer<Uri> btypeIdEqualityComparer)
: base (btypeIdEqualityComparer)
{
}
protected override bool AreEqual (AppointmentItemWrapper atypeEntity, IICalendar btypeEntity)
{
var evt = btypeEntity.Events[0];
return
evt.Summary == atypeEntity.Inner.Subject &&
(evt.IsAllDay && atypeEntity.Inner.AllDayEvent ||
evt.Start.UTC == atypeEntity.Inner.StartUTC &&
((evt.DTEnd == null && evt.Start.UTC == atypeEntity.Inner.EndUTC) || (evt.DTEnd != null && evt.DTEnd.UTC == atypeEntity.Inner.EndUTC )));
}
protected override string GetAtypePropertyValue (AppointmentItemWrapper atypeEntity)
{
return (atypeEntity.Inner.Subject != null ? atypeEntity.Inner.Subject.ToLower() : string.Empty);
}
protected override string GetBtypePropertyValue (IICalendar btypeEntity)
{
return (btypeEntity.Events[0].Summary != null ? btypeEntity.Events[0].Summary.ToLower() : string.Empty);
}
protected override string MapAtypePropertyValue (string value)
{
return value;
}
}
} | // This file is Part of CalDavSynchronizer (http://outlookcaldavsynchronizer.sourceforge.net/)
// Copyright (c) 2015 Gerhard Zehetbauer
//
// 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 System;
using System.Collections.Generic;
using CalDavSynchronizer.Implementation.ComWrappers;
using DDay.iCal;
using GenSync.InitialEntityMatching;
namespace CalDavSynchronizer.Implementation.Events
{
internal class InitialEventEntityMatcher : InitialEntityMatcherByPropertyGrouping<AppointmentItemWrapper, string, DateTime, string, IICalendar, Uri, string, string>
{
public InitialEventEntityMatcher (IEqualityComparer<Uri> btypeIdEqualityComparer)
: base (btypeIdEqualityComparer)
{
}
protected override bool AreEqual (AppointmentItemWrapper atypeEntity, IICalendar btypeEntity)
{
var evt = btypeEntity.Events[0];
return
evt.Summary == atypeEntity.Inner.Subject &&
(evt.IsAllDay && atypeEntity.Inner.AllDayEvent ||
evt.Start.UTC == atypeEntity.Inner.StartUTC &&
evt.DTEnd.UTC == atypeEntity.Inner.EndUTC);
}
protected override string GetAtypePropertyValue (AppointmentItemWrapper atypeEntity)
{
return (atypeEntity.Inner.Subject != null ? atypeEntity.Inner.Subject.ToLower() : string.Empty);
}
protected override string GetBtypePropertyValue (IICalendar btypeEntity)
{
return (btypeEntity.Events[0].Summary != null ? btypeEntity.Events[0].Summary.ToLower() : string.Empty);
}
protected override string MapAtypePropertyValue (string value)
{
return value;
}
}
} | agpl-3.0 | C# |
8153e0c1686480d166abd4e0b49ebff5d95061df | Fix potential null ref exception. | NaosProject/Naos.Deployment,NaosFramework/Naos.Deployment | Naos.Deployment.Core/IHaveInitializationStrategiesExtensionMethods.cs | Naos.Deployment.Core/IHaveInitializationStrategiesExtensionMethods.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret =
(objectWithInitializationStrategies.InitializationStrategies ?? new List<InitializationStrategyBase>())
.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="IHaveInitializationStrategiesExtensionMethods.cs" company="Naos">
// Copyright 2015 Naos
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Naos.Deployment.Core
{
using System.Collections.Generic;
using System.Linq;
using Naos.Deployment.Contract;
/// <summary>
/// Additional behavior to add on IHaveInitializationStrategies.
/// </summary>
public static class IHaveInitializationStrategiesExtensionMethods
{
/// <summary>
/// Retrieves the initialization strategies matching the specified type.
/// </summary>
/// <typeparam name="T">Type of initialization strategy to look for.</typeparam>
/// <param name="objectWithInitializationStrategies">Object to operate on.</param>
/// <returns>Collection of initialization strategies matching the type specified.</returns>
public static ICollection<T> GetInitializationStrategiesOf<T>(
this IHaveInitializationStrategies objectWithInitializationStrategies) where T : InitializationStrategyBase
{
var ret = objectWithInitializationStrategies.InitializationStrategies.Select(strat => strat as T).Where(_ => _ != null).ToList();
return ret;
}
}
}
| mit | C# |
dfdde3093139e1f9489c007f7b20a6bb8e5318df | Fix small codacy issue | themehrdad/NetTelebot,vertigra/NetTelebot-2.0 | NetTelebot.Tests/ResponseTest/GetUserProfilePhotosResultParserTest.cs | NetTelebot.Tests/ResponseTest/GetUserProfilePhotosResultParserTest.cs | using NetTelebot.Result;
using NetTelebot.Tests.ResultTestObject;
using NetTelebot.Tests.TypeTestObject;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace NetTelebot.Tests.ResponseTest
{
[TestFixture]
internal static class GetUserProfilePhotosResultParserTest
{
/// <summary>
/// Test for <see cref="GetUserProfilePhotosResult"/> parse field.
/// </summary>
[Test]
public static void GetUserProfilePhotosResultTest()
{
const int totalCount = 2;
const string fieldId = "testFieldId";
const int width = 123;
const int height = 123;
const int fileSize = 123;
//create UserProfilePhotosInfo
var photoArrayOne = new JArray(PhotoSizeInfoObject.GetObject(fieldId, width, height, fileSize));
var photoArrayTwo = new JArray(PhotoSizeInfoObject.GetObject(fieldId, width, height, fileSize));
var jArray = new JArray(photoArrayOne, photoArrayTwo);
dynamic userProfilePhotosInfo = UserProfilePhotosInfoObject.GetObject(totalCount, jArray);
//create GetUserProfilePhotosResult
dynamic getUserProfileResult = GetUserProfilePhotosResultObject.GetObject(true, userProfilePhotosInfo);
//create instance GetUserProfilePhotosResult
var userProfile = new GetUserProfilePhotosResult(getUserProfileResult.ToString());
Assert.Multiple(() =>
{
Assert.True(userProfile.Ok);
Assert.AreEqual(userProfile.Result.TotalCount, totalCount);
for (var i = 0; i < 1; i++)
{
Assert.AreEqual(userProfile.Result.Photos[i][0].FileId, fieldId);
Assert.AreEqual(userProfile.Result.Photos[i][0].Width, width);
Assert.AreEqual(userProfile.Result.Photos[i][0].Height, height);
Assert.AreEqual(userProfile.Result.Photos[i][0].FileSize, fileSize);
}
});
}
}
}
| using NetTelebot.Result;
using NetTelebot.Tests.ResultTestObject;
using NetTelebot.Tests.TypeTestObject;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace NetTelebot.Tests.ResponseTest
{
[TestFixture]
internal class GetUserProfilePhotosResultParserTest
{
/// <summary>
/// Test for <see cref="GetUserProfilePhotosResult"/> parse field.
/// </summary>
[Test]
public static void GetUserProfilePhotosResultTest()
{
const int totalCount = 2;
const string fieldId = "testFieldId";
const int width = 123;
const int height = 123;
const int fileSize = 123;
//create UserProfilePhotosInfo
var photoArrayOne = new JArray(PhotoSizeInfoObject.GetObject(fieldId, width, height, fileSize));
var photoArrayTwo = new JArray(PhotoSizeInfoObject.GetObject(fieldId, width, height, fileSize));
var jArray = new JArray(photoArrayOne, photoArrayTwo);
dynamic userProfilePhotosInfo = UserProfilePhotosInfoObject.GetObject(totalCount, jArray);
//create GetUserProfilePhotosResult
dynamic getUserProfileResult = GetUserProfilePhotosResultObject.GetObject(true, userProfilePhotosInfo);
//create instance GetUserProfilePhotosResult
var userProfile = new GetUserProfilePhotosResult(getUserProfileResult.ToString());
Assert.Multiple(() =>
{
Assert.True(userProfile.Ok);
Assert.AreEqual(userProfile.Result.TotalCount, totalCount);
for (var i = 0; i < 1; i++)
{
Assert.AreEqual(userProfile.Result.Photos[i][0].FileId, fieldId);
Assert.AreEqual(userProfile.Result.Photos[i][0].Width, width);
Assert.AreEqual(userProfile.Result.Photos[i][0].Height, height);
Assert.AreEqual(userProfile.Result.Photos[i][0].FileSize, fileSize);
}
});
}
}
}
| mit | C# |
2605d9aaf0bbfb113daba52474b9975eea4fb285 | fix typo | castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Facilities.Wcf-READONLY,carcer/Castle.Components.Validator,castleproject/Castle.Facilities.Wcf-READONLY,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,codereflection/Castle.Components.Scheduler | InversionOfControl/Castle.MicroKernel/SubSystems/Naming/IHandlerSelector.cs | InversionOfControl/Castle.MicroKernel/SubSystems/Naming/IHandlerSelector.cs | // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Castle.MicroKernel
{
/// <summary>
/// Implementors of this interface allow to extend the way the container perform
/// component resolution based on some application specific business logic.
/// </summary>
/// <remarks>
/// This is the sibling interface to <seealso cref="ISubDependencyResolver"/>.
/// This is dealing strictly with root components, while the <seealso cref="ISubDependencyResolver"/> is dealing with
/// dependent components.
/// </remarks>
public interface IHandlerSelector
{
/// <summary>
/// Whatever the selector has an opinion about resolving a component with the
/// specified service and key.
/// </summary>
/// <param name="key">The service key - can be null</param>
/// <param name="service">The service interface that we want to resolve</param>
bool HasOpinionAbout(string key, Type service);
/// <summary>
/// Select the appropriate handler from the list of defined handlers.
/// The returned handler should be a member from the <paramref name="handlers"/> array.
/// </summary>
/// <param name="key">The service key - can be null</param>
/// <param name="service">The service interface that we want to resolve</param>
/// <param name="handlers">The defined handlers</param>
/// <returns>The selected handler, or null</returns>
IHandler SelectHandler(string key, Type service, IHandler[] handlers);
}
} | // Copyright 2004-2008 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace Castle.MicroKernel
{
/// <summary>
/// Implementors of this interface allow to extend the way the container perform
/// component resolution based on some application specific business logic.
/// </summary>
/// <remarks>
/// This is the siblig interface to <seealso cref="ISubDependencyResolver"/>.
/// This is dealing strictly with root components, while the <seealso cref="ISubDependencyResolver"/> is dealing with
/// dependent components.
/// </remarks>
public interface IHandlerSelector
{
/// <summary>
/// Whatever the selector has an opinion about resolving a component with the
/// specified service and key.
/// </summary>
/// <param name="key">The service key - can be null</param>
/// <param name="service">The service interface that we want to resolve</param>
bool HasOpinionAbout(string key, Type service);
/// <summary>
/// Select the appropriate handler from the list of defined handlers.
/// The returned handler should be a member from the <paramref name="handlers"/> array.
/// </summary>
/// <param name="key">The service key - can be null</param>
/// <param name="service">The service interface that we want to resolve</param>
/// <param name="handlers">The defined handlers</param>
/// <returns>The selected handler, or null</returns>
IHandler SelectHandler(string key, Type service, IHandler[] handlers);
}
} | apache-2.0 | C# |
cc7199c70975da25910047136b70287309c4372c | Create server side API for single multiple answer question | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | Trappist/src/Promact.Trappist.Core/Controllers/QuestionsController.cs | using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
/// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestionOption"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
[HttpPost]
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
///
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| using Microsoft.AspNetCore.Mvc;
using Promact.Trappist.DomainModel.Models.Question;
using Promact.Trappist.Repository.Questions;
using System;
namespace Promact.Trappist.Core.Controllers
{
[Route("api/question")]
public class QuestionsController : Controller
{
private readonly IQuestionRepository _questionsRepository;
public QuestionsController(IQuestionRepository questionsRepository)
{
_questionsRepository = questionsRepository;
}
[HttpGet]
/// <summary>
/// Gets all questions
/// </summary>
/// <returns>Questions list</returns>
public IActionResult GetQuestions()
{
var questions = _questionsRepository.GetAllQuestions();
return Json(questions);
}
[HttpPost]
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion)
{
_questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion);
return Ok();
}
/// <summary>
/// Add options of single multiple answer question to SingleMultipleAnswerQuestionOption model
/// </summary>
/// <param name="singleMultipleAnswerQuestionOption"></param>
/// <returns></returns>
public IActionResult AddSingleMultipleAnswerQuestionOption(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption)
{
_questionsRepository.AddSingleMultipleAnswerQuestionOption(singleMultipleAnswerQuestionOption);
return Ok();
}
}
}
| mit | C# |
a8fab4cba1deacc0d154546f2d6fd7bdc3457056 | make catcher field readonly | UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,smoogipooo/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu-new | osu.Game.Rulesets.Catch/Mods/CatchModRelax.cs | osu.Game.Rulesets.Catch/Mods/CatchModRelax.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset) =>
(drawableRuleset.Playfield.Parent as Container).Add(new CatchModRelaxHelper(drawableRuleset.Playfield as CatchPlayfield));
private class CatchModRelaxHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private readonly CatcherArea.Catcher catcher;
public CatchModRelaxHelper(CatchPlayfield catchPlayfield)
{
catcher = catchPlayfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
//lock catcher to mouse position horizontally
catcher.X = e.MousePosition.X / DrawSize.X;
//make Yuzu face the direction he's moving
var direction = Math.Sign(e.Delta.X);
if (direction != 0)
catcher.Scale = new Vector2(Math.Abs(catcher.Scale.X) * direction, catcher.Scale.Y);
return base.OnMouseMove(e);
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input;
using osu.Framework.Input.Bindings;
using osu.Framework.Input.Events;
using osu.Game.Rulesets.Catch.Objects;
using osu.Game.Rulesets.Catch.UI;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.UI;
using osuTK;
using System;
namespace osu.Game.Rulesets.Catch.Mods
{
public class CatchModRelax : ModRelax, IApplicableToDrawableRuleset<CatchHitObject>
{
public override string Description => @"Use the mouse to control the catcher.";
public void ApplyToDrawableRuleset(DrawableRuleset<CatchHitObject> drawableRuleset) =>
(drawableRuleset.Playfield.Parent as Container).Add(new CatchModRelaxHelper(drawableRuleset.Playfield as CatchPlayfield));
private class CatchModRelaxHelper : Drawable, IKeyBindingHandler<CatchAction>, IRequireHighFrequencyMousePosition
{
private CatcherArea.Catcher catcher;
public CatchModRelaxHelper(CatchPlayfield catchPlayfield)
{
catcher = catchPlayfield.CatcherArea.MovableCatcher;
RelativeSizeAxes = Axes.Both;
}
//disable keyboard controls
public bool OnPressed(CatchAction action) => true;
public bool OnReleased(CatchAction action) => true;
protected override bool OnMouseMove(MouseMoveEvent e)
{
//lock catcher to mouse position horizontally
catcher.X = e.MousePosition.X / DrawSize.X;
//make Yuzu face the direction he's moving
var direction = Math.Sign(e.Delta.X);
if (direction != 0)
catcher.Scale = new Vector2(Math.Abs(catcher.Scale.X) * direction, catcher.Scale.Y);
return base.OnMouseMove(e);
}
}
}
}
| mit | C# |
2856aef4eb17ee91f8d8f5c0a7852fae2e517870 | Add exception to catch any incorrect defaults of `Bindable<string>` | ppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu | osu.Game/Overlays/Settings/SettingsTextBox.cs | osu.Game/Overlays/Settings/SettingsTextBox.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.Bindables;
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
public override Bindable<string> Current
{
get => base.Current;
set
{
if (value.Default == null)
throw new InvalidOperationException($"Bindable settings of type {nameof(Bindable<string>)} should have a non-null default value.");
base.Current = value;
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
namespace osu.Game.Overlays.Settings
{
public class SettingsTextBox : SettingsItem<string>
{
protected override Drawable CreateControl() => new OutlinedTextBox
{
Margin = new MarginPadding { Top = 5 },
RelativeSizeAxes = Axes.X,
CommitOnFocusLost = true
};
}
}
| mit | C# |
85017a009428ecf9a3ee881a28b209ea1e07b207 | Add test for accuracy heatmap to TestCaseStatisticsPanel | UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu | osu.Game.Tests/Visual/Ranking/TestSceneStatisticsPanel.cs | osu.Game.Tests/Visual/Ranking/TestSceneStatisticsPanel.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Osu;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking.Statistics;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Scoring;
using osuTK;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStatisticsPanel : OsuTestScene
{
[Test]
public void TestScoreWithTimeStatistics()
{
var score = new TestScoreInfo(new OsuRuleset().RulesetInfo)
{
HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents()
};
loadPanel(score);
}
[Test]
public void TestScoreWithPositionStatistics()
{
var score = new TestScoreInfo(new OsuRuleset().RulesetInfo)
{
HitEvents = CreatePositionDistributedHitEvents()
};
loadPanel(score);
}
[Test]
public void TestScoreWithoutStatistics()
{
loadPanel(new TestScoreInfo(new OsuRuleset().RulesetInfo));
}
[Test]
public void TestNullScore()
{
loadPanel(null);
}
private void loadPanel(ScoreInfo score) => AddStep("load panel", () =>
{
Child = new StatisticsPanel
{
RelativeSizeAxes = Axes.Both,
State = { Value = Visibility.Visible },
Score = { Value = score }
};
});
public static List<HitEvent> CreatePositionDistributedHitEvents()
{
var hitEvents = new List<HitEvent>();
// Use constant seed for reproducibility
var random = new Random(0);
for (int i = 0; i < 500; i++)
{
float angle = (float) random.NextDouble() * 2 * (float) Math.PI;
float radius = (float) random.NextDouble() * 0.5f * HitCircle.OBJECT_RADIUS;
Vector2 position = new Vector2(radius * (float) Math.Cos(angle), radius * (float) Math.Sin(angle));
hitEvents.Add(new HitEvent(0, HitResult.Perfect, new HitCircle(), new HitCircle(), position));
}
return hitEvents;
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Rulesets.Osu;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking.Statistics;
namespace osu.Game.Tests.Visual.Ranking
{
public class TestSceneStatisticsPanel : OsuTestScene
{
[Test]
public void TestScoreWithStatistics()
{
var score = new TestScoreInfo(new OsuRuleset().RulesetInfo)
{
HitEvents = TestSceneHitEventTimingDistributionGraph.CreateDistributedHitEvents()
};
loadPanel(score);
}
[Test]
public void TestScoreWithoutStatistics()
{
loadPanel(new TestScoreInfo(new OsuRuleset().RulesetInfo));
}
[Test]
public void TestNullScore()
{
loadPanel(null);
}
private void loadPanel(ScoreInfo score) => AddStep("load panel", () =>
{
Child = new StatisticsPanel
{
RelativeSizeAxes = Axes.Both,
State = { Value = Visibility.Visible },
Score = { Value = score }
};
});
}
}
| mit | C# |
71de7ce0a3abc0af75d210d54ceafca9c1f0f5b2 | Add missing methods to server interface | NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,ppy/osu | osu.Game/Online/RealtimeMultiplayer/IMultiplayerServer.cs | osu.Game/Online/RealtimeMultiplayer/IMultiplayerServer.cs | using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
/// <summary>
/// Transfer the host of the currently joined room to another user in the room.
/// </summary>
/// <param name="userId">The new user which is to become host.</param>
Task TransferHost(long userId);
/// <summary>
/// As the host, update the settings of the currently joined room.
/// </summary>
/// <param name="settings">The new settings to apply.</param>
Task ChangeSettings(MultiplayerRoomSettings settings);
}
}
| using System.Threading.Tasks;
namespace osu.Game.Online.RealtimeMultiplayer
{
/// <summary>
/// An interface defining the spectator server instance.
/// </summary>
public interface IMultiplayerServer
{
/// <summary>
/// Request to join a multiplayer room.
/// </summary>
/// <param name="roomId">The databased room ID.</param>
/// <exception cref="UserAlreadyInMultiplayerRoom">If the user is already in the requested (or another) room.</exception>
Task<MultiplayerRoom> JoinRoom(long roomId);
/// <summary>
/// Request to leave the currently joined room.
/// </summary>
Task LeaveRoom();
}
} | mit | C# |
2ff02aad63f001de9bcdaeb644d43c79ea73825c | Fix code comments | wespday/CategoryTraits.Xunit2 | src/CategoryTraits.Xunit2/CategoryTraitDiscoverer.cs | src/CategoryTraits.Xunit2/CategoryTraitDiscoverer.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CategoryTraitDiscoverer.cs" company="Wes Day">
// The MIT License (MIT)
//
// Copyright (c) 2015 Wes Day
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CategoryTraits.Xunit2
{
using System.Collections.Generic;
using Xunit.Abstractions;
using Xunit.Sdk;
/// <summary>
/// This class discovers all of the xUnit tests and test classes that have
/// applied the TraitDiscoverer attribute for this trait discoverer.
/// This class is referenced for example by the Visual Studio test explorer to discover test traits such as unit tests or integration tests.
/// Originally derived from the <a href="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility">xUnit TraitExtensibility Sample</a>.
/// </summary>
public class CategoryTraitDiscoverer : ITraitDiscoverer
{
/// <summary>
/// The namespace of this class
/// </summary>
internal const string Namespace = nameof(CategoryTraits) + "." + nameof(Xunit2);
/// <summary>
/// The fully qualified name of this class
/// </summary>
internal const string FullyQualifiedName = Namespace + "." + nameof(CategoryTraitDiscoverer);
/// <summary>
/// Gets the trait values from the Category attribute.
/// </summary>
/// <param name="traitAttribute">
/// The trait attribute containing the trait values.
/// </param>
/// <returns>
/// The trait values.
/// </returns>
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var categoryValue = traitAttribute.GetNamedArgument<string>("Category");
if (!string.IsNullOrWhiteSpace(categoryValue))
{
yield return new KeyValuePair<string, string>("Category", categoryValue);
}
}
}
}
| // --------------------------------------------------------------------------------------------------------------------
// <copyright file="CategoryTraitDiscoverer.cs" company="Wes Day">
// The MIT License (MIT)
//
// Copyright (c) 2015 Wes Day
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace CategoryTraits.Xunit2
{
using System.Collections.Generic;
using Xunit.Abstractions;
using Xunit.Sdk;
/// <summary>
/// This class discovers all of the xUnit tests and test classes that have
/// applied the TraitDiscoverer attribute for this trait discoverer.
/// This class is referenced for example by the Visual Studio test explorer to discover test traits such as unit tests or integration tests.
/// Originally derived from the <a href="https://github.com/xunit/samples.xunit/tree/master/TraitExtensibility">xUnit TraitExtensibility Sample</a>.
/// </summary>
public class CategoryTraitDiscoverer : ITraitDiscoverer
{
/// <summary>
/// The namespace of this class
/// </summary>
internal const string Namespace = nameof(CategoryTraits) + "." + nameof(Xunit2);
/// <summary>
/// The namespace of this class
/// </summary>
internal const string FullyQualifiedName = Namespace + "." + nameof(CategoryTraitDiscoverer);
/// <summary>
/// Gets the trait values from the Category attribute.
/// </summary>
/// <param name="traitAttribute">
/// The trait attribute containing the trait values.
/// </param>
/// <returns>
/// The trait values.
/// </returns>
public IEnumerable<KeyValuePair<string, string>> GetTraits(IAttributeInfo traitAttribute)
{
var categoryValue = traitAttribute.GetNamedArgument<string>("Category");
if (!string.IsNullOrWhiteSpace(categoryValue))
{
yield return new KeyValuePair<string, string>("Category", categoryValue);
}
}
}
} | mit | C# |
e0aeb62384c4e0d22af2e466b8ca118cd5ca329d | Mark 'TService' as covariant for 'IFactory' | invio/Invio.Extensions.DependencyInjection,invio/Invio.Extensions.DependencyInjection | src/Invio.Extensions.DependencyInjection/IFactory.cs | src/Invio.Extensions.DependencyInjection/IFactory.cs | using System;
namespace Invio.Extensions.DependencyInjection {
/// <summary>
/// Implementation of factory pattern to provide services for use
/// with a implementation of <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service the factory provides.</typeparam>
public interface IFactory<out TService> {
/// <summary>
/// Provides an object of the type <typeparamref name="TService"/>. It will
/// run based upon the lifetime specified for <typeparamref name="TService"/>
/// in the overarching <see cref="IServiceCollection" />.
/// </summary>
/// <returns>
/// An instance of the <typeparamref name="TService"/> defined for the factory.
/// </returns>
TService Provide();
}
}
| using System;
namespace Invio.Extensions.DependencyInjection {
/// <summary>
/// Implementation of factory pattern to provide services for use
/// with a implementation of <see cref="IServiceCollection" />.
/// </summary>
/// <typeparam name="TService">The type of the service the factory provides.</typeparam>
public interface IFactory<TService> {
/// <summary>
/// Provides an object of the type <typeparamref name="TService"/>. It will
/// run based upon the lifetime specified for <typeparamref name="TService"/>
/// in the overarching <see cref="IServiceCollection" />.
/// </summary>
/// <returns>
/// An instance of the <typeparamref name="TService"/> defined for the factory.
/// </returns>
TService Provide();
}
}
| mit | C# |
a461145d815b0ab07a65da10aa0c73829845cdee | make extension method | StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis | service/DotNetApis.Cecil/CecilExtenstions.FriendlyName.cs | service/DotNetApis.Cecil/CecilExtenstions.FriendlyName.cs | using System.Collections.Generic;
using System.Linq;
using DotNetApis.Common;
using Mono.Cecil;
namespace DotNetApis.Cecil
{
public static partial class CecilExtensions
{
public static FriendlyName GetFriendlyName(this IMemberDefinition member)
{
var ns = member.DeclaringType != null ? member.DeclaringTypesInnerToOuter().Last().Namespace : ((TypeDefinition)member).Namespace;
if (member is TypeDefinition type)
{
var simpleName = GetSimpleName(type);
return new FriendlyName(simpleName, ns + "." + simpleName, ns + "." + simpleName);
}
var declaringType = string.Join(".", member.DeclaringType.GenericDeclaringTypesAndThis().Select(GetSimpleName));
if (member is MethodDefinition method)
{
var methodName = method.Name.StripBacktickSuffix().Name;
return CreateFromDeclaringType(GetSimpleName(methodName, method.GenericParameters), declaringType, ns);
}
return CreateFromDeclaringType(member.Name, declaringType, ns);
}
public static FriendlyName GetOverloadFriendlyName(this MethodDefinition method)
{
var ns = method.DeclaringTypesInnerToOuter().Last().Namespace;
var simpleName = method.Name.StripBacktickSuffix().Name; // Note: no generic parameters
var declaringType = string.Join(".", method.DeclaringType.GenericDeclaringTypesAndThis().Select(GetSimpleName));
return CreateFromDeclaringType(simpleName, declaringType, ns);
}
private static FriendlyName CreateFromDeclaringType(string simpleName, string declaringType, string ns) =>
new FriendlyName(simpleName, declaringType + "." + simpleName, ns + "." + declaringType + "." + simpleName);
private static string GetSimpleName(TypeReference type) => string.Join(".", type.GenericDeclaringTypesAndThis().Select(GetSimpleName));
private static string GetSimpleName(GenericTypeReference type) => GetSimpleName(type.Name, type.GenericParameters);
private static string GetSimpleName(string nameWithoutBacktickSuffix, IEnumerable<GenericParameter> genericParameters)
{
// This approach assumes that cref attributes can only refer to generic types (e.g., List<T>), not concrete generic types (e.g., List<string>).
var parameters = genericParameters.Reify();
if (!parameters.Any())
return nameWithoutBacktickSuffix;
return nameWithoutBacktickSuffix + "<" + string.Join(",", parameters.Select(x => x.Name)) + ">";
}
}
}
| using System.Collections.Generic;
using System.Linq;
using DotNetApis.Common;
using Mono.Cecil;
namespace DotNetApis.Cecil
{
public static partial class CecilExtensions
{
public static FriendlyName GetFriendlyName(this IMemberDefinition member)
{
var ns = member.DeclaringType != null ? member.DeclaringTypesInnerToOuter().Last().Namespace : ((TypeDefinition)member).Namespace;
if (member is TypeDefinition type)
{
var simpleName = GetSimpleName(type);
return new FriendlyName(simpleName, ns + "." + simpleName, ns + "." + simpleName);
}
var declaringType = string.Join(".", member.DeclaringType.GenericDeclaringTypesAndThis().Select(GetSimpleName));
if (member is MethodDefinition method)
{
var methodName = method.Name.StripBacktickSuffix().Name;
return CreateFromDeclaringType(GetSimpleName(methodName, method.GenericParameters), declaringType, ns);
}
return CreateFromDeclaringType(member.Name, declaringType, ns);
}
public static FriendlyName GetOverloadFriendlyName(MethodDefinition method)
{
var ns = method.DeclaringTypesInnerToOuter().Last().Namespace;
var simpleName = method.Name.StripBacktickSuffix().Name; // Note: no generic parameters
var declaringType = string.Join(".", method.DeclaringType.GenericDeclaringTypesAndThis().Select(GetSimpleName));
return CreateFromDeclaringType(simpleName, declaringType, ns);
}
private static FriendlyName CreateFromDeclaringType(string simpleName, string declaringType, string ns) =>
new FriendlyName(simpleName, declaringType + "." + simpleName, ns + "." + declaringType + "." + simpleName);
private static string GetSimpleName(TypeReference type) => string.Join(".", type.GenericDeclaringTypesAndThis().Select(GetSimpleName));
private static string GetSimpleName(GenericTypeReference type) => GetSimpleName(type.Name, type.GenericParameters);
private static string GetSimpleName(string nameWithoutBacktickSuffix, IEnumerable<GenericParameter> genericParameters)
{
// This approach assumes that cref attributes can only refer to generic types (e.g., List<T>), not concrete generic types (e.g., List<string>).
var parameters = genericParameters.Reify();
if (!parameters.Any())
return nameWithoutBacktickSuffix;
return nameWithoutBacktickSuffix + "<" + string.Join(",", parameters.Select(x => x.Name)) + ">";
}
}
}
| mit | C# |
409160859d965c2cfe33b5d20e922f90f3bace98 | Remove explicit namespacing. | Frontear/osuKyzer,DrabWeb/osu,DrabWeb/osu,Damnae/osu,2yangk23/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,tacchinotacchi/osu,johnneijzen/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,Nabile-Rahmani/osu,NeoAdonis/osu,DrabWeb/osu,EVAST9919/osu,smoogipoo/osu,RedNesto/osu,peppy/osu-new,johnneijzen/osu,ppy/osu,smoogipoo/osu,naoey/osu,smoogipoo/osu,UselessToucan/osu,nyaamara/osu,NeoAdonis/osu,naoey/osu,UselessToucan/osu,peppy/osu,peppy/osu,ppy/osu,ZLima12/osu,peppy/osu,ppy/osu,Drezi126/osu,smoogipooo/osu,osu-RP/osu-RP | osu.Game.Modes.Taiko/Objects/Drawable/DrawableDrumRollTick.cs | osu.Game.Modes.Taiko/Objects/Drawable/DrawableDrumRollTick.cs | using OpenTK.Input;
using System.Collections.Generic;
using osu.Game.Modes.Taiko.Judgements;
using System;
using osu.Game.Modes.Objects.Drawables;
using osu.Framework.Input;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableDrumRollTick : DrawableTaikoHitObject
{
/// <summary>
/// A list of keys which this HitObject will accept. These are the standard Taiko keys for now.
/// These should be moved to bindings later.
/// </summary>
private List<Key> validKeys = new List<Key>(new[] { Key.D, Key.F, Key.J, Key.K });
private DrumRollTick tick;
public DrawableDrumRollTick(DrumRollTick tick)
: base(tick)
{
this.tick = tick;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoDrumRollTickJudgementInfo();
protected override void CheckJudgement(bool userTriggered)
{
if (!userTriggered)
{
if (Judgement.TimeOffset > tick.TickTimeDistance / 2)
Judgement.Result = HitResult.Miss;
return;
}
if (Math.Abs(Judgement.TimeOffset) < tick.TickTimeDistance / 2)
{
Judgement.Result = HitResult.Hit;
Judgement.Score = TaikoScoreResult.Great;
}
}
protected override void Update()
{
// Drum roll ticks shouldn't move
}
protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
{
if (args.Repeat)
return false;
if (Judgement.Result.HasValue)
return false;
if (!validKeys.Contains(args.Key))
return false;
return UpdateJudgement(true);
}
}
}
| using OpenTK.Input;
using System.Collections.Generic;
using osu.Game.Modes.Taiko.Judgements;
using System;
using osu.Game.Modes.Objects.Drawables;
using osu.Framework.Input;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableDrumRollTick : DrawableTaikoHitObject
{
/// <summary>
/// A list of keys which this HitObject will accept. These are the standard Taiko keys for now.
/// These should be moved to bindings later.
/// </summary>
private List<Key> validKeys = new List<Key>(new[] { Key.D, Key.F, Key.J, Key.K });
private DrumRollTick tick;
public DrawableDrumRollTick(DrumRollTick tick)
: base(tick)
{
this.tick = tick;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoDrumRollTickJudgementInfo();
protected override void CheckJudgement(bool userTriggered)
{
if (!userTriggered)
{
if (Judgement.TimeOffset > tick.TickTimeDistance / 2)
Judgement.Result = Modes.Objects.Drawables.HitResult.Miss;
return;
}
if (Math.Abs(Judgement.TimeOffset) < tick.TickTimeDistance / 2)
{
Judgement.Result = HitResult.Hit;
Judgement.Score = TaikoScoreResult.Great;
}
}
protected override void Update()
{
// Drum roll ticks shouldn't move
}
protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
{
if (args.Repeat)
return false;
if (Judgement.Result.HasValue)
return false;
if (!validKeys.Contains(args.Key))
return false;
return UpdateJudgement(true);
}
}
}
| mit | C# |
a958c99e2264454f1cc5dd0f704bfe380bbabfe8 | Make ticks smaller (as per flyte's suggestion). | smoogipooo/osu,RedNesto/osu,Damnae/osu,osu-RP/osu-RP,naoey/osu,DrabWeb/osu,NeoAdonis/osu,2yangk23/osu,DrabWeb/osu,johnneijzen/osu,tacchinotacchi/osu,Drezi126/osu,ZLima12/osu,EVAST9919/osu,johnneijzen/osu,Nabile-Rahmani/osu,peppy/osu,naoey/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,2yangk23/osu,ppy/osu,ppy/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,nyaamara/osu,naoey/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,Frontear/osuKyzer,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,ppy/osu | osu.Game.Rulesets.Taiko/Objects/Drawables/Pieces/TickPiece.cs | osu.Game.Rulesets.Taiko/Objects/Drawables/Pieces/TickPiece.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables.Pieces
{
public class TickPiece : TaikoPiece
{
/// <summary>
/// Any tick that is not the first for a drumroll is not filled, but is instead displayed
/// as a hollow circle. This is what controls the border width of that circle.
/// </summary>
private const float tick_border_width = TaikoHitObject.DEFAULT_CIRCLE_DIAMETER / 16;
/// <summary>
/// The size of a tick.
/// </summary>
private const float tick_size = TaikoHitObject.DEFAULT_CIRCLE_DIAMETER / 6;
private bool filled;
public bool Filled
{
get { return filled; }
set
{
filled = value;
fillBox.Alpha = filled ? 1 : 0;
}
}
private readonly Box fillBox;
public TickPiece()
{
Size = new Vector2(tick_size);
Add(new CircularContainer
{
RelativeSizeAxes = Axes.Both,
Masking = true,
BorderThickness = tick_border_width,
BorderColour = Color4.White,
Children = new[]
{
fillBox = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
}
}
});
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
namespace osu.Game.Rulesets.Taiko.Objects.Drawables.Pieces
{
public class TickPiece : TaikoPiece
{
/// <summary>
/// Any tick that is not the first for a drumroll is not filled, but is instead displayed
/// as a hollow circle. This is what controls the border width of that circle.
/// </summary>
private const float tick_border_width = TaikoHitObject.DEFAULT_CIRCLE_DIAMETER / 16;
/// <summary>
/// The size of a tick.
/// </summary>
private const float tick_size = TaikoHitObject.DEFAULT_CIRCLE_DIAMETER / 4;
private bool filled;
public bool Filled
{
get { return filled; }
set
{
filled = value;
fillBox.Alpha = filled ? 1 : 0;
}
}
private readonly Box fillBox;
public TickPiece()
{
Size = new Vector2(tick_size);
Add(new CircularContainer
{
RelativeSizeAxes = Axes.Both,
Masking = true,
BorderThickness = tick_border_width,
BorderColour = Color4.White,
Children = new[]
{
fillBox = new Box
{
RelativeSizeAxes = Axes.Both,
Alpha = 0,
AlwaysPresent = true
}
}
});
}
}
}
| mit | C# |
9d48ae7957013de33b5e8d0c08f08a3e39ee4aac | Handle null values in IsMultilineDocComment | mgoertz-msft/roslyn,VSadov/roslyn,physhi/roslyn,DustinCampbell/roslyn,shyamnamboodiripad/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,diryboy/roslyn,brettfo/roslyn,DustinCampbell/roslyn,agocke/roslyn,CyrusNajmabadi/roslyn,heejaechang/roslyn,stephentoub/roslyn,MichalStrehovsky/roslyn,agocke/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,agocke/roslyn,bartdesmet/roslyn,mavasani/roslyn,jmarolf/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,jcouv/roslyn,eriawan/roslyn,reaction1989/roslyn,aelij/roslyn,reaction1989/roslyn,MichalStrehovsky/roslyn,tmeschter/roslyn,gafter/roslyn,davkean/roslyn,KirillOsenkov/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,aelij/roslyn,bartdesmet/roslyn,brettfo/roslyn,stephentoub/roslyn,jcouv/roslyn,AmadeusW/roslyn,abock/roslyn,cston/roslyn,wvdd007/roslyn,wvdd007/roslyn,DustinCampbell/roslyn,aelij/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,tmat/roslyn,ErikSchierboom/roslyn,genlu/roslyn,panopticoncentral/roslyn,brettfo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinRansom/roslyn,KirillOsenkov/roslyn,davkean/roslyn,sharwell/roslyn,gafter/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,AlekseyTs/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,KevinRansom/roslyn,tmeschter/roslyn,dpoeschl/roslyn,weltkante/roslyn,cston/roslyn,gafter/roslyn,eriawan/roslyn,KirillOsenkov/roslyn,abock/roslyn,tannergooding/roslyn,tmeschter/roslyn,eriawan/roslyn,davkean/roslyn,nguerrera/roslyn,abock/roslyn,reaction1989/roslyn,physhi/roslyn,panopticoncentral/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,xasx/roslyn,AlekseyTs/roslyn,VSadov/roslyn,weltkante/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,xasx/roslyn,dpoeschl/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,diryboy/roslyn,tmat/roslyn,dotnet/roslyn,jmarolf/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,tmat/roslyn,diryboy/roslyn,cston/roslyn,dotnet/roslyn,tannergooding/roslyn,genlu/roslyn,stephentoub/roslyn,jasonmalinowski/roslyn,jcouv/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,dpoeschl/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,nguerrera/roslyn,xasx/roslyn,genlu/roslyn,bartdesmet/roslyn | src/Workspaces/CSharp/Portable/Extensions/DocumentationCommentExtensions.cs | src/Workspaces/CSharp/Portable/Extensions/DocumentationCommentExtensions.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 Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
if (documentationComment == null)
{
return false;
}
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
| // 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 Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class DocumentationCommentExtensions
{
public static bool IsMultilineDocComment(this DocumentationCommentTriviaSyntax documentationComment)
{
return documentationComment.ToFullString().StartsWith("/**", StringComparison.Ordinal);
}
}
}
| mit | C# |
ae41627fb12b6419d8f3b87162f4e91cc062ad2a | Make the IPropertyValueParser interface implement IDiscoveralbe for better perfomance when doing type scanning | dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu | src/Our.Umbraco.Nexu.Common/Interfaces/Models/IPropertyValueParser.cs | src/Our.Umbraco.Nexu.Common/Interfaces/Models/IPropertyValueParser.cs | namespace Our.Umbraco.Nexu.Common.Interfaces.Models
{
using System.Collections.Generic;
using global::Umbraco.Core.Composing;
using global::Umbraco.Core.Models;
/// <summary>
/// Represents the PropertyValueParser interface.
/// </summary>
public interface IPropertyValueParser : IDiscoverable
{
/// <summary>
/// Checks if this is the parser for the current property
/// </summary>
/// <param name="property">
/// The property.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
bool IsParserFor(Property property);
/// <summary>
/// Gets the related entities from the property value
/// </summary>
/// <param name="property">
/// The property.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IRelatedEntity}"/>.
/// </returns>
IEnumerable<IRelatedEntity> GetRelatedEntities(Property property);
}
}
| namespace Our.Umbraco.Nexu.Common.Interfaces.Models
{
using System.Collections.Generic;
using global::Umbraco.Core.Models;
/// <summary>
/// Represents the PropertyValueParser interface.
/// </summary>
public interface IPropertyValueParser
{
/// <summary>
/// Checks if this is the parser for the current property
/// </summary>
/// <param name="property">
/// The property.
/// </param>
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
bool IsParserFor(Property property);
/// <summary>
/// Gets the related entities from the property value
/// </summary>
/// <param name="property">
/// The property.
/// </param>
/// <returns>
/// The <see cref="IEnumerable{IRelatedEntity}"/>.
/// </returns>
IEnumerable<IRelatedEntity> GetRelatedEntities(Property property);
}
}
| mit | C# |
2b33f76a5fd27ed2cc13e74d6f1aa26211159fb3 | Set accepted names/mails to all | dfensgmbh/biz.dfch.CS.CoffeeTracker | src/biz.dfch.CS.CoffeeTracker.Core/Security/AuthRepository.cs | src/biz.dfch.CS.CoffeeTracker.Core/Security/AuthRepository.cs | /**
* Copyright 2017 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using biz.dfch.CS.CoffeeTracker.Core.DbContext;
using biz.dfch.CS.CoffeeTracker.Core.Model;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace biz.dfch.CS.CoffeeTracker.Core.Security
{
public class AuthRepository : IDisposable
{
private AuthContext authContext;
private UserManager<IdentityUser> userManager;
public AuthRepository()
{
authContext = new AuthContext();
userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
userManager.UserValidator = new UserValidator<IdentityUser>(userManager)
{
AllowOnlyAlphanumericUserNames = false
};
}
public async Task<IdentityResult> RegisterUser(User user)
{
var identityUser = new IdentityUser
{
UserName = user.Name
};
var result = await userManager.CreateAsync(identityUser, user.Password);
return result;
}
public async Task<IdentityUser> FindUser(string userName, string password)
{
var user = await userManager.FindAsync(userName, password);
return user;
}
public void Dispose()
{
authContext.Dispose();
userManager.Dispose();
}
}
} | /**
* Copyright 2017 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using biz.dfch.CS.CoffeeTracker.Core.DbContext;
using biz.dfch.CS.CoffeeTracker.Core.Model;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace biz.dfch.CS.CoffeeTracker.Core.Security
{
public class AuthRepository : IDisposable
{
private AuthContext authContext;
private UserManager<IdentityUser> userManager;
public AuthRepository()
{
authContext = new AuthContext();
userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
}
public async Task<IdentityResult> RegisterUser(User user)
{
var identityUser = new IdentityUser
{
UserName = user.Name
};
var result = await userManager.CreateAsync(identityUser, user.Password);
return result;
}
public async Task<IdentityUser> FindUser(string userName, string password)
{
var user = await userManager.FindAsync(userName, password);
return user;
}
public void Dispose()
{
authContext.Dispose();
userManager.Dispose();
}
}
} | apache-2.0 | C# |
71c472d961e1579ba976a5136f922d307e250971 | test fixed | bg0jr/RaynMaker,bg0jr/RaynMaker,bg0jr/RaynMaker | src/RaynMaker.Modules.Analysis.UnitTests/Engine/TextEvaluatorTests.cs | src/RaynMaker.Modules.Analysis.UnitTests/Engine/TextEvaluatorTests.cs | using System.Collections.Generic;
using NUnit.Framework;
using RaynMaker.Modules.Analysis.Engine;
using RaynMaker.Modules.Analysis.UnitTests.Engine.Fakes;
namespace RaynMaker.Modules.Analysis.UnitTests.Engine
{
[TestFixture]
public class TextEvaluatorTests
{
private FakeExpressionEvaluationContext myContext;
private TextEvaluator myEvaluator;
[SetUp]
public void SetUp()
{
myContext = new FakeExpressionEvaluationContext( new[] {
new FakeFigureProvider( "One", ctx => 1d ),
new FakeFigureProvider( "Null", ctx => null ),
new FakeFigureProvider( "STR", ctx => "Hello" ) } );
myEvaluator = new TextEvaluator( new ExpressionEvaluator( myContext ) );
}
[Test]
public void Evaluate_EmptyString_ReturnsEmptyString()
{
Assert.That( myEvaluator.Evaluate( string.Empty ), Is.Empty );
}
[Test]
public void Evaluate_PlainText_ReturnsSameText()
{
Assert.That( myEvaluator.Evaluate( "Sample Text" ), Is.EqualTo( "Sample Text" ) );
}
[Test]
public void Evaluate_TextWithProviders_ReturnsTextWithProviderValue()
{
Assert.That( myEvaluator.Evaluate( "Value: ${STR} ${One}" ), Is.EqualTo( "Value: Hello 1.00" ) );
}
[Test]
public void Evaluate_ProviderReturnsNull_ReturnsNA()
{
Assert.That( myEvaluator.Evaluate( "${Null}" ), Is.EqualTo( "n.a." ) );
}
[Test]
public void Evaluate_WhenCalled_ReturnsFormattedValueOfProvider()
{
Assert.That( myEvaluator.Evaluate( "${One}" ), Is.EqualTo( ( 1d ).ToString( "0.00" ) ) );
}
[Test]
public void ProvideValue_WhenCalled_ReturnsValueOfProvider()
{
Assert.That( myEvaluator.ProvideValue( "${One}" ), Is.EqualTo( 1d ) );
}
}
}
| using System.Collections.Generic;
using NUnit.Framework;
using RaynMaker.Modules.Analysis.Engine;
using RaynMaker.Modules.Analysis.UnitTests.Engine.Fakes;
namespace RaynMaker.Modules.Analysis.UnitTests.Engine
{
[TestFixture]
public class TextEvaluatorTests
{
private FakeExpressionEvaluationContext myContext;
private TextEvaluator myEvaluator;
[SetUp]
public void SetUp()
{
myContext = new FakeExpressionEvaluationContext( new[] {
new FakeFigureProvider( "One", ctx => 1d ),
new FakeFigureProvider( "Null", ctx => null ),
new FakeFigureProvider( "STR", ctx => "Hello" ) } );
myEvaluator = new TextEvaluator( new ExpressionEvaluator( myContext ) );
}
[Test]
public void Evaluate_EmptyString_ReturnsEmptyString()
{
Assert.That( myEvaluator.Evaluate( string.Empty ), Is.Empty );
}
[Test]
public void Evaluate_PlainText_ReturnsSameText()
{
Assert.That( myEvaluator.Evaluate( "Sample Text" ), Is.EqualTo( "Sample Text" ) );
}
[Test]
public void Evaluate_TextWithProviders_ReturnsTextWithProviderValue()
{
Assert.That( myEvaluator.Evaluate( "Value: ${STR} ${One}" ), Is.EqualTo( "Value: Hello 1,00" ) );
}
[Test]
public void Evaluate_ProviderReturnsNull_ReturnsNA()
{
Assert.That( myEvaluator.Evaluate( "${Null}" ), Is.EqualTo( "n.a." ) );
}
[Test]
public void Evaluate_WhenCalled_ReturnsFormattedValueOfProvider()
{
Assert.That( myEvaluator.Evaluate( "${One}" ), Is.EqualTo( ( 1d ).ToString( "0.00" ) ) );
}
[Test]
public void ProvideValue_WhenCalled_ReturnsValueOfProvider()
{
Assert.That( myEvaluator.ProvideValue( "${One}" ), Is.EqualTo( 1d ) );
}
}
}
| bsd-3-clause | C# |
063b8c3d773c3124418a02fde67dc62de35a72fe | Improve a/an word extraction to avoid problematic cases like "Triple-A classification" | EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an,EamonNerbonne/a-vs-an | A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs | A-vs-An/WikipediaAvsAnTrieExtractor/RegexTextUtils.ExtractWordsAfterAOrAn.cs | using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"(^|[\s""()‘’“”'])(?<article>[Aa]n?) [""()‘’“”$']*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
//watch out for dashes before "A" because of things like "Triple-A annotation"
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
| using System.Text.RegularExpressions;
using System.Linq;
using System;
using System.Collections.Generic;
namespace WikipediaAvsAnTrieExtractor {
public partial class RegexTextUtils {
//Note: regexes are NOT static and shared because of... http://stackoverflow.com/questions/7585087/multithreaded-use-of-regex
//This code is bottlenecked by regexes, so this really matters, here.
readonly Regex followingAn = new Regex(@"\b(?<article>[Aa]n?) [""()‘’“”$'-]*(?<word>[^\s""()‘’“”$'-]+)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant);
public IEnumerable<AvsAnSighting> ExtractWordsPrecededByAOrAn(string text) {
return
from Match m in followingAn.Matches(text)
select new AvsAnSighting { Word = m.Groups["word"].Value + " ", PrecededByAn = m.Groups["article"].Value.Length == 2 };
}
}
}
| apache-2.0 | C# |
7ee3f337231bda89fd7c993a36988f42445f597f | Revert "FLEET-9992: Add extra property to use new long Id's" | MiXTelematics/MiX.Integrate.Api.Client | MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs | MiX.Integrate.Shared/Entities/Messages/SendJobMessageCarrier.cs | using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public long[] AddressList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using MiX.Integrate.Shared.Entities.Communications;
namespace MiX.Integrate.Shared.Entities.Messages
{
public class SendJobMessageCarrier
{
public SendJobMessageCarrier() { }
public short VehicleId { get; set; }
public string Description { get; set; }
public string UserDescription { get; set; }
public string Body { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? ExpiryDate { get; set; }
public bool RequiresAddress { get; set; }
public bool AddAddressSummary { get; set; }
public bool UseFirstAddressForSummary { get; set; }
public JobMessageActionNotifications NotificationSettings { get; set; }
public int[] AddressList { get; set; }
public long[] LocationList { get; set; }
public CommsTransports Transport { get; set; }
public bool Urgent { get; set; }
}
}
| mit | C# |
2956a6fcc1521168ed20009612258b3a29a97e5c | Update existing documentation for season. | henrikfroehling/TraktApiSharp | Source/Lib/TraktApiSharp/Objects/Get/Shows/Seasons/TraktSeason.cs | Source/Lib/TraktApiSharp/Objects/Get/Shows/Seasons/TraktSeason.cs | namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Episodes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
/// <summary>A Trakt season of a Trakt show.</summary>
public class TraktSeason
{
/// <summary>Gets or sets the season number.</summary>
[JsonProperty(PropertyName = "number")]
public int? Number { get; set; }
/// <summary>Gets or sets the collection of ids for the season for various web services.</summary>
[JsonProperty(PropertyName = "ids")]
public TraktSeasonIds Ids { get; set; }
/// <summary>Gets or sets the collection of images for the season.</summary>
[JsonProperty(PropertyName = "images")]
public TraktSeasonImages Images { get; set; }
/// <summary>Gets or sets the average user rating of the season.</summary>
[JsonProperty(PropertyName = "rating")]
public float? Rating { get; set; }
/// <summary>Gets or sets the number of votes for the season.</summary>
[JsonProperty(PropertyName = "votes")]
public int? Votes { get; set; }
/// <summary>Gets or sets the number of episodes in the season.</summary>
[JsonProperty(PropertyName = "episode_count")]
public int? TotalEpisodesCount { get; set; }
/// <summary>Gets or sets the number of aired episodes in the season.</summary>
[JsonProperty(PropertyName = "aired_episodes")]
public int? AiredEpisodesCount { get; set; }
/// <summary>Gets or sets the synopsis of the season.</summary>
[JsonProperty(PropertyName = "overview")]
public string Overview { get; set; }
/// <summary>Gets or sets the UTC datetime when the season was first aired.</summary>
[JsonProperty(PropertyName = "first_aired")]
public DateTime? FirstAired { get; set; }
/// <summary>Gets or sets the collection of Trakt episodes in the season.</summary>
[JsonProperty(PropertyName = "episodes")]
public IEnumerable<TraktEpisode> Episodes { get; set; }
}
}
| namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Episodes;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
/// <summary>
/// A Trakt season of a Trakt show.
/// </summary>
public class TraktSeason
{
#region Minimal Info
/// <summary>
/// The season number.
/// </summary>
[JsonProperty(PropertyName = "number")]
public int? Number { get; set; }
/// <summary>
/// A collection of ids for the season for various web services.
/// </summary>
[JsonProperty(PropertyName = "ids")]
public TraktSeasonIds Ids { get; set; }
#endregion
#region Images
/// <summary>
/// A collection of images for the season.
/// </summary>
[JsonProperty(PropertyName = "images")]
public TraktSeasonImages Images { get; set; }
#endregion
#region Full (additional info)
/// <summary>
/// The average user rating of the season.
/// </summary>
[JsonProperty(PropertyName = "rating")]
public float? Rating { get; set; }
/// <summary>
/// The number of votes for the season.
/// </summary>
[JsonProperty(PropertyName = "votes")]
public int? Votes { get; set; }
/// <summary>
/// The number of episodes in the season.
/// </summary>
[JsonProperty(PropertyName = "episode_count")]
public int? TotalEpisodesCount { get; set; }
/// <summary>
/// The number of aired episodes in the season.
/// </summary>
[JsonProperty(PropertyName = "aired_episodes")]
public int? AiredEpisodesCount { get; set; }
/// <summary>
/// A synopsis of the season.
/// </summary>
[JsonProperty(PropertyName = "overview")]
public string Overview { get; set; }
/// <summary>
/// The UTC date when the season was first aired.
/// </summary>
[JsonProperty(PropertyName = "first_aired")]
public DateTime? FirstAired { get; set; }
#endregion
#region Episodes
/// <summary>
/// A collection of Trakt episodes in the season.
/// </summary>
[JsonProperty(PropertyName = "episodes")]
public IEnumerable<TraktEpisode> Episodes { get; set; }
#endregion
}
}
| mit | C# |
4b5638b631a50893d70ec3e2f9867b4c20b55ad8 | Update WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs | WalletWasabi.Gui/Controls/WalletExplorer/ClosedWalletViewModel.cs | using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
protected ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
try
{
var global = Locator.Current.GetService<Global>();
await Task.Run(async () => await global.WalletManager.StartWalletAsync(Wallet));
}
catch (OperationCanceledException ex)
{
Logger.LogTrace(ex);
}
catch (Exception ex)
{
NotificationHelpers.Error($"Couldn't load wallet. Reason: {ex.ToUserFriendlyString()}", sender: wallet);
Logger.LogError(ex);
}
}, this.WhenAnyValue(x => x.WalletState).Select(x => x == WalletState.Uninitialized));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
public static WalletViewModelBase Create(Wallet wallet)
{
return wallet.KeyManager.IsHardwareWallet
? new ClosedHardwareWalletViewModel(wallet)
: wallet.KeyManager.IsWatchOnly
? new ClosedWatchOnlyWalletViewModel(wallet)
: new ClosedWalletViewModel(wallet);
}
}
}
| using AvalonStudio.Extensibility;
using ReactiveUI;
using Splat;
using System;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Gui.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Wallets;
namespace WalletWasabi.Gui.Controls.WalletExplorer
{
public class ClosedWalletViewModel : WalletViewModelBase
{
protected ClosedWalletViewModel(Wallet wallet) : base(wallet)
{
OpenWalletCommand = ReactiveCommand.CreateFromTask(async () =>
{
try
{
var global = Locator.Current.GetService<Global>();
await Task.Run(async () => await global.WalletManager.StartWalletAsync(Wallet));
}
catch (OperationCanceledException ex)
{
Logger.LogTrace(ex);
}
catch (Exception ex)
{
NotificationHelpers.Error($"Couldn't load wallet. Reason: {ex.ToUserFriendlyString()}", sender: wallet);
Logger.LogError(ex);
}
}, this.WhenAnyValue(x => x.WalletState).Select(x => x == WalletState.Uninitialized));
}
public ReactiveCommand<Unit, Unit> OpenWalletCommand { get; }
public static WalletViewModelBase Create(Wallet wallet)
{
if (wallet.KeyManager.IsHardwareWallet)
{
return new ClosedHardwareWalletViewModel(wallet);
}
else if (wallet.KeyManager.IsWatchOnly)
{
return new ClosedWatchOnlyWalletViewModel(wallet);
}
else
{
return new ClosedWalletViewModel(wallet);
}
}
}
}
| mit | C# |
e7e1d150206131b6e100c44d7e881202dab9a874 | Modify option name | Wentao-Xu/GraphEngine,Wentao-Xu/GraphEngine,Wentao-Xu/GraphEngine,Wentao-Xu/GraphEngine | samples/DataImporter/GraphEngine.DataImporter/CmdOptions.cs | samples/DataImporter/GraphEngine.DataImporter/CmdOptions.cs | using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace GraphEngine.DataImporter
{
class CmdOptions
{
[Option('t', "tsl", HelpText = "Specifies the TSL assembly for data importing.", MutuallyExclusiveSet = "Action")]
public string TSLAssembly { get; set; }
[Option('d', "dir", HelpText = "Import all .json and .txt files from directory", Required = false)]
public string InputDirectory { get; set; }
[Option('o', "output", HelpText = "Specifies data import output directory for importing tasks, and specifies the output TSL file name for TSL generation tasks", Required = false)]
public string Output { get; set; }
[Option('g', "generate_tsl", HelpText = "Generates TSL", MutuallyExclusiveSet = "Action")]
public bool GenerateTSL { get; set; }
[Option('s', "sorted", HelpText = "Specifies that the data is already sorted/grouped by entities", DefaultValue = false)]
public bool Sorted { get; set; }
[Option("delimiter", HelpText = "Specifies the delimiter of CSV or TSV file", Required = false)]
public char Delimiter { get; set; }
[Option('f', "fileFormat", HelpText = "Specifies the file format", Required = false)]
public string FileFormat { get; set; }
[Option("notrim", HelpText = "Specifies that the data fields in CSV/TSV files are not trimmed", Required = false)]
public bool NoTrim { get; set; }
[ValueList(typeof(List<string>))]
public IList<string> ExplicitFiles { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
AdditionalNewLineAfterOption = true,
AddDashesToOption = true
};
help.AddPreOptionsLine("Import from files to Graph Engine storage.");
help.AddPreOptionsLine(string.Format("Usage: {0} [-t tsl_assembly|-g] [-d directory] [-o output_dir] [--delimiter delimiter] [-f file_format] [--notrim] [explicit files]", Path.GetFileName(Assembly.GetExecutingAssembly().Location)));
help.AddOptions(this);
help.AddPostOptionsLine("Only files with .json, .csv, .tsv and .ntriples suffix are recognized.");
help.AddPostOptionsLine("The file name of a data file will be used as the type for deserialization (except for RDF files).");
help.AddPostOptionsLine("The type must be defined as a Graph Engine cell in the TSL.\n");
return help;
}
}
}
| using CommandLine;
using CommandLine.Text;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace GraphEngine.DataImporter
{
class CmdOptions
{
[Option('t', "tsl", HelpText = "Specifies the TSL assembly for data importing.", MutuallyExclusiveSet = "Action")]
public string TSLAssembly { get; set; }
[Option('d', "dir", HelpText = "Import all .json and .txt files from directory", Required = false)]
public string InputDirectory { get; set; }
[Option('o', "output", HelpText = "Specifies data import output directory for importing tasks, and specifies the output TSL file name for TSL generation tasks", Required = false)]
public string Output { get; set; }
[Option('g', "generate_tsl", HelpText = "Generates TSL", MutuallyExclusiveSet = "Action")]
public bool GenerateTSL { get; set; }
[Option('s', "sorted", HelpText = "Specifies that the data is already sorted/grouped by entities", DefaultValue = false)]
public bool Sorted { get; set; }
[Option("delimiter", HelpText = "Specifies the delimiter of CSV or TSV file", Required = false)]
public char Delimiter { get; set; }
[Option('f', "fileFormat", HelpText = "Specifies the file format", Required = false)]
public string FileFormat { get; set; }
[Option("nottrim", HelpText = "Specifies that the data fields in CSV/TSV files are not trimmed", Required = false)]
public bool NoTrim { get; set; }
[ValueList(typeof(List<string>))]
public IList<string> ExplicitFiles { get; set; }
[HelpOption]
public string GetUsage()
{
var help = new HelpText
{
AdditionalNewLineAfterOption = true,
AddDashesToOption = true
};
help.AddPreOptionsLine("Import from files to Graph Engine storage.");
help.AddPreOptionsLine(string.Format("Usage: {0} [-t tsl_assembly|-g] [-d directory] [-o output_dir] [--delimiter delimiter] [-f file_format] [--nottrim] [explicit files]", Path.GetFileName(Assembly.GetExecutingAssembly().Location)));
help.AddOptions(this);
help.AddPostOptionsLine("Only files with .json, .csv, .tsv and .ntriples suffix are recognized.");
help.AddPostOptionsLine("The file name of a data file will be used as the type for deserialization (except for RDF files).");
help.AddPostOptionsLine("The type must be defined as a Graph Engine cell in the TSL.\n");
return help;
}
}
}
| mit | C# |
851bd64c04d0e93267fe03db502387e9e320c274 | Add debugger to HelloWorldBlacksboardAI example | meniku/NPBehave | Examples/Scripts/NPBehaveExampleHelloBlackboardsAI.cs | Examples/Scripts/NPBehaveExampleHelloBlackboardsAI.cs | using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
// attach the debugger component if executed in editor (helps to debug in the inspector)
#if UNITY_EDITOR
Debugger debugger = (Debugger)this.gameObject.AddComponent(typeof(Debugger));
debugger.BehaviorTree = behaviorTree;
#endif
}
}
| using UnityEngine;
using NPBehave;
public class NPBehaveExampleHelloBlackboardsAI : MonoBehaviour
{
private Root behaviorTree;
void Start()
{
behaviorTree = new Root(
// toggle the 'toggled' blackboard boolean flag around every 500 milliseconds
new Service(0.5f, () => { behaviorTree.Blackboard.Set("foo", !behaviorTree.Blackboard.GetBool("foo")); },
new Selector(
// Check the 'toggled' flag. Stops.IMMEDIATE_RESTART means that the Blackboard will be observed for changes
// while this or any lower priority branches are executed. If the value changes, the corresponding branch will be
// stopped and it will be immediately jump to the branch that now matches the condition.
new BlackboardCondition("foo", Operator.IS_EQUAL, true, Stops.IMMEDIATE_RESTART,
// when 'toggled' is true, this branch will get executed.
new Sequence(
// print out a message ...
new Action(() => Debug.Log("foo")),
// ... and stay here until the `BlackboardValue`-node stops us because the toggled flag went false.
new WaitUntilStopped()
)
),
// when 'toggled' is false, we'll eventually land here
new Sequence(
new Action(() => Debug.Log("bar")),
new WaitUntilStopped()
)
)
)
);
behaviorTree.Start();
}
}
| mit | C# |
9dde101f12201e66b92005a31773125e44629bd1 | Remove string prefixes | NeoAdonis/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,UselessToucan/osu | osu.Game/Online/API/Requests/Responses/APINewsPost.cs | osu.Game/Online/API/Requests/Responses/APINewsPost.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 Newtonsoft.Json;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class APINewsPost
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("author")]
public string Author { get; set; }
[JsonProperty("edit_url")]
public string EditUrl { get; set; }
[JsonProperty("first_image")]
public string FirstImage { get; set; }
[JsonProperty("published_at")]
public DateTime PublishedAt { get; set; }
[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; set; }
[JsonProperty("slug")]
public string Slug { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("preview")]
public string Preview { get; set; }
}
}
| // 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 Newtonsoft.Json;
using System;
namespace osu.Game.Online.API.Requests.Responses
{
public class APINewsPost
{
[JsonProperty(@"id")]
public long Id { get; set; }
[JsonProperty(@"author")]
public string Author { get; set; }
[JsonProperty(@"edit_url")]
public string EditUrl { get; set; }
[JsonProperty(@"first_image")]
public string FirstImage { get; set; }
[JsonProperty(@"published_at")]
public DateTime PublishedAt { get; set; }
[JsonProperty(@"updated_at")]
public DateTime UpdatedAt { get; set; }
[JsonProperty(@"slug")]
public string Slug { get; set; }
[JsonProperty(@"title")]
public string Title { get; set; }
[JsonProperty(@"preview")]
public string Preview { get; set; }
}
}
| mit | C# |
cf8645d022271bb168b32add4249a3f55092c79d | Remove unused reference | MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net | Mindscape.Raygun4Net/Storage/IRaygunOfflineStorage.cs | Mindscape.Raygun4Net/Storage/IRaygunOfflineStorage.cs | using System.Collections.Generic;
namespace Mindscape.Raygun4Net.Storage
{
public interface IRaygunOfflineStorage
{
/// <summary>
/// Persist the <paramref name="message"/>> to local storage.
/// </summary>
/// <param name="message">The serialized error report to store locally.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <param name="maxReportsStored">The number of reports allowed to be stored locally.</param>
/// <returns></returns>
bool Store(string message, string apiKey, int maxReportsStored);
/// <summary>
/// Retrieve all files from local storage.
/// </summary>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns>A container of files that are currently stored locally.</returns>
IList<IRaygunFile> FetchAll(string apiKey);
/// <summary>
/// Delete a file from local storage that has the following <paramref name="name"/>.
/// </summary>
/// <param name="name">The filename of the local file.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>s
bool Remove(string name, string apiKey);
}
} | using System.Collections.Generic;
using Mindscape.Raygun4Net.Messages;
namespace Mindscape.Raygun4Net.Storage
{
public interface IRaygunOfflineStorage
{
/// <summary>
/// Persist the <paramref name="message"/>> to local storage.
/// </summary>
/// <param name="message">The serialized error report to store locally.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <param name="maxReportsStored">The number of reports allowed to be stored locally.</param>
/// <returns></returns>
bool Store(string message, string apiKey, int maxReportsStored);
/// <summary>
/// Retrieve all files from local storage.
/// </summary>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns>A container of files that are currently stored locally.</returns>
IList<IRaygunFile> FetchAll(string apiKey);
/// <summary>
/// Delete a file from local storage that has the following <paramref name="name"/>.
/// </summary>
/// <param name="name">The filename of the local file.</param>
/// <param name="apiKey">The key for which these file are associated with.</param>
/// <returns></returns>s
bool Remove(string name, string apiKey);
}
} | mit | C# |
9a5d20e581c189fcdf94f5ad1817a9523b56df6d | Disable account online check for now. | Captain-Ice/Project-WildStar | Projects/AuthServer/Network/Packets/Handler/AuthHandler.cs | Projects/AuthServer/Network/Packets/Handler/AuthHandler.cs | // Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
//var account = DB.Auth.Single<Account>(a => a.Email == loginName);
//if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
| // Copyright (c) Multi-Emu.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using AuthServer.Attributes;
using AuthServer.Constants.Net;
using Framework.Database;
using Framework.Database.Auth;
namespace AuthServer.Network.Packets.Handler
{
class AuthHandler
{
[AuthPacket(ClientMessage.State1)]
public static void HandleState1(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.State2)]
public static void HandleState2(Packet packet, AuthSession session)
{
// Send same data back for now.
session.SendRaw(packet.Data);
}
[AuthPacket(ClientMessage.AuthRequest)]
public static void HandleAuthRequest(Packet packet, AuthSession session)
{
packet.Read<uint>(32);
packet.Read<ulong>(64);
var loginName = packet.ReadString();
Console.WriteLine($"Account '{loginName}' tries to connect.");
var account = DB.Auth.Single<Account>(a => a.Email == loginName);
if (account != null && account.Online)
{
var authComplete = new Packet(ServerMessage.AuthComplete);
authComplete.Write(0, 32);
session.Send(authComplete);
var connectToRealm = new Packet(ServerMessage.ConnectToRealm);
// Data...
session.Send(connectToRealm);
}
}
}
}
| mit | C# |
5ae3d6cc74f13a85be1117f717ce9eff4836438a | Add failing asserts | UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,ppy/osu,ppy/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu | osu.Game.Rulesets.Osu.Tests/TestSceneSpinnerApplication.cs | osu.Game.Rulesets.Osu.Tests/TestSceneSpinnerApplication.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 NUnit.Framework;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneSpinnerApplication : OsuTestScene
{
[Test]
public void TestApplyNewSpinner()
{
DrawableSpinner dho = null;
AddStep("create spinner", () => Child = dho = new DrawableSpinner(prepareObject(new Spinner
{
Position = new Vector2(256, 192),
IndexInCurrentCombo = 0,
Duration = 500,
}))
{
Clock = new FramedClock(new StopwatchClock())
});
AddStep("rotate some", () => dho.RotationTracker.AddRotation(180));
AddAssert("rotation is set", () => dho.RotationTracker.RateAdjustedRotation == 180);
AddStep("apply new spinner", () => dho.Apply(prepareObject(new Spinner
{
Position = new Vector2(256, 192),
ComboIndex = 1,
Duration = 1000,
}), null));
AddAssert("rotation is reset", () => dho.RotationTracker.RateAdjustedRotation == 0);
}
private Spinner prepareObject(Spinner circle)
{
circle.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
return circle;
}
}
}
| // 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 NUnit.Framework;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Tests.Visual;
using osuTK;
namespace osu.Game.Rulesets.Osu.Tests
{
public class TestSceneSpinnerApplication : OsuTestScene
{
[Test]
public void TestApplyNewCircle()
{
DrawableSpinner dho = null;
AddStep("create spinner", () => Child = dho = new DrawableSpinner(prepareObject(new Spinner
{
Position = new Vector2(256, 192),
IndexInCurrentCombo = 0,
Duration = 0,
}))
{
Clock = new FramedClock(new StopwatchClock())
});
AddStep("apply new spinner", () => dho.Apply(prepareObject(new Spinner
{
Position = new Vector2(256, 192),
ComboIndex = 1,
Duration = 1000,
}), null));
}
private Spinner prepareObject(Spinner circle)
{
circle.ApplyDefaults(new ControlPointInfo(), new BeatmapDifficulty());
return circle;
}
}
}
| mit | C# |
56c926ac2e5ef560bec31009be105b2317863bdf | Use less refs in NodeLookup to prevent unboxing | Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder,Arkhist/Hacknet-Pathfinder | PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs | PathfinderAPI/BaseGameFixes/Performance/NodeLookup.cs | using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(object __result)
{
ComputerLookup.PopulateLookups((Computer) __result);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(Computer), nameof(Computer.load))]
internal static void PopulateOnComputerLoad(Computer __result)
{
ComputerLookup.PopulateLookups(__result);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(out Computer __result, string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(out Computer __result, string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
} | using Hacknet;
using HarmonyLib;
using Pathfinder.Util;
namespace Pathfinder.BaseGameFixes.Performance
{
[HarmonyPatch]
internal static class NodeLookup
{
[HarmonyPostfix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.loadComputer))]
internal static void PopulateOnComputerCreation(ref object __result)
{
ComputerLookup.PopulateLookups((Computer) __result);
}
[HarmonyPostfix]
[HarmonyPatch(typeof(Computer), nameof(Computer.load))]
internal static void PopulateOnComputerLoad(ref Computer __result)
{
ComputerLookup.PopulateLookups(__result);
}
[HarmonyPrefix]
[HarmonyPatch(typeof(ComputerLoader), nameof(ComputerLoader.findComp))]
internal static bool ModifyComputerLoaderLookup(ref Computer __result, ref string target)
{
__result = ComputerLookup.FindById(target);
return false;
}
[HarmonyPrefix]
[HarmonyPatch(typeof(Programs), nameof(Programs.getComputer))]
internal static bool ModifyProgramsLookup(ref Computer __result, ref string ip_Or_ID_or_Name)
{
__result = ComputerLookup.Find(ip_Or_ID_or_Name);
return false;
}
[HarmonyPostfix]
[HarmonyPatch(typeof(OS), nameof(OS.quitGame))]
internal static void ClearOnQuitGame()
{
ComputerLookup.ClearLookups();
}
}
} | mit | C# |
704c399e78ffd4c78526b8a0a6b390d9ac6e4050 | Update version | EPTamminga/DNNFaq,EPTamminga/DNNFaq | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2011
// by DotNetNuke Corporation
//
// 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.
//
// 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.
// Review the values of the assembly attributes
[assembly:AssemblyTitle("DotNetNuke.Modules.FAQs")]
[assembly:AssemblyDescription("Open Source Web Application Framework")]
[assembly:AssemblyCompany("DotNetNuke Corporation")]
[assembly:AssemblyProduct("http://www.dotnetnuke.com")]
[assembly: AssemblyCopyright("DotNetNuke® is copyright 2002-2012 by DotNetNuke Corporation. All Rights Reserved.")]
[assembly:AssemblyTrademark("DotNetNuke")]
[assembly:ComVisibleAttribute(false)]
//The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly:Guid("1f803b5e-5536-4164-a60c-44cd582a4dde")]
// 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("5.0.2.0")]
[assembly: AssemblyFileVersion("5.0.2.0")]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
//
// DotNetNuke - http://www.dotnetnuke.com
// Copyright (c) 2002-2011
// by DotNetNuke Corporation
//
// 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.
//
// 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.
// Review the values of the assembly attributes
[assembly:AssemblyTitle("DotNetNuke.Modules.FAQs")]
[assembly:AssemblyDescription("Open Source Web Application Framework")]
[assembly:AssemblyCompany("DotNetNuke Corporation")]
[assembly:AssemblyProduct("http://www.dotnetnuke.com")]
[assembly: AssemblyCopyright("DotNetNuke® is copyright 2002-2012 by DotNetNuke Corporation. All Rights Reserved.")]
[assembly:AssemblyTrademark("DotNetNuke")]
[assembly:ComVisibleAttribute(false)]
//The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly:Guid("1f803b5e-5536-4164-a60c-44cd582a4dde")]
// 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("5.0.1.0")]
[assembly: AssemblyFileVersion("5.0.1.0")]
| mit | C# |
ed6ddefc21f6ef0605d5f7d46460f0793803a385 | Fix AssemblyInfo.cs | mganss/XmlValidator | Properties/AssemblyInfo.cs | 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("XmlValidator")]
[assembly: AssemblyDescription("Validate XML files against XML schemas.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlValidator")]
[assembly: AssemblyCopyright("Copyright © 2015 Michael Ganss")]
[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("9622fe50-2840-4771-a0b2-f7237e71b1a9")]
// 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.*")]
| 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("XmlValidator")]
[assembly: AssemblyDescription("Validate XML files against XML schemas.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("XmlValidator")]
[assembly: AssemblyCopyright("Copyright © 2015 Michael Ganss")]
[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("9622fe50-2840-4771-a0b2-f7237e71b1a9")]
// 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.*.*")]
| mit | C# |
605a62636481c8f33d71e712df2dc3e8b46bef87 | load all in current dir | tparnell8/Varanus | src/NOCQ/Extensability/Catalog.cs | src/NOCQ/Extensability/Catalog.cs | using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.Reflection;
namespace NOCQ.Extensability
{
public class Catalog
{
static DirectoryCatalog dcatalog = new DirectoryCatalog(".", "*.dll");
static AssemblyCatalog acatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
private static AggregateCatalog Cat = new AggregateCatalog(acatalog,dcatalog);
private static CompositionContainer _container = new CompositionContainer(Cat);
public CompositionContainer Container { get { return _container; } }
public Catalog()
{
_container.ComposeParts(this);
}
}
}
| using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition;
using System.Reflection;
namespace NOCQ.Extensability
{
public class Catalog
{
//static DirectoryCatalog dcatalog = new DirectoryCatalog("plugins", "*.dll");
static AssemblyCatalog acatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
private static AggregateCatalog Cat = new AggregateCatalog(acatalog);
private static CompositionContainer _container = new CompositionContainer(Cat);
public CompositionContainer Container { get { return _container; } }
public Catalog()
{
_container.ComposeParts(this);
}
}
}
| mit | C# |
08f39fa688cc5c308a92c02d0baac568a843e340 | update file exists | zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning | my_aspnetmvc_learning/Controllers/ImageController.cs | my_aspnetmvc_learning/Controllers/ImageController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
//检查文件夹
string pathDir = Server.MapPath("~/upload");
if (System.IO.File.Exists(pathDir))
{
System.IO.Directory.CreateDirectory(pathDir);
}
//保存文件
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file.IsNotNull())
{
logger.Info(string.Format("FileName : {0}", file.FileName));
file.SaveAs(filename: AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file.IsNotNull())
{
logger.Info(string.Format("FileName : {0}", file.FileName));
file.SaveAs(filename: AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | mit | C# |
d6ec72249f54286686f0059ed8589b9a91f8c708 | fix isnotnull method | zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning | my_aspnetmvc_learning/Controllers/ImageController.cs | my_aspnetmvc_learning/Controllers/ImageController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file.IsNotNull())
{
logger.Info(string.Format("FileName : {0}", file.FileName));
file.SaveAs(filename: AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NLog;
namespace my_aspnetmvc_learning.Controllers
{
public class ImageController : Controller
{
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
// GET: Upload
public ActionResult Index()
{
return View();
}
/// <summary>
/// 文件上传
/// </summary>
/// <returns></returns>
public ActionResult Upload()
{
for (var i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file.IsNotNull())
{
logger.Info("FileName : " + file.FileName);
file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName);
}
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
} | mit | C# |
efa2932a40582a5fb76fe9a17ccb18f4951dc996 | Fix incorrect font indexing in language dropdown | Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare | Assets/Scripts/Menu/Dropdowns/DropdownLanguageFontUpdater.cs | Assets/Scripts/Menu/Dropdowns/DropdownLanguageFontUpdater.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var languages = LocalizationManager.instance.getAllLanguages();
LocalizationManager.Language language = languages[0];
//Determine langauge index based on sibling position and selectable languages
int index = 0;
int objectIndex = transform.GetSiblingIndex() - 1;
for (int i = 0; i < languages.Length; i++)
{
if (!languages[i].disableSelect)
{
if (index >= objectIndex)
{
language = languages[i];
Debug.Log(textComponent.text + " is " + language.getLanguageID());
break;
}
index++;
}
}
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DropdownLanguageFontUpdater : MonoBehaviour
{
[SerializeField]
private Text textComponent;
void Start ()
{
var language = LocalizationManager.instance.getAllLanguages()[transform.GetSiblingIndex() - 1];
if (language.overrideFont != null)
{
textComponent.font = language.overrideFont;
if (language.forceUnbold)
textComponent.fontStyle = FontStyle.Normal;
}
}
void Update ()
{
}
}
| mit | C# |
b86a028392af297b9158375051444e4dec68c25d | Throw correct exceptions for IO errors | kohsuke/winsw | src/Core/WinSWCore/Util/FileHelper.cs | src/Core/WinSWCore/Util/FileHelper.cs | #if !NETCOREAPP
using System;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw GetExceptionForLastWin32Error(sourceFilePath);
}
#endif
}
#if !NETCOREAPP
private static Exception GetExceptionForLastWin32Error(string path) => Marshal.GetLastWin32Error() switch
{
2 => new FileNotFoundException(null, path), // ERROR_FILE_NOT_FOUND
3 => new DirectoryNotFoundException(), // ERROR_PATH_NOT_FOUND
5 => new UnauthorizedAccessException(), // ERROR_ACCESS_DENIED
_ => new IOException()
};
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
| #if !NETCOREAPP
using System.ComponentModel;
#endif
using System.IO;
#if !NETCOREAPP
using System.Runtime.InteropServices;
#endif
namespace winsw.Util
{
public static class FileHelper
{
public static void MoveOrReplaceFile(string sourceFileName, string destFileName)
{
#if NETCOREAPP
File.Move(sourceFileName, destFileName, true);
#else
string sourceFilePath = Path.GetFullPath(sourceFileName);
string destFilePath = Path.GetFullPath(destFileName);
if (!NativeMethods.MoveFileEx(sourceFilePath, destFilePath, NativeMethods.MOVEFILE_REPLACE_EXISTING | NativeMethods.MOVEFILE_COPY_ALLOWED))
{
throw new Win32Exception();
}
#endif
}
#if !NETCOREAPP
private static class NativeMethods
{
internal const uint MOVEFILE_REPLACE_EXISTING = 0x01;
internal const uint MOVEFILE_COPY_ALLOWED = 0x02;
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "MoveFileExW")]
internal static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, uint dwFlags);
}
#endif
}
}
| mit | C# |
2b10e18bc2827a0a0dd1730eab1cef6198e384eb | Support secure websocket | xPaw/SteamWebPipes,Celant/SteamWebPipes,Celant/SteamWebPipes,xPaw/SteamWebPipes | SteamWebPipes/Bootstrap.cs | SteamWebPipes/Bootstrap.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Fleck;
using Newtonsoft.Json;
namespace SteamWebPipes
{
internal static class Bootstrap
{
private static List<IWebSocketConnection> ConnectedClients = new List<IWebSocketConnection>();
private static void Main(string[] args)
{
FleckLog.Level = LogLevel.Debug;
var useCert = File.Exists("cert.pfx");
var server = new WebSocketServer("ws" + (useCert ? "s" : "") + "://0.0.0.0:8181");
server.SupportedSubProtocols = new[] { "steam-pics" };
if (useCert)
{
Log("Using certificate");
server.Certificate = new X509Certificate2("cert.pfx");
}
server.Start(socket =>
{
socket.OnOpen = () =>
{
ConnectedClients.Add(socket);
Log("Client #{2} connected: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, ConnectedClients.Count);
};
socket.OnClose = () =>
{
Log("Client #{2} disconnected: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, ConnectedClients.Count);
ConnectedClients.Remove(socket);
};
});
var thread = new Thread(new Steam().Tick);
thread.Name = "Steam";
thread.Start();
Console.ReadLine();
}
public static void Broadcast(AbstractEvent ev)
{
Broadcast(JsonConvert.SerializeObject(ev));
}
private static void Broadcast(string message)
{
foreach (var socket in ConnectedClients)
{
socket.Send(message);
}
}
public static void Log(string format, params object[] args)
{
Console.WriteLine("[" + DateTime.Now.ToString("R") + "] " + string.Format(format, args));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Fleck;
using Newtonsoft.Json;
namespace SteamWebPipes
{
internal static class Bootstrap
{
private static List<IWebSocketConnection> ConnectedClients = new List<IWebSocketConnection>();
private static void Main(string[] args)
{
FleckLog.Level = LogLevel.Debug;
var server = new WebSocketServer("ws://0.0.0.0:8181");
server.SupportedSubProtocols = new[] { "steam-pics" };
server.Start(socket =>
{
socket.OnOpen = () =>
{
ConnectedClients.Add(socket);
Log("Client #{2} connected: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, ConnectedClients.Count);
};
socket.OnClose = () =>
{
ConnectedClients.Remove(socket);
Log("Client #{2} disconnected: {0}:{1}", socket.ConnectionInfo.ClientIpAddress, socket.ConnectionInfo.ClientPort, ConnectedClients.Count);
};
});
var thread = new Thread(new Steam().Tick);
thread.Name = "Steam";
thread.Start();
Console.ReadLine();
}
public static void Broadcast(AbstractEvent ev)
{
Broadcast(JsonConvert.SerializeObject(ev));
}
private static void Broadcast(string message)
{
foreach (var socket in ConnectedClients)
{
socket.Send(message);
}
}
public static void Log(string format, params object[] args)
{
Console.WriteLine("[" + DateTime.Now.ToString("R") + "] " + string.Format(format, args));
}
}
}
| mit | C# |
c620efa67e1d3d93cb2a8da08e35bc4004c3540c | Update AddinganArrowHead.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/DrawingObjects/Controls/AddinganArrowHead.cs | Examples/CSharp/DrawingObjects/Controls/AddinganArrowHead.cs | using System.IO;
using Aspose.Cells;
using Aspose.Cells.Drawing;
using System.Drawing;
namespace Aspose.Cells.Examples.DrawingObjects.Controls
{
public class AddinganArrowHead
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet in the book.
Worksheet worksheet = workbook.Worksheets[0];
//Add a line to the worksheet
Aspose.Cells.Drawing.LineShape line2 = worksheet.Shapes.AddLine(7, 0, 1, 0, 85, 250);
//Set the line color
line2.LineFormat.ForeColor = Color.Blue;
//Set the line style.
line2.LineFormat.DashStyle = MsoLineDashStyle.Solid;
//Set the weight of the line.
line2.LineFormat.Weight = 3;
//Set the placement.
line2.Placement = PlacementType.FreeFloating;
//Set the line arrows.
line2.EndArrowheadWidth = MsoArrowheadWidth.Medium;
line2.EndArrowheadStyle = MsoArrowheadStyle.Arrow;
line2.EndArrowheadLength = MsoArrowheadLength.Medium;
line2.BeginArrowheadStyle = MsoArrowheadStyle.ArrowDiamond;
line2.BeginArrowheadLength = MsoArrowheadLength.Medium;
//Make the gridlines invisible in the first worksheet.
workbook.Worksheets[0].IsGridlinesVisible = false;
//Save the excel file.
workbook.Save(dataDir+ "book1.out.xls");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
using Aspose.Cells.Drawing;
using System.Drawing;
namespace Aspose.Cells.Examples.DrawingObjects.Controls
{
public class AddinganArrowHead
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook.
Workbook workbook = new Workbook();
//Get the first worksheet in the book.
Worksheet worksheet = workbook.Worksheets[0];
//Add a line to the worksheet
Aspose.Cells.Drawing.LineShape line2 = worksheet.Shapes.AddLine(7, 0, 1, 0, 85, 250);
//Set the line color
line2.LineFormat.ForeColor = Color.Blue;
//Set the line style.
line2.LineFormat.DashStyle = MsoLineDashStyle.Solid;
//Set the weight of the line.
line2.LineFormat.Weight = 3;
//Set the placement.
line2.Placement = PlacementType.FreeFloating;
//Set the line arrows.
line2.EndArrowheadWidth = MsoArrowheadWidth.Medium;
line2.EndArrowheadStyle = MsoArrowheadStyle.Arrow;
line2.EndArrowheadLength = MsoArrowheadLength.Medium;
line2.BeginArrowheadStyle = MsoArrowheadStyle.ArrowDiamond;
line2.BeginArrowheadLength = MsoArrowheadLength.Medium;
//Make the gridlines invisible in the first worksheet.
workbook.Worksheets[0].IsGridlinesVisible = false;
//Save the excel file.
workbook.Save(dataDir+ "book1.out.xls");
}
}
} | mit | C# |
05fbd081134da30cbc4b05b0226778eacaef9326 | add UseForwardedHeaders because nginx | collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists | src/FilterLists.Api/Startup.cs | src/FilterLists.Api/Startup.cs | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddFilterListsRepositories(Configuration);
services.AddFilterListsServices();
services.AddFilterListsApi();
}
public void Configure(IApplicationBuilder app)
{
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});
app.UseMvc();
}
}
} | using FilterLists.Api.DependencyInjection.Extensions;
using FilterLists.Data.DependencyInjection.Extensions;
using FilterLists.Services.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FilterLists.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddFilterListsRepositories(Configuration);
services.AddFilterListsServices();
services.AddFilterListsApi();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
} | mit | C# |
c322a086390b86f69a82a9c1d264cbf98ae4c80c | fix compile | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Cg/Daemon/CgIdentifierTooltipProvider.cs | resharper/resharper-unity/src/Cg/Daemon/CgIdentifierTooltipProvider.cs | using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Feature.Services.Descriptions;
using JetBrains.ReSharper.Feature.Services.UI;
using JetBrains.ReSharper.Plugins.Unity.Cg.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.Cg.Daemon
{
[SolutionComponent]
public class CgIdentifierTooltipProvider : IdentifierTooltipProvider<CgLanguage>
{
public CgIdentifierTooltipProvider(Lifetime lifetime, ISolution solution, IDeclaredElementDescriptionPresenter presenter, DeclaredElementPresenterTextStylesService declaredElementPresenterTextStylesService)
: base(lifetime, solution, presenter, declaredElementPresenterTextStylesService)
{
}
}
} | using JetBrains.Lifetimes;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon;
using JetBrains.ReSharper.Feature.Services.Descriptions;
using JetBrains.ReSharper.Plugins.Unity.Cg.Psi;
namespace JetBrains.ReSharper.Plugins.Unity.Cg.Daemon
{
[SolutionComponent]
public class CgIdentifierTooltipProvider : IdentifierTooltipProvider<CgLanguage>
{
public CgIdentifierTooltipProvider(Lifetime lifetime, ISolution solution, IDeclaredElementDescriptionPresenter presenter)
: base(lifetime, solution, presenter)
{
}
}
} | apache-2.0 | C# |
80c897e09b772b2d5b243bfdcd1bffba60f14a22 | Add better error logging to see why mono build is failing | ewilde/crane,ewilde/crane | src/Crane.Integration.Tests/TestUtilities/ObjectFactory.cs | src/Crane.Integration.Tests/TestUtilities/ObjectFactory.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
private static readonly ILog _log = LogManager.GetLogger(typeof(Run));
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception exception)
{
_log.ErrorFormat("Error trying to create an instance of {0}. {1}{2}", type.FullName, Environment.NewLine, exception.ToString());
}
}
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using Autofac;
using Crane.Core.Configuration.Modules;
using Crane.Core.IO;
using log4net;
namespace Crane.Integration.Tests.TestUtilities
{
public static class ioc
{
private static IContainer _container;
public static T Resolve<T>() where T : class
{
if (_container == null)
{
_container = BootStrap.Start();
}
if (_container.IsRegistered<T>())
{
return _container.Resolve<T>();
}
return ResolveUnregistered(_container, typeof(T)) as T;
}
public static object ResolveUnregistered(IContainer container, Type type)
{
var constructors = type.GetConstructors();
foreach (var constructor in constructors)
{
try
{
var parameters = constructor.GetParameters();
var parameterInstances = new List<object>();
foreach (var parameter in parameters)
{
var service = container.Resolve(parameter.ParameterType);
if (service == null) throw new Exception("Unkown dependency");
parameterInstances.Add(service);
}
return Activator.CreateInstance(type, parameterInstances.ToArray());
}
catch (Exception)
{
}
}
Debugger.Launch();
throw new Exception("No contructor was found that had all the dependencies satisfied.");
}
}
} | apache-2.0 | C# |
822f70ef7187928c92ce65d5ec7fc0cb6487a6f9 | Add GetUrlOfLatestBinary | nikeee/HolzShots | src/HolzShots.Capture.Video/Capture/Video/FFmpegManager.cs | src/HolzShots.Capture.Video/Capture/Video/FFmpegManager.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace HolzShots.Capture.Video
{
public class FFmpegManager
{
const string FFmpegExecutable = "ffmpeg.exe";
// TODO: Ask the user if he wants to use the FFmpeg on the PATH if it is present
public static bool HasFFmpegInPath()
{
var sb = new StringBuilder(Shlwapi.MAX_PATH);
sb.Append(FFmpegExecutable);
return Shlwapi.PathFindOnPath(sb, null);
}
}
record FFmpegBinaryResponse(
[property: JsonPropertyName("version")] string Version, // Version Version
[property: JsonPropertyName("permalink")] string Permalink,
[property: JsonPropertyName("bin")] Dictionary<string, FFmpegBinEntry> binaries
);
record FFmpegBinEntry(
[property: JsonPropertyName("ffmpeg")] string FFmpegUrl,
[property: JsonPropertyName("ffplay")] string? FFplayUrl,
[property: JsonPropertyName("ffprobe")] string FFprobeUrl
);
public class FFmpegFetcher
{
// TODO: Ask the user if he wants to download the binary from that source
public static async Task<string?> GetUrlOfLatestBinary()
{
using var client = new HttpClient();
var res = await client.GetAsync("https://ffbinaries.com/api/v1/version/latest");
var responseStream = await res.Content.ReadAsStreamAsync();
var parsedResponse = JsonSerializer.Deserialize<FFmpegBinaryResponse>(responseStream);
return parsedResponse?.binaries["windows-64"]?.FFplayUrl;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HolzShots.Capture.Video
{
public class FFmpegManager
{
const string FFmpegExecutable = "ffmpeg.exe";
public static bool HasFFmpegInPath()
{
var sb = new StringBuilder(Shlwapi.MAX_PATH);
sb.Append(FFmpegExecutable);
return Shlwapi.PathFindOnPath(sb, null);
}
}
}
| agpl-3.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.