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 |
|---|---|---|---|---|---|---|---|---|
9476149a5036f86142d3e77647e7060494436621 | Check that the container is not null | WebApiContrib/WebApiContrib.IoC.StructureMap,bingnz/WebApiContrib.IoC.StructureMap,jcalder/WebApiContrib.IoC.StructureMap | src/WebApiContrib.IoC.StructureMap/StructureMapResolver.cs | src/WebApiContrib.IoC.StructureMap/StructureMapResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dependencies;
using System.Web.Http.Dispatcher;
using StructureMap;
namespace WebApiContrib.IoC.StructureMap
{
public class StructureMapDependencyScope : IDependencyScope
{
private IContainer container;
public StructureMapDependencyScope(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
this.container = container;
}
public object GetService(Type serviceType)
{
if (container == null)
throw new ObjectDisposedException("this", "This scope has already been disposed.");
return container.TryGetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (container == null)
throw new ObjectDisposedException("this", "This scope has already been disposed.");
return container.GetAllInstances(serviceType).Cast<object>();
}
public void Dispose()
{
if (container != null)
container.Dispose();
container = null;
}
}
public class StructureMapResolver : StructureMapDependencyScope, IDependencyResolver, IHttpControllerActivator
{
private readonly IContainer container;
public StructureMapResolver(IContainer container)
: base(container)
{
if (container == null)
throw new ArgumentNullException("container");
this.container = container;
this.container.Inject(typeof (IHttpControllerActivator), this);
}
public IDependencyScope BeginScope()
{
return new StructureMapDependencyScope(container.GetNestedContainer());
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
return container.GetNestedContainer().GetInstance(controllerType) as IHttpController;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dependencies;
using System.Web.Http.Dispatcher;
using StructureMap;
namespace WebApiContrib.IoC.StructureMap
{
public class StructureMapDependencyScope : IDependencyScope
{
private IContainer container;
public StructureMapDependencyScope(IContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
this.container = container;
}
public object GetService(Type serviceType)
{
if (container == null)
throw new ObjectDisposedException("this", "This scope has already been disposed.");
return container.TryGetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (container == null)
throw new ObjectDisposedException("this", "This scope has already been disposed.");
return container.GetAllInstances(serviceType).Cast<object>();
}
public void Dispose()
{
container.Dispose();
container = null;
}
}
public class StructureMapResolver : StructureMapDependencyScope, IDependencyResolver, IHttpControllerActivator
{
private readonly IContainer container;
public StructureMapResolver(IContainer container)
: base(container)
{
if (container == null)
throw new ArgumentNullException("container");
this.container = container;
this.container.Inject(typeof (IHttpControllerActivator), this);
}
public IDependencyScope BeginScope()
{
return new StructureMapDependencyScope(container.GetNestedContainer());
}
public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
{
return container.GetNestedContainer().GetInstance(controllerType) as IHttpController;
}
}
}
| mit | C# |
be688dc780054fc253b9a304b67fb70a51239a17 | Remove unused parameter queue from DispatchEvent method | Microsoft/bond,ant0nsc/bond,jdubrule/bond,ant0nsc/bond,gencer/bond,chwarr/bond,sapek/bond,sapek/bond,sapek/bond,Microsoft/bond,tstein/bond,tstein/bond,gencer/bond,chwarr/bond,chwarr/bond,chwarr/bond,chwarr/bond,jdubrule/bond,tstein/bond,jdubrule/bond,tstein/bond,Microsoft/bond,gencer/bond,sapek/bond,gencer/bond,tstein/bond,jdubrule/bond,sapek/bond,ant0nsc/bond,gencer/bond,Microsoft/bond,ant0nsc/bond,jdubrule/bond,jdubrule/bond,Microsoft/bond,Microsoft/bond,sapek/bond,chwarr/bond,tstein/bond | cs/src/comm/simpleinmem-transport/Processor/EventProcessor.cs | cs/src/comm/simpleinmem-transport/Processor/EventProcessor.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Comm.SimpleInMem.Processor
{
using Service;
using System;
using System.Threading.Tasks;
internal class EventProcessor : QueueProcessor
{
private InMemFrameQueueCollection m_serverqueues;
private SimpleInMemConnection m_connection;
private ServiceHost m_serviceHost;
internal EventProcessor(SimpleInMemConnection connection, ServiceHost host, InMemFrameQueueCollection queues)
{
if (connection == null) throw new ArgumentNullException(nameof(connection));
if (host == null) throw new ArgumentNullException(nameof(host));
if (queues == null) throw new ArgumentNullException(nameof(queues));
m_connection = connection;
m_serviceHost = host;
m_serverqueues = queues;
}
override internal void Process()
{
const PayloadType payloadType = PayloadType.Event;
foreach (Guid key in m_serverqueues.GetKeys())
{
InMemFrameQueue queue = m_serverqueues.GetQueue(key);
Task.Run(() => ProcessQueue(queue, payloadType));
}
}
private void ProcessQueue(InMemFrameQueue queue, PayloadType payloadType)
{
int queueSize = queue.Count(payloadType);
int batchIndex = 0;
if (queueSize == 0)
{
return;
}
while (batchIndex < PROCESSING_BATCH_SIZE && queueSize > 0)
{
var payload = queue.Dequeue(payloadType);
var headers = payload.m_headers;
var message = payload.m_message;
DispatchEvent(headers, message);
queueSize = queue.Count(payloadType);
batchIndex++;
}
}
private void DispatchEvent(SimpleInMemHeaders headers, IMessage message)
{
Task.Run(async () =>
{
await m_serviceHost.DispatchEvent(headers.method_name, new SimpleInMemReceiveContext(m_connection), message);
});
}
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Bond.Comm.SimpleInMem.Processor
{
using Service;
using System;
using System.Threading.Tasks;
internal class EventProcessor : QueueProcessor
{
private InMemFrameQueueCollection m_serverqueues;
private SimpleInMemConnection m_connection;
private ServiceHost m_serviceHost;
internal EventProcessor(SimpleInMemConnection connection, ServiceHost host, InMemFrameQueueCollection queues)
{
if (connection == null) throw new ArgumentNullException(nameof(connection));
if (host == null) throw new ArgumentNullException(nameof(host));
if (queues == null) throw new ArgumentNullException(nameof(queues));
m_connection = connection;
m_serviceHost = host;
m_serverqueues = queues;
}
override internal void Process()
{
const PayloadType payloadType = PayloadType.Event;
foreach (Guid key in m_serverqueues.GetKeys())
{
InMemFrameQueue queue = m_serverqueues.GetQueue(key);
Task.Run(() => ProcessQueue(queue, payloadType));
}
}
private void ProcessQueue(InMemFrameQueue queue, PayloadType payloadType)
{
int queueSize = queue.Count(payloadType);
int batchIndex = 0;
if (queueSize == 0)
{
return;
}
while (batchIndex < PROCESSING_BATCH_SIZE && queueSize > 0)
{
var payload = queue.Dequeue(payloadType);
var headers = payload.m_headers;
var message = payload.m_message;
DispatchEvent(headers, message, queue);
queueSize = queue.Count(payloadType);
batchIndex++;
}
}
private void DispatchEvent(SimpleInMemHeaders headers, IMessage message, InMemFrameQueue queue)
{
Task.Run(async () =>
{
await m_serviceHost.DispatchEvent(headers.method_name, new SimpleInMemReceiveContext(m_connection), message);
});
}
}
}
| mit | C# |
4b88cd365f6e23dffb2e2747f00515c4e0a9ce54 | fix compile error | kheiakiyama/speech-eng-functions | OxfordKey/run.csx | OxfordKey/run.csx | #r "System.Configuration"
using System.Net;
using System.Net.Http;
using System.Configuration;
using System.Linq;
using System.Collections.Generic;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
if (req.Method == HttpMethod.Get)
return await Get(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation.");
}
private static async Task<HttpResponseMessage> Get(HttpRequestMessage req, TraceWriter log)
{
return req.CreateResponse(HttpStatusCode.OK, ConfigurationManager.AppSettings["BingSpeechKey"]);
} | #r "System.Configuration"
using System.Net;
using System.Net.Http;
using System.Configuration;
using System.Numerics;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
if (req.Method == HttpMethod.Get)
return await Get(req, log);
else
return req.CreateResponse(HttpStatusCode.InternalServerError, "Not implimentation.");
}
private static async Task<HttpResponseMessage> Get(HttpRequestMessage req, TraceWriter log)
{
return req.CreateResponse(HttpStatusCode.OK, ConfigurationManager.AppSettings["BingSpeechKey"]);
} | mit | C# |
41a2fd6c711f08b3b181f312e3e8c4afb5462bcc | Correct comment. | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/Learner.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/Learner.cs | using System;
namespace SFA.DAS.CommitmentsV2.Models
{
// This is a pseudo-entity to represent the result of the GetLearnersBatch stored proc, it's not a table in the database.
public class Learner
{
public long ApprenticeshipId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ULN { get; set; }
public string TrainingCode { get; set; }
public string TrainingCourseVersion { get; set; }
public bool TrainingCourseVersionConfirmed { get; set; }
public string TrainingCourseOption { get; set; }
public string StandardUId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public DateTime? StopDate { get; set; }
public DateTime? PauseDate { get; set; }
public DateTime? CompletionDate { get; set; }
public string StandardReference { get; set; }
public long UKPRN { get; set; }
public string LearnRefNumber { get; set; }
public short PaymentStatus { get; set; }
}
}
| using System;
namespace SFA.DAS.CommitmentsV2.Models
{
// This is a pseudo-entity to represent the result of the GetLearners stored proc, it's not a table in the database.
public class Learner
{
public long ApprenticeshipId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ULN { get; set; }
public string TrainingCode { get; set; }
public string TrainingCourseVersion { get; set; }
public bool TrainingCourseVersionConfirmed { get; set; }
public string TrainingCourseOption { get; set; }
public string StandardUId { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime? UpdatedOn { get; set; }
public DateTime? StopDate { get; set; }
public DateTime? PauseDate { get; set; }
public DateTime? CompletionDate { get; set; }
public string StandardReference { get; set; }
public long UKPRN { get; set; }
public string LearnRefNumber { get; set; }
public short PaymentStatus { get; set; }
}
}
| mit | C# |
23c7dde7248c4752be968404324e9ca7aba2af8f | fix validation context cache | arsouza/Aritter,aritters/Ritter,arsouza/Aritter | src/Domain.Seedwork/Validations/ValidationContextCache.cs | src/Domain.Seedwork/Validations/ValidationContextCache.cs | using Ritter.Infra.Crosscutting;
using System;
using System.Collections.Concurrent;
namespace Ritter.Domain.Validations
{
public class ValidationContextCache : IValidationContextCache
{
private static IValidationContextCache current = null;
private readonly ConcurrentDictionary<CacheKey, ValidationContext> cache = new ConcurrentDictionary<CacheKey, ValidationContext>();
public static IValidationContextCache Current() => (current = current ?? new ValidationContextCache());
public virtual ValidationContext GetOrAdd(Type type, Func<Type, ValidationContext> factory)
{
Ensure.NotNull(type, nameof(type));
return cache.GetOrAdd(new CacheKey(type, factory), ck => ck.Factory(ck.EntityType));
}
private readonly struct CacheKey
{
public CacheKey(Type entityType, Func<Type, ValidationContext> factory)
{
EntityType = entityType;
Factory = factory;
}
public Type EntityType { get; }
public Func<Type, ValidationContext> Factory { get; }
private bool Equals(CacheKey other)
=> EntityType.Equals(other.EntityType);
public override bool Equals(object obj)
{
if (obj.IsNull())
return false;
return obj.Is<CacheKey>() && Equals((CacheKey)obj);
}
public override int GetHashCode()
{
unchecked
{
return EntityType.GetHashCode() * 397;
}
}
}
}
}
| using Ritter.Infra.Crosscutting;
using System;
using System.Collections.Concurrent;
namespace Ritter.Domain.Validations
{
public class ValidationContextCache : IValidationContextCache
{
private static IValidationContextCache current = null;
private readonly ConcurrentDictionary<Type, ValidationContext> cache = new ConcurrentDictionary<Type, ValidationContext>();
public static IValidationContextCache Current() => (current = current ?? new ValidationContextCache());
public virtual ValidationContext GetOrAdd(Type type, Func<Type, ValidationContext> factory)
{
Ensure.NotNull(type, nameof(type));
return cache.GetOrAdd(type, factory?.Invoke(type));
}
}
}
| mit | C# |
f488bfe1ed5a3f7afd6bc97c1ee1264efae48c95 | Bump assembly version | junian/Xamarin.Social,aphex3k/Xamarin.Social,moljac/Xamarin.Social,pacificIT/Xamarin.Social,xamarin/Xamarin.Social,aphex3k/Xamarin.Social,junian/Xamarin.Social,moljac/Xamarin.Social,xamarin/Xamarin.Social,pacificIT/Xamarin.Social | src/Xamarin.Social/AssemblyInfo.cs | src/Xamarin.Social/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2013 Xamarin Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.1.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Xamarin.Social")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xamarin Inc.")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("2012-2013 Xamarin Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| apache-2.0 | C# |
c0e10034632a60ee0b33446b1b520bee674f067e | Add ICaller as partial | StevenThuriot/Horizon | ICaller.cs | ICaller.cs | #region License
//
// Copyright 2015 Steven Thuriot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
namespace Horizon
{
partial interface ICaller
{
object Call(IEnumerable<dynamic> values);
}
} | #region License
//
// Copyright 2015 Steven Thuriot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
using System.Collections.Generic;
namespace Horizon
{
interface ICaller
{
object Call(IEnumerable<dynamic> values);
}
} | mit | C# |
dbbfe1e9dafe0bb140f0a7281e13a50a629da944 | add reverse diff option | busterwood/Data | csv/Difference.cs | csv/Difference.cs | using BusterWood.Data;
using BusterWood.Data.Shared;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace BusterWood.Csv
{
class Difference
{
public static void Run(List<string> args)
{
try
{
if (args.Remove("--help")) Help();
var all = args.Remove("--all");
var reverse = args.Remove("--rev");
DataSequence input = Args.GetDataSequence(args);
var others = args
.Select(file => new { file, reader = new StreamReader(file) })
.Select(r => r.reader.ToCsvDataSequence(r.file))
.ToList();
input.CheckSchemaCompatibility(others);
var unionOp = all ? (Func<DataSequence, DataSequence, DataSequence>)Data.Extensions.DifferenceAll : Data.Extensions.Difference;
DataSequence result = reverse
? others.Aggregate(input, (acc, o) => unionOp(o, acc)) // reverse diff
: others.Aggregate(input, (acc, o) => unionOp(acc, o));
Console.WriteLine(result.Schema.ToCsv());
foreach (var row in result)
Console.WriteLine(row.ToCsv());
}
catch (Exception ex)
{
StdErr.Warning(ex.Message);
Help();
}
}
static void Help()
{
Console.Error.WriteLine($"csv diff[erence] [--all] [--in file] [--rev] [file ...]");
Console.Error.WriteLine($"Outputs the rows in the input CSV that do not appear in any of the additional files");
Console.Error.WriteLine($"\t--all do NOT remove duplicates from the result");
Console.Error.WriteLine($"\t--in read the input from a file path (rather than standard input)");
Console.Error.WriteLine($"\t--rev reverse the difference");
Programs.Exit(1);
}
}
}
| using BusterWood.Data;
using BusterWood.Data.Shared;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace BusterWood.Csv
{
class Difference
{
public static void Run(List<string> args)
{
try
{
if (args.Remove("--help")) Help();
var all = args.Remove("--all");
DataSequence input = Args.GetDataSequence(args);
var others = args
.Select(file => new { file, reader = new StreamReader(file) })
.Select(r => r.reader.ToCsvDataSequence(r.file))
.ToList();
input.CheckSchemaCompatibility(others);
var unionOp = all ? (Func<DataSequence, DataSequence, DataSequence>)Data.Extensions.DifferenceAll : Data.Extensions.Difference;
var result = others.Aggregate(input, (acc, o) => unionOp(acc, o));
Console.WriteLine(result.Schema.ToCsv());
foreach (var row in result)
Console.WriteLine(row.ToCsv());
}
catch (Exception ex)
{
StdErr.Warning(ex.Message);
Help();
}
}
static void Help()
{
Console.Error.WriteLine($"csv diff[erence] [--all] [--in file] [file ...]");
Console.Error.WriteLine($"Outputs the rows in the input CSV that do not appear in any of the additional files");
Console.Error.WriteLine($"\t--all do NOT remove duplicates from the result");
Console.Error.WriteLine($"\t--in read the input from a file path (rather than standard input)");
Programs.Exit(1);
}
}
}
| apache-2.0 | C# |
71c305e7fc5044cbcbfb6f85e3834a6be7a09298 | Hide the blinking console tail on linux. | darkriszty/SnakeApp | src/SnakeApp/GameController.cs | src/SnakeApp/GameController.cs | using SnakeApp.Models;
using System;
using System.Threading.Tasks;
namespace SnakeApp
{
public class GameController
{
public async Task StartNewGame()
{
PrepareConsole();
var game = new Game(80, 25, 5, 100);
game.Start();
ConsoleKeyInfo userInput = new ConsoleKeyInfo();
do
{
userInput = Console.ReadKey(true);
game.ReceiveInput(userInput.Key);
} while (userInput.Key != ConsoleKey.Q);
RestoreConsole();
}
private void PrepareConsole()
{
// getting the current cursor visibility is not supported on linux, so just hide then restore it
Console.Clear();
Console.CursorVisible = false;
}
private void RestoreConsole()
{
Console.Clear();
Console.CursorVisible = true;
}
}
}
| using SnakeApp.Models;
using System;
using System.Threading.Tasks;
namespace SnakeApp
{
public class GameController
{
public async Task StartNewGame()
{
var game = new Game(80, 25, 5, 100);
game.Start();
ConsoleKeyInfo userInput = new ConsoleKeyInfo();
do
{
userInput = Console.ReadKey(true);
game.ReceiveInput(userInput.Key);
} while (userInput.Key != ConsoleKey.Q);
}
}
}
| mit | C# |
1697b41845777b45653688e3bf39c3f5a49c71b3 | Add a way to disable synchronization into SpriterSubstituteEntity. | Noxalus/Xmas-Hell | Xmas-Hell/Xmas-Hell-Core/Spriter/SpriterSubstituteEntity.cs | Xmas-Hell/Xmas-Hell-Core/Spriter/SpriterSubstituteEntity.cs | using Microsoft.Xna.Framework;
using MonoGame.Extended;
namespace XmasHell.Spriter
{
public class SpriterSubstituteEntity
{
public CustomSpriterAnimator SubstituteAnimator;
private string _replacedPartFilename;
private CustomSpriterAnimator _referenceAnimator;
private SpriterDotNet.SpriterFile _replacedSpriterFile;
private Size2 _replacedSpriterFileHalfSize;
private bool _synchronize = true;
public BoundingRectangle BoundingRectangle()
{
return new BoundingRectangle(SubstituteAnimator.Position, _replacedSpriterFileHalfSize);
}
public void EnableSynchronization(bool value)
{
_synchronize = value;
}
public SpriterSubstituteEntity(string replacedPartFilename, CustomSpriterAnimator referenceAnimator, CustomSpriterAnimator substituteAnimator)
{
_replacedPartFilename = replacedPartFilename;
_referenceAnimator = referenceAnimator;
SubstituteAnimator = substituteAnimator;
_replacedSpriterFile = SpriterUtils.GetSpriterFileStaticData(_replacedPartFilename, SubstituteAnimator);
_replacedSpriterFileHalfSize = new Size2(_replacedSpriterFile.Width / 2, _replacedSpriterFile.Height / 2);
referenceAnimator.AddHiddenTexture(replacedPartFilename);
}
public void Update(GameTime gameTime)
{
if (_synchronize)
{
// Synchronize current GUI button animator with the related dummy element from the Spriter file
var spriterDummyData = SpriterUtils.GetSpriterFileData(_replacedPartFilename, _referenceAnimator);
if (spriterDummyData != null)
{
var dummyPosition = new Vector2(spriterDummyData.X, -spriterDummyData.Y);
var dummyScale = new Vector2(spriterDummyData.ScaleX, spriterDummyData.ScaleY);
SubstituteAnimator.Position = _referenceAnimator.Position + dummyPosition;
SubstituteAnimator.Rotation = -MathHelper.ToRadians(spriterDummyData.Angle);
SubstituteAnimator.Scale = dummyScale;
SubstituteAnimator.Color = new Color(SubstituteAnimator.Color, spriterDummyData.Alpha);
}
}
}
}
}
| using Microsoft.Xna.Framework;
using MonoGame.Extended;
namespace XmasHell.Spriter
{
public class SpriterSubstituteEntity
{
public CustomSpriterAnimator SubstituteAnimator;
private string _replacedPartFilename;
private CustomSpriterAnimator _referenceAnimator;
private SpriterDotNet.SpriterFile _replacedSpriterFile;
private Size2 _replacedSpriterFileHalfSize;
public BoundingRectangle BoundingRectangle()
{
return new BoundingRectangle(SubstituteAnimator.Position, _replacedSpriterFileHalfSize);
}
public SpriterSubstituteEntity(string replacedPartFilename, CustomSpriterAnimator referenceAnimator, CustomSpriterAnimator substituteAnimator)
{
_replacedPartFilename = replacedPartFilename;
_referenceAnimator = referenceAnimator;
SubstituteAnimator = substituteAnimator;
_replacedSpriterFile = SpriterUtils.GetSpriterFileStaticData(_replacedPartFilename, SubstituteAnimator);
_replacedSpriterFileHalfSize = new Size2(_replacedSpriterFile.Width / 2, _replacedSpriterFile.Height / 2);
referenceAnimator.AddHiddenTexture(replacedPartFilename);
}
public void Update(GameTime gameTime)
{
// Synchronize current GUI button animator with the related dummy element from the Spriter file
var spriterDummyData = SpriterUtils.GetSpriterFileData(_replacedPartFilename, _referenceAnimator);
if (spriterDummyData != null)
{
var dummyPosition = new Vector2(spriterDummyData.X, -spriterDummyData.Y);
var dummyScale = new Vector2(spriterDummyData.ScaleX, spriterDummyData.ScaleY);
SubstituteAnimator.Position = _referenceAnimator.Position + dummyPosition;
SubstituteAnimator.Rotation = -MathHelper.ToRadians(spriterDummyData.Angle);
SubstituteAnimator.Scale = dummyScale;
SubstituteAnimator.Color = new Color(SubstituteAnimator.Color, spriterDummyData.Alpha);
}
}
}
}
| mit | C# |
c8cd8b7be62cfd3978cf00d18ed174f971db8199 | Change method callings to default static instance | Archie-Yang/PcscDotNet | src/PcscDotNet/Pcsc_1.cs | src/PcscDotNet/Pcsc_1.cs | using System;
namespace PcscDotNet
{
public static class Pcsc<TIPcscProvider> where TIPcscProvider : class, IPcscProvider, new()
{
private static readonly Pcsc _instance = new Pcsc(new TIPcscProvider());
public static Pcsc Instance => _instance;
public static PcscContext CreateContext()
{
return _instance.CreateContext();
}
public static PcscContext EstablishContext(SCardScope scope)
{
return _instance.EstablishContext(scope);
}
}
} | using System;
namespace PcscDotNet
{
public static class Pcsc<TIPcscProvider> where TIPcscProvider : class, IPcscProvider, new()
{
private static readonly Pcsc _instance = new Pcsc(new TIPcscProvider());
public static Pcsc Instance => _instance;
public static PcscContext CreateContext()
{
return new PcscContext(_instance);
}
public static PcscContext EstablishContext(SCardScope scope)
{
return new PcscContext(_instance, scope);
}
}
} | mit | C# |
97245b72ef5e8611ffdc7e84b107f60277153b7b | Update ProcessManager.cs | architecture-building-systems/revitpythonshell,architecture-building-systems/revitpythonshell | RevitPythonShell/Helpers/ProcessManager.cs | RevitPythonShell/Helpers/ProcessManager.cs | using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace RevitPythonShell.Helpers
{
public static class ProcessManager
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static void SetRevitAsWindowOwner(this Window window)
{
if (null == window) { return; }
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
WindowInteropHelper helper = new WindowInteropHelper(window);
helper.Owner = GetActivateWindow();
window.Closing += SetActivateWindow;
}
private static void SetActivateWindow(object sender, CancelEventArgs e)
{
SetActivateWindow();
}
/// <summary>
/// Set process revert use revit
/// </summary>
/// <returns></returns>
public static void SetActivateWindow()
{
IntPtr ptr = GetActivateWindow();
if (ptr != IntPtr.Zero)
{
SetForegroundWindow(ptr);
}
}
/// <summary>
/// return active windows is active
/// </summary>
/// <returns></returns>
public static IntPtr GetActivateWindow()
{
return Process.GetCurrentProcess().MainWindowHandle;
}
}
} | using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace RevitPythonShell.Helpers
{
public static class ProcessManager
{
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
public static void SetRevitAsWindowOwner(this Window window)
{
if (null == window) { return; }
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
WindowInteropHelper helper = new WindowInteropHelper(window);
helper.Owner = GetActivateWindow();
window.Closing += SetActivateWindow;
}
private static void SetActivateWindow(object sender, CancelEventArgs e)
{
SetActivateWindow();
}
/// <summary>
/// Set process revert use revit
/// </summary>
/// <returns></returns>
public static bool SetActivateWindow()
{
IntPtr ptr = GetActivateWindow();
if (ptr != IntPtr.Zero)
{
return SetForegroundWindow(ptr);
}
return false;
}
/// <summary>
/// return active windows is active
/// </summary>
/// <returns></returns>
public static IntPtr GetActivateWindow()
{
return Process.GetCurrentProcess().MainWindowHandle;
}
}
} | mit | C# |
2750880c09152439a5ebf3adcddf1a81d7513d88 | Change OptimizationTest example. | geoem/MSolve,geoem/MSolve | ISAAR.MSolve.SamplesConsole/Optimization/OptimizationTest.cs | ISAAR.MSolve.SamplesConsole/Optimization/OptimizationTest.cs | using ISAAR.MSolve.Analyzers.Optimization;
using ISAAR.MSolve.Analyzers.Optimization.Algorithms.Metaheuristics.DifferentialEvolution;
using ISAAR.MSolve.Analyzers.Optimization.Convergence;
using ISAAR.MSolve.SamplesConsole.Optimization.BenchmarkFunctions;
using System;
namespace ISAAR.MSolve.SamplesConsole.Optimization
{
public class OptimizationTest
{
public static void Main()
{
OptimizationProblem optimizationProblem = new Ackley();
DifferentialEvolutionAlgorithm.Builder builder = new DifferentialEvolutionAlgorithm.Builder(optimizationProblem);
builder.PopulationSize = 100;
builder.MutationFactor = 0.4;
builder.CrossoverProbability = 0.9;
builder.ConvergenceCriterion = new MaxFunctionEvaluations(100000);
//DifferentialEvolutionAlgorithm de = new DifferentialEvolutionAlgorithm(optimizationProblem);
IOptimizationAlgorithm de = builder.Build();
IOptimizationAnalyzer analyzer = new OptimizationAnalyzer(de);
analyzer.Optimize();
// Print results
Console.WriteLine("\n Best Position:");
for (int i = 0; i < optimizationProblem.Dimension; i++)
{
Console.WriteLine(String.Format(@" x[{0}] = {1} ", i, de.BestPosition[i]));
}
Console.WriteLine(String.Format(@"Best Fitness: {0}", de.BestFitness));
}
}
}
| using ISAAR.MSolve.Analyzers.Optimization;
using ISAAR.MSolve.Analyzers.Optimization.Algorithms;
using ISAAR.MSolve.SamplesConsole.Optimization.BenchmarkFunctions;
using System;
namespace ISAAR.MSolve.SamplesConsole.Optimization
{
public class OptimizationTest
{
public static void Main()
{
//IObjectiveFunction objective = new Ackley();
//double[] lowerBounds = { -5, -5 };
//double[] upperBounds = { 5, 5 };
//IObjectiveFunction objective = new Beale();
//double[] lowerBounds = { -4.5, -4.5 };
//double[] upperBounds = { 4.5, 4.5 };
//IObjectiveFunction objective = new GoldsteinPrice();
//double[] lowerBounds = {-2, -2 };
//double[] upperBounds = { 2, 2 };
IObjectiveFunction objective = new McCormick();
double[] lowerBounds = { -1.5, -3.0 };
double[] upperBounds = { 4.0, 4.0 };
DifferentialEvolution de = new DifferentialEvolution(lowerBounds.Length, lowerBounds, upperBounds, objective);
IOptimizationAnalyzer analyzer = new OptimizationAnalyzer(de);
analyzer.Optimize();
// Print results
Console.WriteLine("\n Best Position:");
for (int i = 0; i < lowerBounds.Length; i++)
{
Console.WriteLine(String.Format(@" x[{0}] = {1} ", i, de.BestPosition[i]));
}
Console.WriteLine(String.Format(@"Best Fitness: {0}", de.BestFitness));
}
}
}
| apache-2.0 | C# |
656a63481f8302e9de2a18ba6a1c292da6e6986f | Add registration options for codeAction request | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/CodeAction.cs | src/PowerShellEditorServices.Protocol/LanguageServer/CodeAction.cs | using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Newtonsoft.Json.Linq;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class CodeActionRequest
{
public static readonly
RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions> Type =
RequestType<CodeActionParams, CodeActionCommand[], object, TextDocumentRegistrationOptions>.Create("textDocument/codeAction");
}
/// <summary>
/// Parameters for CodeActionRequest.
/// </summary>
public class CodeActionParams
{
/// <summary>
/// The document in which the command was invoked.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }
/// <summary>
/// The range for which the command was invoked.
/// </summary>
public Range Range { get; set; }
/// <summary>
/// Context carrying additional information.
/// </summary>
public CodeActionContext Context { get; set; }
}
public class CodeActionContext
{
public Diagnostic[] Diagnostics { get; set; }
}
public class CodeActionCommand
{
public string Title { get; set; }
public string Command { get; set; }
public JArray Arguments { get; set; }
}
}
| using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
using Newtonsoft.Json.Linq;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public class CodeActionRequest
{
public static readonly
RequestType<CodeActionParams, CodeActionCommand[], object, object> Type =
RequestType<CodeActionParams, CodeActionCommand[], object, object>.Create("textDocument/codeAction");
}
/// <summary>
/// Parameters for CodeActionRequest.
/// </summary>
public class CodeActionParams
{
/// <summary>
/// The document in which the command was invoked.
/// </summary>
public TextDocumentIdentifier TextDocument { get; set; }
/// <summary>
/// The range for which the command was invoked.
/// </summary>
public Range Range { get; set; }
/// <summary>
/// Context carrying additional information.
/// </summary>
public CodeActionContext Context { get; set; }
}
public class CodeActionContext
{
public Diagnostic[] Diagnostics { get; set; }
}
public class CodeActionCommand
{
public string Title { get; set; }
public string Command { get; set; }
public JArray Arguments { get; set; }
}
}
| mit | C# |
b87a515d9c4a9bf1d4453c32813d6ee428024c43 | Test fix | roberino/linqinfer,roberino/linqinfer,roberino/linqinfer | tests/LinqInfer.UnitTests/Learning/LstmExtensionsTests.cs | tests/LinqInfer.UnitTests/Learning/LstmExtensionsTests.cs | using System;
using LinqInfer.Learning;
using LinqInfer.Utility;
using NUnit.Framework;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace LinqInfer.UnitTests.Learning
{
[TestFixture]
public class LstmExtensionsTests
{
[Test]
public async Task AttachLongShortTermMemoryNetwork_SimpleSequence_ReturnsValidClassifier()
{
var data = Enumerable.Range('a', 10)
.Concat(Enumerable.Range('c', 10))
.Select(c => (char)c)
.AsAsyncEnumerator();
var trainingSet = await data.CreateCategoricalTimeSequenceTrainingSetAsync();
var classifier = trainingSet.AttachLongShortTermMemoryNetwork();
await trainingSet.RunAsync(CancellationToken.None, 5);
var results = classifier.Classify('e');
Assert.That(results.First().ClassType, Is.EqualTo('f'));
}
}
} | using System;
using LinqInfer.Learning;
using LinqInfer.Utility;
using NUnit.Framework;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace LinqInfer.UnitTests.Learning
{
[TestFixture]
public class LstmExtensionsTests
{
[Test]
public async Task AttachLongShortTermMemoryNetwork_SimpleSequence_ReturnsValidClassifier()
{
var data = Enumerable.Range('a', 10)
.Concat(Enumerable.Range('c', 10))
.Select(c => (char)c)
.AsAsyncEnumerator();
var trainingSet = await data.CreateCategoricalTimeSequenceTrainingSetAsync();
var classifier = trainingSet.AttachLongShortTermMemoryNetwork();
await trainingSet.RunAsync(CancellationToken.None);
var results = classifier.Classify('e');
Assert.That(results.First().ClassType, Is.EqualTo('f'));
}
}
} | mit | C# |
b5e22f3f0bdd80c1705b042f8897b19ceea0314c | Bump to 0.4.5 | wasphub/RElmah,wasphub/RElmah | relmah/src/Common/VersionInfo.cs | relmah/src/Common/VersionInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// 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.4.5.0")]
[assembly: AssemblyFileVersion("0.4.5.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// 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.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")] | apache-2.0 | C# |
a9a8c452262efe07df57fb9c0aa6c6c213dba9f3 | Fix the https middleware. | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | backend/src/Squidex.Web/Pipeline/EnforceHttpsMiddleware.cs | backend/src/Squidex.Web/Pipeline/EnforceHttpsMiddleware.cs | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Squidex.Infrastructure;
namespace Squidex.Web.Pipeline
{
public sealed class EnforceHttpsMiddleware : IMiddleware
{
private readonly UrlsOptions urlsOptions;
public EnforceHttpsMiddleware(IOptions<UrlsOptions> urlsOptions)
{
Guard.NotNull(urlsOptions, nameof(urlsOptions));
this.urlsOptions = urlsOptions.Value;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!urlsOptions.EnforceHTTPS)
{
await next(context);
}
else
{
var hostName = context.Request.Host.ToString().ToLowerInvariant();
if (!context.Request.IsHttps)
{
var newUrl = string.Concat("https://", hostName, context.Request.Path, context.Request.QueryString);
context.Response.Redirect(newUrl, true);
}
else
{
await next(context);
}
}
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
using Squidex.Infrastructure;
namespace Squidex.Web.Pipeline
{
public sealed class EnforceHttpsMiddleware : IMiddleware
{
private readonly UrlsOptions urlsOptions;
public EnforceHttpsMiddleware(IOptions<UrlsOptions> urlsOptions)
{
Guard.NotNull(urlsOptions, nameof(urlsOptions));
this.urlsOptions = urlsOptions.Value;
}
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
if (!urlsOptions.EnforceHTTPS)
{
await next(context);
}
else
{
var hostName = context.Request.Host.ToString().ToLowerInvariant();
if (!string.Equals(context.Request.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
var newUrl = string.Concat("https://", hostName, context.Request.Path, context.Request.QueryString);
context.Response.Redirect(newUrl, true);
}
else
{
await next(context);
}
}
}
}
}
| mit | C# |
7899c93597ead3d48c5a69657728fad0f86bc898 | Expand supported versions for unused templates module (#133) | ChristopherJennings/KInspector,ChristopherJennings/KInspector,JosefDvorak/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,JosefDvorak/KInspector,Kentico/KInspector,Kentico/KInspector,JosefDvorak/KInspector,ChristopherJennings/KInspector | KInspector.Modules/Modules/Content/UnusedTemplatesModule.cs | KInspector.Modules/Modules/Content/UnusedTemplatesModule.cs | using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Kentico.KInspector.Core;
namespace Kentico.KInspector.Modules
{
public class UnusedTemplatesModule : IModule
{
public ModuleMetadata GetModuleMetadata()
{
return new ModuleMetadata
{
Name = "Unused templates",
SupportedVersions = new[] {
new Version("8.0"),
new Version("8.1"),
new Version("8.2"),
new Version("9.0"),
new Version("10.0")
},
Comment = @"Looks for unused templates.",
};
}
public ModuleResults GetResults(IInstanceInfo instanceInfo)
{
var dbService = instanceInfo.DBService;
var unusedTemplates = dbService.ExecuteAndGetTableFromFile("UnusedTemplatesModule.sql");
return new ModuleResults
{
Result = unusedTemplates
};
}
}
}
| using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using Kentico.KInspector.Core;
namespace Kentico.KInspector.Modules
{
public class UnusedTemplatesModule : IModule
{
public ModuleMetadata GetModuleMetadata()
{
return new ModuleMetadata
{
Name = "Unused templates",
SupportedVersions = new[] {
//new Version("7.0"),
//new Version("8.0"),
//new Version("8.1"),
//new Version("8.2"),
new Version("9.0")
},
Comment = @"Looks for unused templates.",
};
}
public ModuleResults GetResults(IInstanceInfo instanceInfo)
{
var dbService = instanceInfo.DBService;
var unusedTemplates = dbService.ExecuteAndGetTableFromFile("UnusedTemplatesModule.sql");
return new ModuleResults
{
Result = unusedTemplates
};
}
}
}
| mit | C# |
49d67f663087e08fb220b7229b44b57edc8e3f8c | Move down to highlight the Create methods. | danielwertheim/mycouch,danielwertheim/mycouch | src/Projects/MyCouch/Requests/Factories/AttachmentHttpRequestFactory.cs | src/Projects/MyCouch/Requests/Factories/AttachmentHttpRequestFactory.cs | using System.Net.Http;
using MyCouch.Net;
namespace MyCouch.Requests.Factories
{
public class AttachmentHttpRequestFactory :
HttpRequestFactoryBase,
IHttpRequestFactory<GetAttachmentRequest>,
IHttpRequestFactory<PutAttachmentRequest>,
IHttpRequestFactory<DeleteAttachmentRequest>
{
public AttachmentHttpRequestFactory(IConnection connection) : base(connection) { }
public virtual HttpRequest Create(GetAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Get, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
public virtual HttpRequest Create(PutAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Put, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
httpRequest.SetContent(request.Content, request.ContentType);
return httpRequest;
}
public virtual HttpRequest Create(DeleteAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Delete, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
protected virtual string GenerateRequestUrl(string docId, string docRev, string attachmentName)
{
return string.Format("{0}/{1}/{2}{3}",
Connection.Address,
docId,
attachmentName,
docRev == null ? string.Empty : string.Concat("?rev=", docRev));
}
}
}
| using System.Net.Http;
using MyCouch.Net;
namespace MyCouch.Requests.Factories
{
public class AttachmentHttpRequestFactory :
HttpRequestFactoryBase,
IHttpRequestFactory<GetAttachmentRequest>,
IHttpRequestFactory<PutAttachmentRequest>,
IHttpRequestFactory<DeleteAttachmentRequest>
{
public AttachmentHttpRequestFactory(IConnection connection) : base(connection) { }
protected virtual string GenerateRequestUrl(string docId, string docRev, string attachmentName)
{
return string.Format("{0}/{1}/{2}{3}",
Connection.Address,
docId,
attachmentName,
docRev == null ? string.Empty : string.Concat("?rev=", docRev));
}
public virtual HttpRequest Create(GetAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Get, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
public virtual HttpRequest Create(PutAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Put, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
httpRequest.SetContent(request.Content, request.ContentType);
return httpRequest;
}
public virtual HttpRequest Create(DeleteAttachmentRequest request)
{
var httpRequest = new HttpRequest(HttpMethod.Delete, GenerateRequestUrl(request.DocId, request.DocRev, request.Name));
httpRequest.SetIfMatch(request.DocRev);
return httpRequest;
}
}
}
| mit | C# |
4ff649fbf5c7cd8a9cb09b64160ac6915c836b1a | Use ContextIsPresent in XCorrelationIdHttpMessageHandler | bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework | src/Server/Bit.Core/Implementations/XCorrelationIdHttpMessageHandler.cs | src/Server/Bit.Core/Implementations/XCorrelationIdHttpMessageHandler.cs | using Bit.Core.Contracts;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Bit.Core.Implementations
{
public class XCorrelationIdHttpMessageHandler : DelegatingHandler
{
private readonly IRequestInformationProvider _requestInformationProvider;
public XCorrelationIdHttpMessageHandler(IRequestInformationProvider requestInformationProvider)
{
_requestInformationProvider = requestInformationProvider;
}
public XCorrelationIdHttpMessageHandler(IRequestInformationProvider requestInformationProvider, HttpMessageHandler innerHandler)
: base(innerHandler)
{
_requestInformationProvider = requestInformationProvider;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("X-Correlation-ID") && _requestInformationProvider.ContextIsPresent)
request.Headers.Add("X-Correlation-ID", _requestInformationProvider.XCorrelationId);
return base.SendAsync(request, cancellationToken);
}
}
}
| using Bit.Core.Contracts;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Bit.Core.Implementations
{
public class XCorrelationIdHttpMessageHandler : DelegatingHandler
{
private readonly IRequestInformationProvider _requestInformationProvider;
public XCorrelationIdHttpMessageHandler(IRequestInformationProvider requestInformationProvider)
{
_requestInformationProvider = requestInformationProvider;
}
public XCorrelationIdHttpMessageHandler(IRequestInformationProvider requestInformationProvider, HttpMessageHandler innerHandler)
: base(innerHandler)
{
_requestInformationProvider = requestInformationProvider;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (!request.Headers.Contains("X-Correlation-ID"))
request.Headers.Add("X-Correlation-ID", _requestInformationProvider.XCorrelationId);
return base.SendAsync(request, cancellationToken);
}
}
}
| mit | C# |
6d62e80c9911f4d5664474fc3b1fb8cf14310802 | Add toggle back to Crazy Talk | samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays | Assets/Scripts/ComponentSolvers/Modded/Perky/CrazyTalkComponentSolver.cs | Assets/Scripts/ComponentSolvers/Modded/Perky/CrazyTalkComponentSolver.cs | using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
public class CrazyTalkComponentSolver : ComponentSolver
{
public CrazyTalkComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_toggle = (MonoBehaviour)_toggleField.GetValue(bombComponent.GetComponent(_componentType));
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
int downtime;
int uptime;
var commands = inputCommand.ToLowerInvariant().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (commands.Length != 3 || !commands[0].EqualsAny("toggle", "flip", "switch") ||
!int.TryParse(commands[1], out downtime) || !int.TryParse(commands[2], out uptime))
yield break;
if (downtime < 0 || downtime > 9 || uptime < 0 || uptime > 9)
yield break;
yield return "Crazy Talk Solve Attempt";
MonoBehaviour timerComponent = (MonoBehaviour)CommonReflectedTypeInfo.GetTimerMethod.Invoke(BombCommander.Bomb, null);
int timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
while ((timeRemaining%10) != downtime)
{
yield return null;
timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
}
yield return DoInteractionClick(_toggle);
while ((timeRemaining % 10) != uptime)
{
yield return null;
timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
}
yield return DoInteractionClick(_toggle);
}
static CrazyTalkComponentSolver()
{
_componentType = ReflectionHelper.FindType("CrazyTalkModule");
_toggleField = _componentType.GetField("toggleSwitch", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _componentType = null;
private static FieldInfo _toggleField = null;
private MonoBehaviour _toggle = null;
}
| using System;
using System.Collections;
using System.Reflection;
using UnityEngine;
public class CrazyTalkComponentSolver : ComponentSolver
{
public CrazyTalkComponentSolver(BombCommander bombCommander, MonoBehaviour bombComponent, IRCConnection ircConnection, CoroutineCanceller canceller) :
base(bombCommander, bombComponent, ircConnection, canceller)
{
_toggle = (MonoBehaviour)_toggleField.GetValue(bombComponent.GetComponent(_componentType));
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType());
}
protected override IEnumerator RespondToCommandInternal(string inputCommand)
{
int downtime;
int uptime;
var commands = inputCommand.ToLowerInvariant().Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
if (commands.Length != 3 || !commands[0].EqualsAny("flip", "switch") ||
!int.TryParse(commands[1], out downtime) || !int.TryParse(commands[2], out uptime))
yield break;
if (downtime < 0 || downtime > 9 || uptime < 0 || uptime > 9)
yield break;
yield return "Crazy Talk Solve Attempt";
MonoBehaviour timerComponent = (MonoBehaviour)CommonReflectedTypeInfo.GetTimerMethod.Invoke(BombCommander.Bomb, null);
int timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
while ((timeRemaining%10) != downtime)
{
yield return null;
timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
}
yield return DoInteractionClick(_toggle);
while ((timeRemaining % 10) != uptime)
{
yield return null;
timeRemaining = (int)((float)CommonReflectedTypeInfo.TimeRemainingField.GetValue(timerComponent));
}
yield return DoInteractionClick(_toggle);
}
static CrazyTalkComponentSolver()
{
_componentType = ReflectionHelper.FindType("CrazyTalkModule");
_toggleField = _componentType.GetField("toggleSwitch", BindingFlags.Public | BindingFlags.Instance);
}
private static Type _componentType = null;
private static FieldInfo _toggleField = null;
private MonoBehaviour _toggle = null;
}
| mit | C# |
d8bee86d8066eb63f9d22988fc92dd344ac16987 | fix SBMessagingProperties' type | icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory,icraftsoftware/BizTalk.Factory | src/BizTalk.Schemas/ContextProperties/SBMessagingProperties.cs | src/BizTalk.Schemas/ContextProperties/SBMessagingProperties.cs | #region Copyright & License
// Copyright © 2012 - 2019 François Chabot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using SBMessaging;
namespace Be.Stateless.BizTalk.ContextProperties
{
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public static class SBMessagingProperties
{
public static readonly MessageContextProperty<ContentType, string> ContentType
= new MessageContextProperty<ContentType, string>();
public static readonly MessageContextProperty<CorrelationId, string> CorrelationId
= new MessageContextProperty<CorrelationId, string>();
public static readonly MessageContextProperty<CustomBrokeredMessagePropertyNamespace, string> CustomBrokeredMessagePropertyNamespace
= new MessageContextProperty<CustomBrokeredMessagePropertyNamespace, string>();
public static readonly MessageContextProperty<DeliveryCount, int> DeliveryCount
= new MessageContextProperty<DeliveryCount, int>();
public static readonly MessageContextProperty<EnqueuedTimeUtc, DateTime> EnqueuedTimeUtc
= new MessageContextProperty<EnqueuedTimeUtc, DateTime>();
public static readonly MessageContextProperty<ExpiresAtUtc, DateTime> ExpiresAtUtc
= new MessageContextProperty<ExpiresAtUtc, DateTime>();
public static readonly MessageContextProperty<Label, string> Label
= new MessageContextProperty<Label, string>();
public static readonly MessageContextProperty<LockedUntilUtc, DateTime> LockedUntilUtc
= new MessageContextProperty<LockedUntilUtc, DateTime>();
public static readonly MessageContextProperty<LockToken, string> LockToken
= new MessageContextProperty<LockToken, string>();
public static readonly MessageContextProperty<MessageId, string> MessageId
= new MessageContextProperty<MessageId, string>();
public static readonly MessageContextProperty<ReplyTo, string> ReplyTo
= new MessageContextProperty<ReplyTo, string>();
public static readonly MessageContextProperty<ReplyToSessionId, string> ReplyToSessionId
= new MessageContextProperty<ReplyToSessionId, string>();
public static readonly MessageContextProperty<ScheduledEnqueueTimeUtc, DateTime> ScheduledEnqueueTimeUtc
= new MessageContextProperty<ScheduledEnqueueTimeUtc, DateTime>();
public static readonly MessageContextProperty<SequenceNumber, string> SequenceNumber
= new MessageContextProperty<SequenceNumber, string>();
public static readonly MessageContextProperty<SessionId, string> SessionId
= new MessageContextProperty<SessionId, string>();
public static readonly MessageContextProperty<TimeToLive, string> TimeToLive
= new MessageContextProperty<TimeToLive, string>();
public static readonly MessageContextProperty<To, string> To
= new MessageContextProperty<To, string>();
}
}
| #region Copyright & License
// Copyright © 2012 - 2019 François Chabot
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Diagnostics.CodeAnalysis;
using SBMessaging;
namespace Be.Stateless.BizTalk.ContextProperties
{
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public static class SBMessagingProperties
{
public static readonly MessageContextProperty<ContentType, string> ContentType
= new MessageContextProperty<ContentType, string>();
public static readonly MessageContextProperty<CorrelationId, string> CorrelationId
= new MessageContextProperty<CorrelationId, string>();
public static readonly MessageContextProperty<CustomBrokeredMessagePropertyNamespace, string> CustomBrokeredMessagePropertyNamespace
= new MessageContextProperty<CustomBrokeredMessagePropertyNamespace, string>();
public static readonly MessageContextProperty<DeliveryCount, int> DeliveryCount
= new MessageContextProperty<DeliveryCount, int>();
public static readonly MessageContextProperty<EnqueuedTimeUtc, DateTime> EnqueuedTimeUtc
= new MessageContextProperty<EnqueuedTimeUtc, DateTime>();
public static readonly MessageContextProperty<ExpiresAtUtc, DateTime> ExpiresAtUtc
= new MessageContextProperty<ExpiresAtUtc, DateTime>();
public static readonly MessageContextProperty<Label, string> Label
= new MessageContextProperty<Label, string>();
public static readonly MessageContextProperty<LockedUntilUtc, string> LockedUntilUtc
= new MessageContextProperty<LockedUntilUtc, string>();
public static readonly MessageContextProperty<LockToken, string> LockToken
= new MessageContextProperty<LockToken, string>();
public static readonly MessageContextProperty<MessageId, string> MessageId
= new MessageContextProperty<MessageId, string>();
public static readonly MessageContextProperty<ReplyTo, string> ReplyTo
= new MessageContextProperty<ReplyTo, string>();
public static readonly MessageContextProperty<ReplyToSessionId, string> ReplyToSessionId
= new MessageContextProperty<ReplyToSessionId, string>();
public static readonly MessageContextProperty<ScheduledEnqueueTimeUtc, DateTime> ScheduledEnqueueTimeUtc
= new MessageContextProperty<ScheduledEnqueueTimeUtc, DateTime>();
public static readonly MessageContextProperty<SequenceNumber, DateTime> SequenceNumber
= new MessageContextProperty<SequenceNumber, DateTime>();
public static readonly MessageContextProperty<SessionId, DateTime> SessionId
= new MessageContextProperty<SessionId, DateTime>();
public static readonly MessageContextProperty<TimeToLive, string> TimeToLive
= new MessageContextProperty<TimeToLive, string>();
public static readonly MessageContextProperty<To, string> To
= new MessageContextProperty<To, string>();
}
}
| apache-2.0 | C# |
f2769c2b73429da82016fb39a2d32bbbc361d2f5 | Update BasketController.cs | dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,skynode/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,TypeW/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,andrelmp/eShopOnContainers,dotnet-architecture/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,dotnet-architecture/eShopOnContainers,TypeW/eShopOnContainers | src/Services/Basket/Basket.API/Controllers/BasketController.cs | src/Services/Basket/Basket.API/Controllers/BasketController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.AspNetCore.Authorization;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
{
[Route("/")]
[Authorize]
public class BasketController : Controller
{
private IBasketRepository _repository;
public BasketController(IBasketRepository repository)
{
_repository = repository;
}
// GET /id
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var basket = await _repository.GetBasketAsync(id);
return Ok(basket);
}
// POST /value
[HttpPost]
public async Task<IActionResult> Post([FromBody]CustomerBasket value)
{
var basket = await _repository.UpdateBasketAsync(value);
return Ok(basket);
}
// DELETE /id
[HttpDelete("{id}")]
public void Delete(string id)
{
_repository.DeleteBasketAsync(id);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.AspNetCore.Authorization;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
{
[Route("/")]
[Authorize]
public class BasketController : Controller
{
private IBasketRepository _repository;
public BasketController(IBasketRepository repository)
{
_repository = repository;
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var basket = await _repository.GetBasketAsync(id);
return Ok(basket);
}
// POST api/values
[HttpPost]
public async Task<IActionResult> Post([FromBody]CustomerBasket value)
{
var basket = await _repository.UpdateBasketAsync(value);
return Ok(basket);
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(string id)
{
_repository.DeleteBasketAsync(id);
}
}
}
| mit | C# |
dbd0869eb299464ab9e07aacc997f2bbca8ca26b | Fix repeat submenu disappearing | babycaseny/banshee,arfbtwn/banshee,petejohanson/banshee,allquixotic/banshee-gst-sharp-work,directhex/banshee-hacks,Dynalon/banshee-osx,Carbenium/banshee,lamalex/Banshee,arfbtwn/banshee,arfbtwn/banshee,Carbenium/banshee,GNOME/banshee,dufoli/banshee,Dynalon/banshee-osx,Carbenium/banshee,dufoli/banshee,ixfalia/banshee,Carbenium/banshee,GNOME/banshee,babycaseny/banshee,babycaseny/banshee,directhex/banshee-hacks,stsundermann/banshee,mono-soc-2011/banshee,arfbtwn/banshee,stsundermann/banshee,mono-soc-2011/banshee,Dynalon/banshee-osx,ixfalia/banshee,arfbtwn/banshee,Dynalon/banshee-osx,arfbtwn/banshee,petejohanson/banshee,petejohanson/banshee,lamalex/Banshee,dufoli/banshee,babycaseny/banshee,stsundermann/banshee,GNOME/banshee,ixfalia/banshee,stsundermann/banshee,directhex/banshee-hacks,Carbenium/banshee,petejohanson/banshee,Carbenium/banshee,allquixotic/banshee-gst-sharp-work,GNOME/banshee,mono-soc-2011/banshee,mono-soc-2011/banshee,allquixotic/banshee-gst-sharp-work,petejohanson/banshee,ixfalia/banshee,Dynalon/banshee-osx,stsundermann/banshee,lamalex/Banshee,babycaseny/banshee,arfbtwn/banshee,dufoli/banshee,directhex/banshee-hacks,lamalex/Banshee,dufoli/banshee,GNOME/banshee,arfbtwn/banshee,petejohanson/banshee,ixfalia/banshee,GNOME/banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,GNOME/banshee,allquixotic/banshee-gst-sharp-work,dufoli/banshee,stsundermann/banshee,babycaseny/banshee,mono-soc-2011/banshee,babycaseny/banshee,dufoli/banshee,GNOME/banshee,stsundermann/banshee,allquixotic/banshee-gst-sharp-work,babycaseny/banshee,stsundermann/banshee,ixfalia/banshee,Dynalon/banshee-osx,ixfalia/banshee,lamalex/Banshee,directhex/banshee-hacks,mono-soc-2011/banshee,Dynalon/banshee-osx,mono-soc-2011/banshee,lamalex/Banshee,directhex/banshee-hacks,Dynalon/banshee-osx,ixfalia/banshee | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/NextButton.cs | src/Core/Banshee.ThickClient/Banshee.Gui.Widgets/NextButton.cs | //
// NextButton.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Gui;
using Hyena.Widgets;
namespace Banshee.Gui.Widgets
{
public class NextButton : MenuButton
{
PlaybackShuffleActions shuffle_actions;
Widget button;
bool with_repeat_actions;
public NextButton (InterfaceActionService actionService) : this (actionService, false)
{
}
public NextButton (InterfaceActionService actionService, bool withRepeatActions)
{
with_repeat_actions = withRepeatActions;
shuffle_actions = actionService.PlaybackActions.ShuffleActions;
button = actionService.PlaybackActions["NextAction"].CreateToolItem ();
var menu = shuffle_actions.CreateMenu (with_repeat_actions);
Construct (button, menu, true);
TooltipText = actionService.PlaybackActions["NextAction"].Tooltip;
shuffle_actions.Changed += OnActionsChanged;
}
private void OnActionsChanged (object o, EventArgs args)
{
if (!shuffle_actions.Sensitive) {
Menu.Deactivate ();
}
Menu = shuffle_actions.CreateMenu (with_repeat_actions);
ToggleButton.Sensitive = shuffle_actions.Sensitive;
if (Arrow != null) {
Arrow.Sensitive = shuffle_actions.Sensitive;
}
}
}
}
| //
// NextButton.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Banshee.Gui;
using Hyena.Widgets;
namespace Banshee.Gui.Widgets
{
public class NextButton : MenuButton
{
PlaybackShuffleActions shuffle_actions;
Widget button;
public NextButton (InterfaceActionService actionService) : this (actionService, false)
{
}
public NextButton (InterfaceActionService actionService, bool withRepeatActions)
{
shuffle_actions = actionService.PlaybackActions.ShuffleActions;
button = actionService.PlaybackActions["NextAction"].CreateToolItem ();
var menu = shuffle_actions.CreateMenu (withRepeatActions);
Construct (button, menu, true);
TooltipText = actionService.PlaybackActions["NextAction"].Tooltip;
shuffle_actions.Changed += OnActionsChanged;
}
private void OnActionsChanged (object o, EventArgs args)
{
if (!shuffle_actions.Sensitive) {
Menu.Deactivate ();
}
Menu = shuffle_actions.CreateMenu ();
ToggleButton.Sensitive = shuffle_actions.Sensitive;
if (Arrow != null) {
Arrow.Sensitive = shuffle_actions.Sensitive;
}
}
}
}
| mit | C# |
a1a8e717e93a2b2fd8ebe2aec1215cb8a9a7c23a | build version | agileharbor/shipStationAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) 2013 Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.26.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ShipStationAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) 2013 Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ShipStation webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// 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.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "1.3.25.0" ) ] | bsd-3-clause | C# |
c7b454cbbb4bafaf50037c5ed7235af7bef6104b | Remove static Create method from SpriteSubclass | hig-ag/CocosSharp,mono/CocosSharp,mono/CocosSharp,netonjm/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,MSylvia/CocosSharp,netonjm/CocosSharp,hig-ag/CocosSharp,haithemaraissia/CocosSharp | tests/tests/classes/tests/SpriteTest/SpriteSubclass.cs | tests/tests/classes/tests/SpriteTest/SpriteSubclass.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
internal class MySprite1 : CCSprite
{
private void InitSprite()
{
ivar = 10;
}
public MySprite1(CCSpriteFrame frame): base(frame)
{
InitSprite();
}
public static MySprite1 Create(string pszSpriteFrameName)
{
CCSpriteFrame pFrame = CCApplication.SharedApplication.SpriteFrameCache[pszSpriteFrameName];
MySprite1 pobSprite = new MySprite1(pFrame);
return pobSprite;
}
private int ivar;
}
internal class MySprite2 : CCSprite
{
private void InitSprite()
{
ivar = 10;
}
public MySprite2(string fileName): base(fileName)
{
InitSprite();
}
private int ivar;
}
public class SpriteSubclass : SpriteTestDemo
{
public SpriteSubclass()
{
CCSize s = CCApplication.SharedApplication.MainWindowDirector.WindowSizeInPoints;
CCApplication.SharedApplication.SpriteFrameCache.AddSpriteFrames("animations/ghosts.plist");
CCSpriteBatchNode aParent = new CCSpriteBatchNode("animations/ghosts");
// MySprite1
MySprite1 sprite = MySprite1.Create("father.gif");
sprite.Position = (new CCPoint(s.Width / 4 * 1, s.Height / 2));
aParent.AddChild(sprite);
AddChild(aParent);
// MySprite2
MySprite2 sprite2 = new MySprite2("Images/grossini");
AddChild(sprite2);
sprite2.Position = (new CCPoint(s.Width / 4 * 3, s.Height / 2));
}
public override string title()
{
return "Sprite subclass";
}
public override string subtitle()
{
return "Testing initWithTexture:rect method";
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CocosSharp;
namespace tests
{
internal class MySprite1 : CCSprite
{
private void InitSprite()
{
ivar = 10;
}
public MySprite1(CCSpriteFrame frame): base(frame)
{
InitSprite();
}
public static MySprite1 Create(string pszSpriteFrameName)
{
CCSpriteFrame pFrame = CCApplication.SharedApplication.SpriteFrameCache[pszSpriteFrameName];
MySprite1 pobSprite = new MySprite1(pFrame);
return pobSprite;
}
private int ivar;
}
internal class MySprite2 : CCSprite
{
private void InitSprite()
{
ivar = 10;
}
public MySprite2(string fileName): base(fileName)
{
InitSprite();
}
public new static MySprite2 Create(string pszName)
{
MySprite2 pobSprite = new MySprite2(pszName);
return pobSprite;
}
private int ivar;
}
public class SpriteSubclass : SpriteTestDemo
{
public SpriteSubclass()
{
CCSize s = CCApplication.SharedApplication.MainWindowDirector.WindowSizeInPoints;
CCApplication.SharedApplication.SpriteFrameCache.AddSpriteFrames("animations/ghosts.plist");
CCSpriteBatchNode aParent = new CCSpriteBatchNode("animations/ghosts");
// MySprite1
MySprite1 sprite = MySprite1.Create("father.gif");
sprite.Position = (new CCPoint(s.Width / 4 * 1, s.Height / 2));
aParent.AddChild(sprite);
AddChild(aParent);
// MySprite2
MySprite2 sprite2 = MySprite2.Create("Images/grossini");
AddChild(sprite2);
sprite2.Position = (new CCPoint(s.Width / 4 * 3, s.Height / 2));
}
public override string title()
{
return "Sprite subclass";
}
public override string subtitle()
{
return "Testing initWithTexture:rect method";
}
}
}
| mit | C# |
65d24c429d1c9c0b850c9a21c4478c6378794476 | fix comment typo | StephenClearyExamples/FunctionsAuth0 | src/FunctionApp/Function.cs | src/FunctionApp/Function.cs | using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
namespace FunctionApp
{
public static class Function
{
[FunctionName("Function")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "hello")]HttpRequestMessage req, TraceWriter log)
{
try
{
log.Info("C# HTTP trigger function processed a request.");
// The "user" returned here is an actual ClaimsPrincipal with the claims that were in the access_token.
// The "token" is a SecurityToken that can be used to invoke services on the part of the user. E.g., create a Google Calendar event on the user's calendar.
var (user, token) = await req.AuthenticateAsync(log);
// Dump the claims details in the user
log.Info("User authenticated");
foreach (var claim in user.Claims)
log.Info($"Claim `{claim.Type}` is `{claim.Value}`");
// Return the user details to the calling app.
var result = user.Claims.Select(c => new { type = c.Type, value = c.Value }).ToList();
return req.CreateResponse(HttpStatusCode.OK, result);
}
catch (ExpectedException ex)
{
return req.CreateErrorResponse(ex.Code, ex.Message);
}
}
}
}
| using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using System.Threading.Tasks;
namespace FunctionApp
{
public static class Function
{
[FunctionName("Function")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "hello")]HttpRequestMessage req, TraceWriter log)
{
try
{
log.Info("C# HTTP trigger function processed a request.");
// The "user" returned here is an actual ClaimsIdentity with the claims that were in the access_token.
// The "token" is a SecurityToken that can be used to invoke services on the part of the user. E.g., create a Google Calendar event on the user's calendar.
var (user, token) = await req.AuthenticateAsync(log);
// Dump the claims details in the user
log.Info("User authenticated");
foreach (var claim in user.Claims)
log.Info($"Claim `{claim.Type}` is `{claim.Value}`");
// Return the user details to the calling app.
var result = user.Claims.Select(c => new { type = c.Type, value = c.Value }).ToList();
return req.CreateResponse(HttpStatusCode.OK, result);
}
catch (ExpectedException ex)
{
return req.CreateErrorResponse(ex.Code, ex.Message);
}
}
}
}
| mit | C# |
17b61f8e1d75ae8cfbce2d04d710c0be54be65fb | Update ValueChangedTriggerBehavior.cs | wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors | src/Avalonia.Xaml.Interactions/Custom/ValueChangedTriggerBehavior.cs | src/Avalonia.Xaml.Interactions/Custom/ValueChangedTriggerBehavior.cs | using System;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that performs actions when the bound data produces new value.
/// </summary>
public class ValueChangedTriggerBehavior : Trigger
{
static ValueChangedTriggerBehavior() => BindingProperty.Changed.Subscribe(OnValueChanged);
/// <summary>
/// Identifies the <seealso cref="Binding"/> avalonia property.
/// </summary>
public static readonly StyledProperty<object?> BindingProperty =
AvaloniaProperty.Register<ValueChangedTriggerBehavior, object?>(nameof(Binding));
/// <summary>
/// Gets or sets the bound object that the <see cref="ValueChangedTriggerBehavior"/> will listen to. This is a avalonia property.
/// </summary>
public object? Binding
{
get => GetValue(BindingProperty);
set => SetValue(BindingProperty, value);
}
private static void OnValueChanged(AvaloniaPropertyChangedEventArgs args)
{
if (args.Sender is not ValueChangedTriggerBehavior behavior || behavior.AssociatedObject is null)
{
return;
}
var binding = behavior.Binding;
if (binding is { })
{
Interaction.ExecuteActions(behavior.AssociatedObject, behavior.Actions, args);
}
}
}
| using System;
using Avalonia.Xaml.Interactivity;
namespace Avalonia.Xaml.Interactions.Custom;
/// <summary>
/// A behavior that performs actions when the bound data produces new value.
/// </summary>
public class ValueChangedTriggerBehavior : Trigger
{
static ValueChangedTriggerBehavior()
{
BindingProperty.Changed.Subscribe(e => OnValueChanged(e.Sender, e));
}
/// <summary>
/// Identifies the <seealso cref="Binding"/> avalonia property.
/// </summary>
public static readonly StyledProperty<object?> BindingProperty =
AvaloniaProperty.Register<ValueChangedTriggerBehavior, object?>(nameof(Binding));
/// <summary>
/// Gets or sets the bound object that the <see cref="ValueChangedTriggerBehavior"/> will listen to. This is a avalonia property.
/// </summary>
public object? Binding
{
get => GetValue(BindingProperty);
set => SetValue(BindingProperty, value);
}
private static void OnValueChanged(IAvaloniaObject avaloniaObject, AvaloniaPropertyChangedEventArgs args)
{
if (avaloniaObject is not ValueChangedTriggerBehavior behavior || behavior.AssociatedObject is null)
{
return;
}
var binding = behavior.Binding;
if (binding is { })
{
Interaction.ExecuteActions(behavior.AssociatedObject, behavior.Actions, args);
}
}
} | mit | C# |
dd5948863cbdcb77a05532615f9e192828d16002 | Add pub/sub test for multiple types | pardahlman/RawRabbit,northspb/RawRabbit | src/RawRabbit.IntegrationTests/SimpleUse/PublishAndSubscribeTests.cs | src/RawRabbit.IntegrationTests/SimpleUse/PublishAndSubscribeTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RawRabbit.Common;
using RawRabbit.IntegrationTests.TestMessages;
using RawRabbit.vNext;
using Xunit;
namespace RawRabbit.IntegrationTests.SimpleUse
{
public class PublishAndSubscribeTests : IntegrationTestBase
{
public override void Dispose()
{
TestChannel.QueueDelete("basicmessage");
TestChannel.ExchangeDelete("rawrabbit.integrationtests.testmessages");
base.Dispose();
}
[Fact]
public async Task Should_Be_Able_To_Subscribe_Without_Any_Additional_Config()
{
/* Setup */
var message = new BasicMessage { Prop = "Hello, world!" };
var recievedTcs = new TaskCompletionSource<BasicMessage>();
var publisher = BusClientFactory.CreateDefault();
var subscriber = BusClientFactory.CreateDefault();
subscriber.SubscribeAsync<BasicMessage>((msg, info) =>
{
recievedTcs.SetResult(msg);
return recievedTcs.Task;
});
/* Test */
publisher.PublishAsync(message);
await recievedTcs.Task;
/* Assert */
Assert.Equal(recievedTcs.Task.Result.Prop, message.Prop);
}
[Fact]
public async Task Should_Be_Able_To_Perform_Multiple_Pub_Subs()
{
/* Setup */
var subscriber = BusClientFactory.CreateDefault();
var publisher = BusClientFactory.CreateDefault();
const int numberOfCalls = 100;
var recived = 0;
var recievedTcs = new TaskCompletionSource<bool>();
subscriber.SubscribeAsync<BasicMessage>((message, context) =>
{
Interlocked.Increment(ref recived);
if (numberOfCalls == recived)
{
recievedTcs.SetResult(true);
}
return Task.FromResult(true);
});
/* Test */
var sw = Stopwatch.StartNew();
for (int i = 0; i < numberOfCalls; i++)
{
publisher.PublishAsync<BasicMessage>();
}
await recievedTcs.Task;
sw.Stop();
/* Assert */
Assert.True(true, $"Completed {numberOfCalls} in {sw.ElapsedMilliseconds} ms.");
}
[Fact]
public void Should_Be_Able_To_Perform_Subscribe_For_Multiple_Types()
{
/* Setup */
var subscriber = BusClientFactory.CreateDefault();
var publisher = BusClientFactory.CreateDefault();
var basicTcs = new TaskCompletionSource<BasicMessage>();
var simpleTcs = new TaskCompletionSource<SimpleMessage>();
subscriber.SubscribeAsync<BasicMessage>((message, context) =>
{
basicTcs.SetResult(message);
return Task.FromResult(true);
});
subscriber.SubscribeAsync<SimpleMessage>((message, context) =>
{
simpleTcs.SetResult(message);
return Task.FromResult(true);
});
/* Test */
publisher.PublishAsync<BasicMessage>();
publisher.PublishAsync<SimpleMessage >();
Task.WaitAll(basicTcs.Task, simpleTcs.Task);
/* Assert */
Assert.True(true, "Successfully recieved messages.");
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RawRabbit.Common;
using RawRabbit.IntegrationTests.TestMessages;
using RawRabbit.vNext;
using Xunit;
namespace RawRabbit.IntegrationTests.SimpleUse
{
public class PublishAndSubscribeTests : IntegrationTestBase
{
public override void Dispose()
{
TestChannel.QueueDelete("basicmessage");
TestChannel.ExchangeDelete("rawrabbit.integrationtests.testmessages");
base.Dispose();
}
[Fact]
public async Task Should_Be_Able_To_Subscribe_Without_Any_Additional_Config()
{
/* Setup */
var message = new BasicMessage { Prop = "Hello, world!" };
var recievedTcs = new TaskCompletionSource<BasicMessage>();
var publisher = BusClientFactory.CreateDefault();
var subscriber = BusClientFactory.CreateDefault();
subscriber.SubscribeAsync<BasicMessage>((msg, info) =>
{
recievedTcs.SetResult(msg);
return recievedTcs.Task;
});
/* Test */
publisher.PublishAsync(message);
await recievedTcs.Task;
/* Assert */
Assert.Equal(recievedTcs.Task.Result.Prop, message.Prop);
}
[Fact]
public async Task Should_Be_Able_To_Perform_Multiple_Pub_Subs()
{
/* Setup */
var subscriber = BusClientFactory.CreateDefault();
var publisher = BusClientFactory.CreateDefault();
const int numberOfCalls = 100;
var recived = 0;
var recievedTcs = new TaskCompletionSource<bool>();
subscriber.SubscribeAsync<BasicMessage>((message, context) =>
{
Interlocked.Increment(ref recived);
if (numberOfCalls == recived)
{
recievedTcs.SetResult(true);
}
return Task.FromResult(true);
});
/* Test */
var sw = Stopwatch.StartNew();
for (int i = 0; i < numberOfCalls; i++)
{
publisher.PublishAsync<BasicMessage>();
}
await recievedTcs.Task;
sw.Stop();
/* Assert */
Assert.True(true, $"Completed {numberOfCalls} in {sw.ElapsedMilliseconds} ms.");
}
}
}
| mit | C# |
ff6e4c927fecd6b4ff4fba236150b750e66f7cd5 | Add more img srcs to csp | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml | src/StockportWebapp/Views/stockportgov/Shared/SecurityHeaders.cshtml | @using System.Threading.Tasks
@using StockportWebapp.FeatureToggling
@inject FeatureToggles FeatureToggles
@{
var host = Context.Request.Host.Host;
}
@if (FeatureToggles.SecurityHeaders && (host.StartsWith("www") || host.StartsWith("int-") || host.StartsWith("qa-") || host.StartsWith("stage-")))
{
<meta http-equiv="Content-Security-Policy" content="default-src https:; font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; img-src 'self' images.contentful.com/ www.google-analytics.com/r/collect www.google-analytics.com/collect stats.g.doubleclick.net/r/collect s3-eu-west-1.amazonaws.com/share.typeform.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; style-src 'self' 'unsafe-inline' *.cludo.com/css/ s3-eu-west-1.amazonaws.com/share.typeform.com/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ m.addthisedge.com/live/boost/ www.google-analytics.com/analytics.js api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; object-src 'self' https://www.youtube.com http://www.youtube.com" >
} | @using System.Threading.Tasks
@using StockportWebapp.FeatureToggling
@inject FeatureToggles FeatureToggles
@{
var host = Context.Request.Host.Host;
}
@if (FeatureToggles.SecurityHeaders && (host.StartsWith("www") || host.StartsWith("int-") || host.StartsWith("qa-") || host.StartsWith("stage-")))
{
<meta http-equiv="Content-Security-Policy" content="default-src https:; font-src 'self' font.googleapis.com maxcdn.bootstrapcdn.com/font-awesome/ fonts.gstatic.com/; img-src 'self' images.contentful.com/ www.google-analytics.com/r/collect s3-eu-west-1.amazonaws.com/share.typeform.com/ s3-eu-west-1.amazonaws.com/live-iag-static-assets/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ customer.cludo.com/img/ uk1.siteimprove.com/ stockportb.logo-net.co.uk/ *.cloudfront.net/butotv/; style-src 'self' 'unsafe-inline' *.cludo.com/css/ s3-eu-west-1.amazonaws.com/share.typeform.com/ maxcdn.bootstrapcdn.com/font-awesome/ fonts.googleapis.com/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ *.cloudfront.net/butotv/; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ajax.googleapis.com/ajax/libs/jquery/ m.addthisedge.com/live/boost/ www.google-analytics.com/analytics.js api.cludo.com/scripts/ customer.cludo.com/scripts/ cdnjs.cloudflare.com/ajax/libs/cookieconsent2/ s3-eu-west-1.amazonaws.com/share.typeform.com/ js.buto.tv/video/ s7.addthis.com/js/300/addthis_widget.js m.addthis.com/live/ siteimproveanalytics.com/js/ *.logo-net.co.uk/Delivery/; connect-src 'self' https://api.cludo.com/ buto-ping-middleman.buto.tv/ m.addthis.com/live/; media-src 'self' https://www.youtube.com/ *.cloudfront.net/butotv/live/videos/; object-src 'self' https://www.youtube.com http://www.youtube.com" >
} | mit | C# |
5c6c2cd179ec4685f808d21c6fb2706aef4a4c1e | Update SharedAssemblyInfo.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Shared/SharedAssemblyInfo.cs | src/Shared/SharedAssemblyInfo.cs | using System;
using System.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("0.0.1")]
[assembly: AssemblyFileVersion("0.0.1")]
[assembly: AssemblyInformationalVersion("0.0.1")]
| using System;
using System.Reflection;
[assembly: AssemblyCompany("Wiesław Šoltés")]
[assembly: AssemblyCopyright("Copyright © Wiesław Šoltés 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: AssemblyInformationalVersion("1.0.1")]
| mit | C# |
9ae05b5b152b1c85ebb4527cece7e43d7013ee71 | Update the descriptions of the Nested Content configuration… (#7224) | leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS | src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs | src/Umbraco.Web/PropertyEditors/NestedContentConfiguration.cs | using Newtonsoft.Json;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// Represents the configuration for the nested content value editor.
/// </summary>
public class NestedContentConfiguration
{
[ConfigurationField("contentTypes", "Element Types", "views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html", Description = "Select the Element Types to use as models for the items.")]
public ContentType[] ContentTypes { get; set; }
[ConfigurationField("minItems", "Min Items", "number", Description = "Minimum number of items allowed.")]
public int? MinItems { get; set; }
[ConfigurationField("maxItems", "Max Items", "number", Description = "Maximum number of items allowed.")]
public int? MaxItems { get; set; }
[ConfigurationField("confirmDeletes", "Confirm Deletes", "boolean", Description = "Requires editor confirmation for delete actions.")]
public bool ConfirmDeletes { get; set; } = true;
[ConfigurationField("showIcons", "Show Icons", "boolean", Description = "Show the Element Type icons.")]
public bool ShowIcons { get; set; } = true;
[ConfigurationField("hideLabel", "Hide Label", "boolean", Description = "Hide the property label and let the item list span the full width of the editor window.")]
public bool HideLabel { get; set; }
public class ContentType
{
[JsonProperty("ncAlias")]
public string Alias { get; set; }
[JsonProperty("ncTabAlias")]
public string TabAlias { get; set; }
[JsonProperty("nameTemplate")]
public string Template { get; set; }
}
}
}
| using Newtonsoft.Json;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Web.PropertyEditors
{
/// <summary>
/// Represents the configuration for the nested content value editor.
/// </summary>
public class NestedContentConfiguration
{
[ConfigurationField("contentTypes", "Document types", "views/propertyeditors/nestedcontent/nestedcontent.doctypepicker.html", Description = "Select the document types to use as the item blueprints. Only \"element\" types can be used.")]
public ContentType[] ContentTypes { get; set; }
[ConfigurationField("minItems", "Min Items", "number", Description = "Set the minimum number of items allowed.")]
public int? MinItems { get; set; }
[ConfigurationField("maxItems", "Max Items", "number", Description = "Set the maximum number of items allowed.")]
public int? MaxItems { get; set; }
[ConfigurationField("confirmDeletes", "Confirm Deletes", "boolean", Description = "Set whether item deletions should require confirming.")]
public bool ConfirmDeletes { get; set; } = true;
[ConfigurationField("showIcons", "Show Icons", "boolean", Description = "Set whether to show the items doc type icon in the list.")]
public bool ShowIcons { get; set; } = true;
[ConfigurationField("hideLabel", "Hide Label", "boolean", Description = "Set whether to hide the editor label and have the list take up the full width of the editor window.")]
public bool HideLabel { get; set; }
public class ContentType
{
[JsonProperty("ncAlias")]
public string Alias { get; set; }
[JsonProperty("ncTabAlias")]
public string TabAlias { get; set; }
[JsonProperty("nameTemplate")]
public string Template { get; set; }
}
}
}
| mit | C# |
37566c67d3c40c512ad4ad49180e8a86ba69a1e7 | fix test | lvermeulen/ProGet.Net | test/ProGet.Net.Tests/Native/ProGetPackages/ProGetClientShould.cs | test/ProGet.Net.Tests/Native/ProGetPackages/ProGetClientShould.cs | using System.Threading.Tasks;
using Xunit;
// ReSharper disable CheckNamespace
namespace ProGet.Net.Tests
{
public partial class ProGetClientShould
{
[Fact]
public async Task ProGetPackages_GetPackageCountAsync()
{
var result = await _client.ProGetPackages_GetPackageCountAsync(1, true, 1000);
Assert.True(result >= 0);
}
[Fact]
public async Task ProGetPackages_GetPackagesAsync()
{
var results = await _client.ProGetPackages_GetPackagesAsync(2, null, null);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_GetPackageVersionsAsync()
{
var results = await _client.ProGetPackages_GetPackageVersionsAsync(2, null, null, null);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_GetPopularPackagesAsync()
{
var results = await _client.ProGetPackages_GetPopularPackagesAsync(2, 1000);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_SearchPackagesAsync()
{
var results = await _client.ProGetPackages_SearchPackagesAsync(2, "antlr");
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
}
}
| using System.Threading.Tasks;
using Xunit;
// ReSharper disable CheckNamespace
namespace ProGet.Net.Tests
{
public partial class ProGetClientShould
{
[Fact]
public async Task ProGetPackages_GetPackageCountAsync()
{
var result = await _client.ProGetPackages_GetPackageCountAsync(1, true, 1000);
//Assert.True(result > 0);
}
[Fact]
public async Task ProGetPackages_GetPackagesAsync()
{
var results = await _client.ProGetPackages_GetPackagesAsync(2, null, null);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_GetPackageVersionsAsync()
{
var results = await _client.ProGetPackages_GetPackageVersionsAsync(2, null, null, null);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_GetPopularPackagesAsync()
{
var results = await _client.ProGetPackages_GetPopularPackagesAsync(2, 1000);
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
[Fact]
public async Task ProGetPackages_SearchPackagesAsync()
{
var results = await _client.ProGetPackages_SearchPackagesAsync(2, "antlr");
Assert.NotNull(results);
//Assert.NotEmpty(results);
}
}
}
| mit | C# |
6de6318a7299c41882b5484b69cdf23e3c390c5c | Update DirtyFighting.cs | BosslandGmbH/BuddyWing.DefaultCombat | trunk/DefaultCombat/Routines/Advanced/Gunslinger/DirtyFighting.cs | trunk/DefaultCombat/Routines/Advanced/Gunslinger/DirtyFighting.cs | // Copyright (C) 2011-2015 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class DirtyFighting : RotationBase
{
public override string Name
{
get { return "Gunslinger Dirty Fighting"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Lucky Shots")
);
}
}
public override Composite Cooldowns
{
get
{
return new PrioritySelector(
Spell.Buff("Escape"),
Spell.Buff("Defense Screen", ret => Me.HealthPercent <= 50),
Spell.Buff("Dodge", ret => Me.HealthPercent <= 30),
Spell.Buff("Cool Head", ret => Me.EnergyPercent <= 50),
Spell.Buff("Smuggler's Luck", ret => Me.CurrentTarget.BossOrGreater()),
Spell.Buff("Illegal Mods", ret => Me.CurrentTarget.BossOrGreater())
);
}
}
public override Composite SingleTarget
{
get
{
return new PrioritySelector(
//Movement
CombatMovement.CloseDistance(Distance.Ranged),
//Low Energy
Spell.Cast("Flurry of Bolts", ret => Me.EnergyPercent < 60),
//Rotation
Spell.Cast("Distraction", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled),
Spell.DoT("Vital Shot", "Vital Shot"),
Spell.DoT("Shrap Bomb", "Shrap Bomb"),
Spell.Cast("Hemorrhaging Blast", ret => Me.CurrentTarget.HasDebuff("Vital Shot") && Me.CurrentTarget.HasDebuff("Shrap Bomb")),
Spell.Cast("Wounding Shots", ret => Me.CurrentTarget.DebuffTimeLeft("Vital Shot") > 3 && Me.CurrentTarget.DebuffTimeLeft("Shrap Bomb") > 3),
Spell.Cast("Quickdraw", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Speed Shot"),
Spell.Cast("Dirty Blast", ret => Me.Level >= 57),
Spell.Cast("Charged Burst", ret => Me.Level < 57)
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldAoe,
new PrioritySelector(
Spell.CastOnGround("XS Freighter Flyby"),
Spell.Cast("Thermal Grenade"),
Spell.Cast("Shrap Bomb", ret => Me.CurrentTarget.HasDebuff("Vital Shot") && !Me.CurrentTarget.HasDebuff("Shrap Bomb")),
Spell.CastOnGround("Sweeping Gunfire")
));
}
}
}
}
| // Copyright (C) 2011-2015 Bossland GmbH
// See the file LICENSE for the source code's detailed license
using Buddy.BehaviorTree;
using DefaultCombat.Core;
using DefaultCombat.Helpers;
namespace DefaultCombat.Routines
{
internal class DirtyFighting : RotationBase
{
public override string Name
{
get { return "Gunslinger Dirty Fighting"; }
}
public override Composite Buffs
{
get
{
return new PrioritySelector(
Spell.Buff("Lucky Shots")
);
}
}
public override Composite Cooldowns
{
get
{
return new LockSelector(
Spell.Buff("Escape"),
Spell.Buff("Defense Screen", ret => Me.HealthPercent <= 50),
Spell.Buff("Dodge", ret => Me.HealthPercent <= 30),
Spell.Buff("Cool Head", ret => Me.EnergyPercent <= 50),
Spell.Buff("Smuggler's Luck"),
Spell.Buff("Illegal Mods")
);
}
}
public override Composite SingleTarget
{
get
{
return new LockSelector(
Spell.Cast("Flurry of Bolts", ret => Me.EnergyPercent < 60),
//Movement
CombatMovement.CloseDistance(Distance.Ranged),
//Rotation
Spell.Cast("Charged Burst", ret => Me.HasBuff("Smuggler's Luck")),
Spell.Cast("Flurry of Bolts", ret => Me.EnergyPercent < 40),
Spell.DoT("Flourish Shot", "Armor Reduced"),
Spell.Cast("Sabotage Charge", ret => Me.IsInCover()),
Spell.DoT("Shrap Bomb", "Shrapbomb"),
Spell.DoT("Vital Shot", "Bleeding (Vital Shot)"),
Spell.Cast("Hemorrhaging Blast"),
Spell.Cast("Quickdraw", ret => Me.CurrentTarget.HealthPercent <= 30),
Spell.Cast("Wounding Shots"),
Spell.Cast("Crouch", ret => !Me.IsInCover()),
Spell.Cast("Speed Shot", ret => Me.IsInCover()),
Spell.Cast("Aimed Shot", ret => Me.IsInCover()),
Spell.Cast("Quick Shot", ret => !Me.IsInCover()),
Spell.Cast("Flurry of Bolts")
);
}
}
public override Composite AreaOfEffect
{
get
{
return new Decorator(ret => Targeting.ShouldAoe,
new LockSelector(
Spell.CastOnGround("XS Freighter Flyby"),
Spell.Cast("Thermal Grenade"),
Spell.DoT("Shrap Bomb", "Shrap Bomb"),
Spell.CastOnGround("Sweeping Gunfire")
));
}
}
}
} | apache-2.0 | C# |
9bb4b36a6bcbfdb40952984baa08e228815b7ad9 | Add byte symmetric algorithm encryption methods | DataGenSoftware/DataGen.Extensions | DataGen.Extensions/DataGen.Extensions/ByteExtensions.cs | DataGen.Extensions/DataGen.Extensions/ByteExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace DataGen.Extensions
{
public static class ByteExtensions
{
public static byte[] ComputeHash(this byte[] value, HashAlgorithm hashAlgorithm)
{
if (value.IsNotNull() == true)
{
return hashAlgorithm.ComputeHash(value);
}
else
return null;
}
public static bool VerifyHash(this byte[] value, byte[] hash, HashAlgorithm hashAlgorithm)
{
byte[] hashToCompare = value.ComputeHash(hashAlgorithm);
if (hash == null || hashToCompare == null)
{
return false;
}
if (hash.Length != hashToCompare.Length)
{
return false;
}
for (int i = 0; i < hash.Length; i++)
{
if (hash[i] !=hashToCompare[i])
{
return false;
}
}
return true;
}
public static byte[] MD5ComputeHash(this byte[] value)
{
return value.ComputeHash(MD5.Create());
}
public static bool MD5VerifyHash(this byte[] value, byte[] hash)
{
return value.VerifyHash(hash, MD5.Create());
}
public static string GetString(this byte[] value)
{
return System.Text.Encoding.Default.GetString(value);
}
public static byte[] SymmetricAlgorithmEncrypt(this byte[] value, SymmetricAlgorithm symmetricAlgorithm, byte[] key)
{
if (value.IsNotNull() && key.IsNotNull())
{
symmetricAlgorithm.Key = key;
ICryptoTransform CryptoTransform = symmetricAlgorithm.CreateEncryptor();
byte[] result = CryptoTransform.TransformFinalBlock(value, 0, value.Length);
symmetricAlgorithm.Clear();
return result;
}
else
return null;
}
public static byte[] SymmetricAlgorithmDecrypt(this byte[] value, SymmetricAlgorithm symmetricAlgorithm, byte[] key)
{
if (value.IsNotNull() && key.IsNotNull())
{
symmetricAlgorithm.Key = key;
ICryptoTransform CryptoTransform = symmetricAlgorithm.CreateDecryptor();
byte[] result = CryptoTransform.TransformFinalBlock(value, 0, value.Length);
symmetricAlgorithm.Clear();
return result;
}
else
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace DataGen.Extensions
{
public static class ByteExtensions
{
public static byte[] ComputeHash(this byte[] value, HashAlgorithm hashAlgorithm)
{
if (value.IsNotNull() == true)
{
return hashAlgorithm.ComputeHash(value);
}
else
return null;
}
public static bool VerifyHash(this byte[] value, byte[] hash, HashAlgorithm hashAlgorithm)
{
byte[] hashToCompare = value.ComputeHash(hashAlgorithm);
if (hash == null || hashToCompare == null)
{
return false;
}
if (hash.Length != hashToCompare.Length)
{
return false;
}
for (int i = 0; i < hash.Length; i++)
{
if (hash[i] !=hashToCompare[i])
{
return false;
}
}
return true;
}
public static byte[] MD5ComputeHash(this byte[] value)
{
return value.ComputeHash(MD5.Create());
}
public static bool MD5VerifyHash(this byte[] value, byte[] hash)
{
return value.VerifyHash(hash, MD5.Create());
}
public static string GetString(this byte[] value)
{
return System.Text.Encoding.Default.GetString(value);
}
}
}
| mit | C# |
d7e67613ba7d43e013ee5dc48ac3417182ae235d | Update DisableCompatibilityChecker.cs | asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET | Examples/CSharp/Articles/DisableCompatibilityChecker.cs | Examples/CSharp/Articles/DisableCompatibilityChecker.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class DisableCompatibilityChecker
{
public static void Main()
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Open a template file
Workbook workbook = new Workbook(dataDir+ "sample.xlsx");
//Disable the compatibility checker
workbook.Settings.CheckComptiliblity = false;
//Saving the Excel file
workbook.Save(dataDir+ "Output_BK_CompCheck.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class DisableCompatibilityChecker
{
public static void Main()
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Open a template file
Workbook workbook = new Workbook(dataDir+ "sample.xlsx");
//Disable the compatibility checker
workbook.Settings.CheckComptiliblity = false;
//Saving the Excel file
workbook.Save(dataDir+ "Output_BK_CompCheck.out.xlsx");
}
}
} | mit | C# |
8ee34381cc0bdc9a39c3792d5698f0d696c075b3 | Correct syntax error | jonstodle/MovieWatchlist | ImdbInterface/DateLocation.cs | ImdbInterface/DateLocation.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImdbInterface {
public struct DateLocation {
private readonly DateTime date;
private readonly string location;
public DateLocation(DateTime date, string location) {
this.date = date;
this.location = location;
}
public DateTime Date {
get {
return date.Date;
}
}
public string Location {
get {
return location;
}
}
public override string ToString() {
return string.Format("{0} ({1})", Date.ToString("d"), Location);
}
public static bool operator ==(DateLocation dl1, DateLocation dl2) {
return dl1.Location == dl2.Location && dl1.Date == dl2.Date;
}
public static bool operator !=(DateLocation dl1, DateLocation dl2) {
return dl1.Location != dl2.Location || dl1.Date != dl2.Date;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ImdbInterface {
public struct DateLocation {
private readonly DateTime date;
private readonly string location;
public DateLocation(DateTime date, string location) {
this.date = date;
this.location = location;
}
public DateTime Date {
get {
return date.Date;
}
}
public string Location {
get {
return location;
}
}
public override string ToString() {
return string.Format("{0] ({1})", Date.ToString("d"), Location);
}
public static bool operator ==(DateLocation dl1, DateLocation dl2) {
return dl1.Location == dl2.Location && dl1.Date == dl2.Date;
}
public static bool operator !=(DateLocation dl1, DateLocation dl2) {
return dl1.Location != dl2.Location || dl1.Date != dl2.Date;
}
}
}
| mit | C# |
e24dccc0280a15f4c7229fd484bff99cd3d74322 | Rename Quaternion to QuaternionField | laicasaane/VFW | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Quaternions.cs | Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Quaternions.cs | using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public Quaternion QuaternionField(Quaternion value)
{
return QuaternionField(string.Empty, value);
}
public Quaternion QuaternionField(string label, Quaternion value)
{
return QuaternionField(label, value, null);
}
public Quaternion QuaternionField(string label, string tooltip, Quaternion value)
{
return QuaternionField(label, tooltip, value, null);
}
public Quaternion QuaternionField(string label, Quaternion value, Layout option)
{
return QuaternionField(label, string.Empty, value, option);
}
public Quaternion QuaternionField(string label, string tooltip, Quaternion value, Layout option)
{
return QuaternionField(GetContent(label, tooltip), value, option);
}
public Quaternion QuaternionField(GUIContent content, Quaternion value, Layout option)
{
if (hasReachedMinScreenWidth &&
content != null && !string.IsNullOrEmpty(content.text))
{
using (Vertical())
{
Prefix(content);
using (Horizontal())
{
Space(15f);
INTERNAL_Quaternion(ref value);
}
}
}
else
{
using (Horizontal())
{
Prefix(content);
INTERNAL_Quaternion(ref value);
}
}
return value;
}
private void INTERNAL_Quaternion(ref Quaternion value)
{
using (LabelWidth(15f))
{
value.x = FloatField("X", value.x);
Space(2f);
value.y = FloatField("Y", value.y);
Space(2f);
value.z = FloatField("Z", value.z);
Space(2f);
value.w = FloatField("W", value.w);
}
}
}
}
| using UnityEngine;
namespace Vexe.Editor.GUIs
{
public abstract partial class BaseGUI
{
public Quaternion Quaternion(Quaternion value)
{
return Quaternion(string.Empty, value);
}
public Quaternion Quaternion(string label, Quaternion value)
{
return Quaternion(label, value, null);
}
public Quaternion Quaternion(string label, string tooltip, Quaternion value)
{
return Quaternion(label, tooltip, value, null);
}
public Quaternion Quaternion(string label, Quaternion value, Layout option)
{
return Quaternion(label, string.Empty, value, option);
}
public Quaternion Quaternion(string label, string tooltip, Quaternion value, Layout option)
{
return Quaternion(GetContent(label, tooltip), value, option);
}
public Quaternion Quaternion(GUIContent content, Quaternion value, Layout option)
{
return UnityEngine.Quaternion.Euler(Vector3(content, value.eulerAngles, option));
}
}
} | mit | C# |
49014f7e69eb873e758e96fa5c312d8e315f387c | Fix copy and past bug. | SamOatesJams/Ludumdare33,SamOatesJams/Ludumdare33 | Assets/Resources/Scripts/Server/Packet/PlayerHandshakePacket.cs | Assets/Resources/Scripts/Server/Packet/PlayerHandshakePacket.cs | using UnityEngine;
using System.Collections;
using Realms.Common.Packet;
using System;
namespace Realms.Server.Packet
{
[Serializable]
public class PlayerHandshakePacket : IPacket
{
/// <summary>
/// Is the connection to the server allowed
/// </summary>
public bool AllowConnection { get; private set; }
/// <summary>
/// If connection is refused, the reason why
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Spawn X position
/// </summary>
public float PositionX { get; private set; }
/// <summary>
/// Spawn Y position
/// </summary>
public float PositionY { get; private set; }
/// <summary>
/// Spawn Z position
/// </summary>
public float PositionZ { get; private set; }
/// <summary>
/// Class constructor
/// </summary>
/// <param name="allowConnection"></param>
/// <param name="errorMessage"></param>
public PlayerHandshakePacket(bool allowConnection, string errorMessage, Vector3 spawnPosition) : base(typeof(PlayerHandshakePacket))
{
this.AllowConnection = allowConnection;
this.ErrorMessage = errorMessage;
this.PositionX = spawnPosition.x;
this.PositionY = spawnPosition.y;
this.PositionZ = spawnPosition.z;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Vector3 GetPosition()
{
return new Vector3(this.PositionX, this.PositionY, this.PositionZ);
}
}
}
| using UnityEngine;
using System.Collections;
using Realms.Common.Packet;
using System;
namespace Realms.Server.Packet
{
[Serializable]
public class PlayerHandshakePacket : IPacket
{
/// <summary>
/// Is the connection to the server allowed
/// </summary>
public bool AllowConnection { get; private set; }
/// <summary>
/// If connection is refused, the reason why
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Spawn X position
/// </summary>
public float PositionX { get; private set; }
/// <summary>
/// Spawn Y position
/// </summary>
public float PositionY { get; private set; }
/// <summary>
/// Spawn Z position
/// </summary>
public float PositionZ { get; private set; }
/// <summary>
/// Class constructor
/// </summary>
/// <param name="allowConnection"></param>
/// <param name="errorMessage"></param>
public PlayerHandshakePacket(bool allowConnection, string errorMessage, Vector3 spawnPosition) : base(typeof(PlayerHandshakePacket))
{
this.AllowConnection = allowConnection;
this.ErrorMessage = errorMessage;
this.PositionX = spawnPosition.x;
this.PositionX = spawnPosition.y;
this.PositionX = spawnPosition.z;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Vector3 GetPosition()
{
return new Vector3(this.PositionX, this.PositionY, this.PositionZ);
}
}
}
| mit | C# |
1b0efdc567bfb0dff44ce681e9e599b45b383cf5 | update version comment | yasokada/unity-150908-udpTimeGraph | Assets/AppInfo.cs | Assets/AppInfo.cs | using UnityEngine;
using System.Collections;
/*
* v0.7 2015/09/12
* - graph date is kept as <System.DateTime, float> so that x axis scale can be changed to weekly, etc.
* v0.6 2015/09/12
* - move several functions to MyPanelUtils.cs
* v0.5 2015/09/11
* - display ymin and ymax on the left of the panel (graphScale)
* v0.4 2015/09/10
* - can handle set,yrange command
*/
namespace NS_appInfo // NS stands for NameSpace
{
public static class AppInfo
{
public const string Version = "v0.7";
public const string Name = "udpTimeGraph";
}
}
| using UnityEngine;
using System.Collections;
/* v0.6 2015/09/12
* - move several functions to MyPanelUtils.cs
* v0.5 2015/09/11
* - display ymin and ymax on the left of the panel (graphScale)
* v0.4 2015/09/10
* - can handle set,yrange command
*/
namespace NS_appInfo // NS stands for NameSpace
{
public static class AppInfo
{
public const string Version = "v0.6";
public const string Name = "udpTimeGraph";
}
}
| mit | C# |
470416db7a7f5666118119c074326a67625d19da | Update GetLines extension method | PowerShell/PSScriptAnalyzer,dlwyatt/PSScriptAnalyzer,daviwil/PSScriptAnalyzer | Engine/Extensions.cs | Engine/Extensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
return text.Split('\n').Select(line => line.TrimEnd('\r'));
}
public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta)
{
var newStartLineNumber = extent.StartLineNumber + lineDelta;
if (newStartLineNumber < 1)
{
throw new ArgumentException(
"Invalid line delta. Resulting start line number must be greather than 1.");
}
var newStartColumnNumber = extent.StartColumnNumber + columnDelta;
var newEndColumnNumber = extent.EndColumnNumber + columnDelta;
if (newStartColumnNumber < 1 || newEndColumnNumber < 1)
{
throw new ArgumentException(@"Invalid column delta.
Resulting start column and end column number must be greather than 1.");
}
return new ScriptExtent(
new ScriptPosition(
extent.File,
newStartLineNumber,
newStartColumnNumber,
extent.StartScriptPosition.Line),
new ScriptPosition(
extent.File,
extent.EndLineNumber + lineDelta,
newEndColumnNumber,
extent.EndScriptPosition.Line));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Management.Automation.Language;
namespace Microsoft.Windows.PowerShell.ScriptAnalyzer.Extensions
{
// TODO Add documentation
public static class Extensions
{
public static IEnumerable<string> GetLines(this string text)
{
var lines = new List<string>();
using (var stringReader = new StringReader(text))
{
string line;
line = stringReader.ReadLine();
while (line != null)
{
yield return line;
line = stringReader.ReadLine();
}
}
}
public static IScriptExtent Translate(this IScriptExtent extent, int lineDelta, int columnDelta)
{
var newStartLineNumber = extent.StartLineNumber + lineDelta;
if (newStartLineNumber < 1)
{
throw new ArgumentException(
"Invalid line delta. Resulting start line number must be greather than 1.");
}
var newStartColumnNumber = extent.StartColumnNumber + columnDelta;
var newEndColumnNumber = extent.EndColumnNumber + columnDelta;
if (newStartColumnNumber < 1 || newEndColumnNumber < 1)
{
throw new ArgumentException(@"Invalid column delta.
Resulting start column and end column number must be greather than 1.");
}
return new ScriptExtent(
new ScriptPosition(
extent.File,
newStartLineNumber,
newStartColumnNumber,
extent.StartScriptPosition.Line),
new ScriptPosition(
extent.File,
extent.EndLineNumber + lineDelta,
newEndColumnNumber,
extent.EndScriptPosition.Line));
}
}
}
| mit | C# |
2ae64e0621e48a6979a8d8a1c6eb44ecf3994e6b | Add test for #54 | awesome-inc/FontAwesome.Sharp,awesome-inc/FontAwesome.Sharp | FontAwesome.Sharp.Tests/WindowsForms/FormsIconHelper_Should.cs | FontAwesome.Sharp.Tests/WindowsForms/FormsIconHelper_Should.cs | using System.Drawing;
using System.Windows.Forms;
using FluentAssertions;
using Xunit;
namespace FontAwesome.Sharp.Tests.WindowsForms
{
// ReSharper disable once InconsistentNaming
public class FormsIconHelper_Should
{
[StaFact]
public void Generate_bitmaps_for_icon_chars()
{
foreach (var icon in IconHelper.Icons)
{
const int size = 16;
var bitmap = icon.ToBitmap(Color.Black, size);
bitmap.Should().BeOfType<Bitmap>($"an image should be generated for '{icon}'");
bitmap.Should().NotBeNull();
bitmap.Size.Width.Should().Be(size);
bitmap.Size.Height.Should().Be(size);
}
}
[StaFact]
public void Add_Icons_to_image_list()
{
const int size = 16;
var imageList = new ImageList();
imageList.AddIcon(IconChar.AccessibleIcon, Color.Black, size);
imageList.AddIcons(Color.Black, size,IconChar.AddressBook, IconChar.AirFreshener);
imageList.Images.Should().HaveCount(3);
}
[StaFact]
public void Support_Font_Styles()
{
// see issue #54
const IconChar brandIcon = IconChar.GoogleDrive;
var bitmap = brandIcon.ToBitmap(IconFont.Brands);
bitmap.Should().BeOfType<Bitmap>($"an image should be generated for '{brandIcon}'");
}
}
}
| using System.Drawing;
using System.Windows.Forms;
using FluentAssertions;
using Xunit;
namespace FontAwesome.Sharp.Tests.WindowsForms
{
// ReSharper disable once InconsistentNaming
public class FormsIconHelper_Should
{
[StaFact]
public void Generate_bitmaps_for_icon_chars()
{
foreach (var icon in IconHelper.Icons)
{
const int size = 16;
var bitmap = icon.ToBitmap(Color.Black, size);
bitmap.Should().BeOfType<Bitmap>($"an image should be generated for '{icon}'");
bitmap.Should().NotBeNull();
bitmap.Size.Width.Should().Be(size);
bitmap.Size.Height.Should().Be(size);
}
}
[StaFact]
public void Add_Icons_to_image_list()
{
const int size = 16;
var imageList = new ImageList();
imageList.AddIcon(IconChar.AccessibleIcon, Color.Black, size);
imageList.AddIcons(Color.Black, size,IconChar.AddressBook, IconChar.AirFreshener);
imageList.Images.Should().HaveCount(3);
}
}
}
| apache-2.0 | C# |
e6a916467a75cc7b9c9e19ab2eebab074c8e5728 | remove "home" link in navbar | olebg/car-mods-heaven,olebg/car-mods-heaven | CarModsHeaven/CarModsHeaven/CarModsHeaven.Web/Views/Shared/_Layout.cshtml | CarModsHeaven/CarModsHeaven/CarModsHeaven.Web/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</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("Car Mods Heaven", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Projects", "Index", "Projects")</li>
<li>@Html.ActionLink("Users", "Index", "Users")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Car Mods Heaven Inc</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</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("Car Mods Heaven", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>@Html.ActionLink("Home", "Index", "Home")</li>
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
<li>@Html.ActionLink("Projects", "Index", "Projects")</li>
<li>@Html.ActionLink("Users", "Index", "Users")</li>
</ul>
@Html.Partial("_LoginPartial")
</div>
</div>
</div>
<div class="container body-content">
@RenderBody()
<hr />
<footer>
<p>© @DateTime.Now.Year - Car Mods Heaven Inc</p>
</footer>
</div>
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)
</body>
</html>
| mit | C# |
04ab600427f7523d3348a093a07a8bd392273967 | Fix HomepageFactoryTests | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | test/StockportWebappTests/Unit/ContentFactory/HomepageFactoryTest.cs | test/StockportWebappTests/Unit/ContentFactory/HomepageFactoryTest.cs | using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Moq;
using StockportWebapp.ContentFactory;
using StockportWebapp.Models;
using StockportWebapp.Utils;
using Xunit;
namespace StockportWebappTests_Unit.Unit.ContentFactory
{
public class HomepageFactoryTest
{
private readonly Mock<MarkdownWrapper> _markdownWrapperMock = new Mock<MarkdownWrapper>();
private readonly HomepageFactory _homepageFactory;
public HomepageFactoryTest()
{
_homepageFactory = new HomepageFactory(_markdownWrapperMock.Object);
}
[Fact]
public void ItBuildsAHomepageWithProcessedBody()
{
var freeText = "free text";
_markdownWrapperMock.Setup(o => o.ConvertToHtml(freeText)).Returns(freeText);
var backgroundImage = "background image";
var homepage = new Homepage(Enumerable.Empty<string>(), string.Empty, string.Empty, new List<SubItem>(), new List<SubItem>(), new List<Alert>(), new List<CarouselContent>(), backgroundImage, freeText, null, string.Empty, string.Empty);
var result = _homepageFactory.Build(homepage);
result.FreeText.Should().Be(freeText);
result.BackgroundImage.Should().Be(backgroundImage);
_markdownWrapperMock.Verify(o => o.ConvertToHtml(freeText), Times.Once);
}
}
} | using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using Moq;
using StockportWebapp.ContentFactory;
using StockportWebapp.Models;
using StockportWebapp.Utils;
using Xunit;
namespace StockportWebappTests_Unit.Unit.ContentFactory
{
public class HomepageFactoryTest
{
private readonly Mock<MarkdownWrapper> _markdownWrapperMock = new Mock<MarkdownWrapper>();
private readonly HomepageFactory _homepageFactory;
public HomepageFactoryTest()
{
_homepageFactory = new HomepageFactory(_markdownWrapperMock.Object);
}
[Fact]
public void ItBuildsAHomepageWithProcessedBody()
{
var freeText = "free text";
_markdownWrapperMock.Setup(o => o.ConvertToHtml(freeText)).Returns(freeText);
var backgroundImage = "background image";
var homepage = new Homepage(Enumerable.Empty<string>(), string.Empty, string.Empty, new List<SubItem>(), new List<SubItem>(), new List<Alert>(), new List<CarouselContent>(), backgroundImage, freeText, null, string.Empty);
var result = _homepageFactory.Build(homepage);
result.FreeText.Should().Be(freeText);
result.BackgroundImage.Should().Be(backgroundImage);
_markdownWrapperMock.Verify(o => o.ConvertToHtml(freeText), Times.Once);
}
}
} | mit | C# |
954cdcb1dd4454bae4d3c69603a52e9ec83cb0b6 | Tweak for performance | phatboyg/MassTransit,MassTransit/MassTransit,MassTransit/MassTransit,SanSYS/MassTransit,phatboyg/MassTransit,jacobpovar/MassTransit,SanSYS/MassTransit,jacobpovar/MassTransit | src/MassTransit/Serialization/JsonConverters/ListJsonConverter.cs | src/MassTransit/Serialization/JsonConverters/ListJsonConverter.cs | // Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Serialization.JsonConverters
{
using System;
using System.Collections;
using System.Collections.Generic;
using Internals.Extensions;
using Newtonsoft.Json;
public class ListJsonConverter :
JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException("This converter should not be used for writing as it can create loops");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (objectType.IsArray)
{
Type elementType = objectType.GetElementType();
return ListConverterCache.GetList(elementType, reader, serializer, true);
}
else
{
Type elementType = objectType.GetGenericArguments()[0];
return ListConverterCache.GetList(elementType, reader, serializer, false);
}
}
public override bool CanConvert(Type objectType)
{
if (objectType.IsGenericType
&& (objectType.GetGenericTypeDefinition() == typeof(IList<>) || objectType.GetGenericTypeDefinition() == typeof(List<>)))
return true;
if (objectType.IsArray)
{
if (objectType.HasElementType && objectType.GetElementType() == typeof(byte))
return false;
return objectType.HasInterface<IEnumerable>();
}
return false;
}
}
} | // Copyright 2007-2014 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.Serialization.JsonConverters
{
using System;
using System.Collections;
using System.Collections.Generic;
using Internals.Extensions;
using Newtonsoft.Json;
public class ListJsonConverter :
JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotSupportedException("This converter should not be used for writing as it can create loops");
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue,
JsonSerializer serializer)
{
if (objectType.IsArray)
{
Type elementType = objectType.GetElementType();
return ListConverterCache.GetList(elementType, reader, serializer, true);
}
else
{
Type elementType = objectType.GetGenericArguments()[0];
return ListConverterCache.GetList(elementType, reader, serializer, false);
}
}
public override bool CanConvert(Type objectType)
{
return IsList(objectType) || IsArray(objectType);
}
static bool IsArray(Type objectType)
{
// leave byte arrays alone, okay?
if (objectType.IsArray && objectType.HasElementType && objectType.GetElementType() == typeof(byte))
return false;
return (objectType.IsArray && objectType.HasInterface<IEnumerable>());
}
static bool IsList(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(IList<>)
|| objectType.GetGenericTypeDefinition() == typeof(List<>));
}
}
} | apache-2.0 | C# |
4a0c0440e0e28921c0235530b4de4bed51ac0925 | Fix CanWriteByteArrayPropertyFromBinary | samus/mongodb-csharp,zh-huan/mongodb,mongodb-csharp/mongodb-csharp | source/MongoDB/Configuration/Mapping/Util/ValueConverter.cs | source/MongoDB/Configuration/Mapping/Util/ValueConverter.cs | using System;
namespace MongoDB.Configuration.Mapping.Util
{
internal static class ValueConverter
{
public static object Convert(object value, Type type)
{
var valueType = value != null ? value.GetType() : typeof(object);
if(value==null)
return null;
if(valueType != type)
try
{
var code = System.Convert.GetTypeCode(value);
if(type.IsEnum)
value = Enum.ToObject(type, value);
else if(type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
value = System.Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
else if(code != TypeCode.Object)
value = System.Convert.ChangeType(value, type);
else if(valueType==typeof(Binary)&&type==typeof(byte[]))
value = (byte[])(Binary)value;
}
catch(FormatException exception)
{
throw new MongoException("Can not convert value from " + valueType + " to " + type, exception);
}
catch(ArgumentException exception)
{
throw new MongoException("Can not convert value from " + valueType + " to " + type, exception);
}
return value;
}
public static Array ConvertArray(object[] elements, Type type)
{
var array = Array.CreateInstance(type, elements.Length);
for(var i = 0; i < elements.Length; i++)
array.SetValue(Convert(elements[i], type), i);
return array;
}
}
} | using System;
namespace MongoDB.Configuration.Mapping.Util
{
internal static class ValueConverter
{
public static object Convert(object value, Type type)
{
var valueType = value != null ? value.GetType() : typeof(object);
if(valueType != type)
try
{
var code = System.Convert.GetTypeCode(value);
if(type.IsEnum)
value = Enum.ToObject(type, value);
else if(type.IsGenericType &&
type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if(value != null)
value = System.Convert.ChangeType(value, Nullable.GetUnderlyingType(type));
}
else if(code != TypeCode.Object)
value = System.Convert.ChangeType(value, type);
}
catch(FormatException exception)
{
throw new MongoException("Can not convert value from " + valueType + " to " + type, exception);
}
catch(ArgumentException exception)
{
throw new MongoException("Can not convert value from " + valueType + " to " + type, exception);
}
return value;
}
public static Array ConvertArray(object[] elements, Type type)
{
var array = Array.CreateInstance(type, elements.Length);
for(var i = 0; i < elements.Length; i++)
array.SetValue(Convert(elements[i], type), i);
return array;
}
}
} | apache-2.0 | C# |
5a4886e7bbc8a15b1a76a21d654f2f5f14a0ba3c | fix `forceRTL` method (#988) | lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows,lbochenek/react-native-windows | ReactWindows/ReactNative.Shared/Modules/I18N/I18NModule.cs | ReactWindows/ReactNative.Shared/Modules/I18N/I18NModule.cs | using ReactNative.Bridge;
using System.Collections.Generic;
using System.Globalization;
namespace ReactNative.Modules.I18N
{
/// <summary>
/// A module that allows JS to get/set right to left preferences.
/// </summary>
class I18NModule : NativeModuleBase
{
private const string ModuleName = "I18nManager";
private const string IsRtl = "isRTL";
private const string LocalIdentifier = "localeIdentifier";
/// <summary>
/// Gets the module name.
/// </summary>
public override string Name
{
get
{
return ModuleName;
}
}
/// <summary>
/// The constants exported by this module.
/// </summary>
public override IReadOnlyDictionary<string, object> Constants
{
get
{
return new Dictionary<string, object>
{
{ IsRtl, I18NUtil.IsRightToLeft },
{ LocalIdentifier, CultureInfo.CurrentCulture.Name }
};
}
}
/// <summary>
/// Sets whether to allow right to left.
/// </summary>
/// <param name="value">true to allow right to left; else false.</param>
[ReactMethod]
public void allowRTL(bool value)
{
I18NUtil.IsRightToLeftAllowed = value;
}
/// <summary>
/// Sets whether to force right to left. This is used for development purposes to force a language such as English to be RTL.
/// </summary>
/// <param name="value">true to force right to left; else false.</param>
[ReactMethod]
public void forceRTL(bool value)
{
I18NUtil.IsRightToLeftForced = value;
}
}
}
| using ReactNative.Bridge;
using System.Collections.Generic;
using System.Globalization;
namespace ReactNative.Modules.I18N
{
/// <summary>
/// A module that allows JS to get/set right to left preferences.
/// </summary>
class I18NModule : NativeModuleBase
{
private const string ModuleName = "I18nManager";
private const string IsRtl = "isRTL";
private const string LocalIdentifier = "localeIdentifier";
/// <summary>
/// Gets the module name.
/// </summary>
public override string Name
{
get
{
return ModuleName;
}
}
/// <summary>
/// The constants exported by this module.
/// </summary>
public override IReadOnlyDictionary<string, object> Constants
{
get
{
return new Dictionary<string, object>
{
{ IsRtl, I18NUtil.IsRightToLeft },
{ LocalIdentifier, CultureInfo.CurrentCulture.Name }
};
}
}
/// <summary>
/// Sets whether to allow right to left.
/// </summary>
/// <param name="value">true to allow right to left; else false.</param>
[ReactMethod]
public void allowRTL(bool value)
{
I18NUtil.IsRightToLeftAllowed = value;
}
/// <summary>
/// Sets whether to force right to left. This is used for development purposes to force a language such as English to be RTL.
/// </summary>
/// <param name="value">true to force right to left; else false.</param>
[ReactMethod]
public void forceRTL(bool value)
{
I18NUtil.IsRightToLeftForced = true;
}
}
}
| mit | C# |
6ae8e1d0c35a921a987aeb3e19fdff454a8a40a6 | Use F.Tap inside F.ForEach | farity/farity | Farity/ForEach.cs | Farity/ForEach.cs | using System;
using System.Collections.Generic;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Iterates over an input enumerable, calling a provided function for each element in the enumerable.
/// Functions that don't mutate the items in the source are recommended.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="function">The function to be called for each element.</param>
/// <param name="source">The source of items.</param>
/// <returns>The items in the source.</returns>
/// <remarks>Category: List</remarks>
public static IEnumerable<T> ForEach<T>(Action<T> function, IEnumerable<T> source)
{
var tap = Partial<Action<T>, T, T>(Tap, function);
foreach (var item in source) yield return tap(item);
}
}
} | using System;
using System.Collections.Generic;
namespace Farity
{
public static partial class F
{
/// <summary>
/// Iterates over an input enumerable, calling a provided function for each element in the enumerable.
/// Functions that don't mutate the items in the source are recommended.
/// </summary>
/// <typeparam name="T">The type of elements in the enumerable.</typeparam>
/// <param name="function">The function to be called for each element.</param>
/// <param name="source">The source of items.</param>
/// <returns>The items in the source.</returns>
/// <remarks>Category: List</remarks>
public static IEnumerable<T> ForEach<T>(Action<T> function, IEnumerable<T> source)
{
foreach (var item in source)
{
function(item);
yield return item;
}
}
}
} | mit | C# |
8e2ea5f7da5a87c2657632a7ecf845976ad66721 | throw for no field scannedTypes on EndpointConfiguration | NServiceBusSqlPersistence/NServiceBus.SqlPersistence | src/AcceptanceTestHelper/EndpointConfigurationExtensions.cs | src/AcceptanceTestHelper/EndpointConfigurationExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NServiceBus;
using NServiceBus.Configuration.AdvancedExtensibility;
public static class EndpointConfigurationExtensions
{
public static List<Type> ScannedTypes(this EndpointConfiguration configuration)
{
var field = typeof(EndpointConfiguration)
.GetField("scannedTypes", BindingFlags.Instance | BindingFlags.NonPublic);
if (field == null)
{
throw new Exception("Could not extract field 'scannedTypes' from EndpointConfiguration.");
}
return (List<Type>)field.GetValue(configuration);
}
public static bool IsSendOnly(this EndpointConfiguration configuration)
{
return configuration.GetSettings().Get<bool>("Endpoint.SendOnly");
}
public static IEnumerable<Type> GetScannedSagaTypes(this EndpointConfiguration configuration)
{
return configuration.ScannedTypes()
.Where(type => !type.IsAbstract && typeof(Saga).IsAssignableFrom(type));
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NServiceBus;
using NServiceBus.Configuration.AdvancedExtensibility;
public static class EndpointConfigurationExtensions
{
public static List<Type> ScannedTypes(this EndpointConfiguration configuration)
{
var field = typeof(EndpointConfiguration)
.GetField("scannedTypes", BindingFlags.Instance | BindingFlags.NonPublic);
return (List<Type>)field.GetValue(configuration);
}
public static bool IsSendOnly(this EndpointConfiguration configuration)
{
return configuration.GetSettings().Get<bool>("Endpoint.SendOnly");
}
public static IEnumerable<Type> GetScannedSagaTypes(this EndpointConfiguration configuration)
{
return configuration.ScannedTypes()
.Where(type => !type.IsAbstract && typeof(Saga).IsAssignableFrom(type));
}
} | mit | C# |
51d19f4e9d120924bfa2fbe65c8607799a1a5e5b | Update NetworkConnectivityService.cs | tiksn/TIKSN-Framework | TIKSN.Framework.Core/Network/NetworkConnectivityService.cs | TIKSN.Framework.Core/Network/NetworkConnectivityService.cs | using System.Net.NetworkInformation;
using System.Reactive.Linq;
namespace TIKSN.Network
{
public class NetworkConnectivityService : NetworkConnectivityServiceBase
{
public NetworkConnectivityService() =>
this.internetConnectivityStateInternal =
Observable.FromEvent<NetworkAvailabilityChangedEventHandler, InternetConnectivityState>(
h => (s, e) => this.GetInternetConnectivityStateInternal(),
h => NetworkChange.NetworkAvailabilityChanged += h,
h => NetworkChange.NetworkAvailabilityChanged -= h);
protected override InternetConnectivityState GetInternetConnectivityStateInternal()
{
var isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var isWiFiAvailable = false;
var isCellularNetworkAvailable = false;
foreach (var networkInterface in allNetworkInterfaces)
{
switch (networkInterface.NetworkInterfaceType)
{
case NetworkInterfaceType.Wireless80211:
isWiFiAvailable = true;
break;
case NetworkInterfaceType.Wman:
case NetworkInterfaceType.Wwanpp:
case NetworkInterfaceType.Wwanpp2:
isCellularNetworkAvailable = true;
break;
}
switch (networkInterface.OperationalStatus)
{
case OperationalStatus.Up:
break;
default:
isWiFiAvailable = false;
isCellularNetworkAvailable = false;
break;
}
}
return new InternetConnectivityState(isNetworkAvailable, isWiFiAvailable, isCellularNetworkAvailable);
}
}
}
| using System.Net.NetworkInformation;
using System.Reactive.Linq;
namespace TIKSN.Network
{
public class NetworkConnectivityService : NetworkConnectivityServiceBase
{
public NetworkConnectivityService() : base()
{
internetConnectivityStateInternal = Observable.FromEvent<NetworkAvailabilityChangedEventHandler, InternetConnectivityState>(
h => (s, e) => GetInternetConnectivityStateInternal(),
h => NetworkChange.NetworkAvailabilityChanged += h,
h => NetworkChange.NetworkAvailabilityChanged -= h);
}
protected override InternetConnectivityState GetInternetConnectivityStateInternal()
{
var isNetworkAvailable = NetworkInterface.GetIsNetworkAvailable();
var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
var isWiFiAvailable = false;
var isCellularNetworkAvailable = false;
foreach (var networkInterface in allNetworkInterfaces)
{
switch (networkInterface.NetworkInterfaceType)
{
case NetworkInterfaceType.Wireless80211:
isWiFiAvailable = true;
break;
case NetworkInterfaceType.Wman:
case NetworkInterfaceType.Wwanpp:
case NetworkInterfaceType.Wwanpp2:
isCellularNetworkAvailable = true;
break;
}
switch (networkInterface.OperationalStatus)
{
case OperationalStatus.Up:
break;
default:
isWiFiAvailable = false;
isCellularNetworkAvailable = false;
break;
}
}
return new InternetConnectivityState(isNetworkAvailable, isWiFiAvailable, isCellularNetworkAvailable);
}
}
} | mit | C# |
35f26a15ee1007c61e0c06c299c6da5a4c510d27 | Bump version to 1.1 | kevinkuszyk/FluentAssertions.Ioc.Ninject,kevinkuszyk/FluentAssertions.Ioc.Ninject | src/FluentAssertions.Ioc.Ninject/Properties/AssemblyInfo.cs | src/FluentAssertions.Ioc.Ninject/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("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Kuszyk")]
[assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyCopyright("Copyright © Kevin Kuszyk 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("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")]
// 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.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Kevin Kuszyk")]
[assembly: AssemblyProduct("FluentAssertions.Ioc.Ninject")]
[assembly: AssemblyCopyright("Copyright © Kevin Kuszyk 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("eb2c95ef-fc68-4d39-9c44-483e9a476c2a")]
// 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")]
| apache-2.0 | C# |
439f03e3b3d78dbdbc8ba3d6db559c13043f1e86 | Fix failing test due to missing dependency | peppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu | osu.Game.Tests/Visual/Editing/TestSceneEditorSummaryTimeline.cs | osu.Game.Tests/Visual/Editing/TestSceneEditorSummaryTimeline.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu;
using osu.Game.Rulesets.Osu.Beatmaps;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[Cached(typeof(EditorBeatmap))]
private readonly EditorBeatmap editorBeatmap = new EditorBeatmap(new OsuBeatmap());
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Rulesets.Osu;
using osu.Game.Screens.Edit.Components.Timelines.Summary;
using osuTK;
namespace osu.Game.Tests.Visual.Editing
{
[TestFixture]
public class TestSceneEditorSummaryTimeline : EditorClockTestScene
{
[BackgroundDependencyLoader]
private void load()
{
Beatmap.Value = CreateWorkingBeatmap(new OsuRuleset().RulesetInfo);
Add(new SummaryTimeline
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(500, 50)
});
}
}
}
| mit | C# |
b1a13a02dc8f0c6074befd26d09e210887c647f6 | Return SubTotal as string | idoban/FinBotApp,idoban/FinBotApp | FinBot/Engine/ExpenseByCategoryAdapter.cs | FinBot/Engine/ExpenseByCategoryAdapter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using Syn.Bot.Siml;
using FinBot.Expenses;
using System.Xml.Linq;
namespace FinBot.Engine
{
public class ExpenseByCategoryAdapter : BaseAdapter
{
private IExpenseService ExpenseService { get; }
public ExpenseByCategoryAdapter(IExpenseService expenseService)
{
ExpenseService = expenseService;
}
public override string Evaluate(Context context)
{
var categoryValue = context.Element.Nodes().OfType<XText>().First().Value;
var category = ExpenseService.Text2Category(categoryValue);
return ExpenseService.GenerateReport(category, Period.Monthly).Subtotal.ToString();
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using Syn.Bot.Siml;
using FinBot.Expenses;
using System.Xml.Linq;
namespace FinBot.Engine
{
public class ExpenseByCategoryAdapter : BaseAdapter
{
private IExpenseService ExpenseService { get; }
public ExpenseByCategoryAdapter(IExpenseService expenseService)
{
ExpenseService = expenseService;
}
public override string Evaluate(Context context)
{
var categoryValue = context.Element.Nodes().OfType<XText>().First().Value;
var category = ExpenseService.Text2Category(categoryValue);
return ExpenseService.GenerateReport(category, Period.Monthly).ToString();
}
}
} | mit | C# |
434e5faf3d11b73464f3ea7a771b06b6c7ad7ddb | Fix the bug | skolima/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper | NuKeeper/Engine/CommitReport.cs | NuKeeper/Engine/CommitReport.cs | using System.Collections.Generic;
using System.Linq;
using System.Text;
using NuKeeper.NuGet.Api;
namespace NuKeeper.Engine
{
public static class CommitReport
{
public static string MakeCommitMessage(List<PackageUpdate> updates)
{
return $"Automatic update of {updates[0].PackageId} to {updates[0].NewVersion}";
}
public static string MakeCommitDetails(List<PackageUpdate> updates)
{
var oldVersions = updates
.Select(u => CodeQuote(u.OldVersion.ToString()))
.Distinct()
.ToList();
var oldVersionsString = string.Join(",", oldVersions);
var newVersion = CodeQuote(updates[0].NewVersion.ToString());
var packageId = CodeQuote(updates[0].PackageId);
var builder = new StringBuilder();
var headline = $"NuKeeper has generated an update of {packageId} from {oldVersionsString} to {newVersion}";
builder.AppendLine(headline);
if (oldVersions.Count > 1)
{
builder.AppendLine($"{oldVersions.Count} versions were found in use: {oldVersionsString}");
}
if (updates.Count == 1)
{
builder.AppendLine("1 project update:");
}
else
{
builder.AppendLine($"{updates.Count} project updates:");
}
foreach (var update in updates)
{
var line = $"Updated {CodeQuote(update.CurrentPackage.Path.RelativePath)} to {packageId} {CodeQuote(update.NewVersion.ToString())} from {CodeQuote(update.OldVersion.ToString())}";
builder.AppendLine(line);
}
builder.AppendLine("This is an automated update. Merge only if it passes tests");
builder.AppendLine("");
builder.AppendLine("**NuKeeper**: https://github.com/NuKeeperDotNet/NuKeeper");
return builder.ToString();
}
private static string CodeQuote(string value)
{
return "`" + value + "`";
}
}
}
| using System.Collections.Generic;
using System.Linq;
using System.Text;
using NuKeeper.NuGet.Api;
namespace NuKeeper.Engine
{
public static class CommitReport
{
public static string MakeCommitMessage(List<PackageUpdate> updates)
{
return $"Automatic update of {updates[0].PackageId} to {updates[0].NewVersion}";
}
public static string MakeCommitDetails(List<PackageUpdate> updates)
{
var oldVersions = updates
.Select(u => CodeQuote(u.OldVersion.ToString()))
.Distinct()
.ToList();
var oldVersionsString = string.Join(",", oldVersions);
var newVersion = CodeQuote(updates[0].NewVersion.ToString());
var packageId = CodeQuote(updates[0].PackageId);
var builder = new StringBuilder();
var headline = $"NuKeeper has generated an update of {packageId} from {oldVersionsString} to {newVersion}";
builder.AppendLine(headline);
if (oldVersions.Count > 1)
{
builder.AppendLine($"{oldVersions} versions were found in use: {oldVersionsString}");
}
if (updates.Count == 1)
{
builder.AppendLine("One project update:");
}
else
{
builder.AppendLine($"{updates.Count} project updates:");
}
foreach (var update in updates)
{
var line = $"Updated {CodeQuote(update.CurrentPackage.Path.RelativePath)} to {packageId} {CodeQuote(update.NewVersion.ToString())} from {CodeQuote(update.OldVersion.ToString())}";
builder.AppendLine(line);
}
builder.AppendLine("This is an automated update. Merge only if it passes tests");
builder.AppendLine("");
builder.AppendLine("**NuKeeper**: https://github.com/NuKeeperDotNet/NuKeeper");
return builder.ToString();
}
private static string CodeQuote(string value)
{
return "`" + value + "`";
}
}
}
| apache-2.0 | C# |
405d46dc38d62c3f2e0e9b6cf7fb7ce63e4f8c44 | fix doc for Orgs API client interface | yonglehou/octokit.net,thedillonb/octokit.net,devkhan/octokit.net,editor-tools/octokit.net,shiftkey/octokit.net,brramos/octokit.net,octokit-net-test/octokit.net,shiftkey/octokit.net,khellang/octokit.net,M-Zuber/octokit.net,chunkychode/octokit.net,ivandrofly/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,forki/octokit.net,nsnnnnrn/octokit.net,ChrisMissal/octokit.net,SamTheDev/octokit.net,yonglehou/octokit.net,SmithAndr/octokit.net,hahmed/octokit.net,TattsGroup/octokit.net,adamralph/octokit.net,daukantas/octokit.net,shana/octokit.net,khellang/octokit.net,shiftkey-tester/octokit.net,fffej/octokit.net,kdolan/octokit.net,devkhan/octokit.net,octokit-net-test-org/octokit.net,SamTheDev/octokit.net,hitesh97/octokit.net,fake-organization/octokit.net,kolbasov/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,dampir/octokit.net,Sarmad93/octokit.net,Sarmad93/octokit.net,mminns/octokit.net,cH40z-Lord/octokit.net,ivandrofly/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,gabrielweyer/octokit.net,octokit/octokit.net,Red-Folder/octokit.net,darrelmiller/octokit.net,M-Zuber/octokit.net,naveensrinivasan/octokit.net,bslliw/octokit.net,shana/octokit.net,SmithAndr/octokit.net,SLdragon1989/octokit.net,alfhenrik/octokit.net,mminns/octokit.net,rlugojr/octokit.net,dampir/octokit.net,hahmed/octokit.net,octokit-net-test-org/octokit.net,chunkychode/octokit.net,eriawan/octokit.net,editor-tools/octokit.net,TattsGroup/octokit.net,octokit/octokit.net,takumikub/octokit.net,alfhenrik/octokit.net,eriawan/octokit.net,nsrnnnnn/octokit.net,gdziadkiewicz/octokit.net,dlsteuer/octokit.net,gabrielweyer/octokit.net,magoswiat/octokit.net,michaKFromParis/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,geek0r/octokit.net | Octokit/IOrganizationsClient.cs | Octokit/IOrganizationsClient.cs | #if NET_45
using System.Collections.Generic;
#endif
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
/// <summary>
/// A client for GitHub's Orgs API.
/// </summary>
/// <remarks>
/// See the <a href="http://developer.github.com/v3/orgs/">Orgs API documentation</a> for more information.
/// </remarks>
public interface IOrganizationsClient
{
/// <summary>
/// Returns the specified <see cref="Organization"/>.
/// </summary>
/// <param name="org">login of the organization to get.</param>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>The specified <see cref="Organization"/>.</returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get"
, Justification = "It's fine. Trust us.")]
Task<Organization> Get(string org);
/// <summary>
/// Returns all <see cref="Organization" />s for the current user.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A list of the current user's <see cref="Organization"/>s.</returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Method makes a network request")]
Task<IReadOnlyList<Organization>> GetAllForCurrent();
/// <summary>
/// Returns all <see cref="Organization" />s for the specified user.
/// </summary>
/// <exception cref="ApiException">Thrown when a general API error occurs.</exception>
/// <returns>A list of the specified user's <see cref="Organization"/>s.</returns>
Task<IReadOnlyList<Organization>> GetAll(string user);
}
}
| using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace Octokit
{
public interface IOrganizationsClient
{
/// <summary>
/// Returns the specified organization.
/// </summary>
/// <param name="org">The login of the specified organization,</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Get"
, Justification = "It's fine. Trust us.")]
Task<Organization> Get(string org);
/// <summary>
/// Returns all the organizations for the current user.
/// </summary>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate",
Justification = "Method makes a network request")]
Task<IReadOnlyList<Organization>> GetAllForCurrent();
/// <summary>
/// Returns all the organizations for the specified user
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
Task<IReadOnlyList<Organization>> GetAll(string user);
}
}
| mit | C# |
df52e3bfa84a312a1c1068199b9e094d294e5283 | Mark the ExtractTest as EndToEnd. | boumenot/Grobid.NET | test/Grobid.Test/GrobidTest.cs | test/Grobid.Test/GrobidTest.cs | using org.grobid.core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using System.Xml.Linq;
using org.apache.log4j;
namespace Grobid.Test
{
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
[Trait("Test", "EndToEnd")]
public void ExtractTest()
{
var factory = new GrobidFactory(
@"c:\dev\grobid.net\grobid.zip",
@"c:\dev\grobid.net\bin\pdf2xml.exe",
@"c:\temp");
var grobid = factory.Create();
var result = grobid.Extract(@"c:\dev\grobid.net\content\essence-linq.pdf");
result.Should().NotBeEmpty();
Action test = () => XDocument.Parse(result);
test.ShouldNotThrow();
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
| using org.grobid.core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FluentAssertions;
using Xunit;
using Grobid.NET;
using System.Xml.Linq;
using org.apache.log4j;
namespace Grobid.Test
{
public class GrobidTest
{
static GrobidTest()
{
BasicConfigurator.configure();
org.apache.log4j.Logger.getRootLogger().setLevel(Level.DEBUG);
}
[Fact]
public void ExtractTest()
{
var factory = new GrobidFactory(
@"c:\dev\grobid.net\grobid.zip",
@"c:\dev\grobid.net\bin\pdf2xml.exe",
@"c:\temp");
var grobid = factory.Create();
var result = grobid.Extract(@"c:\dev\grobid.net\content\essence-linq.pdf");
result.Should().NotBeEmpty();
Action test = () => XDocument.Parse(result);
test.ShouldNotThrow();
}
[Fact]
public void Test()
{
var x = GrobidModels.NAMES_HEADER;
x.name().Should().Be("NAMES_HEADER");
x.toString().Should().Be("name/header");
}
}
}
| apache-2.0 | C# |
d7c73c42651c8826d7d4e688d298f34203af7b52 | Add registration options for documentHighlight request | PowerShell/PowerShellEditorServices | src/PowerShellEditorServices.Protocol/LanguageServer/DocumentHighlight.cs | src/PowerShellEditorServices.Protocol/LanguageServer/DocumentHighlight.cs | //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public enum DocumentHighlightKind
{
Text = 1,
Read = 2,
Write = 3
}
public class DocumentHighlight
{
public Range Range { get; set; }
public DocumentHighlightKind Kind { get; set; }
}
public class DocumentHighlightRequest
{
public static readonly
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, TextDocumentRegistrationOptions> Type =
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, TextDocumentRegistrationOptions>.Create("textDocument/documentHighlight");
}
}
| //
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol;
namespace Microsoft.PowerShell.EditorServices.Protocol.LanguageServer
{
public enum DocumentHighlightKind
{
Text = 1,
Read = 2,
Write = 3
}
public class DocumentHighlight
{
public Range Range { get; set; }
public DocumentHighlightKind Kind { get; set; }
}
public class DocumentHighlightRequest
{
public static readonly
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, object> Type =
RequestType<TextDocumentPositionParams, DocumentHighlight[], object, object>.Create("textDocument/documentHighlight");
}
}
| mit | C# |
b72dc24bc047dc5706037e5f293b52e579df44de | Put obstaclenetworking setup in the right place. | Double-Fine-Game-Club/pongball | Assets/scripts/entity/SpinnerActivator.cs | Assets/scripts/entity/SpinnerActivator.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class SpinnerActivator : MonoBehaviour
{
public bool boostEnabled;
public GameObject boost;
private void Start()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
}
private void Awake()
{
GetComponent<ObstacleNetworking>().ActivateFromServer += ActivateBoost;
GetComponent<ObstacleNetworking>().DeactivateFromServer += DeactivateBoost;
}
void OnCollisionEnter(Collision col)
{
if (!NetworkManager.singleton.isNetworkActive || NetworkServer.connections.Count > 0)
{
//Host only
if (boostEnabled == false)
{
ActivateBoost();
GetComponent<ObstacleNetworking>().ActivateFromServer();
}
else if (boostEnabled == true)
{
DeactivateBoost();
GetComponent<ObstacleNetworking>().DeactivateFromServer();
}
}
}
void DeactivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
boostEnabled = false;
}
void ActivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = true;
boost.GetComponent<BoostPad>().lightEnabled();
boostEnabled = true;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpinnerActivator : MonoBehaviour
{
public bool boostEnabled;
public GameObject boost;
private void Start()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
GetComponent<ObstacleNetworking>().ActivateFromServer += ActivateBoost;
GetComponent<ObstacleNetworking>().DeactivateFromServer += DeactivateBoost;
}
void OnCollisionEnter(Collision col)
{
if (boostEnabled == true)
{
ActivateBoost();
GetComponent<ObstacleNetworking>().ActivateFromServer();
}
else if (boostEnabled == false)
{
DeactivateBoost();
GetComponent<ObstacleNetworking>().DeactivateFromServer();
}
}
void ActivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = false;
boost.GetComponent<BoostPad>().lightDisabled();
boostEnabled = false;
}
void DeactivateBoost()
{
boost.GetComponent<BoostPadForce>().boostEnabled = true;
boost.GetComponent<BoostPad>().lightEnabled();
boostEnabled = true;
}
}
| mit | C# |
21079e85a298d4106fd1c0da4e5205c4c3523175 | Disable Auto-Open behavior for Stack Trace Explorer (#59785) | bartdesmet/roslyn,bartdesmet/roslyn,dotnet/roslyn,KevinRansom/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,weltkante/roslyn,mavasani/roslyn,weltkante/roslyn,dotnet/roslyn,KevinRansom/roslyn | src/VisualStudio/Core/Def/StackTraceExplorer/StackTraceExplorerOptions.cs | src/VisualStudio/Core/Def/StackTraceExplorer/StackTraceExplorerOptions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.StackTraceExplorer
{
[ExportGlobalOptionProvider, Shared]
internal sealed class StackTraceExplorerOptionsMetadata : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StackTraceExplorerOptionsMetadata()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
OpenOnFocus);
private const string FeatureName = "StackTraceExplorerOptions";
/// <summary>
/// Used to determine if a user focusing VS should look at the clipboard for a callstack and automatically
/// open the tool window with the callstack inserted
/// </summary>
public static readonly Option2<bool> OpenOnFocus = new(FeatureName, "OpenOnFocus", defaultValue: false,
storageLocation: new RoamingProfileStorageLocation("StackTraceExplorer.Options.OpenOnFocus"));
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Options.Providers;
namespace Microsoft.CodeAnalysis.StackTraceExplorer
{
[ExportGlobalOptionProvider, Shared]
internal sealed class StackTraceExplorerOptionsMetadata : IOptionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public StackTraceExplorerOptionsMetadata()
{
}
public ImmutableArray<IOption> Options { get; } = ImmutableArray.Create<IOption>(
OpenOnFocus);
private const string FeatureName = "StackTraceExplorerOptions";
/// <summary>
/// Used to determine if a user focusing VS should look at the clipboard for a callstack and automatically
/// open the tool window with the callstack inserted
/// </summary>
public static readonly Option2<bool> OpenOnFocus = new(FeatureName, "OpenOnFocus", defaultValue: true,
storageLocation: new RoamingProfileStorageLocation("StackTraceExplorer.Options.OpenOnFocus"));
}
}
| mit | C# |
cb59b66db65f0ae7072a05d3b2822221d67b19d4 | Update Program.cs | ch0mik/SQ7MRU.Utils | SampleApp/Program.cs | SampleApp/Program.cs | using System;
using Microsoft.Extensions.Logging;
using SQ7MRU.Utils;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("SQ7MRU eQSL Downloader\n");
Console.WriteLine("Hello World!");
ILoggerFactory loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace);
Console.WriteLine("Enter Login to eqsl.cc : ");
string login = Console.ReadLine();
string password = ReadPassword("Enter Password : ");
Console.WriteLine("\nWorking...\n");
var eqsl = new Downloader(login, password, loggerFactory, null, 5, 1000, 10);
eqsl.Download(); //Download ADIFs and e-QSLs
}
static string ReadPassword(string message)
{
Console.WriteLine(message);
string password = "";
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.Escape:
return null;
case ConsoleKey.Enter:
return password;
case ConsoleKey.Backspace:
password = password.Substring(0, (password.Length - 1));
Console.Write("\b \b");
break;
default:
password += key.KeyChar;
Console.Write("*");
break;
}
}
}
}
}
| using System;
using Microsoft.Extensions.Logging;
using SQ7MRU.Utils;
namespace SampleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("SQ7MRU eQSL Downloader\n");
Console.WriteLine("Hello World!");
ILoggerFactory loggerFactory = new LoggerFactory().AddConsole(LogLevel.Trace);
Console.WriteLine("Enter Login to eqsl.cc : ");
string login = Console.ReadLine();
string password = ReadPassword("Enter Password : ");
var eqsl = new Downloader(login, password, loggerFactory, null, 5, 1000, 10);
eqsl.Download(); //Download ADIFs and e-QSLs
}
static string ReadPassword(string message)
{
Console.WriteLine(message);
string password = "";
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.Escape:
return null;
case ConsoleKey.Enter:
return password;
case ConsoleKey.Backspace:
password = password.Substring(0, (password.Length - 1));
Console.Write("\b \b");
break;
default:
password += key.KeyChar;
Console.Write("*");
break;
}
}
}
}
}
| apache-2.0 | C# |
883bf801cd672abd8a42c053668cf5859d67f577 | fix release build | madelson/DistributedLock | DistributedLock.Oracle/OracleDistributedSynchronizationProvider.cs | DistributedLock.Oracle/OracleDistributedSynchronizationProvider.cs | using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Medallion.Threading.Oracle
{
/// <summary>
/// Implements <see cref="IDistributedLockProvider"/> for <see cref="OracleDistributedLock"/>
/// and <see cref="IDistributedUpgradeableReaderWriterLockProvider"/> for <see cref="OracleDistributedReaderWriterLock"/>
/// </summary>
public sealed class OracleDistributedSynchronizationProvider : IDistributedLockProvider, IDistributedUpgradeableReaderWriterLockProvider
{
private readonly Func<string, bool, OracleDistributedLock> _lockFactory;
private readonly Func<string, bool, OracleDistributedReaderWriterLock> _readerWriterLockFactory;
/// <summary>
/// Constructs a provider that connects with <paramref name="connectionString"/> and <paramref name="options"/>.
/// </summary>
public OracleDistributedSynchronizationProvider(string connectionString, Action<OracleConnectionOptionsBuilder>? options = null)
{
if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); }
this._lockFactory = (name, exactName) => new OracleDistributedLock(name, connectionString, options, exactName);
this._readerWriterLockFactory = (name, exactName) => new OracleDistributedReaderWriterLock(name, connectionString, options, exactName);
}
/// <summary>
/// Constructs a provider that connects with <paramref name="connection"/>.
/// </summary>
public OracleDistributedSynchronizationProvider(IDbConnection connection)
{
if (connection == null) { throw new ArgumentNullException(nameof(connection)); }
this._lockFactory = (name, exactName) => new OracleDistributedLock(name, connection, exactName);
this._readerWriterLockFactory = (name, exactName) => new OracleDistributedReaderWriterLock(name, connection, exactName);
}
/// <summary>
/// Creates a <see cref="OracleDistributedLock"/> with the provided <paramref name="name"/>. Unless <paramref name="exactName"/>
/// is specified, invalid names will be escaped/hashed.
/// </summary>
public OracleDistributedLock CreateLock(string name, bool exactName = false) => this._lockFactory(name, exactName);
IDistributedLock IDistributedLockProvider.CreateLock(string name) => this.CreateLock(name);
/// <summary>
/// Creates a <see cref="OracleDistributedReaderWriterLock"/> with the provided <paramref name="name"/>. Unless <paramref name="exactName"/>
/// is specified, invalid names will be escaped/hashed.
/// </summary>
public OracleDistributedReaderWriterLock CreateReaderWriterLock(string name, bool exactName = false) => this._readerWriterLockFactory(name, exactName);
IDistributedUpgradeableReaderWriterLock IDistributedUpgradeableReaderWriterLockProvider.CreateUpgradeableReaderWriterLock(string name) =>
this.CreateReaderWriterLock(name);
IDistributedReaderWriterLock IDistributedReaderWriterLockProvider.CreateReaderWriterLock(string name) =>
this.CreateReaderWriterLock(name);
}
}
| using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Medallion.Threading.Oracle
{
/// <summary>
/// Implements <see cref="IDistributedLockProvider"/> for <see cref="OracleDistributedLock"/>
/// and <see cref="IDistributedUpgradeableReaderWriterLockProvider"/> for <see cref="OracleDistributedReaderWriterLock"/>
/// </summary>
public sealed class OracleDistributedSynchronizationProvider : IDistributedLockProvider, IDistributedUpgradeableReaderWriterLockProvider
{
private readonly Func<string, bool, OracleDistributedLock> _lockFactory;
private readonly Func<string, bool, OracleDistributedReaderWriterLock> _readerWriterLockFactory;
/// <summary>
/// Constructs a provider that connects with <paramref name="connectionString"/> and <paramref name="options"/>.
/// </summary>
public OracleDistributedSynchronizationProvider(string connectionString, Action<OracleConnectionOptionsBuilder>? options = null)
{
if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); }
this._lockFactory = (name, exactName) => new OracleDistributedLock(name, connectionString, options, exactName);
this._readerWriterLockFactory = (name, exactName) => new OracleDistributedReaderWriterLock(name, connectionString, options, exactName);
}
/// <summary>
/// Constructs a provider that connects with <paramref name="connection"/>.
/// </summary>
public OracleDistributedSynchronizationProvider(IDbConnection connection)
{
if (connection == null) { throw new ArgumentNullException(nameof(connection)); }
this._lockFactory = (name, exactName) => new OracleDistributedLock(name, connection, exactName);
this._readerWriterLockFactory = (name, exactName) => new OracleDistributedReaderWriterLock(name, connection, exactName);
}
/// <summary>
/// Creates a <see cref="OracleDistributedLock"/> with the provided <paramref name="name"/>. Unless <paramref name="exactName"/>
/// is specified, invalid names will be escaped/hashed.
/// </summary>
public OracleDistributedLock CreateLock(string name, bool exactName = false) => this._lockFactory(name, exactName);
IDistributedLock IDistributedLockProvider.CreateLock(string name) => this.CreateLock(name);
public OracleDistributedReaderWriterLock CreateReaderWriterLock(string name, bool exactName = false) => this._readerWriterLockFactory(name, exactName);
IDistributedUpgradeableReaderWriterLock IDistributedUpgradeableReaderWriterLockProvider.CreateUpgradeableReaderWriterLock(string name) =>
this.CreateReaderWriterLock(name);
IDistributedReaderWriterLock IDistributedReaderWriterLockProvider.CreateReaderWriterLock(string name) =>
this.CreateReaderWriterLock(name);
}
}
| mit | C# |
26ce61c56333f6a4d80ab04e4682d01ef955c4e2 | Redefine age field as unsigned | SICU-Stress-Measurement-System/frontend-cs | StressMeasurementSystem/Models/Patient.cs | StressMeasurementSystem/Models/Patient.cs | namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
struct PhoneNumber
{
internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}
public string Number { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private uint _age;
private Organization _organization;
private PhoneNumber _phoneNumber;
#endregion
}
} | namespace StressMeasurementSystem.Models
{
public class Patient
{
#region Structs
struct Name
{
public string Prefix { get; set; }
public string First { get; set; }
public string Middle { get; set; }
public string Last { get; set; }
public string Suffix { get; set; }
}
struct Organization
{
public string Company { get; set; }
public string JobTitle { get; set; }
}
struct PhoneNumber
{
internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other}
public string Number { get; set; }
public Type T { get; set; }
}
#endregion
#region Fields
private Name _name;
private int _age;
private Organization _organization;
private PhoneNumber _phoneNumber;
#endregion
}
} | apache-2.0 | C# |
dd93fc3bcd309b873c17f2427bd6df1b023d2ca7 | Remove some hints, function name is clear enough | insthync/unity-utilities | UnityUtilities/Scripts/Misc/UnityUtils.cs | UnityUtilities/Scripts/Misc/UnityUtils.cs | using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Detect headless mode (which has graphicsDeviceType Null)
/// </summary>
/// <returns></returns>
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Networking;
public static class UnityUtils
{
/// <summary>
/// Is any of the keys UP?
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public static bool IsAnyKeyUp(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyUp(key))
return true;
}
return false;
}
/// <summary>
/// Is any of the keys DOWN?
/// </summary>
/// <param name="keys"></param>
/// <returns></returns>
public static bool IsAnyKeyDown(KeyCode[] keys)
{
foreach (KeyCode key in keys)
{
if (Input.GetKeyDown(key))
return true;
}
return false;
}
/// <summary>
/// Detect headless mode (which has graphicsDeviceType Null)
/// </summary>
/// <returns></returns>
public static bool IsHeadless()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.Null;
}
public static bool TryGetByNetId<T>(NetworkInstanceId targetNetId, out T output) where T : Component
{
output = null;
GameObject foundObject = ClientScene.FindLocalObject(targetNetId);
if (foundObject == null)
return false;
output = foundObject.GetComponent<T>();
if (output == null)
return false;
return true;
}
}
| mit | C# |
ed2aae8e7b7144a418105a4de96bfd6525a9259e | Update SuperBlurBase.cs | PavelDoGreat/Super-Blur | SuperBlur/Core/SuperBlurBase.cs | SuperBlur/Core/SuperBlurBase.cs | using UnityEngine;
namespace SuperBlur
{
[ExecuteInEditMode]
public class SuperBlurBase : MonoBehaviour
{
protected static class Uniforms
{
public static readonly int _Radius = Shader.PropertyToID("_Radius");
public static readonly int _BackgroundTexture = Shader.PropertyToID("_SuperBlurTexture");
}
public RenderMode renderMode = RenderMode.Screen;
public BlurKernelSize kernelSize = BlurKernelSize.Small;
[Range(0f, 1f)]
public float interpolation = 1f;
[Range(0, 4)]
public int downsample = 1;
[Range(1, 8)]
public int iterations = 1;
public bool gammaCorrection = true;
public Material blurMaterial;
public Material UIMaterial;
protected void Blur (RenderTexture source, RenderTexture destination)
{
if (gammaCorrection)
{
Shader.EnableKeyword("GAMMA_CORRECTION");
}
else
{
Shader.DisableKeyword("GAMMA_CORRECTION");
}
int kernel = 0;
switch (kernelSize)
{
case BlurKernelSize.Small:
kernel = 0;
break;
case BlurKernelSize.Medium:
kernel = 2;
break;
case BlurKernelSize.Big:
kernel = 4;
break;
}
var rt2 = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
for (int i = 0; i < iterations; i++)
{
// helps to achieve a larger blur
float radius = (float)i * interpolation + interpolation;
blurMaterial.SetFloat(Uniforms._Radius, radius);
Graphics.Blit(source, rt2, blurMaterial, 1 + kernel);
source.DiscardContents();
// is it a last iteration? If so, then blit to destination
if (i == iterations - 1)
{
Graphics.Blit(rt2, destination, blurMaterial, 2 + kernel);
}
else
{
Graphics.Blit(rt2, source, blurMaterial, 2 + kernel);
rt2.DiscardContents();
}
}
RenderTexture.ReleaseTemporary(rt2);
}
}
public enum BlurKernelSize
{
Small,
Medium,
Big
}
public enum RenderMode
{
Screen,
UI,
OnlyUI
}
}
| using UnityEngine;
namespace SuperBlur
{
[ExecuteInEditMode]
public class SuperBlurBase : MonoBehaviour
{
protected static class Uniforms
{
public static readonly int _Radius = Shader.PropertyToID("_Radius");
public static readonly int _BackgroundTexture = Shader.PropertyToID("_SuperBlurTexture");
}
public RenderMode renderMode = RenderMode.Screen;
public BlurKernelSize kernelSize = BlurKernelSize.Small;
[Range(0f, 1f)]
public float interpolation = 1f;
[Range(0, 4)]
public int downsample = 1;
[Range(1, 8)]
public int iterations = 1;
public bool gammaCorrection = true;
public Material blurMaterial;
public Material UIMaterial;
protected void Blur (RenderTexture source, RenderTexture destination)
{
if (gammaCorrection)
{
Shader.EnableKeyword("GAMMA_CORRECTION");
}
else
{
Shader.DisableKeyword("GAMMA_CORRECTION");
}
int kernel = 0;
switch (kernelSize)
{
case BlurKernelSize.Small:
kernel = 0;
break;
case BlurKernelSize.Medium:
kernel = 2;
break;
case BlurKernelSize.Big:
kernel = 4;
break;
}
var rt2 = RenderTexture.GetTemporary(source.width, source.height, 0, source.format);
for (int i = 0; i < iterations; i++)
{
// helps to achieve a larger blur
float radius = (float)i * interpolation + interpolation;
blurMaterial.SetFloat(Uniforms._Radius, radius);
Graphics.Blit(source, rt2, blurMaterial, 1 + kernel);
source.DiscardContents();
// is it a last iteration? If so, then blit to destination
if (i == iterations - 1)
{
Graphics.Blit(rt2, destination, blurMaterial, 2 + kernel);
}
else
{
Graphics.Blit(rt2, source, blurMaterial, 2 + kernel);
rt2.DiscardContents();
}
}
RenderTexture.ReleaseTemporary(rt2);
}
}
public enum BlurKernelSize
{
Small,
Medium,
Big
}
public enum RenderMode
{
Screen,
UI,
OnlyUI
}
} | mit | C# |
d6bff6fe132e6d316ba72cb0357de321db20577b | set realistic version number | eeaquino/DotNetShipping,kylewest/DotNetShipping | DotNetShipping/Properties/AssemblyInfo.cs | DotNetShipping/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("DotNetShipping")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DotNetShipping")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("f0457786-3233-4b05-b385-11051d780f91")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("0.5.0.0")]
[assembly: AssemblyFileVersion("0.5.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("DotNetShipping")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DotNetShipping")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("f0457786-3233-4b05-b385-11051d780f91")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")] | mit | C# |
dfbeccbbf22e892c457d4f5b4e144c2dacf8e72c | Update WindowsForm.cs | vchelaru/FlatRedBall,vchelaru/FlatRedBall,vchelaru/FlatRedBall,vchelaru/FlatRedBall,vchelaru/FlatRedBall | FRBDK/Glue/Glue/Extensions/WindowsForm.cs | FRBDK/Glue/Glue/Extensions/WindowsForm.cs | namespace System.Windows.Forms
{
public static class WindowsFormEx
{
public static void EnsureOnScreen(this System.Windows.Forms.Form form)
{
var screen = Screen.FromControl(form).WorkingArea;
System.Drawing.Point newLocation = form.Location;
if (form.Bounds.Right > screen.Right)
newLocation.X = screen.Right - form.Width - 5;
if (form.Bounds.Bottom > screen.Bottom)
newLocation.Y = screen.Bottom - form.Height - 5;
if (form.Bounds.Left < 0)
newLocation.X = 0;
form.Location = newLocation;
}
}
}
| namespace System.Windows.Forms
{
public static class WindowsFormEx
{
public static void EnsureOnScreen(this System.Windows.Forms.Form form)
{
var screen = Screen.FromControl(form);
System.Drawing.Point newLocation = form.Location;
if (form.Bounds.Right > screen.Bounds.Right)
newLocation.X = screen.Bounds.Right - form.Width - 5;
if (form.Bounds.Bottom > screen.Bounds.Bottom)
newLocation.Y = screen.Bounds.Bottom - form.Height - 5;
if (form.Bounds.Left < 0)
newLocation.X = 0;
form.Location = newLocation;
}
}
}
| mit | C# |
54bc4c7045287ee76c9792eab52c0dd476e1c80b | Update the Assembly Info | SevenSpikes/api-plugin-for-nopcommerce,SevenSpikes/api-plugin-for-nopcommerce | Nop.Plugin.Api/Properties/AssemblyInfo.cs | Nop.Plugin.Api/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("Nop.Plugin.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Seven Spikes, Ltd")]
[assembly: AssemblyProduct("Nop.Plugin.Api")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[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("6a13d01b-5b1a-4932-9a9d-4117ac27011f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.9.0.0")]
[assembly: AssemblyFileVersion("3.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("Nop.Plugin.Api")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nop Solutions, Ltd")]
[assembly: AssemblyProduct("Nop.Plugin.Api")]
[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("6a13d01b-5b1a-4932-9a9d-4117ac27011f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.9.0.0")]
[assembly: AssemblyFileVersion("3.9.0.0")]
| mit | C# |
e0682e2468feda2dae99d741e6ed282da7ff876d | Add choice | archrival/SubsonicSharp | Subsonic.Common/Enums/ItemChoiceType.cs | Subsonic.Common/Enums/ItemChoiceType.cs | using System.Xml.Serialization;
namespace Subsonic.Common.Enums
{
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
[XmlEnum("album")]
Album,
[XmlEnum("albumInfo")]
AlbumInfo,
[XmlEnum("albumInfo2")]
AlbumInfo2,
[XmlEnum("albumList")]
AlbumList,
[XmlEnum("albumList2")]
AlbumList2,
[XmlEnum("artist")]
Artist,
[XmlEnum("artistInfo")]
ArtistInfo,
[XmlEnum("artistInfo2")]
ArtistInfo2,
[XmlEnum("artists")]
Artists,
[XmlEnum("bookmarks")]
Bookmarks,
[XmlEnum("chatMessages")]
ChatMessages,
[XmlEnum("directory")]
Directory,
[XmlEnum("error")]
Error,
[XmlEnum("genres")]
Genres,
[XmlEnum("indexes")]
Indexes,
[XmlEnum("internetRadioStations")]
InternetRadioStations,
[XmlEnum("jukeboxPlaylist")]
JukeboxPlaylist,
[XmlEnum("jukeboxStatus")]
JukeboxStatus,
[XmlEnum("license")]
License,
[XmlEnum("lyrics")]
Lyrics,
[XmlEnum("musicFolders")]
MusicFolders,
[XmlEnum("newestPodcasts")]
NewestPodcasts,
[XmlEnum("nowPlaying")]
NowPlaying,
[XmlEnum("playlist")]
Playlist,
[XmlEnum("playlists")]
Playlists,
[XmlEnum("playQueue")]
PlayQueue,
[XmlEnum("podcasts")]
Podcasts,
[XmlEnum("randomSongs")]
RandomSongs,
[XmlEnum("scanStatus")]
ScanStatus,
[XmlEnum("searchResult")]
SearchResult,
[XmlEnum("searchResult2")]
SearchResult2,
[XmlEnum("searchResult3")]
SearchResult3,
[XmlEnum("shares")]
Shares,
[XmlEnum("similarSongs")]
SimilarSongs,
[XmlEnum("similarSongs2")]
SimilarSongs2,
[XmlEnum("song")]
Song,
[XmlEnum("songsByGenre")]
SongsByGenre,
[XmlEnum("starred")]
Starred,
[XmlEnum("starred2")]
Starred2,
[XmlEnum("topSongs")]
TopSongs,
[XmlEnum("user")]
User,
[XmlEnum("users")]
Users,
[XmlEnum("videoInfo")]
VideoInfo,
[XmlEnum("videos")]
Videos
}
} | using System.Xml.Serialization;
namespace Subsonic.Common.Enums
{
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
[XmlEnum("album")]
Album,
[XmlEnum("albumInfo")]
AlbumInfo,
[XmlEnum("albumInfo2")]
AlbumInfo2,
[XmlEnum("albumList")]
AlbumList,
[XmlEnum("albumList2")]
AlbumList2,
[XmlEnum("artist")]
Artist,
[XmlEnum("artistInfo")]
ArtistInfo,
[XmlEnum("artistInfo2")]
ArtistInfo2,
[XmlEnum("artists")]
Artists,
[XmlEnum("bookmarks")]
Bookmarks,
[XmlEnum("chatMessages")]
ChatMessages,
[XmlEnum("directory")]
Directory,
[XmlEnum("error")]
Error,
[XmlEnum("genres")]
Genres,
[XmlEnum("indexes")]
Indexes,
[XmlEnum("internetRadioStations")]
InternetRadioStations,
[XmlEnum("jukeboxPlaylist")]
JukeboxPlaylist,
[XmlEnum("jukeboxStatus")]
JukeboxStatus,
[XmlEnum("license")]
License,
[XmlEnum("lyrics")]
Lyrics,
[XmlEnum("musicFolders")]
MusicFolders,
[XmlEnum("nowPlaying")]
NowPlaying,
[XmlEnum("playlist")]
Playlist,
[XmlEnum("playlists")]
Playlists,
[XmlEnum("playQueue")]
PlayQueue,
[XmlEnum("podcasts")]
Podcasts,
[XmlEnum("randomSongs")]
RandomSongs,
[XmlEnum("scanStatus")]
ScanStatus,
[XmlEnum("searchResult")]
SearchResult,
[XmlEnum("searchResult2")]
SearchResult2,
[XmlEnum("searchResult3")]
SearchResult3,
[XmlEnum("shares")]
Shares,
[XmlEnum("similarSongs")]
SimilarSongs,
[XmlEnum("similarSongs2")]
SimilarSongs2,
[XmlEnum("song")]
Song,
[XmlEnum("songsByGenre")]
SongsByGenre,
[XmlEnum("starred")]
Starred,
[XmlEnum("starred2")]
Starred2,
[XmlEnum("topSongs")]
TopSongs,
[XmlEnum("user")]
User,
[XmlEnum("users")]
Users,
[XmlEnum("videoInfo")]
VideoInfo,
[XmlEnum("videos")]
Videos
}
} | mit | C# |
ff25c67632520b35c9ce14cc58c1601f693c3a6e | remove debug | DutchBeastman/ProefBekwaamheidIceCubeGames | Assets/Scripts/Audio/AudioPlayer.cs | Assets/Scripts/Audio/AudioPlayer.cs | //Created By: Jeremy Bond
//Date: 27/03/2016
using UnityEngine;
using UnityEngine.Audio;
using System.Collections.Generic;
namespace Utils
{
public class AudioPlayer : MonoBehaviour
{
[SerializeField] private int maxChannels;
private HashSet<AudioChannel> channels;
[SerializeField] private AudioMixerGroup SFXGroup;
[SerializeField] private AudioMixerGroup musicGroup;
private const string AUDIOEVENT = "audioEvent";
protected void Awake ()
{
channels = new HashSet<AudioChannel> ();
for (int i = 0; i < maxChannels; i++)
{
GameObject channel = new GameObject ("channel" + i);
channel.transform.SetParent (transform);
channel.AddComponent<AudioSource> ();
channels.Add (channel.AddComponent<AudioChannel> ());
}
}
private AudioChannel GetFreeChannel ()
{
foreach (AudioChannel channel in channels)
{
if (!channel.IsPlaying)
{
return channel;
}
}
return null;
}
protected void OnEnable ()
{
EventManager.AddAudioSFXListener (PlaySFXAudio);
EventManager.AddAudioMusicListener (PlayMusicAudio);
}
protected void OnDisable ()
{
EventManager.RemoveAudioSFXListener (PlaySFXAudio);
EventManager.RemoveAudioMusicListener (PlayMusicAudio);
}
private void PlaySFXAudio (AudioClip clip)
{
PlayAudio(clip, SFXGroup);
}
private void PlayMusicAudio(AudioClip clip)
{
PlayAudio(clip, musicGroup);
}
private void PlayAudio(AudioClip clip, AudioMixerGroup group)
{
AudioChannel channel = GetFreeChannel ();
if (channel != null)
{
if (group == musicGroup)
{
channel.Loop = true;
}
channel.Play (clip, group);
}
else
{
Debug.LogWarning ("No free AudioChannels");
}
}
}
} | //Created By: Jeremy Bond
//Date: 27/03/2016
using UnityEngine;
using UnityEngine.Audio;
using System.Collections.Generic;
namespace Utils
{
public class AudioPlayer : MonoBehaviour
{
[SerializeField] private int maxChannels;
private HashSet<AudioChannel> channels;
[SerializeField] private AudioMixerGroup SFXGroup;
[SerializeField] private AudioMixerGroup musicGroup;
private const string AUDIOEVENT = "audioEvent";
protected void Awake ()
{
channels = new HashSet<AudioChannel> ();
for (int i = 0; i < maxChannels; i++)
{
GameObject channel = new GameObject ("channel" + i);
channel.transform.SetParent (transform);
channel.AddComponent<AudioSource> ();
channels.Add (channel.AddComponent<AudioChannel> ());
}
}
private AudioChannel GetFreeChannel ()
{
foreach (AudioChannel channel in channels)
{
if (!channel.IsPlaying)
{
Debug.Log ("returning empty channel");
return channel;
}
}
return null;
}
protected void OnEnable ()
{
EventManager.AddAudioSFXListener (PlaySFXAudio);
EventManager.AddAudioMusicListener (PlayMusicAudio);
}
protected void OnDisable ()
{
EventManager.RemoveAudioSFXListener (PlaySFXAudio);
EventManager.RemoveAudioMusicListener (PlayMusicAudio);
}
private void PlaySFXAudio (AudioClip clip)
{
PlayAudio(clip, SFXGroup);
}
private void PlayMusicAudio(AudioClip clip)
{
PlayAudio(clip, musicGroup);
}
private void PlayAudio(AudioClip clip, AudioMixerGroup group)
{
AudioChannel channel = GetFreeChannel ();
if (channel != null)
{
if (group == musicGroup)
{
channel.Loop = true;
}
channel.Play (clip, group);
}
else
{
Debug.LogWarning ("No free AudioChannels");
}
}
}
} | mit | C# |
641c2ed8b12810ad20b002c6b81389bc8cb90665 | Add return codes | CSIS/EnrollmentStation | CertUtilities/RevokeCert/Program.cs | CertUtilities/RevokeCert/Program.cs | using System;
using System.Runtime.InteropServices;
using CERTADMINLib;
using CERTCLIENTLib;
namespace RevokeCert
{
class Program
{
private const int CC_UIPICKCONFIG = 0x1;
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: RevokeCert.exe [SerialNumber]");
return 2;
}
string serial = args[0];
CCertConfig objCertConfig = new CCertConfig();
string strCAConfig = objCertConfig.GetConfig(CC_UIPICKCONFIG);
bool success = RevokeCert(strCAConfig, serial);
return success ? 0 : 1;
}
public static bool RevokeCert(string config, string serial)
{
//config= "192.168.71.128\\My-CA"
//serial = "614870cd000000000014"
const int CRL_REASON_UNSPECIFIED = 0;
CCertAdmin admin = null;
try
{
admin = new CCertAdmin();
admin.RevokeCertificate(config, serial, CRL_REASON_UNSPECIFIED, DateTime.Now);
return true;
}
catch (Exception)
{
return false;
}
finally
{
if (admin != null)
Marshal.FinalReleaseComObject(admin);
}
}
}
}
| using System;
using System.Runtime.InteropServices;
using CERTADMINLib;
using CERTCLIENTLib;
namespace RevokeCert
{
class Program
{
private const int CC_UIPICKCONFIG = 0x1;
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: RevokeCert.exe [SerialNumber]");
return;
}
string serial = args[0];
CCertConfig objCertConfig = new CCertConfig();
string strCAConfig = objCertConfig.GetConfig(CC_UIPICKCONFIG);
RevokeCert(strCAConfig, serial);
}
public static void RevokeCert(string config, string serial)
{
//config= "192.168.71.128\\My-CA"
//serial = "614870cd000000000014"
const int CRL_REASON_UNSPECIFIED = 0;
CCertAdmin admin = null;
try
{
admin = new CCertAdmin();
admin.RevokeCertificate(config, serial, CRL_REASON_UNSPECIFIED, DateTime.Now);
}
finally
{
if (admin != null)
Marshal.FinalReleaseComObject(admin);
}
}
}
}
| mit | C# |
0229684c38a58ec68e19ad803968603912203012 | Fix namespace | leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net | JoinRpg.DataModel/MarkdownString.cs | JoinRpg.DataModel/MarkdownString.cs | namespace JoinRpg.DataModel
{
public class MarkdownString
{
public MarkdownString(string contents)
{
//TODO: Validate for correct Markdown
Contents = contents;
}
public MarkdownString() : this(null)
{
}
public string Contents { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JoinRpg.DataModel
{
public class MarkdownString
{
public MarkdownString(string contents)
{
//TODO: Validate for correct Markdown
Contents = contents;
}
public MarkdownString() : this(null)
{
}
public string Contents { get; set; }
}
}
| mit | C# |
2a69335d718cd56ea7a22f4eadceb121de0162e4 | Build nuget package. | RockFramework/Rock.Messaging,peteraritchie/Rock.Messaging,bfriesen/Rock.Messaging | Rock.Messaging/Properties/AssemblyInfo.cs | Rock.Messaging/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("Rock.Messaging")]
[assembly: AssemblyDescription("Rock Messaging.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Messaging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("58c2f915-e27e-436d-bd97-b6cb117ffd6b")]
// 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.4")]
[assembly: AssemblyInformationalVersion("0.9.4")]
| 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("Rock.Messaging")]
[assembly: AssemblyDescription("Rock Messaging.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Quicken Loans")]
[assembly: AssemblyProduct("Rock.Messaging")]
[assembly: AssemblyCopyright("Copyright © Quicken Loans 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("58c2f915-e27e-436d-bd97-b6cb117ffd6b")]
// 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.3")]
[assembly: AssemblyInformationalVersion("0.9.3")]
| mit | C# |
fa2bd41c63092927fc14529c42de72522e301444 | Change CollationDefinition.IsValid to protected internal | gtryus/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,tombogle/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,andrew-polk/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,tombogle/libpalaso | SIL.WritingSystems/CollationDefinition.cs | SIL.WritingSystems/CollationDefinition.cs | using SIL.Data;
namespace SIL.WritingSystems
{
public abstract class CollationDefinition : DefinitionBase<CollationDefinition>
{
private readonly string _type;
private ICollator _collator;
protected CollationDefinition(string type)
{
_type = type;
}
protected CollationDefinition(CollationDefinition cd)
{
_type = cd._type;
}
public string Type
{
get { return _type; }
}
/// <summary>
/// Returns an ICollator interface that can be used to sort strings based
/// on the custom collation rules.
/// </summary>
public ICollator Collator
{
get
{
if (_collator == null)
{
string message;
if (!Validate(out message))
throw new ValidationException(message);
_collator = CreateCollator();
}
return _collator;
}
}
public abstract bool Validate(out string message);
public bool IsValid { get; protected internal set; }
protected void ResetCollator()
{
_collator = null;
IsValid = false;
}
protected abstract ICollator CreateCollator();
public override bool ValueEquals(CollationDefinition other)
{
return other != null && _type == other._type;
}
}
}
| using SIL.Data;
namespace SIL.WritingSystems
{
public abstract class CollationDefinition : DefinitionBase<CollationDefinition>
{
private readonly string _type;
private ICollator _collator;
protected CollationDefinition(string type)
{
_type = type;
}
protected CollationDefinition(CollationDefinition cd)
{
_type = cd._type;
}
public string Type
{
get { return _type; }
}
/// <summary>
/// Returns an ICollator interface that can be used to sort strings based
/// on the custom collation rules.
/// </summary>
public ICollator Collator
{
get
{
if (_collator == null)
{
string message;
if (!Validate(out message))
throw new ValidationException(message);
_collator = CreateCollator();
}
return _collator;
}
}
public abstract bool Validate(out string message);
public bool IsValid { get; set; }
protected void ResetCollator()
{
_collator = null;
IsValid = false;
}
protected abstract ICollator CreateCollator();
public override bool ValueEquals(CollationDefinition other)
{
return other != null && _type == other._type;
}
}
}
| mit | C# |
28c9f8058111b9ae2d387e3ab02e310e609c1c0a | Convert AllLegalTagNameCharacters flag into an integer CurrentState and use a table (finite automaton) of size 18x41 to transition between states that either accept or reject the symbol as a tag name. Also update comment about tag names. | PenguinF/sandra-three | Sandra.Chess/Pgn/PgnSymbolStateMachine.cs | Sandra.Chess/Pgn/PgnSymbolStateMachine.cs | #region License
/*********************************************************************************
* PgnSymbolStateMachine.cs
*
* Copyright (c) 2004-2020 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
namespace Sandra.Chess.Pgn
{
/// <summary>
/// Contains a state machine which is used during parsing of <see cref="IGreenPgnSymbol"/> instances.
/// </summary>
internal struct PgnSymbolStateMachine
{
// Offset with value 1, because 0 is the illegal character class in the PGN parser.
internal const int UppercaseLetterCharacter = 1;
internal const int LowercaseLetterCharacter = 2;
internal const int DigitCharacter = 3;
internal const int OtherSymbolCharacter = 4;
internal const int CharacterClassLength = 18;
// The default state 0 indicates that the machine has entered an invalid state, and will never become valid again.
private const int StateStart = 1;
private const int StateValidTagName = 40;
private const int StateLength = 41;
private const ulong ValidTagNameStates
= 1ul << StateValidTagName;
// This table is used to transition from state to state given a character class index.
// It is a low level implementation of a regular expression; it is a theorem
// that regular expressions and finite automata are equivalent in their expressive power.
private static readonly int[,] StateTransitionTable;
static PgnSymbolStateMachine()
{
StateTransitionTable = new int[StateLength, CharacterClassLength];
// Tag names must start with a letter or underscore.
// This deviates from the PGN standard which only allows tag names to start with uppercase letters.
StateTransitionTable[StateStart, UppercaseLetterCharacter] = StateValidTagName;
StateTransitionTable[StateStart, LowercaseLetterCharacter] = StateValidTagName;
// Allow only digits, letters or the underscore character in tag names.
StateTransitionTable[StateValidTagName, DigitCharacter] = StateValidTagName;
StateTransitionTable[StateValidTagName, UppercaseLetterCharacter] = StateValidTagName;
StateTransitionTable[StateValidTagName, LowercaseLetterCharacter] = StateValidTagName;
}
private int CurrentState;
public void Start(int characterClass)
=> CurrentState = StateTransitionTable[StateStart, characterClass];
public void Transition(int characterClass)
=> CurrentState = StateTransitionTable[CurrentState, characterClass];
public IGreenPgnSymbol Yield(int length)
{
ulong resultState = 1ul << CurrentState;
if (ValidTagNameStates.Test(resultState)) return new GreenPgnTagNameSyntax(length);
return null;
}
}
}
| #region License
/*********************************************************************************
* PgnSymbolStateMachine.cs
*
* Copyright (c) 2004-2020 Henk Nicolai
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
#endregion
namespace Sandra.Chess.Pgn
{
/// <summary>
/// Contains a state machine which is used during parsing of <see cref="IGreenPgnSymbol"/> instances.
/// </summary>
internal struct PgnSymbolStateMachine
{
internal const int UppercaseLetterCharacter = 1;
internal const int LowercaseLetterCharacter = 2;
internal const int DigitCharacter = 3;
internal const int OtherSymbolCharacter = 4;
private bool AllLegalTagNameCharacters;
public void Start(int characterClass)
// Tag names must start with an uppercase letter.
=> AllLegalTagNameCharacters = characterClass == UppercaseLetterCharacter || characterClass == LowercaseLetterCharacter;
public void Transition(int characterClass)
// Allow only digits, letters or the underscore character in tag names.
=> AllLegalTagNameCharacters = AllLegalTagNameCharacters &&
(characterClass == UppercaseLetterCharacter
|| characterClass == LowercaseLetterCharacter
|| characterClass == DigitCharacter);
public IGreenPgnSymbol Yield(int length)
{
if (AllLegalTagNameCharacters) return new GreenPgnTagNameSyntax(length);
return null;
}
}
}
| apache-2.0 | C# |
8d751a9d8045e05c14dc8d1bf7473c265acee42a | rename generic types in ProxyableFactory | BrainCrumbz/NSpec.VsAdapter,nspec/NSpec.VsAdapter | src/NSpec.VsAdapter/NSpec.VsAdapter/CrossDomain/ProxyableFactory.cs | src/NSpec.VsAdapter/NSpec.VsAdapter/CrossDomain/ProxyableFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSpec.VsAdapter.CrossDomain
{
public class ProxyableFactory<TImplementation, TInterface> : IProxyableFactory<TInterface>
where TImplementation : Proxyable, TInterface
{
public TInterface CreateProxy(ITargetAppDomain targetDomain)
{
var marshaledType = typeof(TImplementation);
var marshaledTypeName = marshaledType.FullName;
var marshaledAssemblyName = marshaledType.Assembly.FullName;
var crossDomainProxy = (TImplementation)targetDomain.CreateInstanceAndUnwrap(
marshaledAssemblyName, marshaledTypeName);
return crossDomainProxy;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NSpec.VsAdapter.CrossDomain
{
public class ProxyableFactory<TProxyableImpl, TIProxyable> : IProxyableFactory<TIProxyable>
where TProxyableImpl : Proxyable, TIProxyable
{
public TIProxyable CreateProxy(ITargetAppDomain targetDomain)
{
var marshaledType = typeof(TProxyableImpl);
var marshaledTypeName = marshaledType.FullName;
var marshaledAssemblyName = marshaledType.Assembly.FullName;
var crossDomainProxy = (TProxyableImpl)targetDomain.CreateInstanceAndUnwrap(
marshaledAssemblyName, marshaledTypeName);
return crossDomainProxy;
}
}
}
| mit | C# |
084ac9c4537300e4172bf82fefb8070657926438 | Allow using MongoDb connectionString including DatabaseName (#22) | diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB,diogodamiani/IdentityServer4.MongoDB | src/IdentityServer4.MongoDB/DbContexts/MongoDBContextBase.cs | src/IdentityServer4.MongoDB/DbContexts/MongoDBContextBase.cs | using IdentityServer4.MongoDB.Configuration;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
namespace IdentityServer4.MongoDB.DbContexts
{
public class MongoDBContextBase : IDisposable
{
private readonly IMongoClient _client;
public MongoDBContextBase(IOptions<MongoDBConfiguration> settings)
{
if (settings.Value == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration cannot be null.");
if (settings.Value.ConnectionString == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration.ConnectionString cannot be null.");
MongoUrl mongoUrl = MongoUrl.Create(settings.Value.ConnectionString);
if (settings.Value.Database == null && mongoUrl.DatabaseName == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration.Database cannot be null.");
var clientSettings = MongoClientSettings.FromUrl(mongoUrl);
if (clientSettings.SslSettings != null)
{
clientSettings.SslSettings = settings.Value.SslSettings;
clientSettings.UseSsl = true;
}
else
{
clientSettings.UseSsl = false;
}
_client = new MongoClient(settings.Value.ConnectionString);
Database = _client.GetDatabase(settings.Value.Database ?? mongoUrl.DatabaseName);
}
protected IMongoDatabase Database { get; }
public void Dispose()
{
// TODO
}
}
}
| using IdentityServer4.MongoDB.Configuration;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
namespace IdentityServer4.MongoDB.DbContexts
{
public class MongoDBContextBase : IDisposable
{
private readonly IMongoClient _client;
public MongoDBContextBase(IOptions<MongoDBConfiguration> settings)
{
if (settings.Value == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration cannot be null.");
if (settings.Value.ConnectionString == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration.ConnectionString cannot be null.");
if (settings.Value.Database == null)
throw new ArgumentNullException(nameof(settings), "MongoDBConfiguration.Database cannot be null.");
var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(settings.Value.ConnectionString));
if (clientSettings.SslSettings != null)
{
clientSettings.SslSettings = settings.Value.SslSettings;
clientSettings.UseSsl = true;
}
else
{
clientSettings.UseSsl = false;
}
_client = new MongoClient(settings.Value.ConnectionString);
Database = _client.GetDatabase(settings.Value.Database);
}
protected IMongoDatabase Database { get; }
public void Dispose()
{
// TODO
}
}
} | apache-2.0 | C# |
e888059404cfc393bad89704eeae15c3f9094217 | Bump version of PortableSettingsProvider to 1.2 | Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller,Klocman/Bulk-Crap-Uninstaller | source/PortableSettingsProvider/Properties/AssemblyInfo.cs | source/PortableSettingsProvider/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("PortableSettingsProvider")]
[assembly: AssemblyDescription("Library that allows saving of .NET settings to a portable file")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Marcin Szeniak, HakanL, CodeChimp")]
[assembly: AssemblyProduct("PortableSettingsProvider")]
[assembly: AssemblyCopyright("Copyright © 2007")]
// 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("68c10a7e-883f-443a-b7a0-41e06ad56602")]
// 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.2.*")]
| 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("PortableSettingsProvider")]
[assembly: AssemblyDescription("Library that allows saving of .NET settings to a portable file")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCompany("Marcin Szeniak, HakanL, CodeChimp")]
[assembly: AssemblyProduct("PortableSettingsProvider")]
[assembly: AssemblyCopyright("Copyright © 2007")]
// 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("68c10a7e-883f-443a-b7a0-41e06ad56602")]
// 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.*")]
| apache-2.0 | C# |
e51b786737cfc88f25adb53d0400e4d07b53a9e6 | fix namespace | elastic/elasticsearch-net,KodrAus/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,azubanov/elasticsearch-net,TheFireCookie/elasticsearch-net,azubanov/elasticsearch-net,jonyadamit/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,UdiBen/elasticsearch-net,RossLieberman/NEST,cstlaurent/elasticsearch-net,cstlaurent/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,KodrAus/elasticsearch-net,KodrAus/elasticsearch-net,RossLieberman/NEST,jonyadamit/elasticsearch-net,cstlaurent/elasticsearch-net,jonyadamit/elasticsearch-net,TheFireCookie/elasticsearch-net,RossLieberman/NEST | src/Tests/QueryDsl/FullText/Match/MatchPhraseUsageTests.cs | src/Tests/QueryDsl/FullText/Match/MatchPhraseUsageTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using static Nest.Static;
namespace Tests.QueryDsl.FullText.Match
{
public class MatchPhrasePrefixUsageTests : QueryDslUsageTestsBase
{
public MatchPhrasePrefixUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object QueryJson => new
{
};
protected override QueryContainer QueryInitializer => new MatchPhrasePrefixQuery
{
Field = Field<Project>(p=>p.Description),
Analyzer = "standard",
Boost = 1.1,
CutoffFrequency = 0.001,
Fuzziness = Fuzziness.EditDistance(2),
FuzzyTranspositions = true,
//TODO more
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> d) => d
.MatchPhrasePrefix(c => c
.OnField(p => p.Description)
.Analyzer("standard")
.Boost(1.1)
.CutoffFrequency(0.001)
);
[I] public void HandlingResponses() { }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.MockData;
using static Nest.Static;
namespace Tests.QueryDsl.FullText.MatchPhrasePrefix
{
public class MatchPhrasePrefixUsageTests : QueryDslUsageTestsBase
{
public MatchPhrasePrefixUsageTests(ReadOnlyCluster i, EndpointUsage usage) : base(i, usage) { }
protected override object QueryJson => new
{
};
protected override QueryContainer QueryInitializer => new MatchPhrasePrefixQuery
{
Field = Field<Project>(p=>p.Description),
Analyzer = "standard",
Boost = 1.1,
CutoffFrequency = 0.001,
Fuzziness = Fuzziness.EditDistance(2),
FuzzyTranspositions = true,
//TODO more
};
protected override QueryContainer QueryFluent(QueryContainerDescriptor<Project> d) => d
.MatchPhrasePrefix(c => c
.OnField(p => p.Description)
.Analyzer("standard")
.Boost(1.1)
.CutoffFrequency(0.001)
);
[I] public void HandlingResponses() { }
}
}
| apache-2.0 | C# |
de21ec7bc94242350b6d763c4b73442080f35de0 | remove claim denial status from my claims export | joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net | src/JoinRpg.WebPortal.Models/Exporters/MyClaimListItemViewModelExporter.cs | src/JoinRpg.WebPortal.Models/Exporters/MyClaimListItemViewModelExporter.cs | using System.Collections.Generic;
using JoinRpg.Services.Interfaces;
using JoinRpg.Web.Models.ClaimList;
namespace JoinRpg.Web.Models.Exporters
{
public class MyClaimListItemViewModelExporter : CustomExporter<ClaimListItemViewModel>
{
public MyClaimListItemViewModelExporter(IUriService uriService) : base(
uriService)
{ }
public override IEnumerable<ITableColumn> ParseColumns()
{
yield return StringColumn(x => x.Name);
yield return UriColumn(x => x);
yield return EnumColumn(x => x.ClaimFullStatusView.ClaimStatus);
yield return DateTimeColumn(x => x.UpdateDate);
yield return DateTimeColumn(x => x.CreateDate);
yield return IntColumn(x => x.TotalFee);
yield return IntColumn(x => x.FeeDue);
yield return IntColumn(x => x.FeePaid);
yield return BoolColumn(x => x.PreferentialFeeUser);
yield return StringColumn(x => x.AccomodationType);
yield return StringColumn(x => x.RoomName);
yield return ShortUserColumn(x => x.LastModifiedBy);
yield return ShortUserColumn(x => x.Responsible);
}
}
}
| using System.Collections.Generic;
using JoinRpg.Services.Interfaces;
using JoinRpg.Web.Models.ClaimList;
namespace JoinRpg.Web.Models.Exporters
{
public class MyClaimListItemViewModelExporter : CustomExporter<ClaimListItemViewModel>
{
public MyClaimListItemViewModelExporter(IUriService uriService) : base(
uriService)
{ }
public override IEnumerable<ITableColumn> ParseColumns()
{
yield return StringColumn(x => x.Name);
yield return UriColumn(x => x);
yield return EnumColumn(x => x.ClaimFullStatusView.ClaimStatus);
yield return EnumColumn(x => x.ClaimFullStatusView.ClaimDenialStatus);
yield return DateTimeColumn(x => x.UpdateDate);
yield return DateTimeColumn(x => x.CreateDate);
yield return IntColumn(x => x.TotalFee);
yield return IntColumn(x => x.FeeDue);
yield return IntColumn(x => x.FeePaid);
yield return BoolColumn(x => x.PreferentialFeeUser);
yield return StringColumn(x => x.AccomodationType);
yield return StringColumn(x => x.RoomName);
yield return ShortUserColumn(x => x.LastModifiedBy);
yield return ShortUserColumn(x => x.Responsible);
}
}
}
| mit | C# |
52ffc89fef5603bcec698bcb49fa73da4b3efbd3 | Remove duplicated UseHttpsRedirection (#437) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.DotNet.Web.ProjectTemplates/content/WebApi-CSharp/Startup.cs | src/Microsoft.DotNet.Web.ProjectTemplates/content/WebApi-CSharp/Startup.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
#if (RequiresHttps)
using Microsoft.AspNetCore.HttpsPolicy;
#endif
using Microsoft.AspNetCore.Mvc;
#if (OrganizationalAuth || IndividualB2CAuth)
using Microsoft.AspNetCore.Authentication;
#endif
#if (OrganizationalAuth)
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
#endif
#if (IndividualB2CAuth)
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
#endif
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Company.WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#if (OrganizationalAuth)
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
#elif (IndividualB2CAuth)
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
#endif
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#if (RequiresHttps)
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
#else
#endif
#if (OrganizationalAuth || IndividualAuth)
app.UseAuthentication();
#endif
app.UseMvc();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
#if (RequiresHttps)
using Microsoft.AspNetCore.HttpsPolicy;
#endif
using Microsoft.AspNetCore.Mvc;
#if (OrganizationalAuth || IndividualB2CAuth)
using Microsoft.AspNetCore.Authentication;
#endif
#if (OrganizationalAuth)
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
#endif
#if (IndividualB2CAuth)
using Microsoft.AspNetCore.Authentication.AzureADB2C.UI;
#endif
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Company.WebApplication1
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
#if (OrganizationalAuth)
services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
#elif (IndividualB2CAuth)
services.AddAuthentication(AzureADB2CDefaults.BearerAuthenticationScheme)
.AddAzureADB2CBearer(options => Configuration.Bind("AzureAdB2C", options));
#endif
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
#if (RequiresHttps)
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
#else
#endif
app.UseHttpsRedirection();
#if (OrganizationalAuth || IndividualAuth)
app.UseAuthentication();
#endif
app.UseMvc();
}
}
}
| apache-2.0 | C# |
7b51849ddb11e8d25da2afd12940786dd8b8896a | Fix grouping issue | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Infrastructure/Data/TrainingProgrammeRepository.cs | src/SFA.DAS.Commitments.Infrastructure/Data/TrainingProgrammeRepository.cs | using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.Commitments.Domain.Data;
using SFA.DAS.Commitments.Domain.Entities.TrainingProgramme;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Sql.Client;
using SFA.DAS.Sql.Dapper;
namespace SFA.DAS.Commitments.Infrastructure.Data
{
public class TrainingProgrammeRepository : BaseRepository, ITrainingProgrammeRepository
{
public TrainingProgrammeRepository(string connectionString, ILog logger) : base(connectionString, logger)
{
}
public async Task<List<Standard>> GetAllStandards()
{
var lookup = new Dictionary<object, Standard>();
var mapper = new ParentChildrenMapper<Standard, FundingPeriod>();
return await WithConnection(async connection =>
{
var results = await connection.QueryAsync(
sql: $"[dbo].[GetStandards]",
commandType: CommandType.StoredProcedure,
map: mapper.Map(lookup, x => x.Id, x => x.FundingPeriods),
splitOn: "Id"
);
return results.GroupBy(c => c.Id).Select(item=>item.First()).ToList();
});
}
public async Task<List<Framework>> GetAllFrameworks()
{
var lookup = new Dictionary<object, Framework>();
var mapper = new ParentChildrenMapper<Framework, FundingPeriod>();
return await WithConnection(async connection =>
{
var results = await connection.QueryAsync(
sql: $"[dbo].[GetFrameworks]",
commandType: CommandType.StoredProcedure,
map: mapper.Map(lookup, x => x.Id, x => x.FundingPeriods),
splitOn: "Id"
);
return results.GroupBy(c => c.Id).Select(item=>item.First()).ToList();
});
}
}
} | using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Dapper;
using SFA.DAS.Commitments.Domain.Data;
using SFA.DAS.Commitments.Domain.Entities.TrainingProgramme;
using SFA.DAS.NLog.Logger;
using SFA.DAS.Sql.Client;
using SFA.DAS.Sql.Dapper;
namespace SFA.DAS.Commitments.Infrastructure.Data
{
public class TrainingProgrammeRepository : BaseRepository, ITrainingProgrammeRepository
{
public TrainingProgrammeRepository(string connectionString, ILog logger) : base(connectionString, logger)
{
}
public async Task<List<Standard>> GetAllStandards()
{
var lookup = new Dictionary<object, Standard>();
var mapper = new ParentChildrenMapper<Standard, FundingPeriod>();
return await WithConnection(async connection =>
{
var results = await connection.QueryAsync(
sql: $"[dbo].[GetStandards]",
commandType: CommandType.StoredProcedure,
map: mapper.Map(lookup, x => x.Id, x => x.FundingPeriods),
splitOn: "Id"
);
return results.ToList();
});
}
public async Task<List<Framework>> GetAllFrameworks()
{
var lookup = new Dictionary<object, Framework>();
var mapper = new ParentChildrenMapper<Framework, FundingPeriod>();
return await WithConnection(async connection =>
{
var results = await connection.QueryAsync(
sql: $"[dbo].[GetFrameworks]",
commandType: CommandType.StoredProcedure,
map: mapper.Map(lookup, x => x.Id, x => x.FundingPeriods),
splitOn: "Id"
);
return results.ToList();
});
}
}
} | mit | C# |
6188586ea99b869349e7402dd4fe741e3223e106 | Fix to test | AndMu/Wikiled.Sentiment | src/Sentiment/Wikiled.Sentiment.AcceptanceTests/Training/SentimentTests.cs | src/Sentiment/Wikiled.Sentiment.AcceptanceTests/Training/SentimentTests.cs | using System.Threading.Tasks;
using NLog;
using NUnit.Framework;
using Wikiled.Amazon.Logic;
namespace Wikiled.Sentiment.AcceptanceTests.Training
{
[TestFixture]
public class SentimentTests
{
private static readonly Logger log = LogManager.GetCurrentClassLogger();
[TestCase("B00002EQCW", "Total:<215> Positive:<98.000%> Negative:<53.333%> F1:<0.973> RMSE:0.89")]
[TestCase("B0026127Y8", "Total:<854> Positive:<90.944%> Negative:<43.210%> F1:<0.924> RMSE:1.12")]
public async Task TestElectronics(string product, string performance)
{
log.Info("TestElectronics: {0} {1}", product, performance);
var testingClient = await Global.ElectronicBaseLine.Test(product, ProductCategory.Electronics).ConfigureAwait(false);
Assert.AreEqual(performance, testingClient.GetPerformanceDescription());
}
[TestCase("B0002L5R78", "Total:<7275> Positive:<91.616%> Negative:<31.529%> F1:<0.919> RMSE:1.22")]
public async Task TestVideo(string product, string performance)
{
log.Info("TestVideo: {0} {1}", product, performance);
var testingClient = await Global.VideoBaseLine.Test(product, ProductCategory.Video).ConfigureAwait(false);
Assert.AreEqual(performance, testingClient.GetPerformanceDescription());
}
}
}
| using System.Threading.Tasks;
using NLog;
using NUnit.Framework;
using Wikiled.Amazon.Logic;
namespace Wikiled.Sentiment.AcceptanceTests.Training
{
[TestFixture]
public class SentimentTests
{
private static readonly Logger log = LogManager.GetCurrentClassLogger();
[TestCase("B00002EQCW", "Total:<215> Positive:<98.000%> Negative:<53.333%> F1:<0.973> RMSE:0.89")]
[TestCase("B0026127Y8", "Total:<854> Positive:<90.944%> Negative:<43.210%> F1:<0.924> RMSE:1.12")]
public async Task TestElectronics(string product, string performance)
{
log.Info("TestElectronics: {0} {1}", product, performance);
var testingClient = await Global.ElectronicBaseLine.Test(product, ProductCategory.Electronics).ConfigureAwait(false);
Assert.AreEqual(performance, testingClient.GetPerformanceDescription());
}
[TestCase("B0002L5R78", "Total:<7275>Positive:<91.616%> Negative:<31.529%> F1:<0.919> RMSE:1.22")]
public async Task TestVideo(string product, string performance)
{
log.Info("TestVideo: {0} {1}", product, performance);
var testingClient = await Global.VideoBaseLine.Test(product, ProductCategory.Video).ConfigureAwait(false);
Assert.AreEqual(performance, testingClient.GetPerformanceDescription());
}
}
}
| apache-2.0 | C# |
c8b4a798da67571c19461a151ee78c55c4109517 | Add view elements for resending Confirm code | SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers | src/SFA.DAS.EmployerUsers.Web/Views/Account/ConfirmChangeEmail.cshtml | src/SFA.DAS.EmployerUsers.Web/Views/Account/ConfirmChangeEmail.cshtml | @model SFA.DAS.EmployerUsers.Web.Models.OrchestratorResponse<SFA.DAS.EmployerUsers.Web.Models.ConfirmChangeEmailViewModel>
<h1 class="heading-xlarge">Enter your security code</h1>
<form method="post">
@Html.AntiForgeryToken()
<fieldset>
<legend class="visuallyhidden">Enter your security code</legend>
<div class="form-group">
<label class="form-label-bold" for="SecurityCode">Enter security code</label>
<input autofocus="autofocus" aria-required="true" class="form-control" id="SecurityCode" name="SecurityCode">
</div>
<div class="form-group">
<label class="form-label-bold" for="Password">Password</label>
<input type="password" aria-required="true" autocomplete="off" class="form-control" id="Password" name="Password">
</div>
</fieldset>
<button type="submit" class="button">Continue</button>
</form>
@if (Model.Data.SecurityCode != null)
{
<div class="form-group">
<h2 class="heading-medium">Not received your security code?</h2>
<p>You can <a href="@Url.Action("ResendActivation")">request another security code.</a> </p>
</div>
} | <h1 class="heading-xlarge">Enter your security code</h1>
<form method="post">
@Html.AntiForgeryToken()
<fieldset>
<legend class="visuallyhidden">Enter your security code</legend>
<div class="form-group">
<label class="form-label-bold" for="SecurityCode">Enter security code</label>
<input autofocus="autofocus" aria-required="true" class="form-control" id="SecurityCode" name="SecurityCode">
</div>
<div class="form-group">
<label class="form-label-bold" for="Password">Password</label>
<input type="password" aria-required="true" autocomplete="off" class="form-control" id="Password" name="Password">
</div>
</fieldset>
<button type="submit" class="button">Continue</button>
</form> | mit | C# |
e2b6a4601f3d36a1f243512d1bc13b52f0382767 | bump assemblyinfo version to 0.1.0 | akatakritos/PygmentSharp | src/PygmentSharp/PygmentSharp.Core/Properties/AssemblyInfo.cs | src/PygmentSharp/PygmentSharp.Core/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PygmentSharp.Core")]
[assembly: AssemblyDescription("Port of Python's Pygments syntax highlighter")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PygmentSharp.Core")]
[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("9eb63a83-0f9d-4c49-bc2a-95e37eb1cb15")]
// 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")]
[assembly: AssemblyFileVersion("0.1.0")]
[assembly: InternalsVisibleTo("PygmentSharp.UnitTests")]
| 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("PygmentSharp.Core")]
[assembly: AssemblyDescription("Port of Python's Pygments syntax highlighter")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PygmentSharp.Core")]
[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("9eb63a83-0f9d-4c49-bc2a-95e37eb1cb15")]
// 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.2")]
[assembly: AssemblyFileVersion("0.0.2")]
[assembly: InternalsVisibleTo("PygmentSharp.UnitTests")]
| mit | C# |
348ab3c3f94c2f422a137f48d3bcd551892d5dcb | revert class | smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp | src/StockportWebapp/ProcessedModels/ProcessedGroupHomepage.cs | src/StockportWebapp/ProcessedModels/ProcessedGroupHomepage.cs | using System.Collections.Generic;
using StockportWebapp.Models;
namespace StockportWebapp.ProcessedModels
{
public class ProcessedGroupHomepage : IProcessedContentType
{
public readonly string Title;
public readonly string MetaDescription;
public readonly List<GroupCategory> Categories = new List<GroupCategory>();
public readonly string BackgroundImage;
public readonly string FeaturedGroupsHeading;
public readonly List<Group> FeaturedGroups;
public readonly GroupCategory FeaturedGroupsCategory;
public readonly GroupSubCategory FeaturedGroupsSubCategory;
public readonly List<Alert> Alerts;
public readonly string BodyHeading;
public readonly string Body;
public readonly string SecondaryBodyHeading;
public readonly string SecondaryBody;
public readonly EventBanner EventBanner;
public ProcessedGroupHomepage() { }
public GenericFeaturedItemList GenericItemList
{
get
{
var result = new GenericFeaturedItemList();
result.Items = new List<GenericFeaturedItem>();
foreach (var cat in Categories)
{
result.Items.Add(new GenericFeaturedItem { Icon = cat.Icon, Title = cat.Name, Url = $"/groups/results?category={cat.Slug}&order=Name+A-Z" });
}
result.ButtonText = "View more categories";
return result;
}
}
public ProcessedGroupHomepage(string title, string metaDescription, string backgroundImage, string featuredGroupsHeading, List<Group> featuredGroups,
GroupCategory featuredGroupsCategory, GroupSubCategory featuredGroupsSubCategory, List<Alert> alerts, string bodyHeading, string body, string secondaryBodyHeading, string secondaryBody, EventBanner eventBanner)
{
Title = title;
MetaDescription = metaDescription;
BackgroundImage = backgroundImage;
FeaturedGroupsHeading = featuredGroupsHeading;
FeaturedGroups = featuredGroups;
FeaturedGroupsCategory = featuredGroupsCategory;
FeaturedGroupsSubCategory = featuredGroupsSubCategory;
Alerts = alerts;
BodyHeading = bodyHeading;
Body = body;
SecondaryBodyHeading = secondaryBodyHeading;
SecondaryBody = secondaryBody;
EventBanner = eventBanner;
}
}
}
| using System.Collections.Generic;
using StockportWebapp.Models;
namespace StockportWebapp.ProcessedModels
{
public class ProcessedGroupHomepage : IProcessedContentType
{
public readonly string Title;
public readonly string MetaDescription;
public readonly List<GroupCategory> Categories = new List<GroupCategory>();
public readonly string BackgroundImage;
public readonly string FeaturedGroupsHeading;
public readonly List<Group> FeaturedGroups;
public readonly GroupCategory FeaturedGroupsCategory;
public readonly GroupSubCategory FeaturedGroupsSubCategory;
public readonly List<Alert> Alerts;
public readonly string BodyHeading;
public readonly string Body;
public readonly string SecondaryBodyHeading;
public readonly string SecondaryBody;
public readonly EventBanner EventBanner;
public ProcessedGroupHomepage() { }
public GenericFeaturedItemList GenericItemList
{
get
{
var result = new GenericFeaturedItemList();
result.Items = new List<GenericFeaturedItem>();
foreach (var cat in Categories)
{
result.Items.Add(new GenericFeaturedItem { Icon = cat.Icon, Title = cat.Name, Url = $"/groups/results?category={cat.Slug}&order=Name+A-Z" });
}
result.ButtonText = string.Empty;
result.HideButton = true;
return result;
}
}
public ProcessedGroupHomepage(string title, string metaDescription, string backgroundImage, string featuredGroupsHeading, List<Group> featuredGroups,
GroupCategory featuredGroupsCategory, GroupSubCategory featuredGroupsSubCategory, List<Alert> alerts, string bodyHeading, string body, string secondaryBodyHeading, string secondaryBody, EventBanner eventBanner)
{
Title = title;
MetaDescription = metaDescription;
BackgroundImage = backgroundImage;
FeaturedGroupsHeading = featuredGroupsHeading;
FeaturedGroups = featuredGroups;
FeaturedGroupsCategory = featuredGroupsCategory;
FeaturedGroupsSubCategory = featuredGroupsSubCategory;
Alerts = alerts;
BodyHeading = bodyHeading;
Body = body;
SecondaryBodyHeading = secondaryBodyHeading;
SecondaryBody = secondaryBody;
EventBanner = eventBanner;
}
}
}
| mit | C# |
97e84e0a020120aa3d5fa745d4c18b416301d114 | fix build issue for windows phone | jamesmontemagno/TextToSpeechPlugin | src/TextToSpeech.Plugin.WinPhone/Properties/AssemblyInfo.cs | src/TextToSpeech.Plugin.WinPhone/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Plugin.TextToSpeech.WinPhone")]
[assembly: AssemblyDescription("")]
[assembly: ComVisible(false)]
[assembly: Guid("6ec1bd3c-a012-4a77-9f1d-bd1347953524")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Resources;
[assembly: AssemblyTitle("Plugin.TextToSpeech.WinPhone")]
[assembly: AssemblyDescription("")]
[assembly: ComVisible(false)]
[assembly: Guid("6ec1bd3c-a012-4a77-9f1d-bd1347953524")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
| mit | C# |
e51b296796b36b819372d1b1c53fe1acbd576d3a | Test for properties column filtering | serilog/serilog-sinks-mssqlserver | test/Serilog.Sinks.MSSqlServer.Tests/TestPropertiesColumnFiltering.cs | test/Serilog.Sinks.MSSqlServer.Tests/TestPropertiesColumnFiltering.cs | using Dapper;
using FluentAssertions;
using System.Data.SqlClient;
using Xunit;
namespace Serilog.Sinks.MSSqlServer.Tests
{
[Collection("LogTest")]
public class TestPropertiesColumnFiltering
{
internal class PropertiesColumns
{
public string Properties { get; set; }
}
[Fact]
public void FilteredProperties()
{
// arrange
var columnOptions = new ColumnOptions();
columnOptions.Properties.PropertiesFilter = (propName) => propName == "A";
Log.Logger = new LoggerConfiguration()
.WriteTo.MSSqlServer
(
connectionString: DatabaseFixture.LogEventsConnectionString,
tableName: DatabaseFixture.LogTableName,
columnOptions: columnOptions,
autoCreateSqlTable: true
)
.CreateLogger();
// act
Log.Logger
.ForContext("A", "AValue")
.ForContext("B", "BValue")
.Information("Logging message");
Log.CloseAndFlush();
// assert
using (var conn = new SqlConnection(DatabaseFixture.LogEventsConnectionString))
{
var logEvents = conn.Query<PropertiesColumns>($"SELECT Properties from {DatabaseFixture.LogTableName}");
logEvents.Should().Contain(e => e.Properties.Contains("AValue"));
logEvents.Should().NotContain(e => e.Properties.Contains("BValue"));
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
namespace Serilog.Sinks.MSSqlServer.Tests
{
class TestPropertiesColumnFiltering
{
}
}
| apache-2.0 | C# |
c284ed92b2584786ceb53fc8d0dd8e7d19da9180 | rename member | json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core | src/JsonApiDotNetCore/Hooks/Execution/UpdatedRelationshipHelper.cs | src/JsonApiDotNetCore/Hooks/Execution/UpdatedRelationshipHelper.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JsonApiDotNetCore.Models;
namespace JsonApiDotNetCore.Hooks
{
public interface IAffectedRelationships { }
/// <summary>
/// A helper class that provides insights in which relationships have been updated for which entities.
/// </summary>
public interface IAffectedRelationships<TDependent> : IAffectedRelationships where TDependent : class, IIdentifiable
{
/// <summary>
/// Gets a dictionary of all entities grouped by affected relationship.
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> All { get; }
/// <summary>
/// Gets a dictionary of all entities that have an affected relationship to type <typeparamref name="TPrincipal"/>
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship<TPrincipal>() where TPrincipal : class, IIdentifiable;
/// <summary>
/// Gets a dictionary of all entities that have an affected relationship to type <paramref name="principalType"/>
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship(Type principalType);
}
public class UpdatedRelationshipHelper<TDependent> : IAffectedRelationships<TDependent> where TDependent : class, IIdentifiable
{
private readonly Dictionary<RelationshipProxy, HashSet<TDependent>> _groups;
public Dictionary<RelationshipAttribute, HashSet<TDependent>> All
{
get { return _groups?.ToDictionary(p => p.Key.Attribute, p => p.Value); }
}
public UpdatedRelationshipHelper(Dictionary<RelationshipProxy, IEnumerable> relationships)
{
_groups = relationships.ToDictionary(kvp => kvp.Key, kvp => new HashSet<TDependent>((IEnumerable<TDependent>)kvp.Value));
}
public Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship<TPrincipal>() where TPrincipal : class, IIdentifiable
{
return GetByRelationship(typeof(TPrincipal));
}
public Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship(Type principalType)
{
return _groups?.Where(p => p.Key.PrincipalType == principalType).ToDictionary(p => p.Key.Attribute, p => p.Value);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using JsonApiDotNetCore.Models;
namespace JsonApiDotNetCore.Hooks
{
public interface IAffectedRelationships { }
/// <summary>
/// A helper class that provides insights in which relationships have been updated for which entities.
/// </summary>
public interface IAffectedRelationships<TDependent> : IAffectedRelationships where TDependent : class, IIdentifiable
{
/// <summary>
/// Gets a dictionary of all entities grouped by affected relationship.
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> GetAll { get; }
/// <summary>
/// Gets a dictionary of all entities that have an affected relationship to type <typeparamref name="TPrincipal"/>
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship<TPrincipal>() where TPrincipal : class, IIdentifiable;
/// <summary>
/// Gets a dictionary of all entities that have an affected relationship to type <paramref name="principalType"/>
/// </summary>
Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship(Type principalType);
}
public class UpdatedRelationshipHelper<TDependent> : IAffectedRelationships<TDependent> where TDependent : class, IIdentifiable
{
private readonly Dictionary<RelationshipProxy, HashSet<TDependent>> _groups;
public Dictionary<RelationshipAttribute, HashSet<TDependent>> GetAll
{
get { return _groups?.ToDictionary(p => p.Key.Attribute, p => p.Value); }
}
public UpdatedRelationshipHelper(Dictionary<RelationshipProxy, IEnumerable> relationships)
{
_groups = relationships.ToDictionary(kvp => kvp.Key, kvp => new HashSet<TDependent>((IEnumerable<TDependent>)kvp.Value));
}
public Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship<TPrincipal>() where TPrincipal : class, IIdentifiable
{
return GetByRelationship(typeof(TPrincipal));
}
public Dictionary<RelationshipAttribute, HashSet<TDependent>> GetByRelationship(Type principalType)
{
return _groups?.Where(p => p.Key.PrincipalType == principalType).ToDictionary(p => p.Key.Attribute, p => p.Value);
}
}
}
| mit | C# |
f83f6bcae7a6a7e57da9c5aa7da477cdf135898c | Fix StatisticLogAggregator | abock/roslyn,gafter/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,nguerrera/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,brettfo/roslyn,tmat/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,jmarolf/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,davkean/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,mavasani/roslyn,wvdd007/roslyn,AmadeusW/roslyn,abock/roslyn,weltkante/roslyn,brettfo/roslyn,heejaechang/roslyn,davkean/roslyn,diryboy/roslyn,tannergooding/roslyn,genlu/roslyn,eriawan/roslyn,reaction1989/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,gafter/roslyn,mavasani/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,weltkante/roslyn,KevinRansom/roslyn,aelij/roslyn,diryboy/roslyn,davkean/roslyn,gafter/roslyn,heejaechang/roslyn,abock/roslyn,agocke/roslyn,genlu/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,tannergooding/roslyn,heejaechang/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,weltkante/roslyn,panopticoncentral/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,wvdd007/roslyn,sharwell/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,nguerrera/roslyn,tmat/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,wvdd007/roslyn,eriawan/roslyn,nguerrera/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,dotnet/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,agocke/roslyn,ErikSchierboom/roslyn,reaction1989/roslyn,physhi/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,physhi/roslyn,dotnet/roslyn,jmarolf/roslyn,stephentoub/roslyn,AmadeusW/roslyn,tmat/roslyn,aelij/roslyn,sharwell/roslyn | src/Workspaces/Core/Portable/Log/StatisticLogAggregator.cs | src/Workspaces/Core/Portable/Log/StatisticLogAggregator.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
if (_count == 0 || value > _maximum)
{
_maximum = value;
}
if (_count == 0 || value < _mininum)
{
_mininum = value;
}
_count++;
_total += value;
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Internal.Log
{
internal sealed class StatisticLogAggregator : AbstractLogAggregator<StatisticLogAggregator.StatisticCounter>
{
protected override StatisticCounter CreateCounter()
{
return new StatisticCounter();
}
public void AddDataPoint(object key, int value)
{
var counter = GetCounter(key);
counter.AddDataPoint(value);
}
public StatisticResult GetStaticticResult(object key)
{
if (TryGetCounter(key, out var counter))
{
return counter.GetStatisticResult();
}
return default;
}
internal sealed class StatisticCounter
{
private int _count;
private int _maximum;
private int _mininum;
private int _total;
public void AddDataPoint(int value)
{
_count++;
_total += value;
if (value > _maximum)
{
_maximum = value;
}
if (value < _mininum)
{
_mininum = value;
}
}
public StatisticResult GetStatisticResult()
{
if (_count == 0)
{
return default;
}
else
{
return new StatisticResult(_maximum, _mininum, median: null, mean: _total / _count, range: _maximum - _mininum, mode: null, count: _count);
}
}
}
}
}
| mit | C# |
3cd5c5c666ee724d49e1f65b67ce929aea7b5e40 | Remove tagbase include and make image protocol relative | rhysgodfrey/trello-cfd,rhysgodfrey/trello-cfd,rhysgodfrey/trello-cfd | TrelloCFD.Website/Views/Home/Index.cshtml | TrelloCFD.Website/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome!</h1>
<h2>Login with your Trello account using the link above to get started.</h2>
</hgroup>
<p>
Quickly create Cumulative Flow Diagrams of the movement of cards through <a href="http://trello.com">Trello</a> boards.
After Logging in with your Trello account, you'll be presented with a list of your boards, simply
choose one to see the Cumulative Flow Diagram.
</p>
<p>
If you have any suggestions, or spot any issues @Html.ActionLink("add them to Trello", "IdeasAndBugs", "Home")
</p>
</div>
</section>
}
<h3>How to use Trello Cumulative Flow?</h3>
<div class="howToUse clear-fix">
<div class="howToUseStep">
<h4>1. Login with your Trello account</h4>
<img src="@Url.Content("~/Content/Images/trellologin.png")" alt="Log in with Trello" />
</div>
<div class="howToUseStep howToUseStepEven">
<h4>2. Select a board</h4>
<img src="@Url.Content("~/Content/Images/boardList.png")" alt="Select a board" />
</div>
<div class="howToUseStep">
<h4>3. View your Cumulative Flow Diagram</h4>
<img src="@Url.Content("~/Content/Images/example1.png")" alt="View your chart" />
</div>
<div class="howToUseStep howToUseStepEven">
<h4>4. Look for bottlenecks</h4>
<div class="tb_imageWrapper" id="tb_d754186c-201d-4b49-bb8a-12c9f5e4422a" style="width:400px; height: 167px;"><img src="//trello-cfd.azurewebsites.net/content/images/example2.png" alt="example2.png" /></div>
</div>
</div>
| @{
ViewBag.Title = "Home";
}
@section featured {
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1>Welcome!</h1>
<h2>Login with your Trello account using the link above to get started.</h2>
</hgroup>
<p>
Quickly create Cumulative Flow Diagrams of the movement of cards through <a href="http://trello.com">Trello</a> boards.
After Logging in with your Trello account, you'll be presented with a list of your boards, simply
choose one to see the Cumulative Flow Diagram.
</p>
<p>
If you have any suggestions, or spot any issues @Html.ActionLink("add them to Trello", "IdeasAndBugs", "Home")
</p>
</div>
</section>
}
<h3>How to use Trello Cumulative Flow?</h3>
<div class="howToUse clear-fix">
<div class="howToUseStep">
<h4>1. Login with your Trello account</h4>
<img src="@Url.Content("~/Content/Images/trellologin.png")" alt="Log in with Trello" />
</div>
<div class="howToUseStep howToUseStepEven">
<h4>2. Select a board</h4>
<img src="@Url.Content("~/Content/Images/boardList.png")" alt="Select a board" />
</div>
<div class="howToUseStep">
<h4>3. View your Cumulative Flow Diagram</h4>
<img src="@Url.Content("~/Content/Images/example1.png")" alt="View your chart" />
</div>
<div class="howToUseStep howToUseStepEven">
<h4>4. Look for bottlenecks</h4>
<div class="tb_imageWrapper" id="tb_d754186c-201d-4b49-bb8a-12c9f5e4422a" style="width:400px; height: 167px;"><img src="http://trello-cfd.azurewebsites.net/content/images/example2.png" alt="example2.png" /></div>
<script type="text/javascript">
(function () {
var tbCore = ('https:' == document.location.protocol ? 'https://tagbase.blob.core.windows.net' : 'http://s.tagba.se') + '/scripts/TagbaseCore.js';
var tbInstance = ('https:' == document.location.protocol ? 'https://www.mytagbase.com' : 'http://d.tagba.se') + '/scripts/Include/d754186c-201d-4b49-bb8a-12c9f5e4422a';
document.write('<scr' + 'ipt type="text/javascript" src="' + tbCore + '"></sc' + 'ript>');
document.write('<scr' + 'ipt type="text/javascript" src="' + tbInstance + '"></sc' + 'ript>');
})();
</script>
</div>
</div>
| bsd-2-clause | C# |
d65e990f179ab858c0af0a172da9839f5a3167cb | Implement SurfaceDescription structure | alesliehughes/monoDX,alesliehughes/monoDX | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/SurfaceDescription.cs | Microsoft.DirectX.Direct3D/Microsoft.DirectX.Direct3D/SurfaceDescription.cs | /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Microsoft.DirectX.Direct3D
{
[Serializable]
public struct SurfaceDescription
{
internal int mHeight;
internal int mWidth;
internal int mMultiSampleQuality;
internal MultiSampleType mMultiSampleType;
internal Pool mMemoryPool;
internal Usage mUsage;
internal ResourceType mType;
internal Format mFormat;
public int Height
{
get
{
return mHeight;
}
set
{
mHeight = value;
}
}
public int Width
{
get
{
return mWidth;
}
set
{
mWidth = value;
}
}
public int MultiSampleQuality
{
get
{
return mMultiSampleQuality;
}
set
{
mMultiSampleQuality = value;
}
}
public MultiSampleType MultiSampleType
{
get
{
return mMultiSampleType;
}
set
{
mMultiSampleType = value;
}
}
public Pool MemoryPool
{
get
{
return mMemoryPool;
}
set
{
mMemoryPool = value;
}
}
public Usage Usage
{
get
{
return mUsage;
}
set
{
mUsage = value;
}
}
public ResourceType Type
{
get
{
return mType;
}
set
{
mType = value;
}
}
public Format Format
{
get
{
return mFormat;
}
set
{
mFormat = value;
}
}
public override string ToString()
{
throw new NotImplementedException ();
}
}
}
| /*
* The MIT License (MIT)
*
* Copyright (c) 2013 Alistair Leslie-Hughes
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Microsoft.DirectX.Direct3D
{
[Serializable]
public struct SurfaceDescription
{
public int Height
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public int Width
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public int MultiSampleQuality
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public MultiSampleType MultiSampleType
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public Pool MemoryPool
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public Usage Usage
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public ResourceType Type
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public Format Format
{
get
{
throw new NotImplementedException ();
}
set
{
throw new NotImplementedException ();
}
}
public override string ToString()
{
throw new NotImplementedException ();
}
}
}
| mit | C# |
c3e77a296f62b1d5a1a8f8ecd5889af39a611241 | Remove exception test | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade/Core/TestEngineFactory.cs | src/Arkivverket.Arkade/Core/TestEngineFactory.cs | using System;
using Arkivverket.Arkade.Core.Addml;
using Serilog;
namespace Arkivverket.Arkade.Core
{
public class TestEngineFactory
{
private readonly ILogger _log = Log.ForContext<TestEngineFactory>();
private readonly TestEngine _noark5TestEngine;
private readonly AddmlDatasetTestEngine _addmlDatasetTestEngine;
public TestEngineFactory(TestEngine noark5TestEngine, AddmlDatasetTestEngine addmlDatasetTestEngine)
{
_noark5TestEngine = noark5TestEngine;
_addmlDatasetTestEngine = addmlDatasetTestEngine;
}
public ITestEngine GetTestEngine(TestSession testSession)
{
_log.Debug("Find test engine for archive {archiveType}", testSession.Archive.ArchiveType);
if (testSession.Archive.ArchiveType == ArchiveType.Noark5)
{
return _noark5TestEngine;
}
else
{
return _addmlDatasetTestEngine;
}
}
}
}
| using System;
using Arkivverket.Arkade.Core.Addml;
using Serilog;
namespace Arkivverket.Arkade.Core
{
public class TestEngineFactory
{
private readonly ILogger _log = Log.ForContext<TestEngineFactory>();
private readonly TestEngine _noark5TestEngine;
private readonly AddmlDatasetTestEngine _addmlDatasetTestEngine;
public TestEngineFactory(TestEngine noark5TestEngine, AddmlDatasetTestEngine addmlDatasetTestEngine)
{
_noark5TestEngine = noark5TestEngine;
_addmlDatasetTestEngine = addmlDatasetTestEngine;
}
public ITestEngine GetTestEngine(TestSession testSession)
{
_log.Debug("Find test engine for archive {archiveType}", testSession.Archive.ArchiveType);
throw new Exception("hepp hopp");
if (testSession.Archive.ArchiveType == ArchiveType.Noark5)
{
return _noark5TestEngine;
}
else
{
return _addmlDatasetTestEngine;
}
}
}
}
| agpl-3.0 | C# |
f5880e3d183b04ff0f47ea548a9371b20b5403bb | make fields readonly. | shyamnamboodiripad/roslyn,abock/roslyn,agocke/roslyn,weltkante/roslyn,tvand7093/roslyn,khyperia/roslyn,xasx/roslyn,wvdd007/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,xasx/roslyn,panopticoncentral/roslyn,akrisiun/roslyn,swaroop-sridhar/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,tannergooding/roslyn,nguerrera/roslyn,KevinRansom/roslyn,cston/roslyn,zooba/roslyn,jcouv/roslyn,jamesqo/roslyn,genlu/roslyn,TyOverby/roslyn,DustinCampbell/roslyn,shyamnamboodiripad/roslyn,drognanar/roslyn,tannergooding/roslyn,jeffanders/roslyn,zooba/roslyn,AnthonyDGreen/roslyn,paulvanbrenk/roslyn,tmat/roslyn,sharwell/roslyn,lorcanmooney/roslyn,bkoelman/roslyn,bkoelman/roslyn,reaction1989/roslyn,davkean/roslyn,aelij/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,tmeschter/roslyn,mmitche/roslyn,jamesqo/roslyn,ErikSchierboom/roslyn,paulvanbrenk/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,pdelvo/roslyn,reaction1989/roslyn,pdelvo/roslyn,dpoeschl/roslyn,agocke/roslyn,physhi/roslyn,gafter/roslyn,ErikSchierboom/roslyn,jkotas/roslyn,ErikSchierboom/roslyn,pdelvo/roslyn,yeaicc/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,bartdesmet/roslyn,Giftednewt/roslyn,orthoxerox/roslyn,aelij/roslyn,mattscheffer/roslyn,mmitche/roslyn,aelij/roslyn,shyamnamboodiripad/roslyn,gafter/roslyn,DustinCampbell/roslyn,yeaicc/roslyn,jcouv/roslyn,orthoxerox/roslyn,physhi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,KevinRansom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MichalStrehovsky/roslyn,genlu/roslyn,Hosch250/roslyn,lorcanmooney/roslyn,abock/roslyn,amcasey/roslyn,sharwell/roslyn,brettfo/roslyn,jmarolf/roslyn,xasx/roslyn,mgoertz-msft/roslyn,srivatsn/roslyn,diryboy/roslyn,tvand7093/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,OmarTawfik/roslyn,DustinCampbell/roslyn,Giftednewt/roslyn,mavasani/roslyn,dotnet/roslyn,paulvanbrenk/roslyn,dotnet/roslyn,lorcanmooney/roslyn,tvand7093/roslyn,nguerrera/roslyn,stephentoub/roslyn,CaptainHayashi/roslyn,Hosch250/roslyn,OmarTawfik/roslyn,genlu/roslyn,robinsedlaczek/roslyn,robinsedlaczek/roslyn,jeffanders/roslyn,gafter/roslyn,AmadeusW/roslyn,tannergooding/roslyn,heejaechang/roslyn,akrisiun/roslyn,cston/roslyn,jeffanders/roslyn,akrisiun/roslyn,drognanar/roslyn,jkotas/roslyn,davkean/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,tmeschter/roslyn,eriawan/roslyn,tmat/roslyn,sharwell/roslyn,cston/roslyn,abock/roslyn,kelltrick/roslyn,OmarTawfik/roslyn,MichalStrehovsky/roslyn,robinsedlaczek/roslyn,mattwar/roslyn,jamesqo/roslyn,yeaicc/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,jkotas/roslyn,drognanar/roslyn,eriawan/roslyn,wvdd007/roslyn,TyOverby/roslyn,agocke/roslyn,VSadov/roslyn,brettfo/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,diryboy/roslyn,panopticoncentral/roslyn,MattWindsor91/roslyn,Hosch250/roslyn,orthoxerox/roslyn,stephentoub/roslyn,diryboy/roslyn,mmitche/roslyn,VSadov/roslyn,eriawan/roslyn,heejaechang/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,wvdd007/roslyn,khyperia/roslyn,dotnet/roslyn,mavasani/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,mattscheffer/roslyn,CaptainHayashi/roslyn,CyrusNajmabadi/roslyn,khyperia/roslyn,srivatsn/roslyn,TyOverby/roslyn,AnthonyDGreen/roslyn,CaptainHayashi/roslyn,kelltrick/roslyn,tmat/roslyn,dpoeschl/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,bkoelman/roslyn,physhi/roslyn,swaroop-sridhar/roslyn,amcasey/roslyn,AlekseyTs/roslyn,MattWindsor91/roslyn,weltkante/roslyn,mattwar/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,bartdesmet/roslyn,mavasani/roslyn,zooba/roslyn,VSadov/roslyn,mattwar/roslyn,stephentoub/roslyn,AnthonyDGreen/roslyn,heejaechang/roslyn,amcasey/roslyn,tmeschter/roslyn,MattWindsor91/roslyn,srivatsn/roslyn,kelltrick/roslyn,KirillOsenkov/roslyn | src/Compilers/Core/Portable/Serialization/ObjectBinderState.cs | src/Compilers/Core/Portable/Serialization/ObjectBinderState.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Roslyn.Utilities
{
internal struct ObjectBinderState
{
public readonly int Version;
private readonly Dictionary<Type, int> _typeToIndex;
private readonly ImmutableArray<Type> _types;
private readonly ImmutableArray<Func<ObjectReader, object>> _typeReaders;
public ObjectBinderState(
int version,
Dictionary<Type, int> typeToIndex,
ImmutableArray<Type> types,
ImmutableArray<Func<ObjectReader, object>> typeReaders)
{
Version = version;
_typeToIndex = typeToIndex;
_types = types;
_typeReaders = typeReaders;
}
public int GetTypeId(Type type)
=> _typeToIndex[type];
public Type GetTypeFromId(int typeId)
=> _types[typeId];
public Func<ObjectReader, object> GetTypeReaderFromId(int typeId)
=> _typeReaders[typeId];
}
} | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace Roslyn.Utilities
{
internal struct ObjectBinderState
{
public readonly int Version;
private readonly Dictionary<Type, int> _typeToIndex;
private ImmutableArray<Type> _types;
private ImmutableArray<Func<ObjectReader, object>> _typeReaders;
public ObjectBinderState(
int version,
Dictionary<Type, int> typeToIndex,
ImmutableArray<Type> types,
ImmutableArray<Func<ObjectReader, object>> typeReaders)
{
Version = version;
_typeToIndex = typeToIndex;
_types = types;
_typeReaders = typeReaders;
}
public int GetTypeId(Type type)
=> _typeToIndex[type];
public Type GetTypeFromId(int typeId)
=> _types[typeId];
public Func<ObjectReader, object> GetTypeReaderFromId(int typeId)
=> _typeReaders[typeId];
}
} | mit | C# |
795f5dfa2d483cf36f0f17299700d1a80ac8037e | Add Newline at String Start | AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning,AArnott/Nerdbank.GitVersioning | src/NerdBank.GitVersioning/CloudBuildServices/GitHubActions.cs | src/NerdBank.GitVersioning/CloudBuildServices/GitHubActions.cs | namespace NerdBank.GitVersioning.CloudBuildServices
{
using System;
using System.Collections.Generic;
using System.IO;
using Nerdbank.GitVersioning;
internal class GitHubActions : ICloudBuild
{
public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";
public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;
public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;
public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");
private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");
private static string EnvironmentFile => Environment.GetEnvironmentVariable("GITHUB_ENV");
public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
{
return new Dictionary<string, string>();
}
public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
{
File.AppendAllText(EnvironmentFile, $"{Environment.NewLine}{name}={value}{Environment.NewLine}");
return GetDictionaryFor(name, value);
}
private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ GetEnvironmentVariableNameForVariable(variableName), value },
};
}
private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_');
}
}
| namespace NerdBank.GitVersioning.CloudBuildServices
{
using System;
using System.Collections.Generic;
using System.IO;
using Nerdbank.GitVersioning;
internal class GitHubActions : ICloudBuild
{
public bool IsApplicable => Environment.GetEnvironmentVariable("GITHUB_ACTIONS") == "true";
public bool IsPullRequest => Environment.GetEnvironmentVariable("GITHUB_EVENT_NAME") == "PullRequestEvent";
public string BuildingBranch => (BuildingRef?.StartsWith("refs/heads/") ?? false) ? BuildingRef : null;
public string BuildingTag => (BuildingRef?.StartsWith("refs/tags/") ?? false) ? BuildingRef : null;
public string GitCommitId => Environment.GetEnvironmentVariable("GITHUB_SHA");
private static string BuildingRef => Environment.GetEnvironmentVariable("GITHUB_REF");
private static string EnvironmentFile => Environment.GetEnvironmentVariable("GITHUB_ENV");
public IReadOnlyDictionary<string, string> SetCloudBuildNumber(string buildNumber, TextWriter stdout, TextWriter stderr)
{
return new Dictionary<string, string>();
}
public IReadOnlyDictionary<string, string> SetCloudBuildVariable(string name, string value, TextWriter stdout, TextWriter stderr)
{
File.AppendAllText(EnvironmentFile, $"{name}={value}{Environment.NewLine}");
return GetDictionaryFor(name, value);
}
private static IReadOnlyDictionary<string, string> GetDictionaryFor(string variableName, string value)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ GetEnvironmentVariableNameForVariable(variableName), value },
};
}
private static string GetEnvironmentVariableNameForVariable(string name) => name.ToUpperInvariant().Replace('.', '_');
}
}
| mit | C# |
e2b65806299941a33df007dc7d16ee8f32e35942 | Update BasketController.cs | andrelmp/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,albertodall/eShopOnContainers,skynode/eShopOnContainers,skynode/eShopOnContainers,BillWagner/eShopOnContainers,BillWagner/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers,albertodall/eShopOnContainers,andrelmp/eShopOnContainers,productinfo/eShopOnContainers,andrelmp/eShopOnContainers,BillWagner/eShopOnContainers,dotnet-architecture/eShopOnContainers,albertodall/eShopOnContainers,dotnet-architecture/eShopOnContainers,BillWagner/eShopOnContainers,albertodall/eShopOnContainers,BillWagner/eShopOnContainers,dotnet-architecture/eShopOnContainers,skynode/eShopOnContainers,TypeW/eShopOnContainers,TypeW/eShopOnContainers,productinfo/eShopOnContainers,TypeW/eShopOnContainers,dotnet-architecture/eShopOnContainers,andrelmp/eShopOnContainers | src/Services/Basket/Basket.API/Controllers/BasketController.cs | src/Services/Basket/Basket.API/Controllers/BasketController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.AspNetCore.Authorization;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
{
[Route("/")]
[Authorize]
public class BasketController : Controller
{
private IBasketRepository _repository;
public BasketController(IBasketRepository repository)
{
_repository = repository;
}
// GET /id
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var basket = await _repository.GetBasketAsync(id);
return Ok(basket);
}
// POST /value
[HttpPost]
public async Task<IActionResult> Post([FromBody]CustomerBasket value)
{
var basket = await _repository.UpdateBasketAsync(value);
return Ok(basket);
}
// DELETE /id
[HttpDelete("{id}")]
public void Delete(string id)
{
_repository.DeleteBasketAsync(id);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.AspNetCore.Authorization;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Controllers
{
[Route("/")]
[Authorize]
public class BasketController : Controller
{
private IBasketRepository _repository;
public BasketController(IBasketRepository repository)
{
_repository = repository;
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<IActionResult> Get(string id)
{
var basket = await _repository.GetBasketAsync(id);
return Ok(basket);
}
// POST api/values
[HttpPost]
public async Task<IActionResult> Post([FromBody]CustomerBasket value)
{
var basket = await _repository.UpdateBasketAsync(value);
return Ok(basket);
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(string id)
{
_repository.DeleteBasketAsync(id);
}
}
}
| mit | C# |
249b3b8609b70cad305e7accffe6b2f0203ad3ca | Update XML documentation | bjarnef/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS | src/Umbraco.Core/PropertyEditors/PropertyValueConverterBase.cs | src/Umbraco.Core/PropertyEditors/PropertyValueConverterBase.cs | using System;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// Provides a default implementation for <see cref="IPropertyValueConverter" />.
/// </summary>
/// <seealso cref="Umbraco.Core.PropertyEditors.IPropertyValueConverter" />
public abstract class PropertyValueConverterBase : IPropertyValueConverter
{
/// <inheritdoc />
public virtual bool IsConverter(IPublishedPropertyType propertyType)
=> false;
/// <inheritdoc />
public virtual bool? IsValue(object value, PropertyValueLevel level)
{
switch (level)
{
case PropertyValueLevel.Source:
// the default implementation uses the old magic null & string comparisons,
// other implementations may be more clever, and/or test the final converted object values
return value != null && (!(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue));
case PropertyValueLevel.Inter:
return null;
case PropertyValueLevel.Object:
return null;
default:
throw new NotSupportedException($"Invalid level: {level}.");
}
}
[Obsolete("This method is not part of the IPropertyValueConverter contract and therefore not used, use IsValue instead.")]
public virtual bool HasValue(IPublishedProperty property, string culture, string segment)
{
var value = property.GetSourceValue(culture, segment);
return value != null && (!(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue));
}
/// <inheritdoc />
public virtual Type GetPropertyValueType(IPublishedPropertyType propertyType)
=> typeof(object);
/// <inheritdoc />
public virtual PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> PropertyCacheLevel.Snapshot;
/// <inheritdoc />
public virtual object ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview)
=> source;
/// <inheritdoc />
public virtual object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
=> inter;
/// <inheritdoc />
public virtual object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
=> inter?.ToString() ?? string.Empty;
}
}
| using System;
using Umbraco.Core.Models.PublishedContent;
namespace Umbraco.Core.PropertyEditors
{
/// <summary>
/// Provides a default overridable implementation for <see cref="IPropertyValueConverter"/> that does nothing.
/// </summary>
public abstract class PropertyValueConverterBase : IPropertyValueConverter
{
public virtual bool IsConverter(IPublishedPropertyType propertyType)
=> false;
public virtual bool? IsValue(object value, PropertyValueLevel level)
{
switch (level)
{
case PropertyValueLevel.Source:
// the default implementation uses the old magic null & string comparisons,
// other implementations may be more clever, and/or test the final converted object values
return value != null && (!(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue));
case PropertyValueLevel.Inter:
return null;
case PropertyValueLevel.Object:
return null;
default:
throw new NotSupportedException($"Invalid level: {level}.");
}
}
[Obsolete("This method is not part of the IPropertyValueConverter contract and therefore not used, use IsValue instead.")]
public virtual bool HasValue(IPublishedProperty property, string culture, string segment)
{
var value = property.GetSourceValue(culture, segment);
return value != null && (!(value is string stringValue) || !string.IsNullOrWhiteSpace(stringValue));
}
public virtual Type GetPropertyValueType(IPublishedPropertyType propertyType)
=> typeof(object);
public virtual PropertyCacheLevel GetPropertyCacheLevel(IPublishedPropertyType propertyType)
=> PropertyCacheLevel.Snapshot;
public virtual object ConvertSourceToIntermediate(IPublishedElement owner, IPublishedPropertyType propertyType, object source, bool preview)
=> source;
public virtual object ConvertIntermediateToObject(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
=> inter;
public virtual object ConvertIntermediateToXPath(IPublishedElement owner, IPublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview)
=> inter?.ToString() ?? string.Empty;
}
}
| mit | C# |
a710688426aa4b45f60917d4c668120a17411020 | Include messages with Assert.True/False | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/FunctionalTests/CoreCLRTests/RazorSdkUsedTest_CoreCLR.cs | test/FunctionalTests/CoreCLRTests/RazorSdkUsedTest_CoreCLR.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
using Xunit.Abstractions;
namespace FunctionalTests
{
// Tests that cover cases where both Razor SDK and MvcPrecompilation are installed. This is the default in 2.1
public class RazorSdkUsedTest_CoreCLR : LoggedTest, IClassFixture<CoreCLRApplicationTestFixture<ApplicationWithRazorSdkUsed.Startup>>
{
public RazorSdkUsedTest_CoreCLR(
CoreCLRApplicationTestFixture<ApplicationWithRazorSdkUsed.Startup> fixture,
ITestOutputHelper output)
: base(output)
{
Fixture = fixture;
}
public ApplicationTestFixture Fixture { get; }
[Fact]
public async Task Publish_UsesRazorSDK()
{
using (StartLog(out var loggerFactory))
{
// Arrange
var deployment = await Fixture.CreateDeploymentAsync(loggerFactory);
var expectedViewLocation = Path.Combine(deployment.ContentRoot, "ApplicationWithRazorSdkUsed.Views.dll");
var expectedPrecompiledViewsLocation = Path.Combine(deployment.ContentRoot, "ApplicationWithRazorSdkUsed.PrecompiledViews.dll");
// Act
var response = await deployment.HttpClient.GetStringWithRetryAsync(
deployment.ApplicationBaseUri,
loggerFactory.CreateLogger(Fixture.ApplicationName));
// Assert
Assert.False(File.Exists(expectedPrecompiledViewsLocation), $"{expectedPrecompiledViewsLocation} existed, but shouldn't have.");
Assert.True(File.Exists(expectedViewLocation), $"{expectedViewLocation} didn't exist.");
TestEmbeddedResource.AssertContent("ApplicationWithRazorSdkUsed.Home.Index.txt", response);
}
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging.Testing;
using Xunit;
using Xunit.Abstractions;
namespace FunctionalTests
{
// Tests that cover cases where both Razor SDK and MvcPrecompilation are installed. This is the default in 2.1
public class RazorSdkUsedTest_CoreCLR : LoggedTest, IClassFixture<CoreCLRApplicationTestFixture<ApplicationWithRazorSdkUsed.Startup>>
{
public RazorSdkUsedTest_CoreCLR(
CoreCLRApplicationTestFixture<ApplicationWithRazorSdkUsed.Startup> fixture,
ITestOutputHelper output)
: base(output)
{
Fixture = fixture;
}
public ApplicationTestFixture Fixture { get; }
[Fact]
public async Task Publish_UsesRazorSDK()
{
using (StartLog(out var loggerFactory))
{
// Arrange
var deployment = await Fixture.CreateDeploymentAsync(loggerFactory);
// Act
var response = await deployment.HttpClient.GetStringWithRetryAsync(
deployment.ApplicationBaseUri,
loggerFactory.CreateLogger(Fixture.ApplicationName));
// Assert
Assert.False(File.Exists(Path.Combine(deployment.ContentRoot, "ApplicationWithRazorSdkUsed.PrecompiledViews.dll")));
Assert.True(File.Exists(Path.Combine(deployment.ContentRoot, "ApplicationWithRazorSdkUsed.Views.dll")));
TestEmbeddedResource.AssertContent("ApplicationWithRazorSdkUsed.Home.Index.txt", response);
}
}
}
}
| apache-2.0 | C# |
34b3e5c06c955737d3ce41c1d8a6548bbc867c2a | Make sure SQL Server tests don't run in parallel | openchain/openchain | test/Openchain.SqlServer.Tests/SqlServerStorageEngineTests.cs | test/Openchain.SqlServer.Tests/SqlServerStorageEngineTests.cs | // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Data.SqlClient;
using Openchain.Tests;
using Xunit;
namespace Openchain.SqlServer.Tests
{
[Collection("SQL Server Tests")]
public class SqlServerStorageEngineTests : BaseStorageEngineTests
{
private readonly int instanceId;
public SqlServerStorageEngineTests()
{
SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", 1, TimeSpan.FromSeconds(10));
engine.OpenConnection().Wait();
SqlCommand command = engine.Connection.CreateCommand();
command.CommandText = @"
DELETE FROM [Openchain].[RecordMutations];
DELETE FROM [Openchain].[Records];
DELETE FROM [Openchain].[Transactions];
";
command.ExecuteNonQuery();
this.Store = engine;
}
}
}
| // Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Data.SqlClient;
using Openchain.Tests;
namespace Openchain.SqlServer.Tests
{
public class SqlServerStorageEngineTests : BaseStorageEngineTests
{
private readonly int instanceId;
public SqlServerStorageEngineTests()
{
Random rnd = new Random();
this.instanceId = rnd.Next(0, int.MaxValue);
SqlServerStorageEngine engine = new SqlServerStorageEngine("Data Source=.;Initial Catalog=Openchain;Integrated Security=True", this.instanceId, TimeSpan.FromSeconds(10));
engine.OpenConnection().Wait();
SqlCommand command = engine.Connection.CreateCommand();
command.CommandText = @"
DELETE FROM [Openchain].[RecordMutations];
DELETE FROM [Openchain].[Records];
DELETE FROM [Openchain].[Transactions];
";
command.ExecuteNonQuery();
this.Store = engine;
}
}
}
| apache-2.0 | C# |
a6a4628885b60981cb3d96d4d883e350ae15d2c3 | Use ShapeFactory as base class | Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D | Dependencies/ScriptEngine.Roslyn/Roslyn/RoslynScriptGlobals.cs | Dependencies/ScriptEngine.Roslyn/Roslyn/RoslynScriptGlobals.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test2d;
namespace Test2d
{
/// <summary>
///
/// </summary>
public class RoslynScriptGlobals : ShapeFactory
{
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test2d;
namespace Test2d
{
/// <summary>
///
/// </summary>
public class RoslynScriptGlobals
{
/// <summary>
///
/// </summary>
public EditorContext Context;
}
}
| mit | C# |
719228d35eee3be8dfb8946b0761c90c9d2fc77c | add parse to avaloniaxamlloader | wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,Perspex/Perspex,grokys/Perspex,Perspex/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jazzay/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex | src/Markup/Avalonia.Markup.Xaml/AvaloniaXamlLoader.cs | src/Markup/Avalonia.Markup.Xaml/AvaloniaXamlLoader.cs | namespace Avalonia.Markup.Xaml
{
public class AvaloniaXamlLoader :
#if OMNIXAML
AvaloniaXamlLoaderOmniXaml
#else
AvaloniaXamlLoaderPortableXaml
#endif
{
public static object Parse(string xaml)
=> new AvaloniaXamlLoader().Load(xaml);
public static T Parse<T>(string xaml)
=> (T)Parse(xaml);
}
} | namespace Avalonia.Markup.Xaml
{
public class AvaloniaXamlLoader :
#if OMNIXAML
AvaloniaXamlLoaderOmniXaml
#else
AvaloniaXamlLoaderPortableXaml
#endif
{
}
} | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.