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
5fe1c012dedc8ae9fa428f77c348c86a01b6ee07
Fix Stylet.Samples.RedditBrowser
canton7/Stylet,canton7/Stylet,cH40z-Lord/Stylet,cH40z-Lord/Stylet
Samples/Stylet.Samples.RedditBrowser/Pages/SubredditViewModel.cs
Samples/Stylet.Samples.RedditBrowser/Pages/SubredditViewModel.cs
using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class SubredditViewModel : Conductor<IScreen>.StackNavigation { private IPostCommentsViewModelFactory postCommentsViewModelFactory; public string Subreddit { get; set; } public SortMode SortMode { get; set; } private PostsViewModel posts; public SubredditViewModel(PostsViewModel posts, IPostCommentsViewModelFactory postCommentsViewModelFactory) { this.posts = posts; this.postCommentsViewModelFactory = postCommentsViewModelFactory; this.posts.PostCommentsOpened += (o, e) => this.OpenPostComments(e.PostId36); } protected override void OnInitialActivate() { this.DisplayName = String.Format("/r/{0}", this.Subreddit); this.posts.Subreddit = this.Subreddit; this.posts.SortMode = this.SortMode; this.ActivateItem(this.posts); } private void OpenPostComments(string postId36) { var item = this.postCommentsViewModelFactory.CreatePostCommentsViewModel(); item.PostId36 = postId36; item.Subreddit = this.Subreddit; this.ActivateItem(item); } protected override void ChangeActiveItem(IScreen newItem, bool closePrevious) { base.ChangeActiveItem(newItem, closePrevious); // If we're setting the ActiveItem to null, that means everything's been closed - close ourselves if (newItem == null) this.TryClose(); } } public interface IPostCommentsViewModelFactory { PostCommentsViewModel CreatePostCommentsViewModel(); } }
using Stylet.Samples.RedditBrowser.RedditApi; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Stylet.Samples.RedditBrowser.Pages { public class SubredditViewModel : Conductor<IScreen>.StackNavigation { private IPostCommentsViewModelFactory postCommentsViewModelFactory; public string Subreddit { get; set; } public SortMode SortMode { get; set; } private PostsViewModel posts; public SubredditViewModel(PostsViewModel posts, IPostCommentsViewModelFactory postCommentsViewModelFactory) { this.posts = posts; this.postCommentsViewModelFactory = postCommentsViewModelFactory; this.posts.PostCommentsOpened += (o, e) => this.OpenPostComments(e.PostId36); } protected override void OnInitialActivate() { this.DisplayName = String.Format("/r/{0}", this.Subreddit); this.posts.Subreddit = this.Subreddit; this.posts.SortMode = this.SortMode; this.ActivateItem(this.posts); } private void OpenPostComments(string postId36) { var item = this.postCommentsViewModelFactory.CreatePostCommentsViewModel(); item.PostId36 = postId36; this.ActivateItem(item); } protected override void ChangeActiveItem(IScreen newItem, bool closePrevious) { base.ChangeActiveItem(newItem, closePrevious); // If we're setting the ActiveItem to null, that means everything's been closed - close ourselves if (newItem == null) this.TryClose(); } } public interface IPostCommentsViewModelFactory { PostCommentsViewModel CreatePostCommentsViewModel(); } }
mit
C#
c2e4037a155ab3a78042ae45e5c29fac04db7d5c
Fix "Cannot deserialize a 'Decimal' from BsonType 'Document'." #resolved
InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform
InfinniPlatform.DocumentStorage/MongoDB/MongoDecimalBsonSerializer.cs
InfinniPlatform.DocumentStorage/MongoDB/MongoDecimalBsonSerializer.cs
using System; using MongoDB.Bson; using MongoDB.Bson.IO; using MongoDB.Bson.Serialization; namespace InfinniPlatform.DocumentStorage.MongoDB { internal class MongoDecimalBsonSerializer : MongoBsonSerializerBase<decimal> { public static readonly MongoDecimalBsonSerializer Default = new MongoDecimalBsonSerializer(); protected override void SerializeValue(BsonSerializationContext context, object value) { var number = (decimal)value; var writer = context.Writer; writer.WriteDecimal128(number); } protected override object DeserializeValue(BsonDeserializationContext context) { var reader = context.Reader; var currentBsonType = reader.GetCurrentBsonType(); Decimal128 decimal128; switch (currentBsonType) { case BsonType.Decimal128: decimal128 = reader.ReadDecimal128(); break; case BsonType.Document: // Workaroud for deserializing values like: // { "_t" : "System.Decimal", "_v" : "99.9" } decimal128 = ReadDecimalFromDocument(reader, currentBsonType); break; default: throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(ValueType)}' from BsonType '{currentBsonType}'."); } return (decimal)decimal128; } private Decimal128 ReadDecimalFromDocument(IBsonReader reader, BsonType currentBsonType) { reader.ReadStartDocument(); var memberName = reader.ReadName(); var stringValue = reader.ReadString(); if (memberName == "_t" && stringValue == typeof(decimal).FullName) { memberName = reader.ReadName(); if (memberName == "_v") { var value = reader.ReadString(); reader.ReadEndDocument(); return Decimal128.Parse(value); } } throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(ValueType)}' from BsonType '{currentBsonType}'."); } } }
using System; using MongoDB.Bson; using MongoDB.Bson.Serialization; namespace InfinniPlatform.DocumentStorage.MongoDB { internal class MongoDecimalBsonSerializer : MongoBsonSerializerBase<decimal> { public static readonly MongoDecimalBsonSerializer Default = new MongoDecimalBsonSerializer(); protected override void SerializeValue(BsonSerializationContext context, object value) { var number = (decimal)value; var writer = context.Writer; writer.WriteDecimal128(number); } protected override object DeserializeValue(BsonDeserializationContext context) { var reader = context.Reader; var currentBsonType = reader.GetCurrentBsonType(); Decimal128 decimal128; switch (currentBsonType) { case BsonType.Decimal128: decimal128 = reader.ReadDecimal128(); break; default: throw new FormatException($"Cannot deserialize a '{BsonUtils.GetFriendlyTypeName(ValueType)}' from BsonType '{currentBsonType}'."); } return (decimal)decimal128; } } }
agpl-3.0
C#
9d9d618430c78d4a55d2ef806d3eaa2a58969c6d
Add Ok return.
bigfont/webapi-cors
CORS/Controllers/ValuesController.cs
CORS/Controllers/ValuesController.cs
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do return Ok(); } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.Cors; namespace CORS.Controllers { public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "This is a CORS request.", "That works from any origin." }; } // GET api/values/another [HttpGet] [EnableCors(origins:"http://www.bigfont.ca", headers:"*", methods: "*")] public IEnumerable<string> Another() { return new string[] { "This is a CORS request.", "It works only from www.bigfont.ca." }; } public class EstimateQuery { public string username { get; set; } } public IHttpActionResult GetTitleEstimate([FromUri] EstimateQuery query) { // All the values in "query" are null or zero // Do some stuff with query if there were anything to do return new string[] { "This is a CORS request.", "That works from any origin." }; } } }
mit
C#
91b7a95485136062541252d6c8d45189a9e7d465
Update the Initialize method
BillWagner/NonVirtualEventAnalyzer
NonVirtualEventAnalyzer/NonVirtualEventAnalyzer/DiagnosticAnalyzer.cs
NonVirtualEventAnalyzer/NonVirtualEventAnalyzer/DiagnosticAnalyzer.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace NonVirtualEventAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NonVirtualEventAnalyzerAnalyzer : DiagnosticAnalyzer { public const string FieldEventDiagnosticId = "MoreEffectiveAnalyzersItem24Field"; public const string PropertyEventDiagnosticId = "MoreEffectiveAnalyzersItem24Property"; // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat. private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources)); private const string Category = "DesignPractices"; private static readonly DiagnosticDescriptor RuleField = new DiagnosticDescriptor(FieldEventDiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); private static readonly DiagnosticDescriptor RuleProperty = new DiagnosticDescriptor(PropertyEventDiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleField, RuleProperty); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeEventDeclaration, SyntaxKind.EventDeclaration, SyntaxKind.EventFieldDeclaration); } private void AnalyzeEventDeclaration(SyntaxNodeAnalysisContext obj) { throw new NotImplementedException(); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { // TODO: Replace the following code with your own analysis, generating Diagnostic objects for any issues you find var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // Find just those named type symbols with names containing lowercase letters. if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower)) { // For all such symbols, produce a diagnostic. //var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name); //context.ReportDiagnostic(diagnostic); } } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; namespace NonVirtualEventAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NonVirtualEventAnalyzerAnalyzer : DiagnosticAnalyzer { public const string FieldEventDiagnosticId = "MoreEffectiveAnalyzersItem24Field"; public const string PropertyEventDiagnosticId = "MoreEffectiveAnalyzersItem24Property"; // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat. private static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); private static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources)); private const string Category = "DesignPractices"; private static readonly DiagnosticDescriptor RuleField = new DiagnosticDescriptor(FieldEventDiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); private static readonly DiagnosticDescriptor RuleProperty = new DiagnosticDescriptor(PropertyEventDiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(RuleField, RuleProperty); public override void Initialize(AnalysisContext context) { // TODO: Consider registering other actions that act on syntax instead of or in addition to symbols context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { // TODO: Replace the following code with your own analysis, generating Diagnostic objects for any issues you find var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // Find just those named type symbols with names containing lowercase letters. if (namedTypeSymbol.Name.ToCharArray().Any(char.IsLower)) { // For all such symbols, produce a diagnostic. //var diagnostic = Diagnostic.Create(Rule, namedTypeSymbol.Locations[0], namedTypeSymbol.Name); //context.ReportDiagnostic(diagnostic); } } } }
apache-2.0
C#
ae7c5a20f4d2e98e55cb4e601a8ecc9e97c673d5
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")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [Route("single-multiple-question")] [HttpPost] /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } [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")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [Route("single-multiple-question")] [HttpPost] /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } [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#
a59a2fa6498561670823003ff7ecd97ea4d747eb
Solve build related issue
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")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> /// <returns></returns> [Route("single-multiple-question")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, 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")] public class QuestionsController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } [Route("single-multiple-question")] [HttpPost] /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> public IActionResult AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOption) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleAnswerQuestion, singleMultipleAnswerQuestionOption); return Ok(); } } }
mit
C#
0a0f2658b5fe91880e90fa390598d655541dca24
Fix CodeFactor
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/Dialog/DialogViewModelBaseOfTResult.cs
WalletWasabi.Fluent/ViewModels/Dialog/DialogViewModelBaseOfTResult.cs
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace WalletWasabi.Fluent.ViewModels.Dialog { /// <summary> /// Base ViewModel class for Dialogs that returns a value back. /// </summary> /// <typeparam name="TResult">The type of the value to be returned when the dialog is finished.</typeparam> public abstract class DialogViewModelBase<TResult> : DialogViewModelBase { public DialogViewModelBase(MainViewModel mainViewModel) : base(mainViewModel) { } private TaskCompletionSource<TResult> CurrentTaskCompletionSource { get; set; } /// <summary> /// Method to be called when the dialog intends to close /// and ready to pass a value back to the caller. /// </summary> /// <param name="value">The return value of the dialog</param> public void CloseDialog(TResult value) { CurrentTaskCompletionSource.SetResult(value); CurrentTaskCompletionSource = null; } /// <summary> /// Shows the dialog. /// </summary> /// <returns>The value to be returned when the dialog is finished.</returns> public Task<TResult> ShowDialogAsync() { if (CurrentTaskCompletionSource is { }) { throw new InvalidOperationException("Can't open a new dialog since there's already one active."); } CurrentTaskCompletionSource = new TaskCompletionSource<TResult>(); DialogHost.ShowDialog(this); DialogShown(); return CurrentTaskCompletionSource.Task; } /// <summary> /// Method that is triggered when the dialog /// is to be shown. /// </summary> protected abstract void DialogShown(); } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace WalletWasabi.Fluent.ViewModels.Dialog { /// <summary> /// Base ViewModel class for Dialogs that returns a value back. /// </summary> /// <typeparam name="TResult">The type of the value to be returned when the dialog is finished.</typeparam> public abstract class DialogViewModelBase<TResult> : DialogViewModelBase { public DialogViewModelBase(MainViewModel mainViewModel) : base(mainViewModel) { } private TaskCompletionSource<TResult> CurrentTaskCompletionSource { get; set; } /// <summary> /// Method to be called when the dialog intends to close /// and ready to pass a value back to the caller. /// </summary> /// <param name="value">The return value of the dialog</param> public void CloseDialog(TResult value) { CurrentTaskCompletionSource.SetResult(value); CurrentTaskCompletionSource = null; } /// <summary> /// Shows the dialog. /// </summary> /// <returns>The value to be returned when the dialog is finished.</returns> public Task<TResult> ShowDialogAsync() { if (CurrentTaskCompletionSource != null) { throw new InvalidOperationException("Can't open a new dialog since there's already one active."); } CurrentTaskCompletionSource = new TaskCompletionSource<TResult>(); DialogHost.ShowDialog(this); DialogShown(); return CurrentTaskCompletionSource.Task; } /// <summary> /// Method that is triggered when the dialog /// is to be shown. /// </summary> protected abstract void DialogShown(); } }
mit
C#
35113c0a784e822e34e8fa6c1059174240047ab1
Add a description
bretcope/Mayflower.NET
Mayflower/Properties/AssemblyInfo.cs
Mayflower/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("Mayflower")] [assembly: AssemblyDescription("A simple forward-only database migrator for SQL Server based on the migrator Stack Overflow uses.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mayflower")] [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("f8b16d25-faff-4605-8f17-3583795aafbd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
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("Mayflower")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mayflower")] [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("f8b16d25-faff-4605-8f17-3583795aafbd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")]
mit
C#
1f412d0337e2212440bd9cfa15db9425219c7dd0
Allow a zone and version to be specified in the tzvalidate controller
malcolmr/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,nodatime/nodatime,malcolmr/nodatime,jskeet/nodatime,jskeet/nodatime,nodatime/nodatime
src/NodaTime.Web/Controllers/TzValidateController.cs
src/NodaTime.Web/Controllers/TzValidateController.cs
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using NodaTime.Web.Models; using System.IO; using System.Linq; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { private readonly ITzdbRepository repository; public TzValidateController(ITzdbRepository repository) => this.repository = repository; [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035, string zone = null, string version = null) { if (startYear < 1 || endYear > 3000 || startYear > endYear) { return BadRequest("Invalid start/end year combination"); } var source = TzdbDateTimeZoneSource.Default; if (version != null) { var release = repository.GetRelease($"tzdb{version}.nzd"); if (release == null) { return BadRequest("Unknown version"); } source = TzdbDateTimeZoneSource.FromStream(release.GetContent()); } if (zone != null && !source.GetIds().Contains(zone)) { return BadRequest("Unknown zone"); } var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear, ZoneId = zone }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } }
// Copyright 2016 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using Microsoft.AspNetCore.Mvc; using NodaTime.TimeZones; using NodaTime.TzValidate.NodaDump; using System.IO; using System.Net; namespace NodaTime.Web.Controllers { public class TzValidateController : Controller { // This will do something soon :) [Route("/tzvalidate/generate")] public IActionResult Generate(int startYear = 1, int endYear = 2035) { var source = TzdbDateTimeZoneSource.Default; var writer = new StringWriter(); var options = new Options { FromYear = startYear, ToYear = endYear }; var dumper = new ZoneDumper(source, options); dumper.Dump(writer); return new ContentResult { Content = writer.ToString(), ContentType = "text/plain", StatusCode = (int) HttpStatusCode.OK }; } } }
apache-2.0
C#
2035883559aeca0e30b4668a2dd079e3c86def90
Update OrderManager.cs
tonyc4800/Papa_Bobs_Pizza_Challenge,tonyc4800/Papa_Bobs_Pizza_Challenge
PapaBobsPizza.Domain/OrderManager.cs
PapaBobsPizza.Domain/OrderManager.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PapaBobsPizza.Domain { public class OrderManager { public static List<DTO.OrderListDTO> GetOrders() => Persistence.OrderRepository.GetOrders(); public static void AddOrderToDB(DTO.OrderDTO newOrder) { newOrder.TotalCost = PriceManager.CalculateTotalCost(newOrder); Persistence.OrderRepository.AddOrderToDB(newOrder); } public static void CompleteOrder(Guid orderId) => Persistence.OrderRepository.CompleteOrder(orderId); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PapaBobsPizza.Domain { public class OrderManager { public static List<DTO.OrderListDTO> GetOrders() { return Persistence.OrderRepository.GetOrders(); } public static void AddOrderToDB(DTO.OrderDTO newOrder) { newOrder.TotalCost = PriceManager.CalculateTotalCost(newOrder); Persistence.OrderRepository.AddOrderToDB(newOrder); } public static void CompleteOrder(Guid orderId) { Persistence.OrderRepository.CompleteOrder(orderId); } } }
apache-2.0
C#
15bf45619270384c5b6c8a9192761925b6b755fc
Remove AssemblyFileVersion property
segrived/WTManager
WTManager/Properties/AssemblyInfo.cs
WTManager/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WTManager")] [assembly: AssemblyDescription("Control your Windows services with tray")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Babaev Evgeniy")] [assembly: AssemblyProduct("WTManager")] [assembly: AssemblyCopyright("Copyright © 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("9fad443f-f504-47fa-802c-6470413097d0")] [assembly: AssemblyVersion("0.2.*")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WTManager")] [assembly: AssemblyDescription("Control your Windows services with tray")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Babaev Evgeniy")] [assembly: AssemblyProduct("WTManager")] [assembly: AssemblyCopyright("Copyright © 2015-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("9fad443f-f504-47fa-802c-6470413097d0")] [assembly: AssemblyVersion("0.2.*")] [assembly: AssemblyFileVersion("0.2.0.0")]
mit
C#
10e52a8360f273175c2875d27fe8eb451035285d
fix NSUUID gen
aritchie/bluetoothle,aritchie/bluetoothle
Acr.Ble.iOS/Extensions.cs
Acr.Ble.iOS/Extensions.cs
using System; using Foundation; using CoreBluetooth; namespace Acr.Ble { internal static class BleExtensions { public static Guid ToGuid(this NSUuid uuid) { return Guid.ParseExact(uuid.AsString(), "d"); } public static Guid ToGuid(this CBUUID uuid) { var id = uuid.ToString(); if (id.Length == 4) id = $"0000{id}-0000-1000-8000-00805f9b34fb"; return Guid.ParseExact(id, "d"); } public static CBUUID ToCBUuid(this Guid guid) { return CBUUID.FromBytes(guid.ToByteArray()); } public static NSUuid ToNSUuid(this Guid guid) { return new NSUuid(guid.ToString()); } } }
using System; using Foundation; using CoreBluetooth; namespace Acr.Ble { internal static class BleExtensions { public static Guid ToGuid(this NSUuid uuid) { return Guid.ParseExact(uuid.AsString(), "d"); } public static Guid ToGuid(this CBUUID uuid) { var id = uuid.ToString(); if (id.Length == 4) id = $"0000{id}-0000-1000-8000-00805f9b34fb"; return Guid.ParseExact(id, "d"); } public static CBUUID ToCBUuid(this Guid guid) { return CBUUID.FromBytes(guid.ToByteArray()); } public static NSUuid ToNSUuid(this Guid guid) { return new NSUuid(guid.ToByteArray()); } } }
mit
C#
ce6e3323c0fe30f79c4704ffacebdc2f686a7d1d
handle http content provided as content
aonweb/fluent-http
AonWeb.FluentHttp/Formatter.cs
AonWeb.FluentHttp/Formatter.cs
using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using AonWeb.FluentHttp.Helpers; using AonWeb.FluentHttp.Serialization; namespace AonWeb.FluentHttp { public class Formatter : IFormatter { public Formatter() { MediaTypeFormatters = new MediaTypeFormatterCollection().FluentAdd(new StringMediaFormatter()); } public MediaTypeFormatterCollection MediaTypeFormatters { get; } public async Task<HttpContent> CreateContent(object value, ITypedBuilderContext context) { var content = value as HttpContent; if (content != null) return content; var type = context.ContentType; var mediaType = context.MediaType; var header = new MediaTypeHeaderValue(mediaType); var formatter = MediaTypeFormatters.FindWriter(type, header); if (formatter == null) throw new UnsupportedMediaTypeException(string.Format(SR.NoWriteFormatterForMimeTypeErrorFormat, type.FormattedTypeName(), mediaType), header); using (var stream = new MemoryStream()) { await formatter.WriteToStreamAsync(type, value, stream, null, null); content = new ByteArrayContent(stream.ToArray()); } formatter.SetDefaultContentHeaders(type, content.Headers, header); return content; } public Task<object> DeserializeResult(HttpResponseMessage response, ITypedBuilderContext context) { return ObjectHelpers.Deserialize(response, context.ResultType, MediaTypeFormatters, context.Token); } public Task<object> DeserializeError(HttpResponseMessage response, ITypedBuilderContext context) { return ObjectHelpers.Deserialize(response, context.ErrorType, MediaTypeFormatters, context.Token); } } }
using System.IO; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Threading.Tasks; using AonWeb.FluentHttp.Helpers; using AonWeb.FluentHttp.Serialization; namespace AonWeb.FluentHttp { public class Formatter : IFormatter { public Formatter() { MediaTypeFormatters = new MediaTypeFormatterCollection().FluentAdd(new StringMediaFormatter()); } public MediaTypeFormatterCollection MediaTypeFormatters { get; } public async Task<HttpContent> CreateContent(object value, ITypedBuilderContext context) { var type = context.ContentType; var mediaType = context.MediaType; var header = new MediaTypeHeaderValue(mediaType); var formatter = MediaTypeFormatters.FindWriter(type, header); if (formatter == null) throw new UnsupportedMediaTypeException(string.Format(SR.NoWriteFormatterForMimeTypeErrorFormat, type.FormattedTypeName(), mediaType), header); HttpContent content; using (var stream = new MemoryStream()) { await formatter.WriteToStreamAsync(type, value, stream, null, null); content = new ByteArrayContent(stream.ToArray()); } formatter.SetDefaultContentHeaders(type, content.Headers, header); return content; } public Task<object> DeserializeResult(HttpResponseMessage response, ITypedBuilderContext context) { return ObjectHelpers.Deserialize(response, context.ResultType, MediaTypeFormatters, context.Token); } public Task<object> DeserializeError(HttpResponseMessage response, ITypedBuilderContext context) { return ObjectHelpers.Deserialize(response, context.ErrorType, MediaTypeFormatters, context.Token); } } }
mit
C#
e2848a17b3827ab32e22582164eed4c233c560f0
Fix for URL Encoding
saguiitay/DropboxRestAPI,timerickson/DropboxRestAPI,hurricanepkt/DropboxRestAPI
src/DropboxRestAPI/Utils/HttpUtility.cs
src/DropboxRestAPI/Utils/HttpUtility.cs
using System; using System.Linq; namespace DropboxRestAPI.Utils { public static class HttpValueCollectionExtensions { public static HttpValueCollection ParseQueryString(this string query) { if (query == null) { throw new ArgumentNullException("query"); } if ((query.Length > 0) && (query[0] == '?')) { query = query.Substring(1); } return new HttpValueCollection(query, true); } public static string ToQueryString(this HttpValueCollection nvc, bool includePrefix = true) { string[] array = (from kvp in nvc select string.Format("{0}={1}", Uri.EscapeUriString(kvp.Key), Uri.EscapeDataString(kvp.Value))) .ToArray(); return (includePrefix ? "?" : "") + string.Join("&", array); } } }
using System; using System.Linq; namespace DropboxRestAPI.Utils { public static class HttpValueCollectionExtensions { public static HttpValueCollection ParseQueryString(this string query) { if (query == null) { throw new ArgumentNullException("query"); } if ((query.Length > 0) && (query[0] == '?')) { query = query.Substring(1); } return new HttpValueCollection(query, true); } public static string ToQueryString(this HttpValueCollection nvc, bool includePrefix = true) { string[] array = (from kvp in nvc select string.Format("{0}={1}", Uri.EscapeUriString(kvp.Key), Uri.EscapeUriString(kvp.Value))) .ToArray(); return (includePrefix ? "?" : "") + string.Join("&", array); } } }
mit
C#
21922315f93653e6a95194fac13f7b7cf0be06de
add running message
tsqllint/tsqllint,tsqllint/tsqllint
source/TSQLLint/Program.cs
source/TSQLLint/Program.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using TSQLLint.Infrastructure.Reporters; namespace TSQLLint { public class Program { [ExcludeFromCodeCoverage] public static void Main(string[] args) { try { NonBlockingConsole.WriteLine("running tsqllint"); var application = new Application(args, new ConsoleReporter()); application.Run(); Task.Run(() => { while (NonBlockingConsole.messageQueue.Count > 0) { } }).Wait(); } catch (Exception exception) { Console.WriteLine("TSQLLint encountered a problem."); Console.WriteLine(exception); } } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using TSQLLint.Infrastructure.Reporters; namespace TSQLLint { public class Program { [ExcludeFromCodeCoverage] public static void Main(string[] args) { try { var application = new Application(args, new ConsoleReporter()); application.Run(); Task.Run(() => { while (NonBlockingConsole.messageQueue.Count > 0) { } }).Wait(); } catch (Exception exception) { Console.WriteLine("TSQLLint encountered a problem."); Console.WriteLine(exception); } } } }
mit
C#
5a9f27f3210e140242d91f6ff0763feb202e38f3
Remove semicolon from view
ritterim/AspNetBrowserLocale,kendaleiv/AspNetBrowserLocale
src/Mvc5Sample/Views/Shared/_Layout.cshtml
src/Mvc5Sample/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - AspNetBrowserLocale Mvc5Sample</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/Content/Site.css" /> </head> <body> <div class="container body-content"> @RenderBody() </div> <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script> @Html.InitializeLocaleDateTime() @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - AspNetBrowserLocale Mvc5Sample</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/Content/Site.css" /> </head> <body> <div class="container body-content"> @RenderBody() </div> <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script> <script src="https://ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.min.js"></script> @Html.InitializeLocaleDateTime(); @RenderSection("scripts", required: false) </body> </html>
mit
C#
804d2768f7c9ba94e30c91531720d3a6d74b5db3
Update version
takuya-takeuchi/RedArmory
source/RedArmory/AssemblyProperty.cs
source/RedArmory/AssemblyProperty.cs
namespace Ouranos.RedArmory { internal static class AssemblyProperty { /// <summary> /// アセンブリ マニフェストに含める、製品名に関するカスタム属性を定義します。 /// </summary> public const string Product = "Red Armory"; /// <summary> /// RedArmory.exe の説明を指定します。 /// </summary> public const string Title = "Red Armory"; /// <summary> /// アセンブリ マニフェストに含める、会社名に関するカスタム属性を定義します。 /// </summary> public const string Company = ""; /// <summary> /// アセンブリ マニフェストに含める、著作権に関するカスタム属性を表します。 /// </summary> public const string Copyright = "Copyright © Takuya Takeuchi All Rights Reserved."; /// <summary> /// アセンブリ マニフェストに含める、ファイル バージョンを定義します。 /// </summary> public const string FileVersion = "1.5.0.0"; /// <summary> /// アセンブリ マニフェストに含める、アセンブリ バージョンを定義します。 /// </summary> public const string Version = "1.5.0.0"; } }
namespace Ouranos.RedArmory { internal static class AssemblyProperty { /// <summary> /// アセンブリ マニフェストに含める、製品名に関するカスタム属性を定義します。 /// </summary> public const string Product = "Red Armory"; /// <summary> /// RedArmory.exe の説明を指定します。 /// </summary> public const string Title = "Red Armory"; /// <summary> /// アセンブリ マニフェストに含める、会社名に関するカスタム属性を定義します。 /// </summary> public const string Company = ""; /// <summary> /// アセンブリ マニフェストに含める、著作権に関するカスタム属性を表します。 /// </summary> public const string Copyright = "Copyright © Takuya Takeuchi All Rights Reserved."; /// <summary> /// アセンブリ マニフェストに含める、ファイル バージョンを定義します。 /// </summary> public const string FileVersion = "1.1.1.0"; /// <summary> /// アセンブリ マニフェストに含める、アセンブリ バージョンを定義します。 /// </summary> public const string Version = "1.1.1.0"; } }
mit
C#
00b93cd8da3b9509bba3eb453c6a1d1cf7cd7d35
include exceptions in logs
ArsenShnurkov/BitSharp
BitSharp.Node/LoggingModule.cs
BitSharp.Node/LoggingModule.cs
using Ninject; using Ninject.Modules; using NLog; using NLog.Config; using NLog.Targets; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitSharp.Node { public class LoggingModule : NinjectModule { private readonly LogLevel logLevel; public LoggingModule(LogLevel logLevel) { this.logLevel = logLevel; } public override void Load() { // initialize logging configuration var config = new LoggingConfiguration(); // create console target var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); // console settings consoleTarget.Layout = "${message} ${exception}"; // console rules config.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget)); // create file target var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // file settings fileTarget.FileName = "${specialfolder:folder=localapplicationdata}/BitSharp/BitSharp.log"; fileTarget.Layout = "${message} ${exception}"; fileTarget.DeleteOldFileOnStartup = true; // file rules config.LoggingRules.Add(new LoggingRule("*", logLevel, fileTarget)); // activate configuration and bind LogManager.Configuration = config; this.Kernel.Bind<Logger>().ToMethod(context => LogManager.GetLogger("BitSharp")); } } }
using Ninject; using Ninject.Modules; using NLog; using NLog.Config; using NLog.Targets; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BitSharp.Node { public class LoggingModule : NinjectModule { private readonly LogLevel logLevel; public LoggingModule(LogLevel logLevel) { this.logLevel = logLevel; } public override void Load() { // initialize logging configuration var config = new LoggingConfiguration(); // create console target var consoleTarget = new ColoredConsoleTarget(); config.AddTarget("console", consoleTarget); // console settings consoleTarget.Layout = "${message}"; // console rules config.LoggingRules.Add(new LoggingRule("*", logLevel, consoleTarget)); // create file target var fileTarget = new FileTarget(); config.AddTarget("file", fileTarget); // file settings fileTarget.FileName = "${specialfolder:folder=localapplicationdata}/BitSharp/BitSharp.log"; fileTarget.Layout = "${message}"; fileTarget.DeleteOldFileOnStartup = true; // file rules config.LoggingRules.Add(new LoggingRule("*", logLevel, fileTarget)); // activate configuration and bind LogManager.Configuration = config; this.Kernel.Bind<Logger>().ToMethod(context => LogManager.GetLogger("BitSharp")); } } }
unlicense
C#
84195930bcb1e6d0f4b6eb4cc9dc85d5238aae7f
add reloadOnChange for Log4NetLoggerFactory
zclmoon/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,Nongzhsh/aspnetboilerplate,carldai0106/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,andmattia/aspnetboilerplate,andmattia/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,Nongzhsh/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate,carldai0106/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,carldai0106/aspnetboilerplate,zclmoon/aspnetboilerplate,luchaoshuai/aspnetboilerplate,Nongzhsh/aspnetboilerplate,ilyhacker/aspnetboilerplate,verdentk/aspnetboilerplate,andmattia/aspnetboilerplate,virtualcca/aspnetboilerplate,ryancyq/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,zclmoon/aspnetboilerplate
src/Abp.Castle.Log4Net/Castle/Logging/Log4Net/Log4NetLoggerFactory.cs
src/Abp.Castle.Log4Net/Castle/Logging/Log4Net/Log4NetLoggerFactory.cs
using System; using System.IO; using System.Xml; using Abp.Reflection.Extensions; using Castle.Core.Logging; using log4net; using log4net.Config; using log4net.Repository; namespace Abp.Castle.Logging.Log4Net { public class Log4NetLoggerFactory : AbstractLoggerFactory { internal const string DefaultConfigFileName = "log4net.config"; private readonly ILoggerRepository _loggerRepository; public Log4NetLoggerFactory() : this(DefaultConfigFileName) { } public Log4NetLoggerFactory(string configFileName, bool reloadOnChange = false) { _loggerRepository = LogManager.CreateRepository( typeof(Log4NetLoggerFactory).GetAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy) ); if (reloadOnChange) { XmlConfigurator.ConfigureAndWatch(_loggerRepository, new FileInfo(configFileName)); } else { var log4NetConfig = new XmlDocument(); log4NetConfig.Load(File.OpenRead(configFileName)); XmlConfigurator.Configure(_loggerRepository, log4NetConfig["log4net"]); } } public override ILogger Create(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } return new Log4NetLogger(LogManager.GetLogger(_loggerRepository.Name, name), this); } public override ILogger Create(string name, LoggerLevel level) { throw new NotSupportedException("Logger levels cannot be set at runtime. Please review your configuration file."); } } }
using System; using System.IO; using System.Xml; using Abp.Reflection.Extensions; using Castle.Core.Logging; using log4net; using log4net.Config; using log4net.Repository; namespace Abp.Castle.Logging.Log4Net { public class Log4NetLoggerFactory : AbstractLoggerFactory { internal const string DefaultConfigFileName = "log4net.config"; private readonly ILoggerRepository _loggerRepository; public Log4NetLoggerFactory() : this(DefaultConfigFileName) { } public Log4NetLoggerFactory(string configFileName) { _loggerRepository = LogManager.CreateRepository( typeof(Log4NetLoggerFactory).GetAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy) ); var log4NetConfig = new XmlDocument(); log4NetConfig.Load(File.OpenRead(configFileName)); XmlConfigurator.Configure(_loggerRepository, log4NetConfig["log4net"]); } public override ILogger Create(string name) { if (name == null) { throw new ArgumentNullException(nameof(name)); } return new Log4NetLogger(LogManager.GetLogger(_loggerRepository.Name, name), this); } public override ILogger Create(string name, LoggerLevel level) { throw new NotSupportedException("Logger levels cannot be set at runtime. Please review your configuration file."); } } }
mit
C#
75cac7340fa0f4931cbdcdc3b02ff96bc55bae4e
test results were duplicated because of lists not being cleared
continuoustests/AutoTest.Net,acken/AutoTest.Net,acken/AutoTest.Net,acken/AutoTest.Net,continuoustests/AutoTest.Net,continuoustests/AutoTest.Net,acken/AutoTest.Net,continuoustests/AutoTest.Net,continuoustests/AutoTest.Net,acken/AutoTest.Net,acken/AutoTest.Net,continuoustests/AutoTest.Net
src/AutoTest.TestRunner/AutoTest.TestRunners.Shared/TestRunProcess.cs
src/AutoTest.TestRunner/AutoTest.TestRunners.Shared/TestRunProcess.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AutoTest.TestRunners.Shared.Options; using System.Threading; using AutoTest.TestRunners.Shared.Results; using AutoTest.TestRunners.Shared.Targeting; using AutoTest.TestRunners.Shared.AssemblyAnalysis; namespace AutoTest.TestRunners.Shared { public class TestRunProcess { private static List<TestResult> _results = new List<TestResult>(); private ITargetFrameworkLocator _locator; private ITestRunProcessFeedback _feedback = null; public static void AddResults(IEnumerable<TestResult> results) { lock (_results) { _results.AddRange(results); } } public TestRunProcess() { _locator = new TargetFrameworkLocator(); } public TestRunProcess(ITestRunProcessFeedback feedback) { _locator = new TargetFrameworkLocator(); _feedback = feedback; } public IEnumerable<TestResult> ProcessTestRuns(RunOptions options) { _results = new List<TestResult>(); var workers = new List<Thread>(); var testRuns = getTargetedRuns(options); foreach (var target in testRuns) { var process = new TestProcess(target, _feedback); var thread = new Thread(new ThreadStart(process.Start)); thread.Start(); workers.Add(thread); } foreach (var worker in workers) worker.Join(); return _results; } private IEnumerable<TargetedRun> getTargetedRuns(RunOptions options) { var assembler = new TargetedRunAssembler(options, _locator); return assembler.Assemble(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AutoTest.TestRunners.Shared.Options; using System.Threading; using AutoTest.TestRunners.Shared.Results; using AutoTest.TestRunners.Shared.Targeting; using AutoTest.TestRunners.Shared.AssemblyAnalysis; namespace AutoTest.TestRunners.Shared { public class TestRunProcess { private static List<TestResult> _results = new List<TestResult>(); private ITargetFrameworkLocator _locator; private ITestRunProcessFeedback _feedback = null; public static void AddResults(IEnumerable<TestResult> results) { lock (_results) { _results.AddRange(results); } } public TestRunProcess() { _locator = new TargetFrameworkLocator(); } public TestRunProcess(ITestRunProcessFeedback feedback) { _locator = new TargetFrameworkLocator(); _feedback = feedback; } public IEnumerable<TestResult> ProcessTestRuns(RunOptions options) { var workers = new List<Thread>(); var testRuns = getTargetedRuns(options); foreach (var target in testRuns) { var process = new TestProcess(target, _feedback); var thread = new Thread(new ThreadStart(process.Start)); thread.Start(); workers.Add(thread); } foreach (var worker in workers) worker.Join(); return _results; } private IEnumerable<TargetedRun> getTargetedRuns(RunOptions options) { var assembler = new TargetedRunAssembler(options, _locator); return assembler.Assemble(); } } }
mit
C#
4bdcdad81a6f70987f0d8c152402ce37fca979ca
check status code in httpclientservice
srdjan-bozovic/sinergijaspeakers013
src/MsCampus.Win8.Shared/Implementation/Services/HttpClientService.cs
src/MsCampus.Win8.Shared/Implementation/Services/HttpClientService.cs
using MsCampus.Win8.Shared.Contracts.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MsCampus.Win8.Shared.Implementation.Services { public class HttpClientService : IHttpClientService { public async Task<T> GetJsonAsync<T>(string url, CancellationToken cancellationToken) { var httpClientHandler = new HttpClientHandler(); httpClientHandler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; var client = new HttpClient(httpClientHandler); var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); if (response != null && (response.StatusCode == System.Net.HttpStatusCode.OK)) return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); else return default(T); } } }
using MsCampus.Win8.Shared.Contracts.Services; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MsCampus.Win8.Shared.Implementation.Services { public class HttpClientService : IHttpClientService { public async Task<T> GetJsonAsync<T>(string url, CancellationToken cancellationToken) { var httpClientHandler = new HttpClientHandler(); httpClientHandler.AutomaticDecompression = System.Net.DecompressionMethods.GZip; var client = new HttpClient(httpClientHandler); var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false); if (response != null) return JsonConvert.DeserializeObject<T>(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); else return default(T); } } }
unlicense
C#
222c970969d9682c86e0e048fbd5c8e759eedbd1
Update page title.
neptuo/com.neptuo.go,neptuo/com.neptuo.go
src/WebSite/Views/Shared/_Layout.cshtml
src/WebSite/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>List of all links to all Neptuo pages</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/web.css" rel="stylesheet" /> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - My ASP.NET Application</title> <link href="~/Content/bootstrap.min.css" rel="stylesheet" /> <link href="~/Content/web.css" rel="stylesheet" /> </head> <body> <div class="container"> @RenderBody() </div> </body> </html>
apache-2.0
C#
1d6712a40cfd3db0e04078e96089c47fd8547360
Change Scope to support multi-tenant scenarios
mag-dev/chassis
src/Chassis/Startup/StartUpFeature.cs
src/Chassis/Startup/StartUpFeature.cs
using Autofac; using Chassis.Features; using Chassis.Types; namespace Chassis.Startup { public class StartupFeature : Feature { public override void RegisterComponents(ContainerBuilder builder, TypePool pool) { builder.RegisterType<StartupBootstrapper>() .InstancePerLifetimeScope() .AsSelf(); var actions = pool.FindImplementorsOf<IStartupStep>(); foreach (var action in actions) { builder.RegisterType(action) .As<IStartupStep>() .AsSelf(); } var webActions = pool.FindImplementorsOf<IWebStartupStep>(); foreach (var action in webActions) { builder.RegisterType(action) .As<IWebStartupStep>() .AsSelf(); } } } }
using Autofac; using Chassis.Features; using Chassis.Types; namespace Chassis.Startup { public class StartupFeature : Feature { public override void RegisterComponents(ContainerBuilder builder, TypePool pool) { builder.RegisterType<StartupBootstrapper>() .SingleInstance() .AsSelf(); var actions = pool.FindImplementorsOf<IStartupStep>(); foreach (var action in actions) { builder.RegisterType(action) .As<IStartupStep>() .AsSelf(); } var webActions = pool.FindImplementorsOf<IWebStartupStep>(); foreach (var action in webActions) { builder.RegisterType(action) .As<IWebStartupStep>() .AsSelf(); } } } }
apache-2.0
C#
c0da41da8fc576bfe5907a1acc735e0a2a8487f2
Update MarkWragg.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/MarkWragg.cs
src/Firehose.Web/Authors/MarkWragg.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MarkWragg : IAmACommunityMember { public string FirstName => "Mark"; public string LastName => "Wragg"; public string ShortBioOrTagLine => "Operations Manager interested in all things Windows, Powershell, AWS, Azure, Chef etc."; public string StateOrRegion => "Hook, England"; public string EmailAddress => "mark@wragg.io"; public string GitHubHandle => "markwragg"; public string TwitterHandle => "markwragg"; public string GravatarHash => "e8e1b8d0e98f84b10a03f9430334b02f"; public GeoPosition Position => new GeoPosition(51.2809060,-0.9630430); public Uri WebSite => new Uri("https://wragg.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://wragg.io/feed.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MarkWragg : IAmACommunityMember { public string FirstName => "Mark"; public string LastName => "Wragg"; public string ShortBioOrTagLine => "Operations Manager interested in all things Windows, Powershell, AWS, Azure, Chef etc."; public string StateOrRegion => "Hook, England"; public string EmailAddress => "mark@wragg.io"; public string GitHubHandle => "markwragg"; public string TwitterHandle => "markwragg"; public string GravatarHash => "e8e1b8d0e98f84b10a03f9430334b02f"; public GeoPosition Position => new GeoPosition(51.2809060,-0.9630430); public Uri WebSite => new Uri("https://wragg.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://wragg.io/tag/powershell/rss"); } } public string FeedLanguageCode => "en"; } }
mit
C#
9344d41e3a91e0597e45429a3af4db5815ce4693
Change default for DetailedAppointments to 'false'
waf/CalSync
src/CalSync/Infrastructure/Config.cs
src/CalSync/Infrastructure/Config.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool Send { get; private set; } public bool DetailedAppointment { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "false"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; namespace CalSync.Infrastructure { class Config { public int SyncRangeDays { get; private set; } public string TargetEmailAddress { get; private set; } public bool Receive { get; private set; } public bool DetailedAppointment { get; private set; } public bool Send { get; private set; } public String ErrorMessage { get; private set; } public static Config Read() { try { return new Config() { SyncRangeDays = int.Parse(ConfigurationManager.AppSettings["SyncRangeDays"]), TargetEmailAddress = ConfigurationManager.AppSettings["TargetEmailAddress"], Receive = bool.Parse(ConfigurationManager.AppSettings["Receive"] ?? "true"), DetailedAppointment = bool.Parse(ConfigurationManager.AppSettings["DetailedAppointment"] ?? "true"), Send = bool.Parse(ConfigurationManager.AppSettings["Send"] ?? "true"), }; } catch(Exception e) { if(e is ConfigurationErrorsException || e is FormatException || e is OverflowException ) { return new Config() { ErrorMessage = e.Message }; } throw; } } } }
mit
C#
48784e5259b5faad984a76f0d4140dacae5b34a3
add lnk prefix to links generated in the list
mvbalaw/FluentWebControls
src/FluentWebControls/CommandItem.cs
src/FluentWebControls/CommandItem.cs
using System; using System.Text; using FluentWebControls.Extensions; namespace FluentWebControls { public class CommandItem { public static CommandItem<T> For<T>(Func<T, string> getHref) { return new CommandItem<T>(getHref); } } public interface ICommandItem { AlignAttribute Align { get; } string Alt { get; } //string Href { get; } string CssClass { get; } string ImageUrl { get; } string Text { get; } } public class CommandItem<T> : ICommandItem, IListItem<T> { private readonly Func<T, string> _getLink; public CommandItem(Func<T, string> getLink) { _getLink = getLink; Align = AlignAttribute.Left; } internal AlignAttribute Align { private get; set; } internal string Alt { private get; set; } internal string CssClass { private get; set; } internal string ImageUrl { private get; set; } internal string Text { private get; set; } string ICommandItem.Text { get { return Text; } } string ICommandItem.ImageUrl { get { return ImageUrl; } } string ICommandItem.Alt { get { return Alt; } } AlignAttribute ICommandItem.Align { get { return Align; } } string ICommandItem.CssClass { get { return CssClass; } } public StringBuilder Render(T item) { var listItem = new StringBuilder(); listItem.Append("<"); listItem.Append("div"); listItem.Append(Align.Text.CreateQuotedAttribute("align")); listItem.Append(">"); string link = getLink(item).ToString(); listItem.Append(link); listItem.Append("</div>"); return listItem; } private LinkData getLink(T item) { string navigateUrl = _getLink(item); string linkId = String.Format("lnk{0}", navigateUrl.Replace('/', '_').TrimStart(new[] { '_' })); return new LinkData().WithId(linkId).WithUrl(navigateUrl).WithLinkText(Text).WithLinkImageUrl(ImageUrl, Alt); } } }
using System; using System.Text; using FluentWebControls.Extensions; namespace FluentWebControls { public class CommandItem { public static CommandItem<T> For<T>(Func<T, string> getHref) { return new CommandItem<T>(getHref); } } public interface ICommandItem { AlignAttribute Align { get; } string Alt { get; } //string Href { get; } string CssClass { get; } string ImageUrl { get; } string Text { get; } } public class CommandItem<T> : ICommandItem, IListItem<T> { private readonly Func<T, string> _getLink; public CommandItem(Func<T, string> getLink) { _getLink = getLink; Align = AlignAttribute.Left; } internal AlignAttribute Align { private get; set; } internal string Alt { private get; set; } internal string CssClass { private get; set; } internal string ImageUrl { private get; set; } internal string Text { private get; set; } string ICommandItem.Text { get { return Text; } } string ICommandItem.ImageUrl { get { return ImageUrl; } } string ICommandItem.Alt { get { return Alt; } } AlignAttribute ICommandItem.Align { get { return Align; } } string ICommandItem.CssClass { get { return CssClass; } } public StringBuilder Render(T item) { var listItem = new StringBuilder(); listItem.Append("<"); listItem.Append("div"); listItem.Append(Align.Text.CreateQuotedAttribute("align")); listItem.Append(">"); string link = getLink(item).ToString(); listItem.Append(link); listItem.Append("</div>"); return listItem; } private LinkData getLink(T item) { string navigateUrl = _getLink(item); string linkId = navigateUrl.Replace('/', '_').TrimStart(new[] { '_' }); return new LinkData().WithId(linkId).WithUrl(navigateUrl).WithLinkText(Text).WithLinkImageUrl(ImageUrl, Alt); } } }
mit
C#
2f59889835b1797b6f31f2366de3c0a509fc7b82
add DisposableAction
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/NullDisposable.cs
src/WeihanLi.Common/NullDisposable.cs
using System; using System.Threading; namespace WeihanLi.Common { /// <summary> /// A singleton disposable that does nothing when disposed. /// </summary> public sealed class NullDisposable : IDisposable { private NullDisposable() { } public void Dispose() { } /// <summary> /// Gets the instance of <see cref="NullDisposable"/>. /// </summary> public static NullDisposable Instance { get; } = new NullDisposable(); } public sealed class DisposableAction : IDisposable { public static readonly DisposableAction Empty = new DisposableAction(null); private Action _disposeAction; public DisposableAction(Action disposeAction) { _disposeAction = disposeAction; } public void Dispose() { Interlocked.Exchange(ref _disposeAction, null)?.Invoke(); } } }
using System; namespace WeihanLi.Common { /// <summary> /// A singleton disposable that does nothing when disposed. /// </summary> public sealed class NullDisposable : IDisposable { private NullDisposable() { } public void Dispose() { } /// <summary> /// Gets the instance of <see cref="NullDisposable"/>. /// </summary> public static NullDisposable Instance { get; } = new NullDisposable(); } }
mit
C#
7a5b9c5df687d977868c98c0eb38b85ae68a660c
Add ignoredFiles array with files to be ignored
Voxelgon/Voxelgon,Voxelgon/Voxelgon
Assets/Plugins/Voxelgon/Asset.cs
Assets/Plugins/Voxelgon/Asset.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.IO; using SimpleJSON; namespace Voxelgon{ static class Asset{ static string resourcePath; static string[] ignoredFiles= new string[] { ".[Dd][Ss]_[Ss]tore$", ".[Mm]eta$" }; //returns TRUE if the given path is ignored static public bool Ignored(string path){ foreach (string r in ignoredFiles) { if (Regex.Match(path, r).Success) { return true; } } return false; } //returns the parent (../) directory of the given path static public string Parent(string path) { string parent = Directory.GetParent(path).FullName; return parent; } //returns a list of files under the given path directory static public List<string> GetFiles(string path) { List<string> filesRaw = new List<string>(Directory.GetFiles(path)); List<string> files = new List<string>(); foreach(string file in filesRaw){ if(!Ignored(file)){ files.Add(file); } } return files; } //returns a list of directories under the given directory static public List<string> GetDirectories(string path) { List<string> dirs = new List<string>(Directory.GetDirectories(path)); return dirs; } //returns a list of all files under the given directory in the file tree static public List<string> FilesUnderDirectory(string path) { List<string> directories = GetDirectories(path); List<string> files = GetFiles(path); foreach (string dir in directories){ files.AddRange(FilesUnderDirectory(dir)); } return files; } //imports assets (all testing code right now) static public void Import() { resourcePath = Parent(Application.dataPath) + "/Resources"; Debug.Log(resourcePath); foreach (string path in FilesUnderDirectory(resourcePath)) { Debug.Log(path); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using SimpleJSON; namespace Voxelgon{ static class Asset{ static string resourcePath; //returns the parent (../) directory of the given path static public string Parent(string path) { string parent = Directory.GetParent(path).FullName; return parent; } //returns a list of files under the given path directory static public List<string> GetFiles(string path) { List<string> files = new List<string>(Directory.GetFiles(path)); return files; } //returns a list of directories under the given directory static public List<string> GetDirectories(string path) { List<string> files = new List<string>(Directory.GetDirectories(path)); return files; } //returns a list of all files under the given directory in the file tree static public List<string> FilesUnderDirectory(string path) { List<string> directories = GetDirectories(path); List<string> files = GetFiles(path); foreach (string dir in directories){ files.AddRange(FilesUnderDirectory(dir)); } return files; } //imports assets (all testing code right now) static public void Import() { resourcePath = Parent(Application.dataPath) + "/Resources"; Debug.Log(resourcePath); foreach (string path in FilesUnderDirectory(resourcePath)) { Debug.Log(path); } } } }
apache-2.0
C#
cc3ba394afa45c733fec1c6e29e856d6f035af15
Change copyright.
daniellor/My-FyiReporting,chripf/My-FyiReporting,daniellor/My-FyiReporting,daniellor/My-FyiReporting,majorsilence/My-FyiReporting,chripf/My-FyiReporting,chripf/My-FyiReporting,daniellor/My-FyiReporting,daniellor/My-FyiReporting,maratoss/My-FyiReporting,majorsilence/My-FyiReporting,maratoss/My-FyiReporting,daniellor/My-FyiReporting,chripf/My-FyiReporting,majorsilence/My-FyiReporting,majorsilence/My-FyiReporting,majorsilence/My-FyiReporting,daniellor/My-FyiReporting,maratoss/My-FyiReporting,chripf/My-FyiReporting,majorsilence/My-FyiReporting,maratoss/My-FyiReporting,chripf/My-FyiReporting,chripf/My-FyiReporting,majorsilence/My-FyiReporting,maratoss/My-FyiReporting,maratoss/My-FyiReporting,maratoss/My-FyiReporting
RdlEngine/AssemblyInfo.cs
RdlEngine/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // // 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("RDL Engine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("My-FyiReporting Software")] [assembly: AssemblyProduct("RDL Project")] [assembly: AssemblyCopyright("Copyright (C) 2011-2012 Peter Gill")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.*")] [assembly: AllowPartiallyTrustedCallers] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyName("")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Security; // // 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("RDL Engine")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("fyiReporting Software, LLC")] [assembly: AssemblyProduct("RDL Project")] [assembly: AssemblyCopyright("Copyright (C) 2004-2008 fyiReporting Software, LLC")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("4.5.*")] [assembly: AllowPartiallyTrustedCallers] // // In order to sign your assembly you must specify a key to use. Refer to the // Microsoft .NET Framework documentation for more information on assembly signing. // // Use the attributes below to control which key is used for signing. // // Notes: // (*) If no key is specified, the assembly is not signed. // (*) KeyName refers to a key that has been installed in the Crypto Service // Provider (CSP) on your machine. KeyFile refers to a file which contains // a key. // (*) If the KeyFile and the KeyName values are both specified, the // following processing occurs: // (1) If the KeyName can be found in the CSP, that key is used. // (2) If the KeyName does not exist and the KeyFile does exist, the key // in the KeyFile is installed into the CSP and used. // (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility. // When specifying the KeyFile, the location of the KeyFile should be // relative to the project output directory which is // %Project Directory%\obj\<configuration>. For example, if your KeyFile is // located in the project directory, you would specify the AssemblyKeyFile // attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")] // (*) Delay Signing is an advanced option - see the Microsoft .NET Framework // documentation for more information on this. // [assembly: AssemblyDelaySign(false)] [assembly: AssemblyKeyName("")]
apache-2.0
C#
83205cc1c010a740ad0173d3d8979c9387dc6926
Make sure ResourcePump Ratio is non-negative.
allista/AT_Utils
Resources/ResourcePump.cs
Resources/ResourcePump.cs
// ResourcePump.cs // // Author: // Allis Tauri <allista@gmail.com> // // Copyright (c) 2016 Allis Tauri using UnityEngine; namespace AT_Utils { public class ResourcePump { const float eps = 1e-7f; const float min_request = 1e-5f; float request; readonly Part part; public readonly PartResourceDefinition Resource; public float Requested { get; private set; } public float Result { get; private set; } public float Ratio { get { return Mathf.Abs(Result/Requested); } } public bool PartialTransfer { get { return Mathf.Abs(Requested)-Mathf.Abs(Result) > eps; } } public bool Valid { get { return part != null; } } public ResourcePump(Part part, int res_ID) { Resource = PartResourceLibrary.Instance.GetDefinition(res_ID); if(Resource != null) this.part = part; else Utils.Log("WARNING: Cannot find a resource with '{}' ID in the library.", res_ID); } public ResourcePump(Part part, string res_name) { Resource = PartResourceLibrary.Instance.GetDefinition(res_name); if(Resource != null) this.part = part; else Utils.Log("WARNING: Cannot find '{}' in the resource library.", res_name); } public void RequestTransfer(float dR) { request += dR; } public bool TransferResource() { if(Mathf.Abs(request) <= min_request) return false; Result = part.RequestResource(Resource.id, request); Requested = request; request = 0; return true; } public void Clear() { request = Requested = Result = 0; } public void Revert() { if(Result.Equals(0)) return; part.RequestResource(Resource.id, -Result); request = Result; Requested = Result = 0; } } }
// ResourcePump.cs // // Author: // Allis Tauri <allista@gmail.com> // // Copyright (c) 2016 Allis Tauri using UnityEngine; namespace AT_Utils { public class ResourcePump { const float eps = 1e-7f; const float min_request = 1e-5f; float request; readonly Part part; public readonly PartResourceDefinition Resource; public float Requested { get; private set; } public float Result { get; private set; } public float Ratio { get { return Result/Requested; } } public bool PartialTransfer { get { return Mathf.Abs(Requested)-Mathf.Abs(Result) > eps; } } public bool Valid { get { return part != null; } } public ResourcePump(Part part, int res_ID) { Resource = PartResourceLibrary.Instance.GetDefinition(res_ID); if(Resource != null) this.part = part; else Utils.Log("WARNING: Cannot find a resource with '{}' ID in the library.", res_ID); } public ResourcePump(Part part, string res_name) { Resource = PartResourceLibrary.Instance.GetDefinition(res_name); if(Resource != null) this.part = part; else Utils.Log("WARNING: Cannot find '{}' in the resource library.", res_name); } public void RequestTransfer(float dR) { request += dR; } public bool TransferResource() { if(Mathf.Abs(request) <= min_request) return false; Result = part.RequestResource(Resource.id, request); Requested = request; request = 0; return true; } public void Clear() { request = Requested = Result = 0; } public void Revert() { if(Result.Equals(0)) return; part.RequestResource(Resource.id, -Result); request = Result; Requested = Result = 0; } } }
mit
C#
2f81e5d2bd8270d2a9ac321e04500b7a455ee419
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.4.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [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("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.*")]
mit
C#
b7d84b886e8e3604b427a2e7a5723d7290d9d492
Fix unit test after merging in new Component SetStateAsync method signatures - surprised it wasn't a compile time failure for ambiguous call
ProductiveRage/Bridge.React,ProductiveRage/Bridge.React
Bridge.React.Tests/PureComponentTests.cs
Bridge.React.Tests/PureComponentTests.cs
using System; using System.Threading.Tasks; using static Bridge.QUnit.QUnit; namespace Bridge.React.Tests { public static class PureComponentTests { public static void RunTests() { Module("PureComponent Tests"); Test("PureComponent re-rendered with equivalent props should not have to re-render", assert => { // We'll create a Container component that renders a PureComponent. Each component will make a callback when they render so that we can count how many times // they render. The container also allows us a way to receive an async "forceReRender" method which we may call to force the Container to re-render. Since // the PureComponent's props don't change, forcing a single re-render should result in the Container being rendered twice (once for the initial render // and once for the re-render) but the PureComponent only being rendered once. var done = assert.Async(); var numberOfContainerRenders = 0; var numberOfPureComponentRenders = 0; Func<Task> forceReRender = null; TestComponentMounter.Render( component: new Container( onContainerRender: () => numberOfContainerRenders++, onPureComponentRender: () => numberOfPureComponentRenders++, reRenderProvider: force => forceReRender = force ), ready: async container => { await forceReRender(); assert.StrictEqual(numberOfContainerRenders, 2); assert.StrictEqual(numberOfPureComponentRenders, 1); container.Remove(); done(); } ); }); } private sealed class Container : Component<Container.Props, object> { public Container(Action onContainerRender, Action onPureComponentRender, Action<Func<Task>> reRenderProvider) : base(new Props { OnContainerRender = onContainerRender, OnPureComponentRender = onPureComponentRender, ReRenderProvider = reRenderProvider }) { } protected override void ComponentDidMount() { props.ReRenderProvider( () => SetStateAsync((object)null) // There are two SetStateAsync overloads that take a single reference, we want the TState one and not the Func<TState, TProps, TState> one ); } public override ReactElement Render() { props.OnContainerRender(); return new ExamplePureComponent("abc", props.OnPureComponentRender); } public sealed class Props { public Action OnContainerRender { get; set; } public Action OnPureComponentRender { get; set; } public Action<Func<Task>> ReRenderProvider { get; set; } } } private sealed class ExamplePureComponent : PureComponent<ExamplePureComponent.Props> { public ExamplePureComponent(string name, Action onPureComponentRender) : base(new Props { Name = name, OnPureComponentRender = onPureComponentRender }) { } public override ReactElement Render() { props.OnPureComponentRender(); return DOM.Div(props.Name); } public sealed class Props { public string Name { get; set; } public Action OnPureComponentRender { get; set; } } } } }
using System; using System.Threading.Tasks; using static Bridge.QUnit.QUnit; namespace Bridge.React.Tests { public static class PureComponentTests { public static void RunTests() { Module("PureComponent Tests"); Test("PureComponent re-rendered with equivalent props should not have to re-render", assert => { // We'll create a Container component that renders a PureComponent. Each component will make a callback when they render so that we can count how many times // they render. The container also allows us a way to receive an async "forceReRender" method which we may call to force the Container to re-render. Since // the PureComponent's props don't change, forcing a single re-render should result in the Container being rendered twice (once for the initial render // and once for the re-render) but the PureComponent only being rendered once. var done = assert.Async(); var numberOfContainerRenders = 0; var numberOfPureComponentRenders = 0; Func<Task> forceReRender = null; TestComponentMounter.Render( component: new Container( onContainerRender: () => numberOfContainerRenders++, onPureComponentRender: () => numberOfPureComponentRenders++, reRenderProvider: force => forceReRender = force ), ready: async container => { await forceReRender(); assert.StrictEqual(numberOfContainerRenders, 2); assert.StrictEqual(numberOfPureComponentRenders, 1); container.Remove(); done(); } ); }); } private sealed class Container : Component<Container.Props, object> { public Container(Action onContainerRender, Action onPureComponentRender, Action<Func<Task>> reRenderProvider) : base(new Props { OnContainerRender = onContainerRender, OnPureComponentRender = onPureComponentRender, ReRenderProvider = reRenderProvider }) { } protected override void ComponentDidMount() { props.ReRenderProvider( () => SetStateAsync(null) ); } public override ReactElement Render() { props.OnContainerRender(); return new ExamplePureComponent("abc", props.OnPureComponentRender); } public sealed class Props { public Action OnContainerRender { get; set; } public Action OnPureComponentRender { get; set; } public Action<Func<Task>> ReRenderProvider { get; set; } } } private sealed class ExamplePureComponent : PureComponent<ExamplePureComponent.Props> { public ExamplePureComponent(string name, Action onPureComponentRender) : base(new Props { Name = name, OnPureComponentRender = onPureComponentRender }) { } public override ReactElement Render() { props.OnPureComponentRender(); return DOM.Div(props.Name); } public sealed class Props { public string Name { get; set; } public Action OnPureComponentRender { get; set; } } } } }
mit
C#
93c31f5d88a9304f7a1068a038a187623d8e0d7f
Fix to work with Anonymous Roles
fujiy/FujiyBlog,fujiy/FujiyBlog,fujiy/FujiyBlog
src/FujiyBlog.Web/Infrastructure/AuthorizePermissionAttribute.cs
src/FujiyBlog.Web/Infrastructure/AuthorizePermissionAttribute.cs
using System; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; using FujiyBlog.Core.Extensions; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override bool AuthorizeCore(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } IPrincipal user = httpContext.User; var usersSplit = SplitString(Users); var rolesSplit = SplitString(Roles).Select(x => (Permission) Enum.Parse(typeof (Permission), x)).ToArray(); if (usersSplit.Length > 0 && !usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) { return false; } if (rolesSplit.Length > 0 && !rolesSplit.Any(user.IsInRole)) { return false; } return true; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } static string[] SplitString(string original) { if (String.IsNullOrEmpty(original)) { return new string[0]; } var split = from piece in original.Split(',') let trimmed = piece.Trim() where !String.IsNullOrEmpty(trimmed) select trimmed; return split.ToArray(); } } }
using System; using System.Linq; using System.Web.Mvc; using FujiyBlog.Core.DomainObjects; namespace FujiyBlog.Web.Infrastructure { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class AuthorizePermissionAttribute : AuthorizeAttribute { public AuthorizePermissionAttribute(params Permission[] permissions) { if (permissions == null) { throw new ArgumentNullException("permissions"); } Roles = string.Join(",", permissions.Select(r => r.ToString())); } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { base.HandleUnauthorizedRequest(filterContext); filterContext.HttpContext.Response.StatusCode = 401; filterContext.HttpContext.Response.WriteFile("~/errors/401.htm"); filterContext.HttpContext.Response.End(); } } }
mit
C#
6f2c5903a9d219c2c7851665f9508ca1ca9c7301
Update IPathSegment.cs
wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Model/Path/IPathSegment.cs
src/Core2D/Model/Path/IPathSegment.cs
using System.Collections.Generic; using Core2D.Shapes; namespace Core2D.Path { /// <summary> /// Defines path segment contract. /// </summary> public interface IPathSegment : IObservableObject, IStringExporter { /// <summary> /// Gets or sets flag indicating whether segment is stroked. /// </summary> bool IsStroked { get; set; } /// <summary> /// Gets or sets flag indicating whether segment is smooth join. /// </summary> bool IsSmoothJoin { get; set; } /// <summary> /// Get all points in the segment. /// </summary> /// <returns>All points in the segment.</returns> IEnumerable<IPointShape> GetPoints(); } }
using System.Collections.Generic; using Core2D.Shapes; namespace Core2D.Path { /// <summary> /// Defines path segment contract. /// </summary> public interface IPathSegment : IObservableObject { /// <summary> /// Gets or sets flag indicating whether segment is stroked. /// </summary> bool IsStroked { get; set; } /// <summary> /// Gets or sets flag indicating whether segment is smooth join. /// </summary> bool IsSmoothJoin { get; set; } /// <summary> /// Get all points in the segment. /// </summary> /// <returns>All points in the segment.</returns> IEnumerable<IPointShape> GetPoints(); } }
mit
C#
737f0c2eb8e19e4791e008a5e43c3bb772714f21
Rename finished, Bumped version to 0.9
Bobris/Nowin,et1975/Nowin,modulexcite/Nowin,modulexcite/Nowin,pysco68/Nowin,lstefano71/Nowin,lstefano71/Nowin,pysco68/Nowin,et1975/Nowin,modulexcite/Nowin,Bobris/Nowin,lstefano71/Nowin,et1975/Nowin,pysco68/Nowin,Bobris/Nowin
Nowin/Properties/AssemblyInfo.cs
Nowin/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("Nowin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("Nowin")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NowinWebServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("NowinWebServer")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
mit
C#
f52e47499ff9dfcd3d4e81455d95653801ac3827
Add FirstOrDefault
SaberSnail/GoldenAnvil.Utility
GoldenAnvil.Utility/EnumerableUtility.cs
GoldenAnvil.Utility/EnumerableUtility.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace GoldenAnvil.Utility { public static class EnumerableUtility { public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items) => items ?? Enumerable.Empty<T>(); public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items) => items.Where(x => x != null); public static IEnumerable<T> Enumerate<T>(params T[] items) => items; public static IReadOnlyList<T> AsReadOnlyList<T>(this IEnumerable<T> items) { return items as IReadOnlyList<T> ?? (items is IList<T> list ? (IReadOnlyList<T>) new ReadOnlyListAdapter<T>(list) : items.ToList().AsReadOnly()); } public static T FirstOrDefault<T>(this IEnumerable<T> items, T defaultValue) { if (items is null) throw new ArgumentNullException(nameof(items)); foreach (var item in items) return item; return defaultValue; } public static T FirstOrDefault<T>(this IEnumerable<T> items, Func<T, bool> predicate, T defaultValue) { if (items is null) throw new ArgumentNullException(nameof(items)); if (predicate is null) throw new ArgumentNullException(nameof(predicate)); foreach (var item in items) { if (predicate(item)) return item; } return defaultValue; } private sealed class ReadOnlyListAdapter<T> : IReadOnlyList<T> { public ReadOnlyListAdapter(IList<T> list) => m_list = list ?? throw new ArgumentNullException(nameof(list)); public int Count => m_list.Count; public T this[int index] => m_list[index]; public IEnumerator<T> GetEnumerator() => m_list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) m_list).GetEnumerator(); readonly IList<T> m_list; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace GoldenAnvil.Utility { public static class EnumerableUtility { public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> items) { return items ?? Enumerable.Empty<T>(); } public static IEnumerable<T> WhereNotNull<T>(this IEnumerable<T> items) { return items.Where(x => x != null); } public static IEnumerable<T> Enumerate<T>(params T[] items) { return items; } public static IReadOnlyList<T> AsReadOnlyList<T>(this IEnumerable<T> items) { return items as IReadOnlyList<T> ?? (items is IList<T> list ? (IReadOnlyList<T>) new ReadOnlyListAdapter<T>(list) : items.ToList().AsReadOnly()); } private sealed class ReadOnlyListAdapter<T> : IReadOnlyList<T> { public ReadOnlyListAdapter(IList<T> list) => m_list = list ?? throw new ArgumentNullException(nameof(list)); public int Count => m_list.Count; public T this[int index] => m_list[index]; public IEnumerator<T> GetEnumerator() => m_list.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) m_list).GetEnumerator(); readonly IList<T> m_list; } } }
mit
C#
6747ff4b5662749992fb21d58d074b805ec3d27c
Update Logic_Operators.cs
zulaldogan/unity-csharp-beginner
LogicOperators/Assets/Logic_Operators.cs
LogicOperators/Assets/Logic_Operators.cs
using UnityEngine; public class Logic_Operators : MonoBehaviour { public int a; public int b; public int c; public int average; void Start() { average = (a + b + c) / 3; } void Update() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Logic_Operators : MonoBehaviour { public int a; public int b; public int c; public int average; // Use this for initialization void Start () { average = (a + b + c)/ 3; } // Update is called once per frame void Update () { } }
mit
C#
002e9891a4f5b29bd72d36ab1252b75859e7e0d1
update assembly info
MrZANE42/im-only-resting,jordanbtucker/im-only-resting,ItsAGeekThing/im-only-resting,stephen-swensen/im-only-resting,abhinavwaviz/im-only-resting,jordanbtucker/im-only-resting,MrZANE42/im-only-resting,ItsAGeekThing/im-only-resting,nathanwblair/im-only-resting,nathanwblair/im-only-resting,stephen-swensen/im-only-resting,codemonkey493/im-only-resting,SwensenSoftware/im-only-resting,SwensenSoftware/im-only-resting,abhinavwaviz/im-only-resting,codemonkey493/im-only-resting
Ior/Properties/AssemblyInfo.cs
Ior/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("I'm Only Resting")] [assembly: AssemblyDescription("http://www.swensensoftware.com/im-only-resting")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("I'm Only Resting")] [assembly: AssemblyCopyright("Copyright © Swensen Software 2012 - 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("42d77ebc-de54-4916-b931-de852d2bacff")] // 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.1.1.*")] [assembly: AssemblyFileVersion("1.1.1.*")]
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("I'm Only Resting")] [assembly: AssemblyDescription("http://code.google.com/p/im-only-resting/")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("I'm Only Resting")] [assembly: AssemblyCopyright("Copyright © Stephen Swensen 2012-2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("42d77ebc-de54-4916-b931-de852d2bacff")] // 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.1.1.*")] [assembly: AssemblyFileVersion("1.1.1.*")]
apache-2.0
C#
4a904509a742435c636893ff5fc92ff863214daa
Initialize AuthCommand with an IAppHarborClient
appharbor/appharbor-cli
src/AppHarbor/Commands/AuthCommand.cs
src/AppHarbor/Commands/AuthCommand.cs
using System; namespace AppHarbor.Commands { public class AuthCommand : ICommand { private readonly IAppHarborClient _appharborClient; public AuthCommand(IAppHarborClient appharborClient) { _appharborClient = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class AuthCommand : ICommand { public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
mit
C#
f839729186a1aed63ed06728a282a740af149712
Increment patch version
inputfalken/Sharpy
src/Sharpy/Properties/AssemblyInfo.cs
src/Sharpy/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("Sharpy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sharpy")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //Makes my internal items visibile to the test project [assembly: InternalsVisibleTo("Tests")] // 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("e4c60589-e7ce-471c-82e3-28c356cd1191")] // 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("3.5.5.0")] [assembly: AssemblyInformationalVersion("3.5.5")]
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("Sharpy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Sharpy")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //Makes my internal items visibile to the test project [assembly: InternalsVisibleTo("Tests")] // 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("e4c60589-e7ce-471c-82e3-28c356cd1191")] // 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("3.5.4.0")] [assembly: AssemblyInformationalVersion("3.5.4")]
mit
C#
52fc3623362d706454947786e836e8b3f60992f0
Make microgame camera black on pause
Barleytree/NitoriWare,NitorInc/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,plrusek/NitoriWare
Assets/Scripts/Stage/PauseManager.cs
Assets/Scripts/Stage/PauseManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class PauseManager : MonoBehaviour { public UnityEvent onPause, onUnPause; [SerializeField] private bool enableVigorousTesting; //Whitelisted items won't be affected by pause public AudioSource[] audioSourceWhitelist; public MonoBehaviour[] scriptWhitelist; private bool paused; private float timeScale; PauseData pauseData; private struct PauseData { public List<AudioSource> pausedAudioSources; public List<MonoBehaviour> disabledScripts; public int camCullingMask; public Color camColor; } private float pauseTimer = 0f; void Start () { paused = false; } void Update () { if (enableVigorousTesting && Input.GetKey(KeyCode.P)) pauseTimer -= Time.fixedDeltaTime; if (Input.GetKeyDown(KeyCode.Escape) || pauseTimer < 0f) { if (!paused) pause(); else unPause(); pauseTimer = Random.Range(.1f, .2f); } } void pause() { timeScale = Time.timeScale; Time.timeScale = 0f; AudioSource[] audioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[]; pauseData.pausedAudioSources = new List<AudioSource>(); List<AudioSource> whitelistedAudioSources = new List<AudioSource>(audioSourceWhitelist); foreach (AudioSource source in audioSources) { if (!whitelistedAudioSources.Remove(source) && source.isPlaying) { source.Pause(); pauseData.pausedAudioSources.Add(source); } } MonoBehaviour[] scripts = FindObjectsOfType(typeof(MonoBehaviour)) as MonoBehaviour[]; pauseData.disabledScripts = new List<MonoBehaviour>(); List<MonoBehaviour> whitelistedScripts = new List<MonoBehaviour>(scriptWhitelist); foreach( MonoBehaviour script in scripts) { if (!whitelistedScripts.Remove(script) && script.enabled && script != this) { script.enabled = false; pauseData.disabledScripts.Add(script); } } onPause.Invoke(); if (MicrogameController.instance != null) { MicrogameController.instance.onPause.Invoke(); pauseData.camCullingMask = Camera.main.cullingMask; pauseData.camColor = Camera.main.backgroundColor; Camera.main.cullingMask = 0; Camera.main.backgroundColor = Color.black; } paused = true; } void unPause() { Time.timeScale = timeScale; foreach (AudioSource source in pauseData.pausedAudioSources) { if (source != null) source.UnPause(); } foreach (MonoBehaviour script in pauseData.disabledScripts) { if (script != null) script.enabled = true; } onUnPause.Invoke(); if (MicrogameController.instance != null) { Camera.main.cullingMask = pauseData.camCullingMask; Camera.main.backgroundColor = pauseData.camColor; MicrogameController.instance.onUnPause.Invoke(); } paused = false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class PauseManager : MonoBehaviour { public UnityEvent onPause, onUnPause; [SerializeField] private bool enableVigorousTesting; //Whitelisted items won't be affected by pause public AudioSource[] audioSourceWhitelist; public MonoBehaviour[] scriptWhitelist; private bool paused; private float timeScale; private List<AudioSource> pausedAudioSources; private List<MonoBehaviour> disabledScripts; private float pauseTimer = 0f; void Start () { paused = false; } void Update () { if (enableVigorousTesting && Input.GetKey(KeyCode.P)) pauseTimer -= Time.fixedDeltaTime; if (Input.GetKeyDown(KeyCode.Escape) || pauseTimer < 0f) { if (!paused) pause(); else unPause(); pauseTimer = Random.Range(.1f, .2f); } } void pause() { timeScale = Time.timeScale; Time.timeScale = 0f; AudioSource[] audioSources = FindObjectsOfType(typeof(AudioSource)) as AudioSource[]; pausedAudioSources = new List<AudioSource>(); List<AudioSource> whitelistedAudioSources = new List<AudioSource>(audioSourceWhitelist); foreach (AudioSource source in audioSources) { if (!whitelistedAudioSources.Remove(source) && source.isPlaying) { source.Pause(); pausedAudioSources.Add(source); } } MonoBehaviour[] scripts = FindObjectsOfType(typeof(MonoBehaviour)) as MonoBehaviour[]; disabledScripts = new List<MonoBehaviour>(); List<MonoBehaviour> whitelistedScripts = new List<MonoBehaviour>(scriptWhitelist); foreach( MonoBehaviour script in scripts) { if (!whitelistedScripts.Remove(script) && script.enabled && script != this) { script.enabled = false; disabledScripts.Add(script); } } onPause.Invoke(); if (MicrogameController.instance != null) MicrogameController.instance.onPause.Invoke(); paused = true; } void unPause() { Time.timeScale = timeScale; foreach (AudioSource source in pausedAudioSources) { if (source != null) source.UnPause(); } foreach (MonoBehaviour script in disabledScripts) { if (script != null) script.enabled = true; } onUnPause.Invoke(); if (MicrogameController.instance != null) MicrogameController.instance.onUnPause.Invoke(); paused = false; } }
mit
C#
6704f4f90775d5b58a0fab1dcd731cb9777cb60d
Update key-only querystring comparisons to use "" rather than null to make it more compatible with form data
oschwald/mockhttp,richardszalay/mockhttp
RichardSzalay.MockHttp/Matchers/QueryStringMatcher.cs
RichardSzalay.MockHttp/Matchers/QueryStringMatcher.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : "" )) .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace RichardSzalay.MockHttp.Matchers { public class QueryStringMatcher : IMockedRequestMatcher { readonly IEnumerable<KeyValuePair<string, string>> values; public QueryStringMatcher(string queryString) : this(ParseQueryString(queryString)) { } public QueryStringMatcher(IEnumerable<KeyValuePair<string, string>> values) { this.values = values; } public bool Matches(System.Net.Http.HttpRequestMessage message) { var queryString = ParseQueryString(message.RequestUri.Query.TrimStart('?')); return values.All(matchPair => queryString.Any(p => p.Key == matchPair.Key && p.Value == matchPair.Value)); } internal static IEnumerable<KeyValuePair<string, string>> ParseQueryString(string input) { return input.TrimStart('?').Split('&') .Select(pair => StringUtil.Split(pair, '=', 2)) .Select(pair => new KeyValuePair<string, string>( Uri.UnescapeDataString(pair[0]), pair.Length == 2 ? Uri.UnescapeDataString(pair[1]) : null )) .ToList(); } } }
mit
C#
a43fbd73081158f1aff22b283f3d34d986f873a9
remove redundant version
WojcikMike/docs.particular.net,yuxuac/docs.particular.net,SzymonPobiega/docs.particular.net,eclaus/docs.particular.net,pedroreys/docs.particular.net,pashute/docs.particular.net
Snippets/Snippets_3/Conventions/MessageConventions.cs
Snippets/Snippets_3/Conventions/MessageConventions.cs
using System; using NServiceBus; public class MessageConventions { public void Simple() { #region MessageConventions // NOTE: When you're self hosting, `.DefiningXXXAs()` has to be before `.UnicastBus()`, // otherwise you'll get: `System.InvalidOperationException: "No destination specified for message(s): <message type name>" var configure = Configure.With() .DefaultBuilder() .DefiningCommandsAs(t => t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Commands")) .DefiningEventsAs(t => t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Events")) .DefiningMessagesAs(t => t.Namespace == "Messages") .DefiningEncryptedPropertiesAs(p => p.Name.StartsWith("Encrypted")) .DefiningDataBusPropertiesAs(p => p.Name.EndsWith("DataBus")) .DefiningExpressMessagesAs(t => t.Name.EndsWith("Express")) .DefiningTimeToBeReceivedAs(t => t.Name.EndsWith("Expires") ? TimeSpan.FromSeconds(30) : TimeSpan.MaxValue); #endregion } }
using System; using NServiceBus; public class MessageConventions { public void Simple() { #region MessageConventions 3 // NOTE: When you're self hosting, `.DefiningXXXAs()` has to be before `.UnicastBus()`, // otherwise you'll get: `System.InvalidOperationException: "No destination specified for message(s): <message type name>" var configure = Configure.With() .DefaultBuilder() .DefiningCommandsAs(t => t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Commands")) .DefiningEventsAs(t => t.Namespace == "MyNamespace" && t.Namespace.EndsWith("Events")) .DefiningMessagesAs(t => t.Namespace == "Messages") .DefiningEncryptedPropertiesAs(p => p.Name.StartsWith("Encrypted")) .DefiningDataBusPropertiesAs(p => p.Name.EndsWith("DataBus")) .DefiningExpressMessagesAs(t => t.Name.EndsWith("Express")) .DefiningTimeToBeReceivedAs(t => t.Name.EndsWith("Expires") ? TimeSpan.FromSeconds(30) : TimeSpan.MaxValue); #endregion } }
apache-2.0
C#
6e8e52df9737820a72f782037bcf8538278f6945
Add constructor
rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary
CSharpGameLibrary/Graphics/Bitmap.cs
CSharpGameLibrary/Graphics/Bitmap.cs
using System; using System.Collections.Generic; namespace CSGL.Graphics { public class Bitmap<T> where T : struct { public int Width { get; private set; } public int Height { get; private set; } public T[] Data { get; private set; } public Bitmap(int width, int height) { Width = width; Height = height; Data = new T[width * height]; } public Bitmap(int width, int height, T[] data) { if (data.Length != width * height) throw new ArgumentException("data.Length must equal (width * height)"); Width = width; Height = height; Data = data; } public int GetIndex(int x, int y) { return x + y * Width; } public T this[int x, int y] { get { return Data[GetIndex(x, y)]; } set { Data[GetIndex(x, y)] = value; } } } }
using System; using System.Collections.Generic; namespace CSGL.Graphics { public class Bitmap<T> where T : struct { public int Width { get; private set; } public int Height { get; private set; } public T[] Data { get; private set; } public Bitmap(int width, int height) { Width = width; Height = height; Data = new T[width * height]; } public int GetIndex(int x, int y) { return x + y * Width; } public T this[int x, int y] { get { return Data[GetIndex(x, y)]; } set { Data[GetIndex(x, y)] = value; } } } }
mit
C#
638be50840b237bd0b43199549c3a45177388097
fix test
ilya-murzinov/WhiteSharp
src/SampleTests/SampleTestScenario.cs
src/SampleTests/SampleTestScenario.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using SampleTests.ScreenObjects; using System.Diagnostics; using System.Windows.Automation; namespace SampleTests { [TestClass] [TestFixture] public class SampleTestScenario { public static string Path = @"..\..\..\..\\TestApps\\WpfTestApplication.exe"; private Process _proc; [TestInitialize] [TestFixtureSetUp] public void Init() { _proc = Process.Start(Path); } [TestMethod] [Test] public void SampleTest() { MainWindowTab1.Instance .SelectItemFromCombobox("Test4") .SetItem1CheckboxState(ToggleState.On) .SetItem2CheckboxState(ToggleState.On) .SetItem1CheckboxState(ToggleState.Off) .OpenSecondTab() .SetTextToMultilineTextbox("some text") .SelectRadiobuttonState(); } [TestCleanup] [TestFixtureTearDown] public void Shutdown() { _proc.Kill(); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using SampleTests.ScreenObjects; using System.Windows.Automation; namespace SampleTests { [TestClass] [TestFixture] public class SampleTestScenario { [TestFixtureSetUp] public void Init() { } [TestMethod] [Test] public void SampleTest() { MainWindowTab1.Instance .SelectItemFromCombobox("Test4") .SetItem1CheckboxState(ToggleState.On) .SetItem2CheckboxState(ToggleState.On) .SetItem1CheckboxState(ToggleState.Off) .OpenSecondTab() .SetTextToMultilineTextbox("some text") .SelectRadiobuttonState(); } [TestFixtureTearDown] public void Shutdown() { } } }
mit
C#
49dcdfbec58ceeaed20f074f2994f9ddddd22009
add tests for propertyWriters
Pondidum/Stronk,Pondidum/Stronk
src/Stronk.Tests/StronkConfigTests.cs
src/Stronk.Tests/StronkConfigTests.cs
using System.Collections.Generic; using Shouldly; using Stronk.ConfigurationSourcing; using Stronk.Policies; using Stronk.PropertyWriters; using Xunit; namespace Stronk.Tests { public class StronkConfigTests { private IStronkConfig _config; [Fact] public void When_nothing_is_specified() { _config = new StronkConfig() as IStronkConfig; _config.ShouldSatisfyAllConditions( () => _config.ConfigSources.ShouldBe(Default.ConfigurationSources), () => _config.ValueSelectors.ShouldBe(Default.SourceValueSelectors), () => _config.ValueConverters.ShouldBe(Default.ValueConverters), () => _config.PropertyWriters.ShouldBe(Default.PropertyWriters), () => _config.ErrorPolicy.ShouldBeOfType<ErrorPolicy>() ); } [Fact] public void When_you_specify_a_config_source_it_is_the_only_one_used() { var source = new DictionaryConfigurationSource(new Dictionary<string, string>()); _config = new StronkConfig().From.Source(source) as IStronkConfig; _config.ConfigSources.ShouldBe(new[] { source }); } [Fact] public void When_multiple_config_sources_are_selected() { var one = new AppConfigSource(); var two = new DictionaryConfigurationSource(new Dictionary<string, string>()); _config = new StronkConfig() .From.Source(one) .From.Source(two); _config.ConfigSources.ShouldBe(new IConfigurationSource[] { one, two }); } [Fact] public void When_one_property_writer_is_specified() { var setters = new PrivateSetterPropertyWriter(); _config = new StronkConfig().Write.To(setters); _config.PropertyWriters.ShouldBe(new[] { setters }); } [Fact] public void When_multiple_property_writers_are_specified() { var one = new PrivateSetterPropertyWriter(); var two = new BackingFieldPropertyWriter(); _config = new StronkConfig() .Write.To(one) .Write.To(two); _config.PropertyWriters.ShouldBe(new IPropertyWriter[] { one, two }); } } }
using System.Collections.Generic; using Shouldly; using Stronk.ConfigurationSourcing; using Stronk.Policies; using Xunit; namespace Stronk.Tests { public class StronkConfigTests { private IStronkConfig _config; [Fact] public void When_nothing_is_specified() { _config = new StronkConfig() as IStronkConfig; _config.ShouldSatisfyAllConditions( () => _config.ConfigSources.ShouldBe(Default.ConfigurationSources), () => _config.ValueSelectors.ShouldBe(Default.SourceValueSelectors), () => _config.ValueConverters.ShouldBe(Default.ValueConverters), () => _config.PropertyWriters.ShouldBe(Default.PropertyWriters), () => _config.ErrorPolicy.ShouldBeOfType<ErrorPolicy>() ); } [Fact] public void When_you_specify_a_config_source_it_is_the_only_one_used() { var source = new DictionaryConfigurationSource(new Dictionary<string, string>()); _config = new StronkConfig().From.Source(source) as IStronkConfig; _config.ConfigSources.ShouldBe(new[] { source }); } [Fact] public void When_multiple_config_sources_are_selected() { var one = new AppConfigSource(); var two = new DictionaryConfigurationSource(new Dictionary<string, string>()); _config = new StronkConfig() .From.Source(one) .From.Source(two); _config.ConfigSources.ShouldBe(new IConfigurationSource[] { one, two }); } } }
lgpl-2.1
C#
8bcf35c026558770f34741c84738922c0405a8a3
comment in console write to clean error output
conekta/conekta-.net
src/conekta/conekta/Base/Requestor.cs
src/conekta/conekta/Base/Requestor.cs
using System; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class Requestor { public Requestor () { } public String request (String method, String resource_uri, String data = "{}") { String api_version = conekta.Api.version.Replace(".", ""); if (int.Parse(api_version) < 110) { ConektaException ex = new ConektaException("This package just support api version 1.1 or higher"); ex.details = new JArray(0); ex._object = "error"; ex._type = "api_version_unsupported"; throw ex; } try { HttpWebRequest http = (HttpWebRequest)WebRequest.Create(conekta.Api.baseUri + resource_uri); http.Accept = "application/vnd.conekta-v" + conekta.Api.version + "+json"; http.UserAgent = "Conekta/v1 DotNetBindings10/Conekta::" + conekta.Api.version; http.Method = method; var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(conekta.Api.apiKey); http.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes) + ":"); http.Headers.Add ("Accept-Language", conekta.Api.locale); if (method == "POST" || method == "PUT") { var dataBytes = Encoding.UTF8.GetBytes(data); http.ContentLength = dataBytes.Length; http.ContentType = "application/json"; Stream dataStream = http.GetRequestStream (); dataStream.Write (dataBytes, 0, dataBytes.Length); } WebResponse response = http.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //System.Console.WriteLine(responseString); return responseString; } catch (WebException webExcp) { WebExceptionStatus status = webExcp.Status; HttpWebResponse httpResponse = (HttpWebResponse)webExcp.Response; var encoding = ASCIIEncoding.UTF8; using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream(), encoding)) { string responseText = reader.ReadToEnd(); //System.Console.WriteLine(responseText); JObject obj = JsonConvert.DeserializeObject<JObject>(responseText, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); ConektaException ex = new ConektaException(obj.GetValue("type").ToString()); ex.details = (JArray)obj["details"]; ex._object = obj.GetValue("object").ToString(); ex._type = obj.GetValue("type").ToString(); throw ex; } } catch (Exception e) { System.Console.WriteLine(e.ToString()); return ""; } } } }
using System; using System.IO; using System.Net; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace conekta { public class Requestor { public Requestor () { } public String request (String method, String resource_uri, String data = "{}") { String api_version = conekta.Api.version.Replace(".", ""); if (int.Parse(api_version) < 110) { ConektaException ex = new ConektaException("This package just support api version 1.1 or higher"); ex.details = new JArray(0); ex._object = "error"; ex._type = "api_version_unsupported"; throw ex; } try { HttpWebRequest http = (HttpWebRequest)WebRequest.Create(conekta.Api.baseUri + resource_uri); http.Accept = "application/vnd.conekta-v" + conekta.Api.version + "+json"; http.UserAgent = "Conekta/v1 DotNetBindings10/Conekta::" + conekta.Api.version; http.Method = method; var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(conekta.Api.apiKey); http.Headers.Add("Authorization", "Basic " + System.Convert.ToBase64String(plainTextBytes) + ":"); http.Headers.Add ("Accept-Language", conekta.Api.locale); if (method == "POST" || method == "PUT") { var dataBytes = Encoding.UTF8.GetBytes(data); http.ContentLength = dataBytes.Length; http.ContentType = "application/json"; Stream dataStream = http.GetRequestStream (); dataStream.Write (dataBytes, 0, dataBytes.Length); } WebResponse response = http.GetResponse(); var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd(); //System.Console.WriteLine(responseString); return responseString; } catch (WebException webExcp) { WebExceptionStatus status = webExcp.Status; HttpWebResponse httpResponse = (HttpWebResponse)webExcp.Response; var encoding = ASCIIEncoding.UTF8; using (var reader = new System.IO.StreamReader(httpResponse.GetResponseStream(), encoding)) { string responseText = reader.ReadToEnd(); System.Console.WriteLine(responseText); JObject obj = JsonConvert.DeserializeObject<JObject>(responseText, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); ConektaException ex = new ConektaException(obj.GetValue("type").ToString()); ex.details = (JArray)obj["details"]; ex._object = obj.GetValue("object").ToString(); ex._type = obj.GetValue("type").ToString(); throw ex; } } catch (Exception e) { System.Console.WriteLine(e.ToString()); return ""; } } } }
mit
C#
01dfbc33d5412537b9862457726fc1c8fe2c8521
Fix a bug in BringIntoViewBehavior.
GaoSui/SkyTimer,GaoSui/SkyTimer,GaoSui/SkyTimer
SkyTimer/Helper/BringIntoViewBehavior.cs
SkyTimer/Helper/BringIntoViewBehavior.cs
using System; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Controls; using System.Windows.Interactivity; namespace SkyTimer.Helper { public class BringIntoViewBehavior : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.Loaded += AssociatedObject_Loaded; } protected override void OnDetaching() { dpd.RemoveValueChanged(AssociatedObject, itemsChanged); } private DependencyPropertyDescriptor dpd; private void AssociatedObject_Loaded(object sender, System.Windows.RoutedEventArgs e) { registerEvent(); dpd = DependencyPropertyDescriptor.FromProperty(ItemsControl.ItemsSourceProperty, typeof(ListBox)); dpd.AddValueChanged(AssociatedObject, itemsChanged); if (AssociatedObject.Items.Count == 0) return; AssociatedObject.ScrollIntoView(AssociatedObject.Items[AssociatedObject.Items.Count - 1]); } private void itemsChanged(object sender, EventArgs e) { registerEvent(); } private void registerEvent() { var colle = AssociatedObject.ItemsSource as INotifyCollectionChanged; colle.CollectionChanged -= BringIntoViewBehavior_CollectionChanged; colle.CollectionChanged += BringIntoViewBehavior_CollectionChanged; } private void BringIntoViewBehavior_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { AssociatedObject.ScrollIntoView(e.NewItems[0]); } } } }
using System.Collections.Specialized; using System.Windows.Controls; using System.Windows.Interactivity; namespace SkyTimer.Helper { public class BringIntoViewBehavior : Behavior<ListBox> { protected override void OnAttached() { AssociatedObject.Loaded += AssociatedObject_Loaded; } private void AssociatedObject_Loaded(object sender, System.Windows.RoutedEventArgs e) { (AssociatedObject.ItemsSource as INotifyCollectionChanged).CollectionChanged += BringIntoViewBehavior_CollectionChanged; if (AssociatedObject.Items.Count == 0) return; AssociatedObject.ScrollIntoView(AssociatedObject.Items[AssociatedObject.Items.Count - 1]); } private void BringIntoViewBehavior_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.Action == NotifyCollectionChangedAction.Add) { AssociatedObject.ScrollIntoView(e.NewItems[0]); } } } }
mit
C#
f044bd7027595079e981e9164293cd307a6fcb72
Allow keyboard configs as well
RonnChyran/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1,faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake
Snowflake.API/Emulator/EmulatorBridge.cs
Snowflake.API/Emulator/EmulatorBridge.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Emulator.Configuration.Template; using Snowflake.Emulator.Configuration; using Snowflake.Emulator.Input.Template; using Snowflake.Platform.Controller; using System.Collections; namespace Snowflake.Emulator { public class EmulatorBridge { public IReadOnlyDictionary<string, ControllerTemplate> ControllerTemplates { get; private set; } public IReadOnlyDictionary<string, InputTemplate> InputTemplates { get; private set; } public IReadOnlyDictionary<string, ConfigurationTemplate> ConfigurationTemplates { get; private set; } public IReadOnlyList<string> SupportedPlatforms { get; private set; } public string CompileConfiguration(ConfigurationTemplate template, ConfigurationProfile profile) { return String.Empty; } public string CompileController(int playerIndex, ControllerDefinition controllerDefinition, ControllerTemplate controllerTemplate, ControllerProfile controllerProfile, InputTemplate inputTemplate) { StringBuilder template = new StringBuilder(inputTemplate.StringTemplate); var controllerMappings = controllerProfile.ProfileType == ControllerProfileType.KEYBOARD_PROFILE ? controllerTemplate.KeyboardControllerMappings : controllerTemplate.GamepadControllerMappings; foreach (ControllerInput input in controllerDefinition.ControllerInputs.Values) { string templateKey = controllerMappings["default"].InputMappings[input.InputName]; string inputSetting = controllerProfile.InputConfiguration[input.InputName]; string emulatorValue = controllerProfile.ProfileType == ControllerProfileType.KEYBOARD_PROFILE ? inputTemplate.KeyboardMappings.First().Value[inputSetting] : inputTemplate.GamepadMappings.First().Value[inputSetting]; template.Replace("{" + templateKey + "}", emulatorValue); } foreach (var key in inputTemplate.TemplateKeys) { template.Replace("{N}", playerIndex.ToString()); //Player Index if (controllerMappings["default"].KeyMappings.ContainsKey(key)) { template.Replace("{" + key + "}", controllerMappings["default"].KeyMappings[key]); //Non-input keys } else { template.Replace("{" + key + "}", inputTemplate.NoBind); //Non-input keys } } return template.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Snowflake.Emulator.Configuration.Template; using Snowflake.Emulator.Configuration; using Snowflake.Emulator.Input.Template; using Snowflake.Platform.Controller; namespace Snowflake.Emulator { public class EmulatorBridge { public string CompileConfiguration(ConfigurationTemplate template, ConfigurationProfile profile) { return String.Empty; } public string CompileController(int playerIndex, ControllerDefinition controllerDefinition, ControllerTemplate controllerTemplate, ControllerProfile controllerProfile, InputTemplate inputTemplate) { StringBuilder template = new StringBuilder(inputTemplate.StringTemplate); foreach (ControllerInput input in controllerDefinition.ControllerInputs.Values) { string templateKey = controllerTemplate.GamepadControllerMappings["default"].InputMappings[input.InputName]; string inputSetting = controllerProfile.InputConfiguration[input.InputName]; string emulatorValue = inputTemplate.GamepadMappings.First().Value[inputSetting]; template.Replace("{" + templateKey + "}", emulatorValue); } foreach (var key in inputTemplate.TemplateKeys) { template.Replace("{N}", playerIndex.ToString()); //Player Index if (controllerTemplate.GamepadControllerMappings["default"].KeyMappings.ContainsKey(key)) { template.Replace("{" + key + "}", controllerTemplate.GamepadControllerMappings["default"].KeyMappings[key]); //Non-input keys } else { template.Replace("{" + key + "}", inputTemplate.NoBind); //Non-input keys } } return template.ToString(); } } }
mpl-2.0
C#
fb537c79bbbffe92b3fb330fda81c0a19e8f6185
Fix #812 - Add support for AnsiString quoting
dudzon/Glimpse,elkingtonmcb/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse,Glimpse/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,flcdrg/Glimpse,flcdrg/Glimpse,SusanaL/Glimpse,paynecrl97/Glimpse,rho24/Glimpse,sorenhl/Glimpse,Glimpse/Glimpse,SusanaL/Glimpse,dudzon/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,gabrielweyer/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,sorenhl/Glimpse,elkingtonmcb/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,elkingtonmcb/Glimpse,Glimpse/Glimpse,codevlabs/Glimpse,dudzon/Glimpse,rho24/Glimpse
source/Glimpse.Ado/Tab/Support/CommandSanitizer.cs
source/Glimpse.Ado/Tab/Support/CommandSanitizer.cs
using System.Collections.Generic; using Glimpse.Ado.Extensibility; using Glimpse.Ado.Model; namespace Glimpse.Ado.Tab.Support { internal class CommandSanitizer { public CommandSanitizer() { Parsers = new Dictionary<string, ICommandParameterParser>(); PopulateParsers(); } private IDictionary<string, ICommandParameterParser> Parsers { get; set; } private ICommandParameterParser DefaultParser { get; set; } public string Process(string command, IList<CommandParameterMetadata> parameters) { foreach (var parameter in parameters) { ICommandParameterParser parser; if (!Parsers.TryGetValue(parameter.Type, out parser)) { parser = DefaultParser; } command = parser.Parse(command, parameter.Name, parameter.Value, parameter.Type, parameter.Size); } return command; } private void PopulateParsers() { var quoted = new CommandParameterParser(true); var unquoted = new CommandParameterParser(false); DefaultParser = unquoted; Parsers.Add("String", quoted); Parsers.Add("AnsiString", quoted); } } }
using System.Collections.Generic; using Glimpse.Ado.Extensibility; using Glimpse.Ado.Model; namespace Glimpse.Ado.Tab.Support { internal class CommandSanitizer { public CommandSanitizer() { Parsers = new Dictionary<string, ICommandParameterParser>(); PopulateParsers(); } private IDictionary<string, ICommandParameterParser> Parsers { get; set; } private ICommandParameterParser DefaultParser { get; set; } public string Process(string command, IList<CommandParameterMetadata> parameters) { foreach (var parameter in parameters) { ICommandParameterParser parser; if (!Parsers.TryGetValue(parameter.Type, out parser)) { parser = DefaultParser; } command = parser.Parse(command, parameter.Name, parameter.Value, parameter.Type, parameter.Size); } return command; } private void PopulateParsers() { var quoted = new CommandParameterParser(true); var unquoted = new CommandParameterParser(false); DefaultParser = unquoted; Parsers.Add("String", quoted); } } }
apache-2.0
C#
994a57ba3a1dc0bd670c057ec1f6af8ee5e41720
fix blmapper error
danielsmcelhaney/dsm-store
StoreRest/StoreRestBL/Models/BLMapper.cs
StoreRest/StoreRestBL/Models/BLMapper.cs
using StoreRestBL.StoreDASoap; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StoreRestBL.Models { class BLMapper { public product ProductDaoToProduct(productDao pd) { product p = new product(); p.Id = pd.Id; p.Name = pd.Name; p.Price = pd.Price; p.Discount = pd.Discount; return p; } public productDao ProductToProductDao(product p) { productDao pd = new productDao(); pd.Id = p.Id; pd.Name = p.Name; pd.Price = p.Price; pd.Discount = p.Discount; return pd; } public order OrderDaoToOrder(orderDao od) { order o = new order(); o.Id = od.Id; o.Name = od.Name; o.totalPrice = od.totalPrice; List<product> lp = new List<product>(); foreach (var item in od.products) { lp.Add(ProductDaoToProduct(item)); } o.products = lp.ToArray(); return o; } public orderDao OrderToOrderDao(order o) { orderDao od = new orderDao(); od.Id = o.Id; od.Name = o.Name; od.products = new List<productDao>(); foreach (var item in o.products) { od.products.Add(ProductToProductDao(item)); } od.totalPrice = o.totalPrice; return od; } } }
using StoreRestBL.StoreDASoap; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StoreRestBL.Models { class BLMapper { public product ProductDaoToProduct(productDao pd) { product p = new product(); p.Id = pd.Id; p.Name = pd.Name; p.Price = pd.Price; p.Discount = pd.Discount; return p; } public productDao ProductToProductDao(product p) { productDao pd = new productDao(); pd.Id = p.Id; pd.Name = p.Name; pd.Price = p.Price; pd.Discount = p.Discount; return pd; } public order OrderDaoToOrder(orderDao od) { order o = new order(); o.Id = od.Id; o.Name = od.Name; o.totalPrice = od.totalPrice; List<product> lp = new List<product>(); foreach (var item in od.products) { lp.Add(ProductDaoToProduct(item)); } o.products = lp.ToArray(); return o; } public orderDao OrderToOrderDao(order o) { orderDao od = new orderDao(); od.Id = o.Id; od.Name = o.Name; od.products = new List<productDao>(); foreach (var item in o.products) { od.products.Add(ProductToProductDao(item)); } od.totalPrice = o.totalPrice; return od; } } } } }
mit
C#
d8cfb8ac56e0ef7752766535479841d44d6f664c
Update stub to be buildable.
yas-mnkornym/TaihaToolkit
source/TaihaToolkit.Rest.Tests/StubParameterBag.cs
source/TaihaToolkit.Rest.Tests/StubParameterBag.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Studiotaiha.Toolkit.Rest.Tests { class StubParameterBag : IParameterBag { public IDictionary<string, string> Body { get; } = new Dictionary<string, string>(); public IDictionary<string, string> MultiPartHeader { get; } = new Dictionary<string, string>(); public IDictionary<string, string> Query { get; } = new Dictionary<string, string>(); public List<FilePart> FileParts { get; } = new List<FilePart>(); public List<TextPart> TextParts { get; } = new List<TextPart>(); public Stream Stream { get; set; } public int BufferSize { get; set; } public string Text { get; set; } public Encoding Encoding { get; set; } public ERequestBodyType RequestBodyType { get; set; } public Encoding RawTextEncoding { get; set; } public void AddFilePart(string name, Stream stream, IEnumerable<KeyValuePair<string, string>> properties = null) { FileParts.Add(new FilePart { Name = name, Stream = stream, Properties = properties, }); } public void AddFilePart(string name, Stream stream, int bufferSize, IEnumerable<KeyValuePair<string, string>> properties = null) { FileParts.Add(new FilePart { Name = name, Stream = stream, BufferSize = bufferSize, Properties = properties, }); } public void AddTextPart(string value, Encoding encoding = null, IEnumerable<KeyValuePair<string, string>> properties = null) { TextParts.Add(new TextPart { Text = value, Encoding = encoding, Properties = properties }); } public void SetStream(Stream stream, int bufferSize = -1) { Stream = stream; BufferSize = bufferSize; } public void SetText(string text, Encoding encoding = null) { Text = text; Encoding = encoding; } public class FilePart { public string Name { get; set; } public Stream Stream { get; set; } public int? BufferSize { get; set; } public IEnumerable<KeyValuePair<string, string>> Properties { get; set; } } public class TextPart { public string Text { get; set; } public Encoding Encoding { get; set; } public IEnumerable<KeyValuePair<string, string>> Properties { get; set; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Studiotaiha.Toolkit.Rest.Tests { class StubParameterBag : IParameterBag { public IDictionary<string, string> Body { get; } = new Dictionary<string, string>(); public IDictionary<string, string> MultiPartHeader { get; } = new Dictionary<string, string>(); public IDictionary<string, string> Query { get; } = new Dictionary<string, string>(); public List<FilePart> FileParts { get; } = new List<FilePart>(); public List<TextPart> TextParts { get; } = new List<TextPart>(); public Stream Stream { get; set; } public int BufferSize { get; set; } public string Text { get; set; } public Encoding Encoding { get; set; } public void AddFilePart(string name, Stream stream, IEnumerable<KeyValuePair<string, string>> properties = null) { FileParts.Add(new FilePart { Name = name, Stream = stream, Properties = properties, }); } public void AddFilePart(string name, Stream stream, int bufferSize, IEnumerable<KeyValuePair<string, string>> properties = null) { FileParts.Add(new FilePart { Name = name, Stream = stream, BufferSize = bufferSize, Properties = properties, }); } public void AddTextPart(string value, Encoding encoding = null, IEnumerable<KeyValuePair<string, string>> properties = null) { TextParts.Add(new TextPart { Text = value, Encoding = encoding, Properties = properties }); } public void SetStream(Stream stream, int bufferSize = -1) { Stream = stream; BufferSize = bufferSize; } public void SetText(string text, Encoding encoding = null) { Text = text; Encoding = encoding; } public class FilePart { public string Name { get; set; } public Stream Stream { get; set; } public int? BufferSize { get; set; } public IEnumerable<KeyValuePair<string, string>> Properties { get; set; } } public class TextPart { public string Text { get; set; } public Encoding Encoding { get; set; } public IEnumerable<KeyValuePair<string, string>> Properties { get; set; } } } }
mit
C#
58c3ae7fcede8ef947c85a07bcb8a2f1fd05157e
remove assembly versions
letsar/DoLess.Commands
src/DoLess.Commands.Pcl/Properties/AssemblyInfo.cs
src/DoLess.Commands.Pcl/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("DoLess.Commands")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DoLess.Commands")] [assembly: AssemblyCopyright("© Romain Rastel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("DoLess.Commands")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DoLess.Commands")] [assembly: AssemblyCopyright("© Romain Rastel")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
d7f3076dd9cd01a5c2f815196109b5118d1e7297
Update EnemyAI.cs
Panther450/450Game
NEFMA/Assets/Scripts/EnemyAI.cs
NEFMA/Assets/Scripts/EnemyAI.cs
/************************************************************ * Author: Michael Morris * File: EnemyAI.cs * * Credits: * http://www.devination.com/2015/07/unity-2d-platformer-tutorial-part-4.html * (Unity 2D Platformer Tutorial - Part 4 - Enemy Movement) ***********************************************************/ using System.Collections; using UnityEngine; [RequireComponent (typeof (Rigidbody2D))] public class EnemyAI : MonoBehaviour { public LayerMask enemyMask; public Vector2 myDirection; public float speed = 300f; public ForceMode2D forceMode = ForceMode2D.Force; // Cache vars private Rigidbody2D myBody; private float myWidth; private float myHeight; void Start() { myBody = this.GetComponent<Rigidbody2D>(); SpriteRenderer mySprite = this.GetComponent<SpriteRenderer>(); myWidth = mySprite.bounds.extents.x; myHeight = mySprite.bounds.extents.y; } // Great for physics updates, use FixedUpdate instead of Update! void FixedUpdate() { //Use this position to cast the isGrounded/isBlocked lines from Vector2 lineCastPos = toVector2(transform.position) - toVector2(transform.right) * myWidth + Vector2.up * myHeight; // Check to see if there's ground in front of us before moving forward Debug.DrawLine(lineCastPos, lineCastPos + Vector2.down); bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask); Debug.Log("Current Pos: " + transform.position); Debug.Log("LineCastPos: " + lineCastPos); Debug.Log("Grounded: " + isGrounded); // Check to see if there's a wall in front of us before moving forward Debug.DrawLine(lineCastPos, lineCastPos - toVector2(transform.right) * .05f); bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - toVector2(transform.right) * .05f, enemyMask); Debug.Log("Obstructed: " + isGrounded); // If theres no ground, turn around. Or if I hit a wall, turn around if (!isGrounded || isBlocked) { Flip(); } // Always move forward myDirection *= speed * Time.fixedDeltaTime; myDirection.Normalize(); myBody.AddForce(myDirection, forceMode); } // Reverse enemy movement and facing direction public void Flip() { myDirection *= -1; // Flip the sprite by multiplying the x component of localScale by -1. Vector3 flipScale = transform.localScale; flipScale.x *= -1; transform.localScale = flipScale; } public static Vector2 toVector2(Vector3 vec3) { return new Vector2(vec3.x, vec3.y); } }
/************************************************************ * Author: Michael Morris * File: EnemyAI.cs * * Credits: * http://www.devination.com/2015/07/unity-2d-platformer-tutorial-part-4.html * (Unity 2D Platformer Tutorial - Part 4 - Enemy Movement) ***********************************************************/ using System.Collections; using UnityEngine; using Pathfinding; [RequireComponent (typeof (Rigidbody2D))] public class EnemyAI : MonoBehaviour { public LayerMask enemyMask; public Vector2 myDirection; public float speed = 300f; public ForceMode2D forceMode = ForceMode2D.Force; // Cache vars private Rigidbody2D myBody; private float myWidth; private float myHeight; void Start() { myBody = this.GetComponent<Rigidbody2D>(); SpriteRenderer mySprite = this.GetComponent<SpriteRenderer>(); myWidth = mySprite.bounds.extents.x; myHeight = mySprite.bounds.extents.y; } // Great for physics updates, use FixedUpdate instead of Update! void FixedUpdate() { //Use this position to cast the isGrounded/isBlocked lines from Vector2 lineCastPos = toVector2(transform.position) - toVector2(transform.right) * myWidth + Vector2.up * myHeight; // Check to see if there's ground in front of us before moving forward Debug.DrawLine(lineCastPos, lineCastPos + Vector2.down); bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask); Debug.Log("Grounded: " + isGrounded); // Check to see if there's a wall in front of us before moving forward Debug.DrawLine(lineCastPos, lineCastPos - toVector2(transform.right) * .05f); bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - toVector2(transform.right) * .05f, enemyMask); Debug.Log("Obstructed: " + isGrounded); // If theres no ground, turn around. Or if I hit a wall, turn around if (!isGrounded || isBlocked) { Flip(); } // Always move forward myDirection *= speed * Time.fixedDeltaTime; myDirection.Normalize(); myBody.AddForce(myDirection, forceMode); } // Reverse enemy movement and facing direction public void Flip() { myDirection *= -1; // Flip the sprite by multiplying the x component of localScale by -1. Vector3 flipScale = transform.localScale; flipScale.x *= -1; transform.localScale = flipScale; } public static Vector2 toVector2(Vector3 vec3) { return new Vector2(vec3.x, vec3.y); } }
apache-2.0
C#
e841583f3855497da2bccb9972c8a6e3f8c6aae8
Use ticks
numinit/open-waveform-format,numinit/open-waveform-format,numinit/open-waveform-format
c-sharp/OWF-test/Serializers/BinarySerializerTests.cs
c-sharp/OWF-test/Serializers/BinarySerializerTests.cs
using System; using System.Web; using Microsoft.VisualStudio.TestTools.UnitTesting; using OWF.Serializers; using OWF.DTO; using System.Collections.Generic; namespace OWF_test.Serializers { [TestClass] public class BinarySerializerTests { private byte[] ReadOWF(string filename) { return System.IO.File.ReadAllBytes(String.Join("/", "..", "..", "..", "..", "example", "owf1_" + filename + ".owf")); } [TestMethod] public void GeneratesCorrectEmptyObject() { var p = new Package(new List<Channel>()); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty object"); } [TestMethod] public void GeneratesCorrectEmptyChannelObject() { var c = new Channel("BED_42", new List<Namespace>()); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty_channel"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty channel"); } [TestMethod] public void GeneratesCorrectEmptyNamespaceObject() { // XXX: Do ticks work like this? var t0 = new DateTime(14334371443018100L); var dt = new TimeSpan(0, 0, 3); var n = new Namespace("GEWAVE", t0, dt, new List<Signal>(), new List<Event>(), new List<Alarm>()); var c = new Channel("BED_42", new List<Namespace>(new Namespace[] { n })); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty_namespace"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty namespace"); } } }
using System; using System.Web; using Microsoft.VisualStudio.TestTools.UnitTesting; using OWF.Serializers; using OWF.DTO; using System.Collections.Generic; namespace OWF_test.Serializers { [TestClass] public class BinarySerializerTests { private byte[] ReadOWF(string filename) { return System.IO.File.ReadAllBytes(String.Join("/", "..", "..", "..", "..", "example", "owf1_" + filename + ".owf")); } [TestMethod] public void GeneratesCorrectEmptyObject() { var p = new Package(new List<Channel>()); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty object"); } [TestMethod] public void GeneratesCorrectEmptyChannelObject() { var c = new Channel("BED_42", new List<Namespace>()); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty_channel"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty channel"); } [TestMethod] public void GeneratesCorrectEmptyNamespaceObject() { // TODO: This may be incorrect. var t0 = new DateTime(2015, 6, 4, 16, 59, 4, 3018); var dt = new TimeSpan(0, 0, 3); var n = new Namespace("GEWAVE", t0, dt, new List<Signal>(), new List<Event>(), new List<Alarm>()); var c = new Channel("BED_42", new List<Namespace>(new Namespace[] { n })); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = ReadOWF("binary_valid_empty_namespace"); CollectionAssert.AreEqual(buffer, expected, "Incorrect empty namespace"); } } }
apache-2.0
C#
bba77e124aa0228efebff783f856045fe5885f2d
Replace SafeHandleZeroOrMinusOneIsInvalid with SafeHandle
GeertvanHorrik/libgit2sharp,Skybladev2/libgit2sharp,AMSadek/libgit2sharp,jorgeamado/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,Zoxive/libgit2sharp,GeertvanHorrik/libgit2sharp,jamill/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,sushihangover/libgit2sharp,red-gate/libgit2sharp,xoofx/libgit2sharp,vivekpradhanC/libgit2sharp,github/libgit2sharp,OidaTiftla/libgit2sharp,vorou/libgit2sharp,nulltoken/libgit2sharp,carlosmn/libgit2sharp,shana/libgit2sharp,OidaTiftla/libgit2sharp,ethomson/libgit2sharp,libgit2/libgit2sharp,dlsteuer/libgit2sharp,oliver-feng/libgit2sharp,red-gate/libgit2sharp,PKRoma/libgit2sharp,psawey/libgit2sharp,rcorre/libgit2sharp,Zoxive/libgit2sharp,paulcbetts/libgit2sharp,vivekpradhanC/libgit2sharp,jamill/libgit2sharp,ethomson/libgit2sharp,psawey/libgit2sharp,mono/libgit2sharp,whoisj/libgit2sharp,paulcbetts/libgit2sharp,nulltoken/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,AArnott/libgit2sharp,jeffhostetler/public_libgit2sharp,vorou/libgit2sharp,mono/libgit2sharp,AArnott/libgit2sharp,github/libgit2sharp,Skybladev2/libgit2sharp,jeffhostetler/public_libgit2sharp,oliver-feng/libgit2sharp,carlosmn/libgit2sharp,jorgeamado/libgit2sharp,rcorre/libgit2sharp,shana/libgit2sharp,sushihangover/libgit2sharp,whoisj/libgit2sharp,xoofx/libgit2sharp
LibGit2Sharp/RepositorySafeHandle.cs
LibGit2Sharp/RepositorySafeHandle.cs
using System; using System.Runtime.InteropServices; using LibGit2Sharp.Core; namespace LibGit2Sharp { public class RepositorySafeHandle : SafeHandle { public RepositorySafeHandle() : base(IntPtr.Zero, true) { } protected override bool ReleaseHandle() { NativeMethods.git_repository_free(handle); return true; } public override bool IsInvalid { get { return (handle == IntPtr.Zero); } } } }
using LibGit2Sharp.Core; using Microsoft.Win32.SafeHandles; namespace LibGit2Sharp { public class RepositorySafeHandle : SafeHandleZeroOrMinusOneIsInvalid { public RepositorySafeHandle() : base(true) { } protected override bool ReleaseHandle() { NativeMethods.git_repository_free(handle); return true; } } }
mit
C#
643658357eb784a62909537b677726deb44a8380
修改App Title
JunhuaFan/NASA_UNCLE,JunhuaFan/NASA_UNCLE,JunhuaFan/NASA_UNCLE
nasauncle/Views/Shared/_Layout.cshtml
nasauncle/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Nasa 大叔隊</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> --> @Html.ActionLink("上上籤-預卜神算", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("全球", "Index", "Home")</li> <li>@Html.ActionLink("台灣", "TW", "Home")</li> </ul> <!-- @Html.Partial("_LoginPartial") --> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - NASA Hackthon Uncle Team.</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Nasa 大叔隊</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <!-- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> --> @Html.ActionLink("黑客松-大叔隊", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li>@Html.ActionLink("全球", "Index", "Home")</li> <li>@Html.ActionLink("台灣", "TW", "Home")</li> </ul> <!-- @Html.Partial("_LoginPartial") --> </div> </div> </div> <div class="container body-content"> @RenderBody() <hr /> <footer> <p>&copy; @DateTime.Now.Year - NASA Hackthon Uncle Team.</p> </footer> </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
apache-2.0
C#
2b8efb67904102354a7adc12ebc6efdb56fa9641
Add PushRegistration to UserData event
GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity,GoCarrot/teak-unity
Assets/Teak/Teak.UserData.cs
Assets/Teak/Teak.UserData.cs
#region References /// @cond hide_from_doxygen using System; using System.Collections.Generic; /// @endcond #endregion public partial class Teak { /// <summary> /// /// </summary> public class UserData { /// <summary>Arbitrary, per-user, information sent from the Teak server.</summary> public Dictionary<string, object> AdditionalData { get; private set; } /// <summary>True if the user has opted out of Teak email campaigns.</summary> public bool OptOutEmail { get; private set; } /// <summary>True if the user has opted out of Teak push notification campaigns.</summary> public bool OptOutPush { get; private set; } /// <summary>Push registration information for the current user, if available.</summary> public Dictionary<string, object> PushRegistration { get; private set; } internal UserData(Dictionary<string, object> json) { this.AdditionalData = json["additionalData"] as Dictionary<string, object>; this.OptOutEmail = Convert.ToBoolean(json["optOutEmail"]); this.OptOutPush = Convert.ToBoolean(json["optOutPush"]); this.PushRegistration = json["pushRegistration"] as Dictionary<string, object>; } } }
#region References /// @cond hide_from_doxygen using System; using System.Collections.Generic; /// @endcond #endregion public partial class Teak { /// <summary> /// /// </summary> public class UserData { /// <summary>Arbitrary, per-user, information sent from the Teak server.</summary> public Dictionary<string, object> AdditionalData { get; private set; } /// <summary>True if the user has opted out of Teak email campaigns.</summary> public bool OptOutEmail { get; private set; } /// <summary>True if the user has opted out of Teak push notification campaigns.</summary> public bool OptOutPush { get; private set; } internal UserData(Dictionary<string, object> json) { this.AdditionalData = json["additionalData"] as Dictionary<string, object>; this.OptOutEmail = Convert.ToBoolean(json["optOutEmail"]); this.OptOutPush = Convert.ToBoolean(json["optOutPush"]); } } }
apache-2.0
C#
f43643dbd12fe3e6dca9bdf39ca178d30aaa0a81
check for dup keys in dictionary before adding
MrLeebo/unitystation,Lancemaker/unitystation,Necromunger/unitystation,MrLeebo/unitystation,fomalsd/unitystation,MrLeebo/unitystation,fomalsd/unitystation,Lancemaker/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,fomalsd/unitystation,Necromunger/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,krille90/unitystation,fomalsd/unitystation
Assets/scripts/GameMatrix.cs
Assets/scripts/GameMatrix.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameMatrix : MonoBehaviour { public static GameMatrix control; //items public Dictionary<int,GameObject> items = new Dictionary<int,GameObject>(); //cupboards public Dictionary<int,Cupboards.DoorTrigger> cupboards = new Dictionary<int,Cupboards.DoorTrigger>(); private PhotonView photonView; //This is to sync destroy commands void Awake() { if (control == null) { control = this; } else { Destroy(this); } photonView = gameObject.GetComponent<PhotonView>(); } //Add each item to the items dictionary along with their photonView.viewID as key public void AddItem(int viewID, GameObject theItem) { if (!items.ContainsKey(viewID)) { items.Add (viewID, theItem); } else { Debug.Log ("Warning! item already exists in dictionary. ViewID: " + viewID + " Item " + theItem.name); } } //Add each cupB to the items dictionary along with its photonView.viewID as key (this will be doortriggers) public void AddCupboard(int viewID, Cupboards.DoorTrigger theCupB) //To get transform.position then look at the DoorTrigger.transform.parent { cupboards.Add(viewID, theCupB); } public void RemoveItem(int viewID) { //For removing items from the game, on all clients photonView.RPC("MasterClientDestroyItem", PhotonTargets.MasterClient, viewID); //Get masterclient to remove item from game } public void InstantiateItem(string prefabName, Vector3 pos, Quaternion rot, int itemGroup, object[] data) //Need to send this to the client as only the client can make scene objs { photonView.RPC("MasterClientCreateItem", PhotonTargets.MasterClient, prefabName, pos, rot, itemGroup, data); } [PunRPC] void MasterClientCreateItem(string prefabName, Vector3 pos, Quaternion rot, int itemGroup, object[] data){ PhotonNetwork.InstantiateSceneObject(prefabName, pos, rot, itemGroup, data); } [PunRPC] void MasterClientDestroyItem(int viewID) { //Only objects can be destroyed by client PhotonNetwork.Destroy(items[viewID]); } [PunRPC] void RemoveItemOnNetwork(int viewID) { items.Remove(viewID); photonView.RPC("RemoveItemOnNetwork", PhotonTargets.All, viewID); //This removes the dictionary record on all clients including this } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameMatrix : MonoBehaviour { public static GameMatrix control; //items public Dictionary<int,GameObject> items = new Dictionary<int,GameObject>(); //cupboards public Dictionary<int,Cupboards.DoorTrigger> cupboards = new Dictionary<int,Cupboards.DoorTrigger>(); private PhotonView photonView; //This is to sync destroy commands void Awake() { if (control == null) { control = this; } else { Destroy(this); } photonView = gameObject.GetComponent<PhotonView>(); } //Add each item to the items dictionary along with their photonView.viewID as key public void AddItem(int viewID, GameObject theItem) { items.Add(viewID, theItem); } //Add each cupB to the items dictionary along with its photonView.viewID as key (this will be doortriggers) public void AddCupboard(int viewID, Cupboards.DoorTrigger theCupB) //To get transform.position then look at the DoorTrigger.transform.parent { cupboards.Add(viewID, theCupB); } public void RemoveItem(int viewID) { //For removing items from the game, on all clients photonView.RPC("MasterClientDestroyItem", PhotonTargets.MasterClient, viewID); //Get masterclient to remove item from game } public void InstantiateItem(string prefabName, Vector3 pos, Quaternion rot, int itemGroup, object[] data) //Need to send this to the client as only the client can make scene objs { photonView.RPC("MasterClientCreateItem", PhotonTargets.MasterClient, prefabName, pos, rot, itemGroup, data); } [PunRPC] void MasterClientCreateItem(string prefabName, Vector3 pos, Quaternion rot, int itemGroup, object[] data){ PhotonNetwork.InstantiateSceneObject(prefabName, pos, rot, itemGroup, data); } [PunRPC] void MasterClientDestroyItem(int viewID) { //Only objects can be destroyed by client PhotonNetwork.Destroy(items[viewID]); } [PunRPC] void RemoveItemOnNetwork(int viewID) { items.Remove(viewID); photonView.RPC("RemoveItemOnNetwork", PhotonTargets.All, viewID); //This removes the dictionary record on all clients including this } }
agpl-3.0
C#
fcf7feba6eec1ea714fbd4f5e8c72efe07739962
Change name of unitytest
CPLN/en-voiture
EnVoitureUnitTest/TestWay.cs
EnVoitureUnitTest/TestWay.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using EnVoiture; using System.Drawing; namespace EnVoitureUnitTest { [TestClass] public class TestWay { [TestMethod] public void TestLocation() { List<Orientation> o = new List<Orientation>(); Way w = new Way(0, 0, 20, 30, o); Assert.AreEqual(w.Location, new Point(0, 0)); } [TestMethod] public void TestSize() { List<Orientation> o = new List<Orientation>(); Way w = new Way(new Point(0, 0), new Size(20, 30), o); Assert.AreEqual(w.Size, new Size(20, 30)); } [TestMethod] public void TestOppositeOrientationNS() { Assert.AreEqual(Orientation.NORTH.getOpposite(), Orientation.SOUTH); } [TestMethod] public void TestOppositeOrientationWE() { Assert.AreEqual(Orientation.WEST.getOpposite(), Orientation.EAST); } [TestMethod] public void TestCreatWayPosition() { List<Orientation> o = new List<Orientation>(); Way w1 = new Way(2, 1, 20, 30, o); Assert.AreEqual(2, w1.Location.X); Assert.AreEqual(1, w1.Location.Y); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; using EnVoiture; using System.Drawing; namespace EnVoitureUnitTest { [TestClass] public class TestWay { [TestMethod] public void TestLocation() { List<Orientation> o = new List<Orientation>(); Way w = new Way(0, 0, 20, 30, o); Assert.AreEqual(w.Location, new Point(0, 0)); } [TestMethod] public void TestSize() { List<Orientation> o = new List<Orientation>(); Way w = new Way(new Point(0, 0), new Size(20, 30), o); Assert.AreEqual(w.Size, new Size(20, 30)); } [TestMethod] public void TestOppositeOrientationNS() { Assert.AreEqual(Orientation.NORTH.getOpposite(), Orientation.SOUTH); } [TestMethod] public void TestOppositeOrientationWE() { Assert.AreEqual(Orientation.WEST.getOpposite(), Orientation.EAST); } [TestMethod] public void TestCreatWay() { List<Orientation> o = new List<Orientation>(); Way w1 = new Way(2, 1, 20, 30, o); Assert.AreEqual(2, w1.Location.X); Assert.AreEqual(1, w1.Location.Y); } } }
mit
C#
b2a0fa42495bb484dc1d4d4719f72f64657b623d
Set assembly version number of Prexonite to 1.2.2
SealedSun/prx
Prexonite/Properties/AssemblyInfo.cs
Prexonite/Properties/AssemblyInfo.cs
using System; 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("Prexonite")] [assembly: AssemblyDescription("Prexonite Scripting Engine")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Christian Klauser")] [assembly: AssemblyProduct("Prexonite")] [assembly: AssemblyCopyright("Copyright 2011")] [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("08e2ed9a-d0e0-471d-8a8b-d87cd9422bfa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")] [assembly: CLSCompliant(true)]
using System; 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("Prexonite")] [assembly: AssemblyDescription("Prexonite Scripting Engine")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Christian Klauser")] [assembly: AssemblyProduct("Prexonite")] [assembly: AssemblyCopyright("Copyright 2011")] [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("08e2ed9a-d0e0-471d-8a8b-d87cd9422bfa")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")] [assembly: CLSCompliant(true)]
bsd-3-clause
C#
ed85e82c8876d50616872b9f87fb52171dc7997f
Set version.
Jaaromy/gitnet
gitnet.app/Properties/AssemblyInfo.cs
gitnet.app/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("gitnet.app")] [assembly: AssemblyDescription("Repository statistics from GitHub")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("gitnet.app")] [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("777eb724-e7e7-4021-a38a-86ead037798e")] // 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.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("gitnet.app")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("gitnet.app")] [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("777eb724-e7e7-4021-a38a-86ead037798e")] // 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#
940aac0f576184040709adbbe7d4bfa2a5481a1b
Change UserLearntWord to simplify system and reflect changes to system design
mtcairneyleeming/latin
auto_decliner/Database/UserLearntWord.cs
auto_decliner/Database/UserLearntWord.cs
using System; namespace LatinAutoDecline.Database { public class UserLearntWord { public string UserId { get; set; } public int LemmaId { get; set; } public DateTime NextRevision { get; set; } public int RevisionStage { get; set; } public Lemma Lemma { get; set; } } }
using System; namespace LatinAutoDecline.Database { public class UserLearntWord { public string UserId { get; set; } public int LemmaId { get; set; } public double LearntPercentage { get; set; } public DateTime NextRevision { get; set; } public int RevisionStage { get; set; } public Lemma Lemma { get; set; } } }
mit
C#
53d06c32fc46ad26e10ae46803dd351a8ae7eefe
change Insert signature to use interface
sqlkata/querybuilder
QueryBuilder/Query.Insert.cs
QueryBuilder/Query.Insert.cs
using System; using System.Collections.Generic; using System.Linq; namespace SqlKata { public partial class Query { public Query Insert(IEnumerable<string> columns, IEnumerable<object> values) { if (columns.Count() != values.Count()) { throw new InvalidOperationException("Columns count should be equal to Values count"); } Method = "insert"; Clear("insert").Add("insert", new InsertClause { Columns = columns.ToList(), Values = values.ToList() }); return this; } public Query Insert(IReadOnlyDictionary<string, object> data) { Method = "insert"; Clear("insert").Add("insert", new InsertClause { Columns = data.Keys.ToList(), Values = data.Values.ToList() }); return this; } /// <summary> /// Produces insert from subquery /// </summary> /// <param name="columns"></param> /// <param name="query"></param> /// <returns></returns> public Query Insert(IEnumerable<string> columns, Query query) { Method = "insert"; Clear("insert").Add("insert", new InsertQueryClause { Columns = columns.ToList(), Query = query }); return this; } } }
using System; using System.Collections.Generic; using System.Linq; namespace SqlKata { public partial class Query { public Query Insert(IEnumerable<string> columns, IEnumerable<object> values) { if (columns.Count() != values.Count()) { throw new InvalidOperationException("Columns count should be equal to Values count"); } Method = "insert"; Clear("insert").Add("insert", new InsertClause { Columns = columns.ToList(), Values = values.ToList() }); return this; } public Query Insert(Dictionary<string, object> data) { Method = "insert"; Clear("insert").Add("insert", new InsertClause { Columns = data.Keys.ToList(), Values = data.Values.ToList() }); return this; } /// <summary> /// Produces insert from subquery /// </summary> /// <param name="columns"></param> /// <param name="query"></param> /// <returns></returns> public Query Insert(IEnumerable<string> columns, Query query) { Method = "insert"; Clear("insert").Add("insert", new InsertQueryClause { Columns = columns.ToList(), Query = query }); return this; } } }
mit
C#
77ebfd7b2b072f539bc2bcd91ab08de52439b26f
fix spelling
zmira/abremir.AllMyBricks
abremir.AllMyBricks.Onboarding.Tests/Services/OnboardingServiceTests.cs
abremir.AllMyBricks.Onboarding.Tests/Services/OnboardingServiceTests.cs
using abremir.AllMyBricks.Core.Models; using abremir.AllMyBricks.Onboarding.Interfaces; using abremir.AllMyBricks.Onboarding.Services; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace abremir.AllMyBricks.Onboarding.Tests.Services { [TestClass] public class OnboardingServiceTests { private static IRegistrationService _registrationService; private static IApiKeyService _apiKeyService; [ClassInitialize] #pragma warning disable RCS1163 // Unused parameter. #pragma warning disable RECS0154 // Parameter is never used public static void ClassInitialize(TestContext testContext) #pragma warning restore RECS0154 // Parameter is never used #pragma warning restore RCS1163 // Unused parameter. { _registrationService = new RegistrationService(); _apiKeyService = new ApiKeyService(); } [TestMethod, Ignore("Only to be used to validate communication between app and onboarding endpoints")] public void EndToEndTest() { var identification = new Identification { DeviceIdentification = new Device { AppId = Guid.NewGuid().ToString(), DeviceHash = Guid.NewGuid().ToString(), DeviceHashDate = DateTimeOffset.Now, Model = "MODEL", Platform = "PLATFORM", Version = "VERSION" } }; identification = _registrationService.Register(identification); var apiKey = _apiKeyService.GetBricksetApiKey(identification); apiKey.Should().NotBeNullOrEmpty(); _registrationService.Unregister(identification); } } }
using abremir.AllMyBricks.Core.Models; using abremir.AllMyBricks.Onboarding.Interfaces; using abremir.AllMyBricks.Onboarding.Services; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace abremir.AllMyBricks.Onboarding.Tests.Services { [TestClass] public class OnboardingServiceTests { private static IRegistrationService _registrationService; private static IApiKeyService _apiKeyService; [ClassInitialize] #pragma warning disable RCS1163 // Unused parameter. #pragma warning disable RECS0154 // Parameter is never used public static void ClassInitialize(TestContext testContext) #pragma warning restore RECS0154 // Parameter is never used #pragma warning restore RCS1163 // Unused parameter. { _registrationService = new RegistrationService(); _apiKeyService = new ApiKeyService(); } [TestMethod, Ignore("Only to be used to validate comunication between app and onboarding endpoints")] public void EndToEndTest() { var identification = new Identification { DeviceIdentification = new Device { AppId = Guid.NewGuid().ToString(), DeviceHash = Guid.NewGuid().ToString(), DeviceHashDate = DateTimeOffset.Now, Model = "MODEL", Platform = "PLATFORM", Version = "VERSION" } }; identification = _registrationService.Register(identification); var apiKey = _apiKeyService.GetBricksetApiKey(identification); apiKey.Should().NotBeNullOrEmpty(); _registrationService.Unregister(identification); } } }
mit
C#
c1a331b9062370a4d511ddfef2c55bfe03ac86f0
Add App Service.
OrionDevelop/Orion,mika-f/Orion
Source/Orion.UWP/App.xaml.cs
Source/Orion.UWP/App.xaml.cs
using System.Diagnostics; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Microsoft.Azure.Mobile; using Microsoft.Azure.Mobile.Analytics; using Microsoft.Practices.Unity; using Orion.UWP.Models; using Orion.UWP.Services; using Orion.UWP.Services.Interfaces; using Prism.Unity.Windows; namespace Orion.UWP { /// <summary> /// 既定の Application クラスを補完するアプリケーション固有の動作を提供します。 /// </summary> public sealed partial class App : PrismUnityApplication { /// <summary> /// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの /// 最初の行であるため、main() または WinMain() と論理的に等価です。 /// </summary> public App() { InitializeComponent(); UnhandledException += (sender, e) => { if (Debugger.IsAttached) Debugger.Break(); }; } protected override async Task OnInitializeAsync(IActivatedEventArgs args) { // Prism Container.RegisterInstance(NavigationService); Container.RegisterInstance(SessionStateService); // Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader())); // Internal var accountService = new AccountService(); // await accountService.ClearAsync(); await accountService.RestoreAsync(); Container.RegisterInstance<IAccountService>(accountService, new ContainerControlledLifetimeManager()); Container.RegisterType<IConfigurationService, ConfigurationService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IDialogService, DialogService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IOrionNavigationService, OrionNavigationService>(new ContainerControlledLifetimeManager()); Container.RegisterType<ITimelineService, TimelineService>(new ContainerControlledLifetimeManager()); Container.RegisterType<GlobalNotifier>(new ContainerControlledLifetimeManager()); await base.OnInitializeAsync(args); } protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) { MobileCenter.Start("da64efe6-0b35-4c47-bd6d-e5ef603162bf", typeof(Analytics)); NavigationService.Navigate("Main", null); return Task.CompletedTask; } } }
using System.Diagnostics; using System.Threading.Tasks; using Windows.ApplicationModel.Activation; using Microsoft.Practices.Unity; using Orion.UWP.Models; using Orion.UWP.Services; using Orion.UWP.Services.Interfaces; using Prism.Unity.Windows; namespace Orion.UWP { /// <summary> /// 既定の Application クラスを補完するアプリケーション固有の動作を提供します。 /// </summary> public sealed partial class App : PrismUnityApplication { /// <summary> /// 単一アプリケーション オブジェクトを初期化します。これは、実行される作成したコードの /// 最初の行であるため、main() または WinMain() と論理的に等価です。 /// </summary> public App() { InitializeComponent(); UnhandledException += (sender, e) => { if (Debugger.IsAttached) Debugger.Break(); }; } protected override async Task OnInitializeAsync(IActivatedEventArgs args) { // Prism Container.RegisterInstance(NavigationService); Container.RegisterInstance(SessionStateService); // Container.RegisterInstance<IResourceLoader>(new ResourceLoaderAdapter(new ResourceLoader())); // Internal var accountService = new AccountService(); // await accountService.ClearAsync(); await accountService.RestoreAsync(); Container.RegisterInstance<IAccountService>(accountService, new ContainerControlledLifetimeManager()); Container.RegisterType<IConfigurationService, ConfigurationService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IDialogService, DialogService>(new ContainerControlledLifetimeManager()); Container.RegisterType<IOrionNavigationService, OrionNavigationService>(new ContainerControlledLifetimeManager()); Container.RegisterType<ITimelineService, TimelineService>(new ContainerControlledLifetimeManager()); Container.RegisterType<GlobalNotifier>(new ContainerControlledLifetimeManager()); await base.OnInitializeAsync(args); } protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args) { NavigationService.Navigate("Main", null); return Task.CompletedTask; } } }
mit
C#
7bed4eb23b73ec49bba20136d5aa6c257cb474f1
Tidy up WaveformTestBeatmap
peppy/osu-new,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,ZLima12/osu,ppy/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,ZLima12/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu
osu.Game.Tests/WaveformTestBeatmap.cs
osu.Game.Tests/WaveformTestBeatmap.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.IO; using System.Linq; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; namespace osu.Game.Tests { /// <summary> /// A <see cref="WorkingBeatmap"/> that is used for test scenes that include waveforms. /// </summary> public class WaveformTestBeatmap : WorkingBeatmap { private readonly ZipArchiveReader reader; private readonly Stream stream; private readonly ITrackStore trackStore; public WaveformTestBeatmap(AudioManager audioManager) : base(new BeatmapInfo(), audioManager) { stream = TestResources.GetTestBeatmapStream(); reader = new ZipArchiveReader(stream); trackStore = audioManager.GetTrackStore(reader); } public override void Dispose() { base.Dispose(); stream?.Dispose(); reader?.Dispose(); trackStore?.Dispose(); } protected override IBeatmap GetBeatmap() => createTestBeatmap(); protected override Texture GetBackground() => null; protected override Waveform GetWaveform() => new Waveform(trackStore.GetStream(firstAudioFile)); protected override Track GetTrack() => trackStore.Get(firstAudioFile); private string firstAudioFile => reader.Filenames.First(f => f.EndsWith(".mp3")); private Stream getBeatmapStream() => reader.GetStream(reader.Filenames.First(f => f.EndsWith(".osu"))); private Beatmap createTestBeatmap() { using (var beatmapStream = getBeatmapStream()) using (var beatmapReader = new StreamReader(beatmapStream)) return Decoder.GetDecoder<Beatmap>(beatmapReader).Decode(beatmapReader); } } }
// 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.IO; using System.Linq; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Formats; using osu.Game.IO.Archives; using osu.Game.Tests.Resources; namespace osu.Game.Tests { /// <summary> /// A <see cref="WorkingBeatmap"/> that is used for test scenes that include waveforms. /// </summary> public class WaveformTestBeatmap : WorkingBeatmap { private readonly ZipArchiveReader reader; private readonly Stream stream; private readonly ITrackStore trackStore; public WaveformTestBeatmap(AudioManager audioManager) : base(new BeatmapInfo(), audioManager) { stream = TestResources.GetTestBeatmapStream(); reader = new ZipArchiveReader(stream); trackStore = audioManager.GetTrackStore(reader); } public override void Dispose() { base.Dispose(); stream?.Dispose(); reader?.Dispose(); trackStore?.Dispose(); } protected override IBeatmap GetBeatmap() => createTestBeatmap(); protected override Texture GetBackground() => null; protected override Waveform GetWaveform() => new Waveform(trackStore.GetStream(reader.Filenames.First(f => f.EndsWith(".mp3")))); protected override Track GetTrack() => trackStore.Get(reader.Filenames.First(f => f.EndsWith(".mp3"))); private Stream getBeatmapStream() => reader.GetStream(reader.Filenames.First(f => f.EndsWith(".osu"))); private Beatmap createTestBeatmap() { using (var beatmapStream = getBeatmapStream()) using (var beatmapReader = new StreamReader(beatmapStream)) return Decoder.GetDecoder<Beatmap>(beatmapReader).Decode(beatmapReader); } } }
mit
C#
d983c9a97f8ccaf6599299798bfbff387557ae3e
Support OpenCL 2.0 at test execution time
tunnelvisionlabs/NOpenCL,sharwell/NOpenCL
NOpenCL.Test/TestPlatform.cs
NOpenCL.Test/TestPlatform.cs
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class TestPlatform { [TestMethod] public void TestGetPlatforms() { Platform[] platforms = Platform.GetPlatforms(); Assert.IsNotNull(platforms); if (platforms.Length == 0) { Assert.Inconclusive("No OpenCL platforms found."); return; } foreach (Platform platform in platforms) { TestPlatformProperties(platform); } } private static void TestPlatformProperties(Platform platform) { Assert.IsNotNull(platform); Console.WriteLine(platform.ToString()); string profile = platform.Profile; Assert.IsNotNull(profile); switch (profile) { case "FULL_PROFILE": case "EMBEDDED_PROFILE": break; default: Assert.Inconclusive("Unknown platform profile: " + profile); break; } string version = platform.Version; StringAssert.Matches(version, new Regex("^OpenCL (?:1.[12]|2.0) .*$")); string name = platform.Name; Assert.IsNotNull(name); Assert.AreNotEqual(string.Empty, name); string vendor = platform.Vendor; Assert.IsNotNull(vendor); Assert.AreNotEqual(string.Empty, vendor); IReadOnlyList<string> extensions = platform.Extensions; Assert.IsNotNull(extensions); foreach (string extension in extensions) { Assert.IsNotNull(extension); Assert.AreNotEqual(string.Empty, extension); } } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NOpenCL.Test { using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class TestPlatform { [TestMethod] public void TestGetPlatforms() { Platform[] platforms = Platform.GetPlatforms(); Assert.IsNotNull(platforms); if (platforms.Length == 0) { Assert.Inconclusive("No OpenCL platforms found."); return; } foreach (Platform platform in platforms) { TestPlatformProperties(platform); } } private static void TestPlatformProperties(Platform platform) { Assert.IsNotNull(platform); Console.WriteLine(platform.ToString()); string profile = platform.Profile; Assert.IsNotNull(profile); switch (profile) { case "FULL_PROFILE": case "EMBEDDED_PROFILE": break; default: Assert.Inconclusive("Unknown platform profile: " + profile); break; } string version = platform.Version; StringAssert.Matches(version, new Regex("^OpenCL 1.[12] .*$")); string name = platform.Name; Assert.IsNotNull(name); Assert.AreNotEqual(string.Empty, name); string vendor = platform.Vendor; Assert.IsNotNull(vendor); Assert.AreNotEqual(string.Empty, vendor); IReadOnlyList<string> extensions = platform.Extensions; Assert.IsNotNull(extensions); foreach (string extension in extensions) { Assert.IsNotNull(extension); Assert.AreNotEqual(string.Empty, extension); } } } }
mit
C#
db60f393b7ec36c2e295f0ccf340895ba6038605
Add offsite types for installment citi
omise/omise-dotnet
Omise/Models/OffsiteTypes.cs
Omise/Models/OffsiteTypes.cs
using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "installment_citi")] InstallmentCiti, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } }
using System.Runtime.Serialization; namespace Omise.Models { public enum OffsiteTypes { [EnumMember(Value = null)] None, [EnumMember(Value = "internet_banking_scb")] InternetBankingSCB, [EnumMember(Value = "internet_banking_bbl")] InternetBankingBBL, [EnumMember(Value = "internet_banking_ktb")] InternetBankingKTB, [EnumMember(Value = "internet_banking_bay")] InternetBankingBAY, [EnumMember(Value = "alipay")] AlipayOnline, [EnumMember(Value = "installment_bay")] InstallmentBAY, [EnumMember(Value = "installment_kbank")] InstallmentKBank, [EnumMember(Value = "bill_payment_tesco_lotus")] BillPaymentTescoLotus, [EnumMember(Value = "barcode_alipay")] BarcodeAlipay, [EnumMember(Value = "paynow")] Paynow, [EnumMember(Value = "points_citi")] PointsCiti, [EnumMember(Value = "promptpay")] PromptPay, [EnumMember(Value = "truemoney")] TrueMoney } }
mit
C#
d7418111740255f8ae485d80d3989e5c1195164d
add tests for AddRoute<>
Pondidum/Conifer,Pondidum/Conifer
Conifer.Tests/RouterConfigurationExpressionTests.cs
Conifer.Tests/RouterConfigurationExpressionTests.cs
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using Conifer.Conventions; using NSubstitute; using Shouldly; using Xunit; namespace Conifer.Tests { public class RouterConfigurationExpressionTests { private readonly IConventionalRouter _router; private readonly RouterConfigurationExpression _expression; public RouterConfigurationExpressionTests() { _router = Substitute.For<IConventionalRouter>(); _expression = new RouterConfigurationExpression(_router); } [Fact] public void When_no_default_conventions_are_specified() { _expression.AddAll<Controller>(); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(Default.Conventions))); } [Fact] public void When_no_default_conventions_are_specified_and_individual_are_used() { _expression.AddAll<Controller>(new[] { new ControllerNameRouteConvention() }); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } [Fact] public void When_no_default_conventions_are_specified_and_null_is_specified() { _expression.AddAll<Controller>(null); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBeEmpty())); } [Fact] public void When_default_conventions_are_specified() { _expression.DefaultConventionsAre(new[] { new ControllerNameRouteConvention() }); _expression.AddAll<Controller>(); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } [Fact] public void When_adding_a_single_method_and_no_default_conventions_are_specified() { _expression.Add<Controller>(c => c.Test()); _router.Received().AddRoute<Controller>(Arg.Any<Expression<Action<Controller>>>(), Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(Default.Conventions))); } [Fact] public void When_adding_a_single_method_and_no_default_conventions_are_specified_and_individual_are_used() { _expression.Add<Controller>(c => c.Test(), new[] { new ControllerNameRouteConvention() }); _router.Received().AddRoute<Controller>(Arg.Any<Expression<Action<Controller>>>(), Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } [Fact] public void When_adding_a_single_method_and_no_default_conventions_are_specified_and_null_is_specified() { _expression.Add<Controller>(c => c.Test(), null); _router.Received().AddRoute<Controller>(Arg.Any<Expression<Action<Controller>>>(), Arg.Do<List<IRouteConvention>>(x => x.ShouldBeEmpty())); } [Fact] public void When_adding_a_single_method_and_default_conventions_are_specified() { _expression.DefaultConventionsAre(new[] { new ControllerNameRouteConvention() }); _expression.Add<Controller>(c => c.Test()); _router.Received().AddRoute<Controller>(Arg.Any<Expression<Action<Controller>>>(), Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } private class Controller : IHttpController { public Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } public string Test() { return string.Empty; } } } }
using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; using Conifer.Conventions; using NSubstitute; using Shouldly; using Xunit; namespace Conifer.Tests { public class RouterConfigurationExpressionTests { private readonly IConventionalRouter _router; private readonly RouterConfigurationExpression _expression; public RouterConfigurationExpressionTests() { _router = Substitute.For<IConventionalRouter>(); _expression = new RouterConfigurationExpression(_router); } [Fact] public void When_no_default_conventions_are_specified() { _expression.AddAll<Controller>(); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(Default.Conventions))); } [Fact] public void When_no_default_conventions_are_specified_and_individual_are_used() { _expression.AddAll<Controller>(new[] { new ControllerNameRouteConvention() }); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } [Fact] public void When_no_default_conventions_are_specified_and_null_is_specified() { _expression.AddAll<Controller>(null); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBeEmpty())); } [Fact] public void When_default_conventions_are_specified() { _expression.DefaultConventionsAre(new[] { new ControllerNameRouteConvention() }); _expression.AddAll<Controller>(); _router.Received().AddRoutes<Controller>(Arg.Do<List<IRouteConvention>>(x => x.ShouldBe(new[] { new ControllerNameRouteConvention() }))); } private class Controller : IHttpController { public Task<HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) { throw new System.NotImplementedException(); } } } }
lgpl-2.1
C#
6c4b83d6fe67884470a1876b8f2e7b1d999810b8
Fix failing tests on dotnetcore
criteo/zipkin4net,criteo/zipkin4net
Criteo.Profiling.Tracing/Properties/AssemblyInfo.cs
Criteo.Profiling.Tracing/Properties/AssemblyInfo.cs
// Copyright 2017 Criteo // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Reflection; using System.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("Criteo.Profiling.Tracing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Criteo")] [assembly: AssemblyProduct("Criteo.Profiling.Tracing")] [assembly: AssemblyCopyright("Copyright © Criteo 2017")] [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("c86bf56d-9ac9-41d1-bbe4-6887a4176779")] // 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.1")] [assembly: AssemblyFileVersion("0.0.0.1")] [assembly: InternalsVisibleTo("Criteo.Profiling.Tracing.UTest")] [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// Copyright 2017 Criteo // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Reflection; using System.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("Criteo.Profiling.Tracing")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Criteo")] [assembly: AssemblyProduct("Criteo.Profiling.Tracing")] [assembly: AssemblyCopyright("Copyright © Criteo 2017")] [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("c86bf56d-9ac9-41d1-bbe4-6887a4176779")] // 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.1")] [assembly: AssemblyFileVersion("0.0.0.1")] [assembly: InternalsVisibleTo("Criteo.Profiling.Tracing.UTest")]
apache-2.0
C#
a19cac6ebe6892bc88c0244a031dabc12ee235ec
Update Program.cs
ddecours/building-blocks-demo
DemoConsoleApp/DemoConsoleApp/Program.cs
DemoConsoleApp/DemoConsoleApp/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello Doug!"); /// More } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DemoConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello"); /// More } } }
mit
C#
ad60e9dc82b549074302f85e487dd5014c7bbe64
Allow "user"-specified delegates to be passed to ShowOutputFromXmlRpcPInvoke, and prefix the output of the default delegate with a string indicating the source of the console spam.
uml-robotics/ROS.NET,nickkazepis/ROS.NET,beanstalk42/ROS.NET,nickkazepis/ROS.NET,nickkazepis/ROS.NET
XmlRpc_Wrapper/XmlRpcUtil.cs
XmlRpc_Wrapper/XmlRpcUtil.cs
using System; using System.Runtime.InteropServices; namespace XmlRpc_Wrapper { public static class XmlRpcUtil { private static printint _PRINTINT; private static printstr _PRINTSTR; private static void thisishowawesomeyouare(string s) { Console.WriteLine("XMLRPC NATIVE OUT: "+s); } public static void ShowOutputFromXmlRpcPInvoke(printstr handler = null) { if (handler == null) handler = thisishowawesomeyouare; if (handler != _PRINTSTR) { _PRINTSTR = thisishowawesomeyouare; SetAwesomeFunctionPtr(_PRINTSTR); } } #region bad voodoo [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void printstr(string s); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate void printint(int val); [DllImport("XmlRpcWin32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int IntegerEcho(int val); [DllImport("XmlRpcWin32.dll", EntryPoint = "IntegerEchoFunctionPtr", CallingConvention = CallingConvention.Cdecl )] private static extern void IntegerEchoFunctionPtr([MarshalAs(UnmanagedType.FunctionPtr)] printint callback); [DllImport("XmlRpcWin32.dll", EntryPoint = "IntegerEchoRepeat", CallingConvention = CallingConvention.Cdecl)] private static extern byte IntegerEchoRepeat(int val); [DllImport("XmlRpcWin32.dll", EntryPoint = "SetStringOutFunc", CallingConvention = CallingConvention.Cdecl)] private static extern void SetAwesomeFunctionPtr( [MarshalAs(UnmanagedType.FunctionPtr)] printstr callback); [DllImport("XmlRpcWin32.dll", EntryPoint = "StringPassingTest", CallingConvention = CallingConvention.Cdecl)] private static extern void StringTest([In] [Out] [MarshalAs(UnmanagedType.LPStr)] string str); #endregion } }
using System; using System.Runtime.InteropServices; namespace XmlRpc_Wrapper { public static class XmlRpcUtil { private static printint _PRINTINT; private static printstr _PRINTSTR; private static void thisishowawesomeyouare(string s) { Console.WriteLine(s); } public static void ShowOutputFromXmlRpcPInvoke() { if (_PRINTSTR == null) { _PRINTSTR = thisishowawesomeyouare; SetAwesomeFunctionPtr(_PRINTSTR); } } #region bad voodoo [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void printstr(string s); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void printint(int val); [DllImport("XmlRpcWin32.dll", CallingConvention = CallingConvention.Cdecl)] private static extern int IntegerEcho(int val); [DllImport("XmlRpcWin32.dll", EntryPoint = "IntegerEchoFunctionPtr", CallingConvention = CallingConvention.Cdecl )] private static extern void IntegerEchoFunctionPtr([MarshalAs(UnmanagedType.FunctionPtr)] printint callback); [DllImport("XmlRpcWin32.dll", EntryPoint = "IntegerEchoRepeat", CallingConvention = CallingConvention.Cdecl)] private static extern byte IntegerEchoRepeat(int val); [DllImport("XmlRpcWin32.dll", EntryPoint = "SetStringOutFunc", CallingConvention = CallingConvention.Cdecl)] private static extern void SetAwesomeFunctionPtr( [MarshalAs(UnmanagedType.FunctionPtr)] printstr callback); [DllImport("XmlRpcWin32.dll", EntryPoint = "StringPassingTest", CallingConvention = CallingConvention.Cdecl)] private static extern void StringTest([In] [Out] [MarshalAs(UnmanagedType.LPStr)] string str); #endregion } }
bsd-2-clause
C#
55231f833aabd312a5690178c1f5e2cc7dc38184
Bump version to 1.1.2
rosolko/WebDriverManager.Net
WebDriverManager/Properties/AssemblyInfo.cs
WebDriverManager/Properties/AssemblyInfo.cs
using System; 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("WebDriverManager.Net")] [assembly: AssemblyDescription("Automatic Selenium WebDriver binaries management for .Net")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Alexander Rosolko")] [assembly: AssemblyProduct("WebDriverManager.Net")] [assembly: AssemblyCopyright("Copyright © Alexander Rosolko 2016")] // 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("0066742e-391b-407c-9dc1-ff71a60bec53")] // 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.1.2.0")] [assembly: AssemblyFileVersion("1.1.2.0")]
using System; 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("WebDriverManager.Net")] [assembly: AssemblyDescription("Automatic Selenium WebDriver binaries management for .Net")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("Alexander Rosolko")] [assembly: AssemblyProduct("WebDriverManager.Net")] [assembly: AssemblyCopyright("Copyright © Alexander Rosolko 2016")] // 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("0066742e-391b-407c-9dc1-ff71a60bec53")] // 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.1.1.0")] [assembly: AssemblyFileVersion("1.1.1.0")]
mit
C#
a5a2336b4708403f6c395470be3944b047b0df71
add device name to low battery message
xpressive-websolutions/Xpressive.Home.ProofOfConcept,xpressive-websolutions/Xpressive.Home.ProofOfConcept,xpressive-websolutions/Xpressive.Home,xpressive-websolutions/Xpressive.Home.ProofOfConcept,xpressive-websolutions/Xpressive.Home,xpressive-websolutions/Xpressive.Home
Xpressive.Home.Services/LowBatteryDeviceObserver.cs
Xpressive.Home.Services/LowBatteryDeviceObserver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Autofac; using Xpressive.Home.Contracts.Gateway; using Xpressive.Home.Contracts.Messaging; namespace Xpressive.Home.Services { internal sealed class LowBatteryDeviceObserver : IStartable, IDisposable { private readonly IMessageQueue _messageQueue; private readonly IList<IGateway> _gateways; private readonly CancellationTokenSource _cancellationToken = new CancellationTokenSource(); public LowBatteryDeviceObserver(IMessageQueue messageQueue, IEnumerable<IGateway> gateways) { _messageQueue = messageQueue; _gateways = gateways.ToList(); } public void Start() { Task.Run(Observe); } public void Dispose() { _cancellationToken.Cancel(); _cancellationToken.Dispose(); } private async Task Observe() { while (!_cancellationToken.IsCancellationRequested) { foreach (var gateway in _gateways) { foreach (var device in gateway.Devices) { if (device.BatteryStatus == DeviceBatteryStatus.Low) { _messageQueue.Publish(new NotifyUserMessage($"Low battery on device {device.Name} ({gateway.Name}.{device.Id})")); } } } await Task.Delay(TimeSpan.FromHours(1), _cancellationToken.Token).ContinueWith(_ => { }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Autofac; using Xpressive.Home.Contracts.Gateway; using Xpressive.Home.Contracts.Messaging; namespace Xpressive.Home.Services { internal sealed class LowBatteryDeviceObserver : IStartable, IDisposable { private readonly IMessageQueue _messageQueue; private readonly IList<IGateway> _gateways; private readonly CancellationTokenSource _cancellationToken = new CancellationTokenSource(); public LowBatteryDeviceObserver(IMessageQueue messageQueue, IEnumerable<IGateway> gateways) { _messageQueue = messageQueue; _gateways = gateways.ToList(); } public void Start() { Task.Run(Observe); } public void Dispose() { _cancellationToken.Cancel(); _cancellationToken.Dispose(); } private async Task Observe() { while (!_cancellationToken.IsCancellationRequested) { foreach (var gateway in _gateways) { foreach (var device in gateway.Devices) { if (device.BatteryStatus == DeviceBatteryStatus.Low) { _messageQueue.Publish(new NotifyUserMessage($"Low battery on device {gateway.Name}.{device.Id}")); } } } await Task.Delay(TimeSpan.FromHours(1), _cancellationToken.Token).ContinueWith(_ => { }); } } } }
mit
C#
b03c1631d645c814141dc8c88457ef1af022f893
Remove unnecessary comment
peppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,peppy/osu-framework
osu.Framework/Platform/Linux/Sdl/SdlClipboard.cs
osu.Framework/Platform/Linux/Sdl/SdlClipboard.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { #if ANDROID const string lib = "libSDL2.so"; #elif IPHONE const string lib = "__Internal"; #else private const string lib = "libSDL2-2.0.so.0"; #endif [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern string SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { return SDL_GetClipboardText(); } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE // using System.Windows.Forms; using System.Runtime.InteropServices; namespace osu.Framework.Platform.Linux.Sdl { public class SdlClipboard : Clipboard { #if ANDROID const string lib = "libSDL2.so"; #elif IPHONE const string lib = "__Internal"; #else private const string lib = "libSDL2-2.0.so.0"; #endif [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_GetClipboardText", ExactSpelling = true)] internal static extern string SDL_GetClipboardText(); [DllImport(lib, CallingConvention = CallingConvention.Cdecl, EntryPoint = "SDL_SetClipboardText", ExactSpelling = true)] internal static extern int SDL_SetClipboardText(string text); public override string GetText() { return SDL_GetClipboardText(); } public override void SetText(string selectedText) { SDL_SetClipboardText(selectedText); } } }
mit
C#
9410234264342b70a91b4c6db56de15fdb67cb0d
fix Throttler limit condition
WasimAhmad/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity,dfaruque/Serenity,dfaruque/Serenity,dfaruque/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,dfaruque/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity
Serenity.Core/Authorization/Throttler.cs
Serenity.Core/Authorization/Throttler.cs
using Serenity.Abstractions; using System; namespace Serenity { public class Throttler { public Throttler(string key, TimeSpan duration, int limit) { Key = key; Duration = duration; Limit = limit; CacheKey = "Throttling:" + key + ":" + duration.Ticks.ToInvariant(); } public string Key { get; private set; } public TimeSpan Duration { get; private set; } public int Limit { get; private set; } public string CacheKey { get; private set; } private class HitInfo { public int Counter; } public bool Check() { var hit = Dependency.Resolve<ILocalCache>().Get<object>(this.CacheKey) as HitInfo; if (hit == null) { hit = new HitInfo { Counter = 1 }; Dependency.Resolve<ILocalCache>().Add(this.CacheKey, hit, this.Duration); } else { if (hit.Counter++ >= this.Limit) return false; } return true; } public void Reset() { Dependency.Resolve<ILocalCache>().Remove(CacheKey); } } }
using Serenity.Abstractions; using System; namespace Serenity { public class Throttler { public Throttler(string key, TimeSpan duration, int limit) { Key = key; Duration = duration; Limit = limit; CacheKey = "Throttling:" + key + ":" + duration.Ticks.ToInvariant(); } public string Key { get; private set; } public TimeSpan Duration { get; private set; } public int Limit { get; private set; } public string CacheKey { get; private set; } private class HitInfo { public int Counter; } public bool Check() { var hit = Dependency.Resolve<ILocalCache>().Get<object>(this.CacheKey) as HitInfo; if (hit == null) { hit = new HitInfo { Counter = 1 }; Dependency.Resolve<ILocalCache>().Add(this.CacheKey, hit, this.Duration); } else { if (hit.Counter++ > this.Limit) return false; } return true; } public void Reset() { Dependency.Resolve<ILocalCache>().Remove(CacheKey); } } }
mit
C#
3e80b9c5ae9153b17e1ec46c453c630905242b7b
Normalize line endings in text viewer
SteamDatabase/ValveResourceFormat
GUI/Types/Viewers/ByteViewer.cs
GUI/Types/Viewers/ByteViewer.cs
using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = Utils.Utils.NormalizeLineEndings(System.Text.Encoding.UTF8.GetString(input)), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } }
using System.IO; using System.Linq; using System.Windows.Forms; using GUI.Utils; namespace GUI.Types.Viewers { public class ByteViewer : IViewer { public static bool IsAccepted() => true; public TabPage Create(VrfGuiContext vrfGuiContext, byte[] input) { var tab = new TabPage(); var resTabs = new TabControl { Dock = DockStyle.Fill, }; tab.Controls.Add(resTabs); var bvTab = new TabPage("Hex"); var bv = new System.ComponentModel.Design.ByteViewer { Dock = DockStyle.Fill, }; bvTab.Controls.Add(bv); resTabs.TabPages.Add(bvTab); if (input == null) { input = File.ReadAllBytes(vrfGuiContext.FileName); } if (!input.Contains<byte>(0x00)) { var textTab = new TabPage("Text"); var text = new TextBox { Dock = DockStyle.Fill, ScrollBars = ScrollBars.Vertical, Multiline = true, ReadOnly = true, Text = System.Text.Encoding.UTF8.GetString(input), }; textTab.Controls.Add(text); resTabs.TabPages.Add(textTab); resTabs.SelectedTab = textTab; } Program.MainForm.Invoke((MethodInvoker)(() => { bv.SetBytes(input); })); return tab; } } }
mit
C#
006b07e9e9363d583b42bdc78240b8b98743fadf
Handle nullable value types in cursor
RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate
Source/Content/GraphQLTemplate/Cursor.cs
Source/Content/GraphQLTemplate/Cursor.cs
namespace GraphQLTemplate { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; public static class Cursor { public static T FromCursor<T>(string cursor) { if (string.IsNullOrEmpty(cursor)) { return default; } string decodedValue; try { decodedValue = Base64Decode(cursor); } catch (FormatException) { return default; } var type = typeof(T); type = Nullable.GetUnderlyingType(type) ?? type; return (T)Convert.ChangeType(decodedValue, type, CultureInfo.InvariantCulture); } public static (string firstCursor, string lastCursor) GetFirstAndLastCursor<TItem, TCursor>( IEnumerable<TItem> enumerable, Func<TItem, TCursor> getCursorProperty) { if (getCursorProperty == null) { throw new ArgumentNullException(nameof(getCursorProperty)); } if (enumerable == null || enumerable.Count() == 0) { return (null, null); } var firstCursor = ToCursor(getCursorProperty(enumerable.First())); var lastCursor = ToCursor(getCursorProperty(enumerable.Last())); return (firstCursor, lastCursor); } public static string ToCursor<T>(T value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Base64Encode(value.ToString()); } private static string Base64Decode(string value) => Encoding.UTF8.GetString(Convert.FromBase64String(value)); private static string Base64Encode(string value) => Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); } }
namespace GraphQLTemplate { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; public static class Cursor { public static T FromCursor<T>(string cursor) { if (string.IsNullOrEmpty(cursor)) { return default; } string decodedValue; try { decodedValue = Base64Decode(cursor); } catch (FormatException) { return default; } return (T)Convert.ChangeType(decodedValue, typeof(T), CultureInfo.InvariantCulture); } public static (string firstCursor, string lastCursor) GetFirstAndLastCursor<TItem, TCursor>( IEnumerable<TItem> enumerable, Func<TItem, TCursor> getCursorProperty) { if (getCursorProperty == null) { throw new ArgumentNullException(nameof(getCursorProperty)); } if (enumerable == null || enumerable.Count() == 0) { return (null, null); } var firstCursor = ToCursor(getCursorProperty(enumerable.First())); var lastCursor = ToCursor(getCursorProperty(enumerable.Last())); return (firstCursor, lastCursor); } public static string ToCursor<T>(T value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return Base64Encode(value.ToString()); } private static string Base64Decode(string value) => Encoding.UTF8.GetString(Convert.FromBase64String(value)); private static string Base64Encode(string value) => Convert.ToBase64String(Encoding.UTF8.GetBytes(value)); } }
mit
C#
56ae8629c13d81a8f05f3977a518bd7b9ac5731c
Change public field to property
fluentassertions/fluentassertions,dennisdoomen/fluentassertions,jnyrup/fluentassertions,dennisdoomen/fluentassertions,fluentassertions/fluentassertions,jnyrup/fluentassertions
Src/FluentAssertions/AssertionOptions.cs
Src/FluentAssertions/AssertionOptions.cs
#region using System; using FluentAssertions.Common; using FluentAssertions.Equivalency; #endregion namespace FluentAssertions { /// <summary> /// Holds any global options that control the behavior of FluentAssertions. /// </summary> public static class AssertionOptions { private static EquivalencyAssertionOptions defaults = new EquivalencyAssertionOptions(); static AssertionOptions() { EquivalencySteps = new EquivalencyStepCollection(); } public static EquivalencyAssertionOptions<T> CloneDefaults<T>() { return new EquivalencyAssertionOptions<T>(defaults); } /// <summary> /// Defines a predicate with which the <see cref="EquivalencyValidator"/> determines if it should process /// an object's properties or not. /// </summary> /// <returns> /// Returns <c>true</c> if the object should be treated as a value type and its <see cref="object.Equals(object)"/> /// must be used during a structural equivalency check. /// </returns> public static Func<Type, bool> IsValueType { get; set; } = type => (type.Namespace == typeof(int).Namespace) && !type.IsSameOrInherits(typeof(Exception)); /// <summary> /// Allows configuring the defaults used during a structural equivalency assertion. /// </summary> /// <param name="defaultsConfigurer"> /// An action that is used to configure the defaults. /// </param> public static void AssertEquivalencyUsing( Func<EquivalencyAssertionOptions, EquivalencyAssertionOptions> defaultsConfigurer) { defaults = defaultsConfigurer(defaults); } /// <summary> /// Represents a mutable collection of steps that are executed while asserting a (collection of) object(s) /// is structurally equivalent to another (collection of) object(s). /// </summary> public static EquivalencyStepCollection EquivalencySteps { get; private set; } } }
#region using System; using FluentAssertions.Common; using FluentAssertions.Equivalency; #endregion namespace FluentAssertions { /// <summary> /// Holds any global options that control the behavior of FluentAssertions. /// </summary> public static class AssertionOptions { private static EquivalencyAssertionOptions defaults = new EquivalencyAssertionOptions(); static AssertionOptions() { EquivalencySteps = new EquivalencyStepCollection(); } public static EquivalencyAssertionOptions<T> CloneDefaults<T>() { return new EquivalencyAssertionOptions<T>(defaults); } /// <summary> /// Defines a predicate with which the <see cref="EquivalencyValidator"/> determines if it should process /// an object's properties or not. /// </summary> /// <returns> /// Returns <c>true</c> if the object should be treated as a value type and its <see cref="object.Equals(object)"/> /// must be used during a structural equivalency check. /// </returns> public static Func<Type, bool> IsValueType = type => (type.Namespace == typeof (int).Namespace) && !type.IsSameOrInherits(typeof(Exception)); /// <summary> /// Allows configuring the defaults used during a structural equivalency assertion. /// </summary> /// <param name="defaultsConfigurer"> /// An action that is used to configure the defaults. /// </param> public static void AssertEquivalencyUsing( Func<EquivalencyAssertionOptions, EquivalencyAssertionOptions> defaultsConfigurer) { defaults = defaultsConfigurer(defaults); } /// <summary> /// Represents a mutable collection of steps that are executed while asserting a (collection of) object(s) /// is structurally equivalent to another (collection of) object(s). /// </summary> public static EquivalencyStepCollection EquivalencySteps { get; private set; } } }
apache-2.0
C#
5498f5e4da6b111a869e7fc93653850f75522493
Test commit 2
HaraGabi/TestProject
TestHElloWorld/TestHElloWorld/Program.cs
TestHElloWorld/TestHElloWorld/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestHElloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Speak your mind!"); string message = Console.ReadLine(); Console.WriteLine($"Your message was: {message}" + Environment.NewLine + "Thank you!"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestHElloWorld { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadKey(); } } }
apache-2.0
C#
8bfdfe3672997fcacfed8a571629c17403348d9e
Add literal string marker
peppy/osu-new,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu
osu.Game/Beatmaps/IBeatmapSetInfo.cs
osu.Game/Beatmaps/IBeatmapSetInfo.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 System.Linq; using osu.Game.Database; #nullable enable namespace osu.Game.Beatmaps { /// <summary> /// A representation of a collection of beatmap difficulties, generally packaged as an ".osz" archive. /// </summary> public interface IBeatmapSetInfo : IHasOnlineID { /// <summary> /// The date when this beatmap was imported. /// </summary> DateTimeOffset DateAdded { get; } /// <summary> /// The best-effort metadata representing this set. In the case metadata differs between contained beatmaps, one is arbitrarily chosen. /// </summary> IBeatmapMetadataInfo? Metadata { get; } /// <summary> /// All beatmaps contained in this set. /// </summary> IEnumerable<IBeatmapInfo> Beatmaps { get; } /// <summary> /// All files used by this set. /// </summary> IEnumerable<INamedFileUsage> Files { get; } /// <summary> /// The maximum star difficulty of all beatmaps in this set. /// </summary> double MaxStarDifficulty { get; } /// <summary> /// The maximum playable length in milliseconds of all beatmaps in this set. /// </summary> double MaxLength { get; } /// <summary> /// The maximum BPM of all beatmaps in this set. /// </summary> double MaxBPM { get; } /// <summary> /// The filename for the storyboard. /// </summary> string StoryboardFile => Files.FirstOrDefault(f => f.Filename.EndsWith(@".osb", StringComparison.OrdinalIgnoreCase))?.Filename ?? string.Empty; } }
// 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 System.Linq; using osu.Game.Database; #nullable enable namespace osu.Game.Beatmaps { /// <summary> /// A representation of a collection of beatmap difficulties, generally packaged as an ".osz" archive. /// </summary> public interface IBeatmapSetInfo : IHasOnlineID { /// <summary> /// The date when this beatmap was imported. /// </summary> DateTimeOffset DateAdded { get; } /// <summary> /// The best-effort metadata representing this set. In the case metadata differs between contained beatmaps, one is arbitrarily chosen. /// </summary> IBeatmapMetadataInfo? Metadata { get; } /// <summary> /// All beatmaps contained in this set. /// </summary> IEnumerable<IBeatmapInfo> Beatmaps { get; } /// <summary> /// All files used by this set. /// </summary> IEnumerable<INamedFileUsage> Files { get; } /// <summary> /// The maximum star difficulty of all beatmaps in this set. /// </summary> double MaxStarDifficulty { get; } /// <summary> /// The maximum playable length in milliseconds of all beatmaps in this set. /// </summary> double MaxLength { get; } /// <summary> /// The maximum BPM of all beatmaps in this set. /// </summary> double MaxBPM { get; } /// <summary> /// The filename for the storyboard. /// </summary> string StoryboardFile => Files.FirstOrDefault(f => f.Filename.EndsWith(".osb", StringComparison.OrdinalIgnoreCase))?.Filename ?? string.Empty; } }
mit
C#
f3992c1b29cb204b0ff8bf8b98163edec6e58f29
Add separate overloads for Vector3/Quaternion to remove casts
SteamDatabase/ValveResourceFormat
ValveResourceFormat/Resource/ResourceTypes/ModelAnimation/Frame.cs
ValveResourceFormat/Resource/ResourceTypes/ModelAnimation/Frame.cs
using System; using System.Collections.Generic; using System.Numerics; namespace ValveResourceFormat.ResourceTypes.ModelAnimation { public class Frame { public Dictionary<string, FrameBone> Bones { get; } public Frame() { Bones = new Dictionary<string, FrameBone>(); } public void SetAttribute(string bone, string attribute, Vector3 data) { switch (attribute) { case "Position": GetBone(bone).Position = data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Vector3 data"); break; #endif } } public void SetAttribute(string bone, string attribute, Quaternion data) { switch (attribute) { case "Angle": GetBone(bone).Angle = data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered with Quaternion data"); break; #endif } } private FrameBone GetBone(string name) { if (!Bones.TryGetValue(name, out var bone)) { bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1)); Bones[name] = bone; } return bone; } } }
using System; using System.Collections.Generic; using System.Numerics; namespace ValveResourceFormat.ResourceTypes.ModelAnimation { public class Frame { public Dictionary<string, FrameBone> Bones { get; } public Frame() { Bones = new Dictionary<string, FrameBone>(); } public void SetAttribute(string bone, string attribute, object data) { switch (attribute) { case "Position": GetBone(bone).Position = (Vector3)data; break; case "Angle": GetBone(bone).Angle = (Quaternion)data; break; case "data": //ignore break; #if DEBUG default: Console.WriteLine($"Unknown frame attribute '{attribute}' encountered"); break; #endif } } private FrameBone GetBone(string name) { if (!Bones.TryGetValue(name, out var bone)) { bone = new FrameBone(new Vector3(0, 0, 0), new Quaternion(0, 0, 0, 1)); Bones[name] = bone; } return bone; } } }
mit
C#
f6018a81149955902b618185664113683137f6a2
Remove usage of TypeSwitch.
jmarolf/roslyn,KevinH-MS/roslyn,mattwar/roslyn,CyrusNajmabadi/roslyn,tmeschter/roslyn,eriawan/roslyn,bkoelman/roslyn,jcouv/roslyn,tmat/roslyn,mattscheffer/roslyn,swaroop-sridhar/roslyn,jkotas/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,reaction1989/roslyn,nguerrera/roslyn,lorcanmooney/roslyn,AmadeusW/roslyn,MattWindsor91/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,a-ctor/roslyn,pdelvo/roslyn,bartdesmet/roslyn,khyperia/roslyn,a-ctor/roslyn,khyperia/roslyn,drognanar/roslyn,jamesqo/roslyn,kelltrick/roslyn,jasonmalinowski/roslyn,tvand7093/roslyn,gafter/roslyn,vslsnap/roslyn,tvand7093/roslyn,mavasani/roslyn,stephentoub/roslyn,mavasani/roslyn,srivatsn/roslyn,tannergooding/roslyn,MichalStrehovsky/roslyn,AlekseyTs/roslyn,davkean/roslyn,aelij/roslyn,yeaicc/roslyn,wvdd007/roslyn,dpoeschl/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,wvdd007/roslyn,srivatsn/roslyn,OmarTawfik/roslyn,CaptainHayashi/roslyn,ErikSchierboom/roslyn,AArnott/roslyn,davkean/roslyn,weltkante/roslyn,weltkante/roslyn,agocke/roslyn,amcasey/roslyn,bartdesmet/roslyn,bbarry/roslyn,tmat/roslyn,Hosch250/roslyn,VSadov/roslyn,brettfo/roslyn,AnthonyDGreen/roslyn,yeaicc/roslyn,AnthonyDGreen/roslyn,diryboy/roslyn,panopticoncentral/roslyn,jkotas/roslyn,Hosch250/roslyn,heejaechang/roslyn,AArnott/roslyn,DustinCampbell/roslyn,VSadov/roslyn,weltkante/roslyn,bartdesmet/roslyn,TyOverby/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,agocke/roslyn,bkoelman/roslyn,dotnet/roslyn,Giftednewt/roslyn,brettfo/roslyn,xoofx/roslyn,abock/roslyn,heejaechang/roslyn,OmarTawfik/roslyn,akrisiun/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,bkoelman/roslyn,physhi/roslyn,tmeschter/roslyn,diryboy/roslyn,akrisiun/roslyn,robinsedlaczek/roslyn,drognanar/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,AArnott/roslyn,aelij/roslyn,jcouv/roslyn,gafter/roslyn,cston/roslyn,eriawan/roslyn,mattscheffer/roslyn,MichalStrehovsky/roslyn,AmadeusW/roslyn,vslsnap/roslyn,tannergooding/roslyn,sharwell/roslyn,Hosch250/roslyn,cston/roslyn,dpoeschl/roslyn,physhi/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,reaction1989/roslyn,cston/roslyn,abock/roslyn,MattWindsor91/roslyn,OmarTawfik/roslyn,srivatsn/roslyn,lorcanmooney/roslyn,reaction1989/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,jcouv/roslyn,heejaechang/roslyn,jmarolf/roslyn,orthoxerox/roslyn,TyOverby/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,MattWindsor91/roslyn,xoofx/roslyn,zooba/roslyn,tmat/roslyn,ErikSchierboom/roslyn,mmitche/roslyn,jamesqo/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,dotnet/roslyn,genlu/roslyn,jkotas/roslyn,robinsedlaczek/roslyn,AmadeusW/roslyn,diryboy/roslyn,amcasey/roslyn,nguerrera/roslyn,panopticoncentral/roslyn,AnthonyDGreen/roslyn,lorcanmooney/roslyn,jeffanders/roslyn,shyamnamboodiripad/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,kelltrick/roslyn,tvand7093/roslyn,swaroop-sridhar/roslyn,stephentoub/roslyn,jmarolf/roslyn,xasx/roslyn,abock/roslyn,mgoertz-msft/roslyn,TyOverby/roslyn,akrisiun/roslyn,drognanar/roslyn,aelij/roslyn,bbarry/roslyn,paulvanbrenk/roslyn,nguerrera/roslyn,xasx/roslyn,mmitche/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,mgoertz-msft/roslyn,zooba/roslyn,jeffanders/roslyn,pdelvo/roslyn,VSadov/roslyn,khyperia/roslyn,kelltrick/roslyn,mgoertz-msft/roslyn,xoofx/roslyn,jamesqo/roslyn,KevinRansom/roslyn,KevinH-MS/roslyn,CaptainHayashi/roslyn,DustinCampbell/roslyn,orthoxerox/roslyn,sharwell/roslyn,orthoxerox/roslyn,CaptainHayashi/roslyn,dpoeschl/roslyn,agocke/roslyn,amcasey/roslyn,vslsnap/roslyn,mattwar/roslyn,robinsedlaczek/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,davkean/roslyn,dotnet/roslyn,tmeschter/roslyn,a-ctor/roslyn,paulvanbrenk/roslyn,paulvanbrenk/roslyn,mattscheffer/roslyn,jeffanders/roslyn,pdelvo/roslyn,gafter/roslyn,jasonmalinowski/roslyn,mattwar/roslyn,physhi/roslyn,xasx/roslyn,KevinH-MS/roslyn,Giftednewt/roslyn,yeaicc/roslyn,genlu/roslyn,MichalStrehovsky/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,zooba/roslyn,tannergooding/roslyn,bbarry/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn
src/Workspaces/Core/Portable/Utilities/IReadOnlyDictionaryExtensions.cs
src/Workspaces/Core/Portable/Utilities/IReadOnlyDictionaryExtensions.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.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Roslyn.Utilities { internal static class IReadOnlyDictionaryExtensions { public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } return default(TValue); } public static IEnumerable<T> GetEnumerableMetadata<T>(this IReadOnlyDictionary<string, object> metadata, string name) { switch (metadata.GetValueOrDefault(name)) { case IEnumerable<T> enumerable: return enumerable; case T s: return SpecializedCollections.SingletonEnumerable(s); default: return SpecializedCollections.EmptyEnumerable<T>(); } } } }
// 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.Collections.Generic; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Roslyn.Utilities { internal static class IReadOnlyDictionaryExtensions { public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) { TValue value; if (dictionary.TryGetValue(key, out value)) { return value; } return default(TValue); } public static IEnumerable<T> GetEnumerableMetadata<T>(this IReadOnlyDictionary<string, object> metadata, string name) { object value = metadata.GetValueOrDefault(name); return value.TypeSwitch((IEnumerable<T> enumerable) => enumerable, (T s) => SpecializedCollections.SingletonEnumerable(s), _ => SpecializedCollections.EmptyEnumerable<T>()); } } }
mit
C#
d21efc27af040eaa8ee36e0617c92632e6f3c1d0
Make PlayerScore cloneable
TheEadie/PlayerRank,TheEadie/PlayerRank
PlayerRank/PlayerScore.cs
PlayerRank/PlayerScore.cs
using System; using System.Runtime.InteropServices; namespace PlayerRank { /// <summary> /// A single line on a scoreboard /// Stores a players name, points and position /// </summary> public class PlayerScore : ICloneable { public string Name { get; set; } public Points Points { get; internal set; } public Position Position { get; internal set; } public PlayerScore(string name) { Name = name; Points = new Points(0); Position = new Position(0); } public PlayerScore(string name, Position position) : this(name) { Position = position; } public PlayerScore(string name, Points points) : this(name) { Points = points; } internal void AddPoints(Points points) { Points += points; } internal void SubtractPoints(Points points) { Points -= points; } public object Clone() { return new PlayerScore(Name) { Points = Points, Position = Position }; } } }
using System; using System.Runtime.InteropServices; namespace PlayerRank { /// <summary> /// A single line on a scoreboard /// Stores a players name, points and position /// </summary> public class PlayerScore { public string Name { get; set; } public Points Points { get; internal set; } public Position Position { get; internal set; } public PlayerScore(string name) { Name = name; Points = new Points(0); Position = new Position(0); } public PlayerScore(string name, Position position) : this(name) { Position = position; } public PlayerScore(string name, Points points) : this(name) { Points = points; } internal void AddPoints(Points points) { Points += points; } internal void SubtractPoints(Points points) { Points -= points; } } }
mit
C#
d5e64bcb115a7507d0fcbca52d2084ae733fdab0
Bump version.
kyourek/Pagination,kyourek/Pagination,kyourek/Pagination
sln/AssemblyVersion.cs
sln/AssemblyVersion.cs
using System.Reflection; [assembly: AssemblyVersion("2.1.2")]
using System.Reflection; [assembly: AssemblyVersion("2.1.1.2")]
mit
C#
8f6861bbd764083af22cbc74b6bf1b743c03a057
Remove my Mixpanel token
jellybob/jump-frog,jellybob/jump-frog
Assets/GameController.cs
Assets/GameController.cs
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public bool PlayerHasPreviouslyDied() { return false; return PlayerPrefs.HasKey ("PlayerHasPreviouslyDied"); } public void Start() { SetupMixpanel (); if (PlayerHasPreviouslyDied ()) { Mixpanel.SendEvent("Tried to restart"); GameOver (); return; } Mixpanel.SendEvent("Started game"); } public void SetupMixpanel() { Mixpanel.Token = "MIXPANEL TOKEN GOES HERE"; Mixpanel.SuperProperties.Add("Platform", Application.platform.ToString()); Mixpanel.SuperProperties.Add("Quality", QualitySettings.names[QualitySettings.GetQualityLevel()]); Mixpanel.SuperProperties.Add("Fullscreen", Screen.fullScreen); Mixpanel.SuperProperties.Add("Screen Height", Screen.height); Mixpanel.SuperProperties.Add("Screen Width", Screen.width); Mixpanel.SuperProperties.Add("Resolution", Screen.width + "x" + Screen.height); Mixpanel.SendEvent("Ran program"); } public void GameOver() { PlayerPrefs.SetInt("PlayerHasPreviouslyDied", 1); PlayerPrefs.Save (); Application.LoadLevel (1); } public void Winner() { Mixpanel.SendEvent("Did the smart thing"); Application.LoadLevel (2); } }
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { public bool PlayerHasPreviouslyDied() { return false; return PlayerPrefs.HasKey ("PlayerHasPreviouslyDied"); } public void Start() { SetupMixpanel (); if (PlayerHasPreviouslyDied ()) { Mixpanel.SendEvent("Tried to restart"); GameOver (); return; } Mixpanel.SendEvent("Started game"); } public void SetupMixpanel() { Mixpanel.Token = "f792f223b1632465191da18a668c2ea3"; Mixpanel.SuperProperties.Add("Platform", Application.platform.ToString()); Mixpanel.SuperProperties.Add("Quality", QualitySettings.names[QualitySettings.GetQualityLevel()]); Mixpanel.SuperProperties.Add("Fullscreen", Screen.fullScreen); Mixpanel.SuperProperties.Add("Screen Height", Screen.height); Mixpanel.SuperProperties.Add("Screen Width", Screen.width); Mixpanel.SuperProperties.Add("Resolution", Screen.width + "x" + Screen.height); Mixpanel.SendEvent("Ran program"); } public void GameOver() { PlayerPrefs.SetInt("PlayerHasPreviouslyDied", 1); PlayerPrefs.Save (); Application.LoadLevel (1); } public void Winner() { Mixpanel.SendEvent("Did the smart thing"); Application.LoadLevel (2); } }
mit
C#
ea0449f1c6e3b5a7468d7b251dd37a28676908b1
Revert "#3 Modified Legato.Sample Program.cs"
Legato-Dev/Legato
Legato.Sample/Program.cs
Legato.Sample/Program.cs
using System; using System.Windows.Forms; namespace AimpAccesser.Sample { static class Program { /// <summary> /// アプリケーションのメイン エントリ ポイントです。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
using System; using System.Windows.Forms; namespace Legato.Sample { static class Program { /// <summary> /// アプリケーションのメイン エントリ ポイントです。 /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
mit
C#
f4572f140c9fd396354031f4557d1ab965397625
remove reference on terminate
JaredGG/GameWork
States/StateController.cs
States/StateController.cs
using System.Collections.Generic; using GameWork.Interfaces; using GameWork.States.Interfaces; namespace GameWork.States { public class StateController : IController { private readonly Dictionary<string, IState> _states = new Dictionary<string, IState>(); private string _activeState; public StateController(params IState[] states) { foreach (var state in states) { _states.Add(state.Name, state); } } public void SetState(string name) { var newState = _states[name]; _activeState = name; newState.ChangeStateEvent += ChangeState; newState.Enter(); } public void ChangeState(string name) { var newState = _states[name]; var prevState = _states[_activeState]; _activeState = name; prevState.ChangeStateEvent -= ChangeState; newState.ChangeStateEvent += ChangeState; prevState.Exit(); newState.Enter(); } public void Tick(float deltaTime) { _states[_activeState].Tick(deltaTime); } public void Initialize() { } public void Terminate() { _states = null; } } }
using System.Collections.Generic; using GameWork.Interfaces; using GameWork.States.Interfaces; namespace GameWork.States { public class StateController : IController { private readonly Dictionary<string, IState> _states = new Dictionary<string, IState>(); private string _activeState; public StateController(params IState[] states) { foreach (var state in states) { _states.Add(state.Name, state); } } public void SetState(string name) { var newState = _states[name]; _activeState = name; newState.ChangeStateEvent += ChangeState; newState.Enter(); } public void ChangeState(string name) { var newState = _states[name]; var prevState = _states[_activeState]; _activeState = name; prevState.ChangeStateEvent -= ChangeState; newState.ChangeStateEvent += ChangeState; prevState.Exit(); newState.Enter(); } public void Tick(float deltaTime) { _states[_activeState].Tick(deltaTime); } public void Initialize() { } public void Terminate() { } } }
mit
C#
0086bcd22c9e4395bbf93ae02dda71fb3f723175
Move default Dashboard API base address to constant
anthonylangsworth/Meraki
src/Meraki/MerakiDashboardClientSettingsSetup.cs
src/Meraki/MerakiDashboardClientSettingsSetup.cs
using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { public static readonly string DefaultMerakiDashboardApiBaseAddress = "https://dashboard.meraki.com"; /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri(DefaultMerakiDashboardApiBaseAddress, UriKind.Absolute); options.Key = ""; } } }
using System; using Microsoft.Extensions.Options; namespace Meraki { /// <summary> /// Initialize a <see cref="MerakiDashboardClientSettings"/> object. /// </summary> internal class MerakiDashboardClientSettingsSetup : ConfigureOptions<MerakiDashboardClientSettings> { /// <summary> /// Create a new <see cref="MerakiDashboardClientSettingsSetup"/> object. /// </summary> public MerakiDashboardClientSettingsSetup() : base(ConfigureOptions) { // Do nothing } /// <summary> /// Configure the <see cref="MerakiDashboardClientSettings"/> object. /// </summary> /// <param name="options"> /// The <see cref="MerakiDashboardClientSettings"/> object to configure. /// </param> private static void ConfigureOptions(MerakiDashboardClientSettings options) { options.Address = new Uri("https://dashboard.meraki.com", UriKind.Absolute); options.Key = ""; } } }
mit
C#
fafcbec71fb6a2670f60d558032605b27f7b1daf
add try ... catch to handle https service exception
poumason/MixpanelClientDotNet,poumason/Mixpanel.Net.Client
Library/MixpanelClientDotNet.Shared/ServiceModel/Services/HttpService.cs
Library/MixpanelClientDotNet.Shared/ServiceModel/Services/HttpService.cs
using System; using System.Net.Http; using System.Threading.Tasks; namespace MixpanelDotNet.ServiceModel { public class HttpService { private HttpClient httpClient; public HttpService() { httpClient = new HttpClient(); } public async Task<string> SendRequest(string uri, string query) { try { string url = $"{uri}?{query}"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); var response = await httpClient.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); return result; } catch (Exception ex) { DebugLogger.Write(ex); return string.Empty; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace MixpanelDotNet.ServiceModel { public class HttpService { private HttpClient httpClient; public HttpService() { httpClient = new HttpClient(); } public async Task<string> SendRequest(string uri, string query) { string url = $"{uri}?{query}"; HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, url); var response = await httpClient.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); return result; } } }
apache-2.0
C#
1fff5213f9faf63c8e1546f4f4bf355a8d8999bd
Rename twitchpageoptions to pageoptions
Aux/NTwitch,Aux/NTwitch
src/NTwitch.Rest/API/Common/TwitchPageOptions.cs
src/NTwitch.Rest/API/Common/TwitchPageOptions.cs
using System; namespace NTwitch.Rest { public class PageOptions { public int Limit { get; set; } public int Page { get; set; } public int Offset => (Limit * Page) - Limit; public PageOptions(int limit = 10, int page = 1) { if (limit < 1 || limit > 100) throw new ArgumentOutOfRangeException("Limit must be a number between 1 and 100."); else Limit = limit; if (page < 1) throw new ArgumentOutOfRangeException("Page must be a number greater than 0."); else Page = page; } } }
using System; namespace NTwitch.Rest { public class TwitchPageOptions { public int Limit { get; set; } public int Page { get; set; } public int Offset => (Limit * Page) - Limit; public TwitchPageOptions(int limit = 10, int page = 1) { if (limit < 1 || limit > 100) throw new ArgumentOutOfRangeException("Limit must be a number between 1 and 100."); else Limit = limit; if (page < 1) throw new ArgumentOutOfRangeException("Page must be a number greater than 0."); else Page = page; } } }
mit
C#
375e5901566db2580c92239240ee7302e21a870a
Change user.config format to app.confg schema
Ackara/Daterpillar
src/Test.Daterpillar/Helpers/ConnectionString.cs
src/Test.Daterpillar/Helpers/ConnectionString.cs
using System.Configuration; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var fileMap = new ExeConfigurationFileMap() { ExeConfigFilename = "user.config" }; var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); return config.ConnectionStrings.ConnectionStrings[name].ConnectionString; } } }
using System.Linq; using System.Xml.Linq; namespace Tests.Daterpillar.Helpers { public static class ConnectionString { private static readonly string _configFile = "database.config.xml"; public static string GetMySQLServerConnectionString() { return GetConnectionString("mysql"); } public static string GetSQLServerConnectionString() { return GetConnectionString("mssql"); } internal static string GetConnectionString(string name) { var doc = XDocument.Load(_configFile); var connectionStrings = doc.Element("connectionStrings"); var record = (from element in connectionStrings.Descendants("add") where element.Attribute("name").Value == name select element) .First(); var connStr = new System.Data.Common.DbConnectionStringBuilder(); connStr.Add("server", record.Attribute("server").Value); connStr.Add("user", record.Attribute("user").Value); connStr.Add("password", record.Attribute("password").Value); return connStr.ConnectionString; } } }
mit
C#
456f759f181cd93d72dc9761ec029c51fb8a447f
Remove temporary test
villermen/runescape-cache-tools,villermen/runescape-cache-tools
RuneScapeCacheToolsTests/Tests/FileTypesTests/ReferenceTableFileTests.cs
RuneScapeCacheToolsTests/Tests/FileTypesTests/ReferenceTableFileTests.cs
using System.Linq; using RuneScapeCacheToolsTests.Fixtures; using Villermen.RuneScapeCacheTools.Cache; using Villermen.RuneScapeCacheTools.Cache.FileTypes; using Xunit; namespace Villermen.RuneScapeCacheTools.Tests.Tests.FileTypesTests { [Collection(TestCacheCollection.Name)] public class ReferenceTableFileTests { private readonly TestCacheFixture _fixture; public ReferenceTableFileTests(TestCacheFixture fixture) { this._fixture = fixture; } [Theory] [InlineData(Index.Music)] [InlineData(Index.AnimationFrames)] public void TestDecodeEncode(Index index) { var referenceTableFile = this._fixture.RuneTek5Cache.GetFile<BinaryFile>(Index.ReferenceTables, (int)index); var referenceTable = new ReferenceTableFile(); referenceTable.FromBinaryFile(referenceTableFile); var encodedFile = referenceTable.ToBinaryFile(); Assert.True(referenceTableFile.Data.SequenceEqual(encodedFile.Data)); } } }
using System.Linq; using RuneScapeCacheToolsTests.Fixtures; using Villermen.RuneScapeCacheTools.Cache; using Villermen.RuneScapeCacheTools.Cache.FileTypes; using Xunit; namespace Villermen.RuneScapeCacheTools.Tests.Tests.FileTypesTests { [Collection(TestCacheCollection.Name)] public class ReferenceTableFileTests { private readonly TestCacheFixture _fixture; public ReferenceTableFileTests(TestCacheFixture fixture) { this._fixture = fixture; } [Theory] [InlineData(Index.Music)] [InlineData(Index.AnimationFrames)] public void TestDecodeEncode(Index index) { var referenceTableFile = this._fixture.RuneTek5Cache.GetFile<BinaryFile>(Index.ReferenceTables, (int)index); var referenceTable = new ReferenceTableFile(); referenceTable.FromBinaryFile(referenceTableFile); var encodedFile = referenceTable.ToBinaryFile(); Assert.True(referenceTableFile.Data.SequenceEqual(encodedFile.Data)); } [Fact] public void TestTemp() { this._fixture.DownloaderCache.GetFile<ReferenceTableFile>(Index.ReferenceTables, (int)Index.Enums); } } }
mit
C#
10adb504a44178c53df7ab9cdc1c4d3856d448f9
Test Commit
lsadam0/BEx
BEx/UserTransactions.cs
BEx/UserTransactions.cs
using System; using System.Collections.Generic; using System.Linq; namespace BEx { public class UserTransactions : APIResult { internal UserTransactions(List<UserTransaction> transactions, Currency baseCurrency, Currency counterCurrency, ExchangeType sourceExchange) : base(DateTime.Now, sourceExchange) { UserTrans = transactions; BaseCurrency = baseCurrency; CounterCurrency = counterCurrency; } public Currency BaseCurrency { get; set; } public Currency CounterCurrency { get; set; } public List<UserTransaction> UserTrans { get; set; } public override string ToString() { string output = "{0}/{1} - Transactions: {2} - Oldest: {3} - Newest: {4}"; if (UserTrans.Count > 0) { DateTime oldest = UserTrans.Min(x => x.CompletedTime); DateTime newest = UserTrans.Max(x => x.CompletedTime); return string.Format(output, BaseCurrency, CounterCurrency, UserTrans.Count, oldest.ToString(), newest.ToString()); } else return "No Transactions in Collection"; } } }
using System; using System.Collections.Generic; using System.Linq; namespace BEx { public class UserTransactions : APIResult { internal UserTransactions(List<UserTransaction> transactions, Currency baseCurrency, Currency counterCurrency, ExchangeType sourceExchange) : base(DateTime.Now, sourceExchange) { UserTrans = transactions; BaseCurrency = baseCurrency; CounterCurrency = counterCurrency; } public Currency BaseCurrency { get; set; } public Currency CounterCurrency { get; set; } public List<UserTransaction> UserTrans { get; set; } public override string ToString() { string output = "{0}/{1} - Transactions: {2} - Oldest: {3} - Newest: {4}"; if (UserTrans.Count > 0) { DateTime oldest = UserTrans.Min(x => x.CompletedTime); DateTime newest = UserTrans.Max(x => x.CompletedTime); return string.Format(output, BaseCurrency, CounterCurrency, UserTrans.Count, oldest.ToString(), newest.ToString()); } else return "No Transactions in Collection"; } } }
mit
C#
191c82738ba84b3fe2d8b532c5794290897aa656
Update documentation for Product enum.
danpierce1/Colore,WolfspiritM/Colore,CoraleStudios/Colore,Sharparam/Colore
Colore/Razer/Product.cs
Colore/Razer/Product.cs
// --------------------------------------------------------------------------------------- // <copyright file="Product.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer { /// <summary> /// Chroma-supported products. /// </summary> public enum Product { /// <summary> /// No product. /// </summary> None = 0, /// <summary> /// The Razer Blackwidow Chroma. /// </summary> /// <remarks> /// Device Id = <c>2EA1BB63-CA28-428D-9F06-196B88330BBB</c>. /// </remarks> BlackwidowChroma, /// <summary> /// Invalid product. /// </summary> Invalid } }
// --------------------------------------------------------------------------------------- // <copyright file="Product.cs" company=""> // Copyright © 2015 by Adam Hellberg and Brandon Scott. // // 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. // // Disclaimer: Colore is in no way affiliated with Razer and/or any of its employees // and/or licensors. Adam Hellberg and Brandon Scott do not take responsibility // for any harm caused, direct or indirect, to any Razer peripherals // via the use of Colore. // // "Razer" is a trademark of Razer USA Ltd. // </copyright> // --------------------------------------------------------------------------------------- namespace Colore.Razer { /// <summary> /// Chroma-supported products. /// </summary> public enum Product { None = 0, /// <summary> /// /// </summary> /// <remarks> /// Device Id = <c>2EA1BB63-CA28-428D-9F06-196B88330BBB</c>. /// </remarks> BlackwidowChroma, /// <summary> /// Invalid product. /// </summary> Invalid } }
mit
C#
11fa13f0bb772d49b3fc37c77d2c5efdc8ed7d6b
Tweak google analytics detection to work on twitter.com
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
Core/Handling/RequestHandlerBrowser.cs
Core/Handling/RequestHandlerBrowser.cs
using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } }
using CefSharp; namespace TweetDuck.Core.Handling{ class RequestHandlerBrowser : RequestHandler{ public override void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status){ browser.Reload(); } public override CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback){ if (request.ResourceType == ResourceType.Script && request.Url.Contains("google_analytics.")){ return CefReturnValue.Cancel; } return CefReturnValue.Continue; } } }
mit
C#
da17b22185ddef57ba6cc8ade95295f07e64bafe
change pattern for -1 files
UnstableMutex/DropboxCameraUploadsSorter
DropboxSorter/DropboxSorter/Program.cs
DropboxSorter/DropboxSorter/Program.cs
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace DropboxSorter { class Program { static void Main(string[] args) { var UserFolder=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string mainFolder = Path.Combine(UserFolder, @"Dropbox\Camera Uploads"); const string mask = @"\d{4}-\d{2}-\d{2} \d{2}\.\d{2}\.\d{2}(-\d)?.jpg"; var re=new Regex(mask); var directory = new DirectoryInfo(mainFolder); var files = directory.GetFiles(); var filteredfiles = files.Where(x => re.IsMatch(x.Name)); foreach (var filteredfile in filteredfiles) { var date = filteredfile.Name.Substring(0, 10); const string dateFormat = "yyyy-MM-dd"; var dt =DateTime.ParseExact(date, dateFormat, CultureInfo.CurrentCulture); var subdir= directory.CreateSubdirectory(dt.ToString(dateFormat)); var newfn = filteredfile.Name.Substring(11); var fullfn = Path.Combine(subdir.FullName, newfn); filteredfile.MoveTo(fullfn); } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace DropboxSorter { class Program { static void Main(string[] args) { var UserFolder=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); string mainFolder = Path.Combine(UserFolder, @"Dropbox\Camera Uploads"); const string mask = @"\d{4}-\d{2}-\d{2} \d{2}\.\d{2}\.\d{2}.jpg"; var re=new Regex(mask); var directory = new DirectoryInfo(mainFolder); var files = directory.GetFiles(); var filteredfiles = files.Where(x => re.IsMatch(x.Name)); foreach (var filteredfile in filteredfiles) { var date = filteredfile.Name.Substring(0, 10); const string dateFormat = "yyyy-MM-dd"; var dt =DateTime.ParseExact(date, dateFormat, CultureInfo.CurrentCulture); var subdir= directory.CreateSubdirectory(dt.ToString(dateFormat)); var newfn = filteredfile.Name.Substring(11); var fullfn = Path.Combine(subdir.FullName, newfn); filteredfile.MoveTo(fullfn); } } } }
mit
C#
3fa1b53b2ae3d670bc7f1f2a6f8b55cb57659b93
Add back combo colours for osu!classic
ZLima12/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,ppy/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,EVAST9919/osu,peppy/osu-new,smoogipoo/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Skinning/DefaultLegacySkin.cs
osu.Game/Skinning/DefaultLegacySkin.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.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); Configuration.ComboColours.AddRange(new[] { new Color4(255, 192, 0, 255), new Color4(0, 202, 0, 255), new Color4(18, 124, 255, 255), new Color4(242, 24, 57, 255), }); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } }
// 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.Audio; using osu.Framework.IO.Stores; using osuTK.Graphics; namespace osu.Game.Skinning { public class DefaultLegacySkin : LegacySkin { public DefaultLegacySkin(IResourceStore<byte[]> storage, AudioManager audioManager) : base(Info, storage, audioManager, string.Empty) { Configuration.CustomColours["SliderBall"] = new Color4(2, 170, 255, 255); } public static SkinInfo Info { get; } = new SkinInfo { ID = -1, // this is temporary until database storage is decided upon. Name = "osu!classic", Creator = "team osu!" }; } }
mit
C#
4e441600ee3f786c8b488381cb8a93b25c4c2390
Fix not allowing to compile project with no implementation of IDotvvmServiceConfigurator
riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm
src/DotVVM.Compiler/Resolving/DotvvmServiceConfiguratorResolver.cs
src/DotVVM.Compiler/Resolving/DotvvmServiceConfiguratorResolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using DotVVM.Compiler.Exceptions; using DotVVM.Framework.Configuration; using DotVVM.Framework.Utils; using Microsoft.Extensions.DependencyInjection; namespace DotVVM.Compiler.Resolving { public class DotvvmServiceConfiguratorResolver : IDotvvmServiceConfiguratorResolver { private Type ResolveIDotvvmServiceConfiguratorClassType(Assembly assembly) { var interfaceType = typeof(IDotvvmServiceConfigurator); var resultTypes = assembly.GetLoadableTypes().Where(s => s.GetTypeInfo().ImplementedInterfaces.Any(i => i.Name == interfaceType.Name)).Where(s => s != null).ToList(); if (resultTypes.Count > 1) { throw new ConfigurationInitializationException( $"Assembly '{assembly.FullName}' contains more the one implementaion of IDotvvmServiceConfigurator."); } return resultTypes.FirstOrDefault(); } private MethodInfo ResolveConfigureServicesMethods(Type startupType) { var method = startupType.GetMethod("ConfigureServices", new[] {typeof(IDotvvmServiceCollection)}); if (method == null) { throw new ConfigurationInitializationException("Missing method 'void ConfigureServices(IDotvvmServiceCollection services)'."); } return method; } public IServiceConfiguratorExecutor GetServiceConfiguratorExecutor(Assembly assembly) { var startupType = ResolveIDotvvmServiceConfiguratorClassType(assembly); if (startupType == null) { return new NoServiceConfiguratorExecutor(); } var resolvedMethod = ResolveConfigureServicesMethods(startupType); return new ServiceConfiguratorExecutor(resolvedMethod, startupType); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using DotVVM.Compiler.Exceptions; using DotVVM.Framework.Configuration; using DotVVM.Framework.Utils; using Microsoft.Extensions.DependencyInjection; namespace DotVVM.Compiler.Resolving { public class DotvvmServiceConfiguratorResolver : IDotvvmServiceConfiguratorResolver { private Type ResolveIDotvvmServiceConfiguratorClassType(Assembly assembly) { var interfaceType = typeof(IDotvvmServiceConfigurator); var resultTypes = assembly.GetLoadableTypes().Where(s => s.GetTypeInfo().ImplementedInterfaces.Any(i => i.Name == interfaceType.Name)).Where(s => s != null).ToList(); if (resultTypes.Count > 1) { throw new ConfigurationInitializationException( $"Assembly '{assembly.FullName}' contains more the one implementaion of IDotvvmServiceConfigurator."); } return resultTypes.Single(); } private MethodInfo ResolveConfigureServicesMethods(Type startupType) { var method = startupType.GetMethod("ConfigureServices", new[] {typeof(IDotvvmServiceCollection)}); if (method == null) { throw new ConfigurationInitializationException("Missing method 'void ConfigureServices(IDotvvmServiceCollection services)'."); } return method; } public IServiceConfiguratorExecutor GetServiceConfiguratorExecutor(Assembly assembly) { var startupType = ResolveIDotvvmServiceConfiguratorClassType(assembly); if (startupType == null) { return new NoServiceConfiguratorExecutor(); } var resolvedMethod = ResolveConfigureServicesMethods(startupType); return new ServiceConfiguratorExecutor(resolvedMethod, startupType); } } }
apache-2.0
C#