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 |
---|---|---|---|---|---|---|---|---|
7381399502476ca5813685772fbae22a82d34b64
|
Apply expression bodied functions convention
|
shaynevanasperen/Data.Operations,shaynevanasperen/Magneto
|
src/Magneto/Dispatcher.cs
|
src/Magneto/Dispatcher.cs
|
using System;
using System.Threading.Tasks;
namespace Magneto
{
/// <summary>
/// If using an IoC container, it is highly recommended that this be registered as a scoped service
/// so that the injected <see cref="IServiceProvider"/> is scoped appropriately.
/// </summary>
public class Dispatcher : IDispatcher
{
public Dispatcher(IServiceProvider serviceProvider, IInvoker invoker)
{
ServiceProvider = serviceProvider;
Invoker = invoker;
}
protected IServiceProvider ServiceProvider { get; }
protected IInvoker Invoker { get; }
protected virtual TContext GetContext<TContext>() =>
(TContext)ServiceProvider.GetService(typeof(TContext));
public virtual TResult Query<TContext, TResult>(ISyncQuery<TContext, TResult> query) =>
Invoker.Query(query, GetContext<TContext>());
public virtual Task<TResult> QueryAsync<TContext, TResult>(IAsyncQuery<TContext, TResult> query) =>
Invoker.QueryAsync(query, GetContext<TContext>());
public virtual TResult Query<TContext, TResult, TCacheEntryOptions>(ISyncCachedQuery<TContext, TCacheEntryOptions, TResult> query, CacheOption cacheOption = CacheOption.Default) =>
Invoker.Query(query, GetContext<TContext>(), cacheOption);
public virtual Task<TResult> QueryAsync<TContext, TResult, TCacheEntryOptions>(IAsyncCachedQuery<TContext, TCacheEntryOptions, TResult> query, CacheOption cacheOption = CacheOption.Default) =>
Invoker.QueryAsync(query, GetContext<TContext>(), cacheOption);
public virtual void EvictCachedResult<TCacheEntryOptions>(ISyncCachedQuery<TCacheEntryOptions> query) =>
Invoker.EvictCachedResult(query);
public virtual Task EvictCachedResultAsync<TCacheEntryOptions>(IAsyncCachedQuery<TCacheEntryOptions> query) =>
Invoker.EvictCachedResultAsync(query);
public virtual void UpdateCachedResult<TCacheEntryOptions>(ISyncCachedQuery<TCacheEntryOptions> executedQuery) =>
Invoker.UpdateCachedResult(executedQuery);
public virtual Task UpdateCachedResultAsync<TCacheEntryOptions>(IAsyncCachedQuery<TCacheEntryOptions> executedQuery) =>
Invoker.UpdateCachedResultAsync(executedQuery);
public virtual void Command<TContext>(ISyncCommand<TContext> command) =>
Invoker.Command(command, GetContext<TContext>());
public virtual Task CommandAsync<TContext>(IAsyncCommand<TContext> command) =>
Invoker.CommandAsync(command, GetContext<TContext>());
public virtual TResult Command<TContext, TResult>(ISyncCommand<TContext, TResult> command) =>
Invoker.Command(command, GetContext<TContext>());
public virtual Task<TResult> CommandAsync<TContext, TResult>(IAsyncCommand<TContext, TResult> command) =>
Invoker.CommandAsync(command, GetContext<TContext>());
}
}
|
using System;
using System.Threading.Tasks;
namespace Magneto
{
/// <summary>
/// If using an IoC container, it is highly recommended that this be registered as a scoped service
/// so that the injected <see cref="IServiceProvider"/> is scoped appropriately.
/// </summary>
public class Dispatcher : IDispatcher
{
public Dispatcher(IServiceProvider serviceProvider, IInvoker invoker)
{
ServiceProvider = serviceProvider;
Invoker = invoker;
}
protected IServiceProvider ServiceProvider { get; }
protected IInvoker Invoker { get; }
protected virtual TContext GetContext<TContext>()
=> (TContext)ServiceProvider.GetService(typeof(TContext));
public virtual TResult Query<TContext, TResult>(ISyncQuery<TContext, TResult> query)
=> Invoker.Query(query, GetContext<TContext>());
public virtual Task<TResult> QueryAsync<TContext, TResult>(IAsyncQuery<TContext, TResult> query)
=> Invoker.QueryAsync(query, GetContext<TContext>());
public virtual TResult Query<TContext, TResult, TCacheEntryOptions>(ISyncCachedQuery<TContext, TCacheEntryOptions, TResult> query, CacheOption cacheOption = CacheOption.Default)
=> Invoker.Query(query, GetContext<TContext>(), cacheOption);
public virtual Task<TResult> QueryAsync<TContext, TResult, TCacheEntryOptions>(IAsyncCachedQuery<TContext, TCacheEntryOptions, TResult> query, CacheOption cacheOption = CacheOption.Default)
=> Invoker.QueryAsync(query, GetContext<TContext>(), cacheOption);
public virtual void EvictCachedResult<TCacheEntryOptions>(ISyncCachedQuery<TCacheEntryOptions> query)
=> Invoker.EvictCachedResult(query);
public virtual Task EvictCachedResultAsync<TCacheEntryOptions>(IAsyncCachedQuery<TCacheEntryOptions> query)
=> Invoker.EvictCachedResultAsync(query);
public virtual void UpdateCachedResult<TCacheEntryOptions>(ISyncCachedQuery<TCacheEntryOptions> executedQuery)
=> Invoker.UpdateCachedResult(executedQuery);
public virtual Task UpdateCachedResultAsync<TCacheEntryOptions>(IAsyncCachedQuery<TCacheEntryOptions> executedQuery)
=> Invoker.UpdateCachedResultAsync(executedQuery);
public virtual void Command<TContext>(ISyncCommand<TContext> command)
=> Invoker.Command(command, GetContext<TContext>());
public virtual Task CommandAsync<TContext>(IAsyncCommand<TContext> command)
=> Invoker.CommandAsync(command, GetContext<TContext>());
public virtual TResult Command<TContext, TResult>(ISyncCommand<TContext, TResult> command)
=> Invoker.Command(command, GetContext<TContext>());
public virtual Task<TResult> CommandAsync<TContext, TResult>(IAsyncCommand<TContext, TResult> command)
=> Invoker.CommandAsync(command, GetContext<TContext>());
}
}
|
mit
|
C#
|
ad54ba3c2264869a73bc743aa07fb134ea36dbb4
|
Fix - Modificata notifica delete utente
|
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
|
src/backend/SO115App.SignalR/Sender/GestioneUtenti/NotificationDeleteUtente.cs
|
src/backend/SO115App.SignalR/Sender/GestioneUtenti/NotificationDeleteUtente.cs
|
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
//await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
//await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
|
using Microsoft.AspNetCore.SignalR;
using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente;
using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti;
using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti;
using System;
using System.Threading.Tasks;
namespace SO115App.SignalR.Sender.GestioneUtenti
{
public class NotificationDeleteUtente : INotifyDeleteUtente
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
private readonly IGetUtenteByCF _getUtenteByCF;
public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF)
{
_notificationHubContext = notificationHubContext;
_getUtenteByCF = getUtenteByCF;
}
public async Task Notify(DeleteUtenteCommand command)
{
var utente = _getUtenteByCF.Get(command.CodFiscale);
await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true);
await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id);
}
}
}
|
agpl-3.0
|
C#
|
94a94dd954ac6054c72250e6b55464d96bdb1070
|
change settings and log dir
|
stanac/shutdown
|
ShutDown/Data/DataBase.cs
|
ShutDown/Data/DataBase.cs
|
using System;
using System.IO;
namespace ShutDown.Data
{
public abstract class DataBase
{
protected static readonly string FolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShutDown_stanac"); // to avoid collisions
static DataBase()
{
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
}
}
}
|
using System;
using System.IO;
namespace ShutDown.Data
{
public abstract class DataBase
{
protected static readonly string FolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ShutDown_cJ51KAf2ckeBsFCJ2wP3pQ"); // to avoid collisions
static DataBase()
{
if (!Directory.Exists(FolderPath))
{
Directory.CreateDirectory(FolderPath);
}
}
}
}
|
mit
|
C#
|
49fbbafa4683d1763fc228ef0165ee931984bad9
|
Add explanation of why having 2 yield return
|
wangkanai/Detection
|
src/Hosting/PageLocationExpander.cs
|
src/Hosting/PageLocationExpander.cs
|
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Wangkanai.Detection.Hosting
{
public class ResponsivePageLocationExpander : IViewLocationExpander
{
private const string ValueKey = "device";
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
context.Values.TryGetValue(ValueKey, out var device);
if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
return viewLocations;
if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
return viewLocations;
var expandLocations = ExpandPageHierarchy().ToList();
return expandLocations;
IEnumerable<string> ExpandPageHierarchy()
{
foreach (var location in viewLocations)
{
if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
{
yield return location;
continue;
}
// Device View if exist on disk
yield return location.Replace("{0}", "{0}." + device);
// Fallback to the original default view
yield return location;
}
}
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
}
}
}
|
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved.
// The Apache v2. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Wangkanai.Detection.Hosting
{
public class ResponsivePageLocationExpander : IViewLocationExpander
{
private const string ValueKey = "device";
public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations)
{
context.Values.TryGetValue(ValueKey, out var device);
if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor))
return viewLocations;
if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device))
return viewLocations;
var expandLocations = ExpandPageHierarchy().ToList();
return expandLocations;
IEnumerable<string> ExpandPageHierarchy()
{
foreach (var location in viewLocations)
{
if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/"))
{
yield return location;
continue;
}
yield return location.Replace("{0}", "{0}." + device);
yield return location;
}
}
}
public void PopulateValues(ViewLocationExpanderContext context)
{
context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower();
}
}
}
|
apache-2.0
|
C#
|
850d2f22432ebb28a09e425b2d9c329d97bbf684
|
Update UTypeCache.cs
|
KoborSoft/UniversalAgent
|
USerializer/UTypeCache.cs
|
USerializer/UTypeCache.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace KS.USerializer
{
public class TypeCacheEntry : ITypeCacheEntry
{
public uint Id { get; protected set; }
public bool IsGeneric { get; protected set; }
public Type BaseType { get; protected set; }
public List<FieldInfo> Fields { get; protected set; }
public bool IsArray { get; protected set; }
public TypeCacheEntry(Type type, uint id)
{
Id = id;
IsGeneric = type.IsGenericType;
IsArray = type.IsArray;
BaseType = type;
if (!IsGeneric)
Fields = Utils.GetAllInstanceFields(BaseType);
}
}
public class UTypeCache : ITypeCache
{
protected object lockObject = new object();
protected uint newTypeId = 0;
protected Dictionary<Type, ITypeCacheEntry> typeCache = new Dictionary<Type, ITypeCacheEntry>();
protected uint GetNewTypeId()
{
lock (lockObject)
return ++newTypeId;
}
public ITypeCacheEntry GetTypeCacheEntry(Type type)
{
Type baseType = Utils.GetBaseType(type);
if (typeCache.ContainsKey(baseType))
return typeCache[baseType];
return RegisterNewTypeCache(BaseType);
}
protected ITypeCacheEntry RegisterNewTypeCache(Type baseType)
{
var baseTypeCache = new TypeCacheEntry(baseType, GetNewTypeId());
typeCache[BaseType] = baseTypeCache;
return baseTypeCache;
}
public ITypeCacheEntry GetTypeCacheById(uint typeId)
{
return typeCache.Values.First(tc => tc.Id == typeId);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace KS.USerializer
{
public class TypeCacheEntry : ITypeCacheEntry
{
public uint Id { get; protected set; }
public bool IsGeneric { get; protected set; }
public Type BaseType { get; protected set; }
public List<FieldInfo> Fields { get; protected set; }
public bool IsArray { get; protected set; }
public TypeCacheEntry(Type type, uint id)
{
Id = id;
IsGeneric = type.IsGenericType;
IsArray = type.IsArray;
BaseType = type;
if (!IsGeneric)
Fields = Utils.GetAllInstanceFields(BaseType);
}
}
public class UTypeCache : ITypeCache
{
protected object lockObject = new object();
protected uint newTypeId = 0;
protected Dictionary<Type, ITypeCacheEntry> typeCache = new Dictionary<Type, ITypeCacheEntry>();
protected uint GetNewTypeId()
{
lock (lockObject)
return ++newTypeId;
}
public ITypeCacheEntry GetTypeCacheEntry(Type type)
{
Type BaseType = Utils.GetBaseType(type);
if (typeCache.ContainsKey(BaseType))
return typeCache[BaseType];
var baseTypeCache = new TypeCacheEntry(BaseType, GetNewTypeId());
typeCache[BaseType] = baseTypeCache;
return baseTypeCache;
}
public ITypeCacheEntry GetTypeCacheById(uint typeId)
{
return typeCache.Values.First(tc => tc.Id == typeId);
}
}
}
|
agpl-3.0
|
C#
|
4c8057905bfe75753a852bdd634c6d020fdad555
|
Remove validation from Speakr Create
|
DonSchenck/DotNetOnLinux,DonSchenck/DotNetOnLinux,DonSchenck/DotNetOnLinux,DonSchenck/DotNetOnLinux
|
cli-samples-master/Speakr/Views/Submissions/Create.cshtml
|
cli-samples-master/Speakr/Views/Submissions/Create.cshtml
|
@model Speakr.Models.Submission
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Submission</h4>
<hr />
<div class="form-group">
<label asp-for="ConferenceName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ConferenceName" class="form-control" />
</div>
</div>
<div class="form-group">
<label asp-for="SessionTitle" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="SessionTitle" class="form-control" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
|
@model Speakr.Models.Submission
@{
ViewData["Title"] = "Create";
}
<h2>Create</h2>
<form asp-action="Create">
<div class="form-horizontal">
<h4>Submission</h4>
<hr />
<div asp-validation-summary="ValidationSummary.ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ConferenceName" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="ConferenceName" class="form-control" />
<span asp-validation-for="ConferenceName" class="text-danger" />
</div>
</div>
<div class="form-group">
<label asp-for="SessionTitle" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="SessionTitle" class="form-control" />
<span asp-validation-for="SessionTitle" class="text-danger" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
</form>
<div>
<a asp-action="Index">Back to List</a>
</div>
@section Scripts {
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
}
|
apache-2.0
|
C#
|
645542356a4c3863f9f34f211b447593c39f9a7c
|
Remove Seq compact flag, default now
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Program.cs
|
Battery-Commander.Web/Program.cs
|
namespace BatteryCommander.Web
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
|
namespace BatteryCommander.Web
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
public class Program
{
public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information);
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
private static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369")
.UseStartup<Startup>();
})
.ConfigureLogging((context, builder) =>
{
Log.Logger =
new LoggerConfiguration()
.Enrich.FromLogContext()
.Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName)
.Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName)
.Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}")
.WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel)
.MinimumLevel.ControlledBy(LogLevel)
.CreateLogger();
builder.AddSerilog();
});
}
}
|
mit
|
C#
|
e712075ce95d4ef4505735f506b2ac3920350844
|
make serializers protected
|
BoomaNation/Booma.Client.Network.Common,BoomaNation/Booma.Client.Network.Common
|
src/Booma.Client.Network.Common/Peer/BoomaNetworkWebPeer.cs
|
src/Booma.Client.Network.Common/Peer/BoomaNetworkWebPeer.cs
|
using GladNet.Engine.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using GladNet.Common;
using GladNet.ASP.Client.Lib;
using SceneJect.Common;
using GladNet.ASP.Client.RestSharp;
using GladNet.Message;
using GladNet.Serializer;
using Common.Logging;
using GladNet.Message.Handlers;
using Easyception;
using GladNet.ASP.Client.RestSharp.Middleware.Authentication;
namespace Booma.Client.Network.Common
{
[Injectee]
public class BoomaNetworkWebPeer<TInheritingType> : MonoBehaviour, INetPeer, INetworkMessageReceiver
where TInheritingType : BoomaNetworkWebPeer<TInheritingType>
{
[SerializeField]
private string BaseUrl;
//INetPeer
public INetworkMessageRouterService NetworkSendService { get; private set; }
public IConnectionDetails PeerDetails { get; private set; }
public NetStatus Status { get; private set; }
protected IWebRequestEnqueueStrategy enqueuStrat { get; private set; }
[Inject]
protected readonly ISerializerStrategy serializer;
[Inject]
protected readonly IDeserializerStrategy deserializer;
[Inject]
protected readonly ILog classLogger;
/// <summary>
/// Handler service that will deal with dispatching <see cref="ResponseMessage"/> payloads that are of
/// type <see cref="PacketPayload"/> and will generally have handling logic implemented/abstracted from this peer.
/// </summary>
[Inject]
private IResponseMessageHandlerService<TInheritingType> responseHandler { get; set; } //we have to have a setter, can't use C#6 readonly prop because FasterFlect when using SceneJect will complain that it can't find a setter.
//call on Start, not awake.
public virtual void Start()
{
//Uses HTTPS so default to established encryption
Status = NetStatus.EncryptionEstablished;
enqueuStrat = new RestSharpCurrentThreadEnqueueRequestHandlerStrategy(BaseUrl, deserializer, serializer, this, 0, new DefaultNetworkMessageRouteBackService(new AUIDServiceCollection<INetPeer>(1), classLogger));
NetworkSendService = new WebPeerClientMessageSender(enqueuStrat);
PeerDetails = new WebClientPeerDetails(BaseUrl, 0, 0);
}
public bool CanSend(OperationType opType)
{
//Web peers can only send requests.
return opType == OperationType.Request;
}
public void OnNetworkMessageReceive(IRequestMessage message, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle requests.");
}
public void OnNetworkMessageReceive(IResponseMessage message, IMessageParameters parameters)
{
Throw<ArgumentNullException>.If.IsNull(message)?.Now(nameof(message), $"Cannot have a null {nameof(IResponseMessage)} in on recieve. This should never occur internally. Indicates major fault. Should never reach this point.");
responseHandler.TryProcessMessage(message, null, this as TInheritingType);
}
public void OnNetworkMessageReceive(IEventMessage message, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle events.");
}
public void OnNetworkMessageReceive(IStatusMessage status, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle status updates.");
}
}
}
|
using GladNet.Engine.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using GladNet.Common;
using GladNet.ASP.Client.Lib;
using SceneJect.Common;
using GladNet.ASP.Client.RestSharp;
using GladNet.Message;
using GladNet.Serializer;
using Common.Logging;
using GladNet.Message.Handlers;
using Easyception;
using GladNet.ASP.Client.RestSharp.Middleware.Authentication;
namespace Booma.Client.Network.Common
{
[Injectee]
public class BoomaNetworkWebPeer<TInheritingType> : MonoBehaviour, INetPeer, INetworkMessageReceiver
where TInheritingType : BoomaNetworkWebPeer<TInheritingType>
{
[SerializeField]
private string BaseUrl;
//INetPeer
public INetworkMessageRouterService NetworkSendService { get; private set; }
public IConnectionDetails PeerDetails { get; private set; }
public NetStatus Status { get; private set; }
protected IWebRequestEnqueueStrategy enqueuStrat { get; private set; }
[Inject]
private readonly ISerializerStrategy serializer;
[Inject]
private readonly IDeserializerStrategy deserializer;
[Inject]
protected readonly ILog classLogger;
/// <summary>
/// Handler service that will deal with dispatching <see cref="ResponseMessage"/> payloads that are of
/// type <see cref="PacketPayload"/> and will generally have handling logic implemented/abstracted from this peer.
/// </summary>
[Inject]
private IResponseMessageHandlerService<TInheritingType> responseHandler { get; set; } //we have to have a setter, can't use C#6 readonly prop because FasterFlect when using SceneJect will complain that it can't find a setter.
//call on Start, not awake.
public virtual void Start()
{
//Uses HTTPS so default to established encryption
Status = NetStatus.EncryptionEstablished;
enqueuStrat = new RestSharpCurrentThreadEnqueueRequestHandlerStrategy(BaseUrl, deserializer, serializer, this, 0, new DefaultNetworkMessageRouteBackService(new AUIDServiceCollection<INetPeer>(1), classLogger));
NetworkSendService = new WebPeerClientMessageSender(enqueuStrat);
PeerDetails = new WebClientPeerDetails(BaseUrl, 0, 0);
}
public bool CanSend(OperationType opType)
{
//Web peers can only send requests.
return opType == OperationType.Request;
}
public void OnNetworkMessageReceive(IRequestMessage message, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle requests.");
}
public void OnNetworkMessageReceive(IResponseMessage message, IMessageParameters parameters)
{
Throw<ArgumentNullException>.If.IsNull(message)?.Now(nameof(message), $"Cannot have a null {nameof(IResponseMessage)} in on recieve. This should never occur internally. Indicates major fault. Should never reach this point.");
responseHandler.TryProcessMessage(message, null, this as TInheritingType);
}
public void OnNetworkMessageReceive(IEventMessage message, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle events.");
}
public void OnNetworkMessageReceive(IStatusMessage status, IMessageParameters parameters)
{
throw new NotImplementedException("Web peers cannot handle status updates.");
}
}
}
|
mit
|
C#
|
0b4c6f4c045580bbfd512bd35e3f0a4522fa36dc
|
Use var instead.
|
dlemstra/Magick.NET,dlemstra/Magick.NET
|
src/Magick.NET/Drawables/Coordinates/DrawableCoordinates.cs
|
src/Magick.NET/Drawables/Coordinates/DrawableCoordinates.cs
|
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Generic;
namespace ImageMagick
{
internal abstract class DrawableCoordinates<TCoordinateType>
{
protected DrawableCoordinates(IEnumerable<TCoordinateType> coordinates, int minCount)
{
Throw.IfNull(nameof(coordinates), coordinates);
Coordinates = DrawableCoordinates<TCoordinateType>.CheckCoordinates(new List<TCoordinateType>(coordinates), minCount);
}
protected List<TCoordinateType> Coordinates { get; }
public IList<TCoordinateType> ToList()
=> Coordinates;
private static List<TCoordinateType> CheckCoordinates(List<TCoordinateType> coordinates, int minCount)
{
if (coordinates.Count == 0)
throw new ArgumentException("Value cannot be empty", nameof(coordinates));
foreach (var coordinate in coordinates)
{
if (coordinate == null)
throw new ArgumentNullException(nameof(coordinates), "Value should not contain null values");
}
if (coordinates.Count < minCount)
throw new ArgumentException("Value should contain at least " + minCount + " coordinates.", nameof(coordinates));
return coordinates;
}
}
}
|
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET.
// Licensed under the Apache License, Version 2.0.
using System;
using System.Collections.Generic;
namespace ImageMagick
{
internal abstract class DrawableCoordinates<TCoordinateType>
{
protected DrawableCoordinates(IEnumerable<TCoordinateType> coordinates, int minCount)
{
Throw.IfNull(nameof(coordinates), coordinates);
Coordinates = CheckCoordinates(new List<TCoordinateType>(coordinates), minCount);
}
protected List<TCoordinateType> Coordinates { get; }
public IList<TCoordinateType> ToList()
=> Coordinates;
private List<TCoordinateType> CheckCoordinates(List<TCoordinateType> coordinates, int minCount)
{
if (coordinates.Count == 0)
throw new ArgumentException("Value cannot be empty", nameof(coordinates));
foreach (TCoordinateType coordinate in coordinates)
{
if (coordinate == null)
throw new ArgumentNullException(nameof(coordinates), "Value should not contain null values");
}
if (coordinates.Count < minCount)
throw new ArgumentException("Value should contain at least " + minCount + " coordinates.", nameof(coordinates));
return coordinates;
}
}
}
|
apache-2.0
|
C#
|
dc4d9d613892b5d0e7d4dbdbed5acd64869df912
|
Update BazaarAccountController.cs
|
Merchello/Merchello.Bazaar,Merchello/Merchello,clausjensen/Merchello,clausjensen/Merchello,ProNotion/Merchello,Merchello/Merchello,rasmusjp/Merchello,rasmusjp/Merchello,Merchello/Merchello,rasmusjp/Merchello,Merchello/Merchello.Bazaar,ProNotion/Merchello,clausjensen/Merchello,Merchello/Merchello.Bazaar,ProNotion/Merchello
|
src/Merchello.Bazaar/Controllers/BazaarAccountController.cs
|
src/Merchello.Bazaar/Controllers/BazaarAccountController.cs
|
namespace Merchello.Bazaar.Controllers
{
using System;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
/// <summary>
/// The bazaar account controller.
/// </summary>
[PluginController("Bazaar")]
[Authorize]
public class BazaarAccountController : CheckoutRenderControllerBase
{
/// <summary>
/// The index <see cref="ActionResult"/>.
/// </summary>
/// <param name="model">
/// The current render model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
public override ActionResult Index(RenderModel model)
{
// add in webconfig appsetting <add key="umbracoHomeStoreUrl" value="/store" />
string homeUrl = Convert.ToString(ConfigurationManager.AppSettings["umbracoHomeStoreUrl"]);
if (CurrentCustomer.IsAnonymous)
{
var error = new Exception("Current customer cannot be Anonymous");
LogHelper.Error<BazaarAccountController>("Anonymous customers should not be allowed to access the Account section.", error);
//throw error;
return this.Redirect(homeUrl);
}
var viewModel = ViewModelFactory.CreateAccount(model, AllCountries, AllowedShipCountries);
return this.View(viewModel.ThemeAccountPath("Account"), viewModel);
}
}
}
|
namespace Merchello.Bazaar.Controllers
{
using System;
using System.Web.Mvc;
using Umbraco.Core.Logging;
using Umbraco.Web.Models;
using Umbraco.Web.Mvc;
/// <summary>
/// The bazaar account controller.
/// </summary>
[PluginController("Bazaar")]
[Authorize]
public class BazaarAccountController : CheckoutRenderControllerBase
{
/// <summary>
/// The index <see cref="ActionResult"/>.
/// </summary>
/// <param name="model">
/// The current render model.
/// </param>
/// <returns>
/// The <see cref="ActionResult"/>.
/// </returns>
public override ActionResult Index(RenderModel model)
{
if (CurrentCustomer.IsAnonymous)
{
var error = new Exception("Current customer cannot be Anonymous");
LogHelper.Error<BazaarAccountController>("Anonymous customers should not be allowed to access the Account section.", error);
throw error;
}
var viewModel = ViewModelFactory.CreateAccount(model, AllCountries, AllowedShipCountries);
return this.View(viewModel.ThemeAccountPath("Account"), viewModel);
}
}
}
|
mit
|
C#
|
1edef94ba563f903acad28b0f91bef9d3e1fefb9
|
fix naming
|
Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen,Pondidum/Dashen
|
Dashen/Components/HeaderModel.cs
|
Dashen/Components/HeaderModel.cs
|
namespace Dashen.Components
{
public class HeaderModel : Model
{
public string Name { get; set; }
public string Version { get; set; }
}
}
|
namespace Dashen.Components
{
public class HeaderModel : Model
{
public string Name { get; set; }
public string Verison { get; set; }
}
}
|
lgpl-2.1
|
C#
|
6e2a9a251d23f0278ba6d15d8d5a4081f2dd920b
|
修复随即发生器的名字错误。 :rat:
|
Zongsoft/Zongsoft.Web.Launcher
|
DefaultController.cs
|
DefaultController.cs
|
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace Zongsoft.Web.Launcher
{
[HandleError]
public class DefaultController : Controller
{
public ActionResult Index()
{
this.ViewData["Now"] = DateTime.Now;
this.ViewData["Random"] = Zongsoft.Common.Randomizer.GenerateInt32();
this.ViewData["Message"] = "Welcome to ASP.NET MVC on Zongsoft.Plugins™";
this.ViewData["Genders"] = Zongsoft.Common.EnumUtility.GetEnumEntries(typeof(Gender), false);
this.ViewData["PluginTree"] = Zongsoft.Plugins.Application.Context.PluginContext.PluginTree;
var people = new Person[]
{
new Person()
{
Id = 101,
Name = "Administrator",
Gender = Gender.Male,
Birthdate = new DateTime(1980, 1, 1),
},
new Person()
{
Id = 102,
Name = "Popeye Zhong",
Gender = Gender.Male,
Birthdate = new DateTime(1979, 5, 15),
},
new Person()
{
Id = 103,
Name = "Lily",
Gender = Gender.Female,
Birthdate = new DateTime(1989, 6, 1),
},
};
return View(people);
}
[HttpPost]
public ActionResult Index(int? id)
{
return View();
}
public ActionResult About()
{
return View();
}
}
#region 测试数据
public enum Gender
{
[Description("先生")]
Male = 1,
[Description("女士")]
Female = 0,
}
[Serializable]
public class Person
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public Gender? Gender
{
get;
set;
}
public DateTime Birthdate
{
get;
set;
}
}
#endregion
}
|
using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
namespace Zongsoft.Web.Launcher
{
[HandleError]
public class DefaultController : Controller
{
public ActionResult Index()
{
this.ViewData["Now"] = DateTime.Now;
this.ViewData["Random"] = Zongsoft.Common.RandomGenerator.GenerateInt32();
this.ViewData["Message"] = "Welcome to ASP.NET MVC on Zongsoft.Plugins™";
this.ViewData["Genders"] = Zongsoft.Common.EnumUtility.GetEnumEntries(typeof(Gender), false);
this.ViewData["PluginTree"] = Zongsoft.Plugins.Application.Context.PluginContext.PluginTree;
var people = new Person[]
{
new Person()
{
Id = 101,
Name = "Administrator",
Gender = Gender.Male,
Birthdate = new DateTime(1980, 1, 1),
},
new Person()
{
Id = 102,
Name = "Popeye Zhong",
Gender = Gender.Male,
Birthdate = new DateTime(1979, 5, 15),
},
new Person()
{
Id = 103,
Name = "Lily",
Gender = Gender.Female,
Birthdate = new DateTime(1989, 6, 1),
},
};
return View(people);
}
[HttpPost]
public ActionResult Index(int? id)
{
return View();
}
public ActionResult About()
{
return View();
}
}
#region 测试数据
public enum Gender
{
[Description("先生")]
Male = 1,
[Description("女士")]
Female = 0,
}
[Serializable]
public class Person
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
public Gender? Gender
{
get;
set;
}
public DateTime Birthdate
{
get;
set;
}
}
#endregion
}
|
mit
|
C#
|
e807da564f5f6de5c43d1ec86b67cde1fc1cc589
|
Add closest line to line point
|
karl-/simple_modeler
|
Assets/Modeler/Code/Scripts/MathUtility.cs
|
Assets/Modeler/Code/Scripts/MathUtility.cs
|
using UnityEngine;
using System;
namespace Modeler
{
public static class MathUtility
{
/**
* Calculate the normal of 3 points: B-A x C-A
*/
public static Vector3 Normal(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 cross = Vector3.Cross(p1 - p0, p2 - p0);
cross.Normalize();
return cross;
}
/**
* Returns true if a raycast intersects a triangle.
* http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
* http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf
*/
public static bool RayIntersectsTriangle(Ray InRay, Vector3 InTriangleA, Vector3 InTriangleB, Vector3 InTriangleC)
{
// @todo lot of unnecessary garbage is generated
Vector3 e1, e2;
Vector3 P, Q, T;
float det, inv_det, u, v;
float t;
// find vectors for two edges sharing V1
e1 = InTriangleB - InTriangleA;
e2 = InTriangleC - InTriangleA;
// begin calculating determinant - also used to calculate `u` parameter
P = Vector3.Cross(InRay.direction, e2);
// if determinant is near zero, ray lies in plane of triangle
det = Vector3.Dot(e1, P);
if(det > -Mathf.Epsilon && det < Mathf.Epsilon)
return false;
inv_det = 1f / det;
// calculate distance from V1 to ray origin
T = InRay.origin - InTriangleA;
// calculate u parameter and test bound
u = Vector3.Dot(T, P) * inv_det;
// the intersection lies outside of the triangle
if(u < 0f || u > 1f)
return false;
// prepare to test v parameter
Q = Vector3.Cross(T, e1);
// calculate V parameter and test bound
v = Vector3.Dot(InRay.direction, Q) * inv_det;
// the intersection lies outside of the triangle
if(v < 0f || u + v > 1f)
return false;
t = Vector3.Dot(e2, Q) * inv_det;
return t > Mathf.Epsilon;
}
/**
* Returns the nearest point on each line to the other line.
*
* http://wiki.unity3d.com/index.php?title=3d_Math_functions
* Two non-parallel lines which may or may not touch each other have a point on each line which are closest
* to each other. This function finds those two points. If the lines are not parallel, the function
* outputs true, otherwise false.
*/
public static bool ClosestPointsOnTwoLines(Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2, out Vector3 closestPointLine1, out Vector3 closestPointLine2)
{
closestPointLine1 = Vector3.zero;
closestPointLine2 = Vector3.zero;
float a = Vector3.Dot(lineVec1, lineVec1);
float b = Vector3.Dot(lineVec1, lineVec2);
float e = Vector3.Dot(lineVec2, lineVec2);
float d = a*e - b*b;
//lines are not parallel
if(d != 0.0f)
{
Vector3 r = linePoint1 - linePoint2;
float c = Vector3.Dot(lineVec1, r);
float f = Vector3.Dot(lineVec2, r);
float s = (b*f - c*e) / d;
float t = (a*f - c*b) / d;
closestPointLine1 = linePoint1 + lineVec1 * s;
closestPointLine2 = linePoint2 + lineVec2 * t;
return true;
}
else
{
return false;
}
}
}
}
|
using UnityEngine;
using System;
namespace Modeler
{
public static class MathUtility
{
/**
* Calculate the normal of 3 points: B-A x C-A
*/
public static Vector3 Normal(Vector3 p0, Vector3 p1, Vector3 p2)
{
Vector3 cross = Vector3.Cross(p1 - p0, p2 - p0);
cross.Normalize();
return cross;
}
/**
* Returns true if a raycast intersects a triangle.
* http://en.wikipedia.org/wiki/M%C3%B6ller%E2%80%93Trumbore_intersection_algorithm
* http://www.cs.virginia.edu/~gfx/Courses/2003/ImageSynthesis/papers/Acceleration/Fast%20MinimumStorage%20RayTriangle%20Intersection.pdf
*/
public static bool RayIntersectsTriangle(Ray InRay, Vector3 InTriangleA, Vector3 InTriangleB, Vector3 InTriangleC)
{
// @todo lot of unnecessary garbage is generated
Vector3 e1, e2;
Vector3 P, Q, T;
float det, inv_det, u, v;
float t;
// find vectors for two edges sharing V1
e1 = InTriangleB - InTriangleA;
e2 = InTriangleC - InTriangleA;
// begin calculating determinant - also used to calculate `u` parameter
P = Vector3.Cross(InRay.direction, e2);
// if determinant is near zero, ray lies in plane of triangle
det = Vector3.Dot(e1, P);
if(det > -Mathf.Epsilon && det < Mathf.Epsilon)
return false;
inv_det = 1f / det;
// calculate distance from V1 to ray origin
T = InRay.origin - InTriangleA;
// calculate u parameter and test bound
u = Vector3.Dot(T, P) * inv_det;
// the intersection lies outside of the triangle
if(u < 0f || u > 1f)
return false;
// prepare to test v parameter
Q = Vector3.Cross(T, e1);
// calculate V parameter and test bound
v = Vector3.Dot(InRay.direction, Q) * inv_det;
// the intersection lies outside of the triangle
if(v < 0f || u + v > 1f)
return false;
t = Vector3.Dot(e2, Q) * inv_det;
return t > Mathf.Epsilon;
}
}
}
|
mit
|
C#
|
bae170652c04bbe34dd415243d732d23c62ca006
|
Use Event not Item
|
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
|
CRP.Mvc/Views/Payments/Confirmation.cshtml
|
CRP.Mvc/Views/Payments/Confirmation.cshtml
|
@using Microsoft.Web.Mvc
@model CRP.Controllers.ViewModels.PaymentConfirmationViewModel
@{
ViewBag.Title = "Confirmation";
}
<div class="boundary">
<h2>Registration Confirmation</h2>
<p>You have successfully registered for the following event:</p>
<div>
<label>Event: </label>
@Model.Transaction.Item.Name
</div>
<div>
<label>Transaction: </label>
@Model.Transaction.TransactionNumber
</div>
<div>
<label>Amount: </label>
@($"{Model.Transaction.Total:C}")
</div>
@if (Model.Transaction.Credit)
{
<div>
@if (Model.Transaction.Paid)
{
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
It appears this has been paid. If you think it hasn't you may still pay.
</div>
}
else
{
<p>Payment is still due:</p>
}
<form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px">
@foreach (var pair in Model.PaymentDictionary)
{
<input type="hidden" name="@pair.Key" value="@pair.Value"/>
}
<input type="hidden" name="signature" value="@Model.Signature"/>
<input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/>
</form>
</div>
}
else if (Model.Transaction.Total > 0)
{
<div>
@Html.Raw(Model.Transaction.Item.CheckPaymentInstructions)
</div>
}
</div>
|
@using Microsoft.Web.Mvc
@model CRP.Controllers.ViewModels.PaymentConfirmationViewModel
@{
ViewBag.Title = "Confirmation";
}
<div class="boundary">
<h2>Registration Confirmation</h2>
<p>You have successfully registered for the following event:</p>
<div>
<label>Item: </label>
@Model.Transaction.Item.Name
</div>
<div>
<label>Transaction: </label>
@Model.Transaction.TransactionNumber
</div>
<div>
<label>Amount: </label>
@($"{Model.Transaction.Total:C}")
</div>
@if (Model.Transaction.Credit)
{
<div>
@if (Model.Transaction.Paid)
{
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
It appears this has been paid. If you think it hasn't you may still pay.
</div>
}
else
{
<p>Payment is still due:</p>
}
<form action="@Model.PostUrl" method="post" autocomplete="off" style="margin-right: 3px">
@foreach (var pair in Model.PaymentDictionary)
{
<input type="hidden" name="@pair.Key" value="@pair.Value"/>
}
<input type="hidden" name="signature" value="@Model.Signature"/>
<input type="submit" class="btn btn-primary" value="Click here to be taken to our payment site"/>
</form>
</div>
}
else if (Model.Transaction.Total > 0)
{
<div>
@Html.Raw(Model.Transaction.Item.CheckPaymentInstructions)
</div>
}
</div>
|
mit
|
C#
|
ad17332723d9da98aba3dc0c5833c89edbef19d0
|
refactor the provider cache
|
HamidMosalla/VisualStudio-ColorCoder
|
ColorCoder/ColorCoderCore/ProviderCache.cs
|
ColorCoder/ColorCoderCore/ProviderCache.cs
|
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace ColorCoder.ColorCoderCore
{
public class ProviderCache
{
public Workspace Workspace { get; private set; }
public Document Document { get; private set; }
public SemanticModel SemanticModel { get; private set; }
public SyntaxNode SyntaxRoot { get; private set; }
public ITextSnapshot Snapshot { get; private set; }
public static async Task<ProviderCache> Resolve(ITextBuffer buffer, ITextSnapshot snapshot)
{
var workspace = buffer.GetWorkspace();
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null) { return null; }
// the ConfigureAwait() calls are important,
// otherwise we'll deadlock VS
var semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);
var syntaxRoot = await document.GetSyntaxRootAsync().ConfigureAwait(false);
return new ProviderCache
{
Workspace = workspace,
Document = document,
SemanticModel = semanticModel,
SyntaxRoot = syntaxRoot,
Snapshot = snapshot
};
}
}
}
|
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace ColorCoder.ColorCoderCore
{
public class ProviderCache
{
public Workspace Workspace { get; private set; }
public Document Document { get; private set; }
public SemanticModel SemanticModel { get; private set; }
public SyntaxNode SyntaxRoot { get; private set; }
public ITextSnapshot Snapshot { get; private set; }
public static async Task<ProviderCache> Resolve(ITextBuffer buffer, ITextSnapshot snapshot)
{
var workspace = buffer.GetWorkspace();
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
// Razor cshtml returns a null document for some reason.
return null;
}
// the ConfigureAwait() calls are important,
// otherwise we'll deadlock VS
var semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);
var syntaxRoot = await document.GetSyntaxRootAsync().ConfigureAwait(false);
return new ProviderCache
{
Workspace = workspace,
Document = document,
SemanticModel = semanticModel,
SyntaxRoot = syntaxRoot,
Snapshot = snapshot
};
}
}
}
|
mit
|
C#
|
e67dd103e22a617a64dbc790616f8133f76a80de
|
Refactor Utf8EncodingGenerator to use ExactTypeSpecification.
|
hackle/AutoFixture,zvirja/AutoFixture,AutoFixture/AutoFixture,dcastro/AutoFixture,adamchester/AutoFixture,adamchester/AutoFixture,sbrockway/AutoFixture,dcastro/AutoFixture,Pvlerick/AutoFixture,sean-gilliam/AutoFixture,sergeyshushlyapin/AutoFixture,sbrockway/AutoFixture,sergeyshushlyapin/AutoFixture,hackle/AutoFixture
|
Src/AutoFixture/Utf8EncodingGenerator.cs
|
Src/AutoFixture/Utf8EncodingGenerator.cs
|
using Ploeh.AutoFixture.Kernel;
using System.Text;
namespace Ploeh.AutoFixture
{
public class Utf8EncodingGenerator : ISpecimenBuilder
{
private readonly ExactTypeSpecification encodingTypeSpecification = new ExactTypeSpecification(typeof(Encoding));
public object Create(object request, ISpecimenContext context)
{
if (request == null)
{
return new NoSpecimen();
}
if (!this.encodingTypeSpecification.IsSatisfiedBy(request))
{
return new NoSpecimen();
}
return Encoding.UTF8;
}
}
}
|
using Ploeh.AutoFixture.Kernel;
using System.Text;
namespace Ploeh.AutoFixture
{
public class Utf8EncodingGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (typeof(Encoding).Equals(request))
{
return Encoding.UTF8;
}
return new NoSpecimen();
}
}
}
|
mit
|
C#
|
97f20fe98ac3bf96fc81adb9a27db98962acba87
|
fix comment cref
|
flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core,flubu-core/flubu.core
|
FlubuCore/Tasks/Process/IRunProgramTask.cs
|
FlubuCore/Tasks/Process/IRunProgramTask.cs
|
namespace FlubuCore.Tasks.Process
{
/// <inheritdoc cref="ITaskOfT{T, TTask}" />
public interface IRunProgramTask : ITaskOfT<int, IRunProgramTask>, IExternalProcess<IRunProgramTask>
{
/// <summary>
/// Capture output of the running program.
/// </summary>
/// <returns></returns>
IRunProgramTask CaptureOutput();
/// <summary>
/// Capture error output of the running program.
/// </summary>
/// <returns></returns>
IRunProgramTask CaptureErrorOutput();
/// <summary>
/// Gets the whole output of the executed command.
/// </summary>
/// <returns></returns>
string GetOutput();
/// <summary>
/// Gets the whole error output of the executed command.
/// </summary>
/// <returns></returns>
string GetErrorOutput();
}
}
|
namespace FlubuCore.Tasks.Process
{
/// <inheritdoc cref="ITaskOfT{T}" />
public interface IRunProgramTask : ITaskOfT<int, IRunProgramTask>, IExternalProcess<IRunProgramTask>
{
/// <summary>
/// Capture output of the running program.
/// </summary>
/// <returns></returns>
IRunProgramTask CaptureOutput();
/// <summary>
/// Capture error output of the running program.
/// </summary>
/// <returns></returns>
IRunProgramTask CaptureErrorOutput();
/// <summary>
/// Gets the whole output of the executed command.
/// </summary>
/// <returns></returns>
string GetOutput();
/// <summary>
/// Gets the whole error output of the executed command.
/// </summary>
/// <returns></returns>
string GetErrorOutput();
}
}
|
bsd-2-clause
|
C#
|
4c7a400e5383297c216b2af954fb24cb57fd4dc0
|
fix test
|
huoxudong125/Fody,shanselman/Fody,shanselman/Fody,ichengzi/Fody,Fody/Fody,jasonholloway/Fody,distantcam/Fody,ColinDabritzViewpoint/Fody,GeertvanHorrik/Fody,shanselman/Fody,furesoft/Fody,PKRoma/Fody
|
Fody.Tests/WeaverProjectFileFinderTests.cs
|
Fody.Tests/WeaverProjectFileFinderTests.cs
|
using System.IO;
using Moq;
using NUnit.Framework;
[TestFixture]
public class WeaverProjectFileFinderTests
{
[Test]
public void Found()
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var combine = Path.Combine(currentDirectory, @"..\..\WeaversProjectFileFinder\WithWeaver");
var loggerMock = new Mock<BuildLogger>();
loggerMock.Setup(x => x.LogInfo(It.IsAny<string>()));
var processor = new Processor
{
SolutionDir = combine,
Logger = loggerMock.Object
};
processor.FindWeaverProjectFile();
Assert.IsTrue(processor.FoundWeaverProjectFile);
loggerMock.Verify();
}
//TODO: add tests where weavers is in references for ncrunch support
[Test]
public void NotFound()
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var combine = Path.Combine(currentDirectory, @"..\..\WeaversProjectFileFinder\WithNoWeaver");
var loggerMock = new Mock<BuildLogger>();
loggerMock.Setup(x => x.LogInfo(It.IsAny<string>()));
var processor = new Processor
{
SolutionDir = combine,
Logger = loggerMock.Object,
References = ""
};
processor.FindWeaverProjectFile();
Assert.IsFalse(processor.FoundWeaverProjectFile);
loggerMock.Verify();
}
}
|
using System.IO;
using Moq;
using NUnit.Framework;
[TestFixture]
public class WeaverProjectFileFinderTests
{
[Test]
public void Found()
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var combine = Path.Combine(currentDirectory, @"..\..\WeaversProjectFileFinder\WithWeaver");
var loggerMock = new Mock<BuildLogger>();
loggerMock.Setup(x => x.LogInfo(It.IsAny<string>()));
var processor = new Processor
{
SolutionDir = combine,
Logger = loggerMock.Object
};
processor.FindWeaverProjectFile();
Assert.IsTrue(processor.FoundWeaverProjectFile);
loggerMock.Verify();
}
[Test]
public void NotFound()
{
var currentDirectory = AssemblyLocation.CurrentDirectory();
var combine = Path.Combine(currentDirectory, @"..\..\WeaversProjectFileFinder\WithNoWeaver");
var loggerMock = new Mock<BuildLogger>();
loggerMock.Setup(x => x.LogInfo(It.IsAny<string>()));
var processor = new Processor
{
SolutionDir = combine,
Logger = loggerMock.Object
};
processor.FindWeaverProjectFile();
Assert.IsFalse(processor.FoundWeaverProjectFile);
loggerMock.Verify();
}
}
|
mit
|
C#
|
98ab52f64c352c1de29b180037eccb70c0723f94
|
Bump version
|
InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET
|
configuration/SharedAssemblyInfo.cs
|
configuration/SharedAssemblyInfo.cs
|
using System.Reflection;
// Assembly Info that is shared across the product
[assembly: AssemblyProduct("InEngine.NET")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0-beta1")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ethan Hann")]
[assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
|
using System.Reflection;
// Assembly Info that is shared across the product
[assembly: AssemblyProduct("InEngine.NET")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0-alpha5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ethan Hann")]
[assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
|
mit
|
C#
|
c286fefbc349cd558dbf802679ba95875cfcb7ef
|
Make ReturnedWhen in BookLoan Class nullable.
|
Programazing/Open-School-Library,Programazing/Open-School-Library
|
src/Open-School-Library/Models/DatabaseModels/BookLoan.cs
|
src/Open-School-Library/Models/DatabaseModels/BookLoan.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class BookLoan
{
public int BookLoanID { get; set; }
public int BookID { get; set; }
public int StudentID { get; set; }
public DateTime CheckedOutWhen { get; set; }
public DateTime DueWhen { get; set; }
public DateTime? ReturnedWhen { get; set; }
public Book Book { get; set; }
public Student Student { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Open_School_Library.Models.DatabaseModels
{
public class BookLoan
{
public int BookLoanID { get; set; }
public int BookID { get; set; }
public int StudentID { get; set; }
public DateTime CheckedOutWhen { get; set; }
public DateTime DueWhen { get; set; }
public DateTime ReturnedWhen { get; set; }
public Book Book { get; set; }
public Student Student { get; set; }
}
}
|
mit
|
C#
|
2e005791b0e5e90c31f35dddfce796390e21375f
|
rename C# class HelloWorld -> Euler
|
lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler,lunixbochs/project-euler
|
01-50/01/1.cs
|
01-50/01/1.cs
|
using System;
public class Euler {
static public void Main() {
int sum = 0;
for (int i = 0; i < 1000; i++) {
if (i % 5 == 0 || i % 3 == 0) {
sum += i;
}
}
Console.Out.WriteLine(sum);
}
}
|
using System;
public class HelloWorld {
static public void Main() {
int sum = 0;
for (int i = 0; i < 1000; i++) {
if (i % 5 == 0 || i % 3 == 0) {
sum += i;
}
}
Console.Out.WriteLine(sum);
}
}
|
mit
|
C#
|
ad7144eb1a5ae979beaf2097f0e5d333567b247c
|
bump version and fix description
|
manesiotise/WebApiContrib.Tracing.NLog,WebApiContrib/WebApiContrib.Tracing.NLog
|
src/WebApiContrib.Tracing.Nlog/Properties/AssemblyInfo.cs
|
src/WebApiContrib.Tracing.Nlog/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("WebApiContrib.Tracing.Nlog")]
[assembly: AssemblyDescription("A tracing extension using NLog for Web API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebApiContrib.Tracing.Nlog")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9c34cf3a-95aa-4d28-ab21-3564cb2ddc3c")]
// 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("0.10.0")]
[assembly: AssemblyFileVersion("0.10.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("WebApiContrib.Tracing.Nlog")]
[assembly: AssemblyDescription("Description")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebApiContrib.Tracing.Nlog")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9c34cf3a-95aa-4d28-ab21-3564cb2ddc3c")]
// 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("0.9.0")]
[assembly: AssemblyFileVersion("0.9.0")]
|
mit
|
C#
|
51a58269add518f7ea68f590fceeff11612cc5c7
|
Fix nullref in case of successfull request but no backgrounds available
|
smoogipooo/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu
|
osu.Game/Graphics/Backgrounds/SeasonalBackgroundLoader.cs
|
osu.Game/Graphics/Backgrounds/SeasonalBackgroundLoader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;
using osu.Game.Configuration;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Graphics.Backgrounds
{
[LongRunningLoad]
public class SeasonalBackgroundLoader : Component
{
private Bindable<APISeasonalBackgrounds> cachedResponse;
private int current;
[BackgroundDependencyLoader]
private void load(SessionStatics sessionStatics, IAPIProvider api)
{
cachedResponse = sessionStatics.GetBindable<APISeasonalBackgrounds>(Static.SeasonalBackgroundsResponse);
if (cachedResponse.Value != null) return;
var request = new GetSeasonalBackgroundsRequest();
request.Success += response =>
{
cachedResponse.Value = response;
current = RNG.Next(0, response.Backgrounds?.Count ?? 0);
};
api.PerformAsync(request);
}
public SeasonalBackground LoadBackground()
{
var backgrounds = cachedResponse.Value.Backgrounds;
if (backgrounds == null || !backgrounds.Any()) return null;
current = (current + 1) % backgrounds.Count;
string url = backgrounds[current].Url;
return new SeasonalBackground(url);
}
public bool IsInSeason => DateTimeOffset.Now < cachedResponse.Value.EndDate;
}
[LongRunningLoad]
public class SeasonalBackground : Background
{
private readonly string url;
private const string fallback_texture_name = @"Backgrounds/bg1";
public SeasonalBackground(string url)
{
this.url = url;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
Sprite.Texture = textures.Get(url) ?? textures.Get(fallback_texture_name);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Textures;
using osu.Framework.Utils;
using osu.Game.Configuration;
using osu.Game.Online.API;
using osu.Game.Online.API.Requests;
using osu.Game.Online.API.Requests.Responses;
namespace osu.Game.Graphics.Backgrounds
{
[LongRunningLoad]
public class SeasonalBackgroundLoader : Component
{
private Bindable<APISeasonalBackgrounds> cachedResponse;
private int current;
[BackgroundDependencyLoader]
private void load(SessionStatics sessionStatics, IAPIProvider api)
{
cachedResponse = sessionStatics.GetBindable<APISeasonalBackgrounds>(Static.SeasonalBackgroundsResponse);
if (cachedResponse.Value != null) return;
var request = new GetSeasonalBackgroundsRequest();
request.Success += response =>
{
cachedResponse.Value = response;
current = RNG.Next(0, cachedResponse.Value.Backgrounds.Count);
};
api.PerformAsync(request);
}
public SeasonalBackground LoadBackground()
{
var backgrounds = cachedResponse.Value.Backgrounds;
if (!backgrounds.Any()) return null;
current = (current + 1) % backgrounds.Count;
string url = backgrounds[current].Url;
return new SeasonalBackground(url);
}
public bool IsInSeason => DateTimeOffset.Now < cachedResponse.Value.EndDate;
}
[LongRunningLoad]
public class SeasonalBackground : Background
{
private readonly string url;
private const string fallback_texture_name = @"Backgrounds/bg1";
public SeasonalBackground(string url)
{
this.url = url;
}
[BackgroundDependencyLoader]
private void load(LargeTextureStore textures)
{
Sprite.Texture = textures.Get(url) ?? textures.Get(fallback_texture_name);
}
}
}
|
mit
|
C#
|
01c9112f82136510ae96dbd918e698ee9623ae81
|
Add a null check to prevent NRE when playing the "no video" version of a beatmap.
|
peppy/osu-new,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu
|
osu.Game/Storyboards/Drawables/DrawableStoryboardVideo.cs
|
osu.Game/Storyboards/Drawables/DrawableStoryboardVideo.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
namespace osu.Game.Storyboards.Drawables
{
public class DrawableStoryboardVideo : CompositeDrawable
{
public readonly StoryboardVideo Video;
private VideoSprite videoSprite;
public override bool RemoveWhenNotAlive => false;
public DrawableStoryboardVideo(StoryboardVideo video)
{
Video = video;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(true)]
private void load(IBindable<WorkingBeatmap> beatmap, TextureStore textureStore)
{
var path = beatmap.Value.BeatmapSetInfo?.Files?.Find(f => f.Filename.Equals(Video.Path, StringComparison.OrdinalIgnoreCase))?.FileInfo.StoragePath;
if (path == null)
return;
var stream = textureStore.GetStream(path);
if (stream == null)
return;
InternalChild = videoSprite = new VideoSprite(stream, false)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
Clock = new FramedOffsetClock(Clock) { Offset = -Video.StartTime }
};
}
protected override void LoadComplete()
{
base.LoadComplete();
if (videoSprite == null) return;
using (videoSprite.BeginAbsoluteSequence(0))
videoSprite.FadeIn(500);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Textures;
using osu.Framework.Graphics.Video;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
namespace osu.Game.Storyboards.Drawables
{
public class DrawableStoryboardVideo : CompositeDrawable
{
public readonly StoryboardVideo Video;
private VideoSprite videoSprite;
public override bool RemoveWhenNotAlive => false;
public DrawableStoryboardVideo(StoryboardVideo video)
{
Video = video;
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader(true)]
private void load(IBindable<WorkingBeatmap> beatmap, TextureStore textureStore)
{
var path = beatmap.Value.BeatmapSetInfo?.Files?.Find(f => f.Filename.Equals(Video.Path, StringComparison.OrdinalIgnoreCase))?.FileInfo.StoragePath;
if (path == null)
return;
var stream = textureStore.GetStream(path);
if (stream == null)
return;
InternalChild = videoSprite = new VideoSprite(stream, false)
{
RelativeSizeAxes = Axes.Both,
FillMode = FillMode.Fill,
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0,
Clock = new FramedOffsetClock(Clock) { Offset = -Video.StartTime }
};
}
protected override void LoadComplete()
{
base.LoadComplete();
using (videoSprite.BeginAbsoluteSequence(0))
videoSprite.FadeIn(500);
}
}
}
|
mit
|
C#
|
a6c34f9f44d98e71e2418e921ee962bc1378b51b
|
Change init of lifetime service
|
danielmundt/csremote
|
source/Remoting.Service/RemoteMessage.cs
|
source/Remoting.Service/RemoteMessage.cs
|
#region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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.
#endregion Header
using System;
using System.Collections.Generic;
using System.Runtime.Remoting.Lifetime;
using System.Text;
namespace Remoting.Service
{
public class RemoteMessage : MarshalByRefObject
{
#region Events
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
#endregion Events
#region Methods
public override object InitializeLifetimeService()
{
// indicate that this lease never expires
ILease lease = (ILease)base.InitializeLifetimeService();
if (lease.CurrentState == LeaseState.Initial)
{
lease.InitialLeaseTime = TimeSpan.FromMinutes(0);
}
return lease;
}
public void Send(object o)
{
OnMessageReceived(new MessageReceivedEventArgs(o));
}
private void OnMessageReceived(MessageReceivedEventArgs e)
{
if (MessageReceived != null)
{
MessageReceived(this, e);
}
}
#endregion Methods
}
}
|
#region Header
// Copyright (C) 2012 Daniel Schubert
//
// 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.
#endregion Header
using System;
using System.Collections.Generic;
using System.Text;
namespace Remoting.Service
{
public class RemoteMessage : MarshalByRefObject
{
#region Events
public event EventHandler<MessageReceivedEventArgs> MessageReceived;
#endregion Events
#region Methods
public override object InitializeLifetimeService()
{
// indicate that this lease never expires
return null;
}
public void Send(object o)
{
OnMessageReceived(new MessageReceivedEventArgs(o));
}
private void OnMessageReceived(MessageReceivedEventArgs e)
{
if (MessageReceived != null)
{
MessageReceived(this, e);
}
}
#endregion Methods
}
}
|
mit
|
C#
|
0597c119c5a52d077694f0d91813f1d26c22d57a
|
Fix copy paste misstake
|
erlingsjostrom/TESS-V2,erlingsjostrom/TESS-V2,erlingsjostrom/TESS-V2,erlingsjostrom/TESS-V2,erlingsjostrom/TESS-V2
|
TestRestfulAPI/App_Start/WebApiConfig.cs
|
TestRestfulAPI/App_Start/WebApiConfig.cs
|
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using Microsoft.OData.Edm;
using TestRestfulAPI.RestApi.odata.v1.Articles.Entities;
using TestRestfulAPI.RestApi.odata.v1.Customers.Entities;
using TestRestfulAPI.RestApi.odata.v1.Users.Entities;
namespace TestRestfulAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "default",
// routeTemplate: "api/{version}/{controller}/{action}/{param}",
// defaults: new { version = "v1", controller = "Default", action = "version", param = RouteParameter.Optional }
//);
config.AddApiVersioning(o => o.AssumeDefaultVersionWhenUnspecified = true);
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata/{apiVersion}/{resource}/",
model: GetEdmModel());
}
private static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Article>("Articles");
builder.EntityType<Article>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Customer>("Customers");
builder.EntityType<Customer>().OrderBy().Filter().Select().Expand();
builder.EntitySet<User>("Users");
builder.EntityType<User>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Role>("Roles");
builder.EntityType<Role>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Permission>("Permissions");
builder.EntityType<Permission>().OrderBy().Filter().Select().Expand();
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}
|
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using Microsoft.OData.Edm;
using TestRestfulAPI.RestApi.odata.v1.Articles.Entities;
using TestRestfulAPI.RestApi.odata.v1.Customers.Entities;
using TestRestfulAPI.RestApi.odata.v1.Users.Entities;
namespace TestRestfulAPI
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
//config.Routes.MapHttpRoute(
// name: "default",
// routeTemplate: "api/{version}/{controller}/{action}/{param}",
// defaults: new { version = "v1", controller = "Default", action = "version", param = RouteParameter.Optional }
//);
config.AddApiVersioning(o => o.AssumeDefaultVersionWhenUnspecified = true);
config.MapODataServiceRoute(
routeName: "odata",
routePrefix: "odata/{apiVersion}/{resource}/",
model: GetEdmModel());
}
private static IEdmModel GetEdmModel()
{
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Article>("Articles");
builder.EntityType<Article>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Customer>("Customers");
builder.EntityType<Customer>().OrderBy().Filter().Select().Expand();
builder.EntitySet<User>("Users");
builder.EntityType<User>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Role>("Roles");
builder.EntityType<Role>().OrderBy().Filter().Select().Expand();
builder.EntitySet<Permission>("Permissions");
builder.EntityType<Role>().OrderBy().Filter().Select().Expand();
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}
|
mit
|
C#
|
45e30f4e6e9162db7102641dbca4d5131ec07fba
|
update version to 1.5
|
yixiangling/toxy,tonyqus/toxy,yixiangling/toxy
|
ToxyFramework/Properties/AssemblyInfo.cs
|
ToxyFramework/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Toxy Framework")]
[assembly: AssemblyDescription(".Net Data/Text Extraction Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Neuzilla")]
[assembly: AssemblyProduct("Toxy")]
[assembly: AssemblyCopyright("Apache 2.0")]
[assembly: AssemblyTrademark("Neuzilla")]
[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("3c5f41de-9f62-45cc-b89e-8e377a2e036e")]
// 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.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyInformationalVersion("Toxy 1.5")]
[assembly: AllowPartiallyTrustedCallers]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Toxy Framework")]
[assembly: AssemblyDescription(".Net Data/Text Extraction Framework")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Neuzilla")]
[assembly: AssemblyProduct("Toxy")]
[assembly: AssemblyCopyright("Apache 2.0")]
[assembly: AssemblyTrademark("Neuzilla")]
[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("3c5f41de-9f62-45cc-b89e-8e377a2e036e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyInformationalVersion("Toxy 1.3")]
[assembly: AllowPartiallyTrustedCallers]
|
apache-2.0
|
C#
|
d4085c4040abab9b6482136e76d9113674b8e6c9
|
Fix tests
|
dwragge/memoriser,dwragge/memoriser,dwragge/memoriser
|
Memoriser.UnitTests/API/Queries/GetWordsQueryHandlerTests.cs
|
Memoriser.UnitTests/API/Queries/GetWordsQueryHandlerTests.cs
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using Memoriser.ApplicationCore.Models;
using System.Linq;
using Memoriser.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Memoriser.App.Query.Handlers;
using Memoriser.App.Query.Queries;
using FluentAssertions;
namespace Memoriser.UnitTests.API.Queries
{
public class GetWordsQueryHandlerTestFixture
{
public readonly DbContextOptions<LearningItemContext> Options;
public readonly List<LearningItem> Items = new List<LearningItem>
{
new LearningItem("salut", "hello"),
new LearningItem("générer", "generate"),
new LearningItem("atteindre", new[] { "reach", "achieve" })
{
Interval = RepetitionInterval.FromValues(3, 3.0f)
}
};
public GetWordsQueryHandlerTestFixture()
{
Options = new DbContextOptionsBuilder<LearningItemContext>()
.UseInMemoryDatabase("Get_All")
.Options;
using (var context = new LearningItemContext(Options))
{
context.AddRange(Items);
context.SaveChanges();
}
}
}
public class GetWordsQueryHandlerTests : IClassFixture<GetWordsQueryHandlerTestFixture>
{
private readonly GetWordsQueryHandlerTestFixture _fixture;
public GetWordsQueryHandlerTests(GetWordsQueryHandlerTestFixture textFixture)
{
_fixture = textFixture;
}
[Fact]
public async Task Should_Return_AllItems()
{
using (var context = new LearningItemContext(_fixture.Options))
{
var handler = new FindItemsQueryHandler(context);
var result = await handler.QueryAsync(FindItemsQuery.All);
result.ToList().ShouldAllBeEquivalentTo(_fixture.Items);
}
}
[Fact]
public async Task Should_Return_BasedOnQuery()
{
using (var context = new LearningItemContext(_fixture.Options))
{
var handler = new FindItemsQueryHandler(context);
var result = await handler.QueryAsync(FindItemsQuery.ByWord("salut"));
var item = result.Single();
item.ShouldBeEquivalentTo(_fixture.Items[0]);
}
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
using Memoriser.ApplicationCore.Models;
using System.Linq;
using Memoriser.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Memoriser.App.Query.Handlers;
using Memoriser.App.Query.Queries;
using FluentAssertions;
namespace Memoriser.UnitTests.API.Queries
{
public class GetWordsQueryHandlerTests
{
private readonly DbContextOptions<LearningItemContext> _options;
private readonly List<LearningItem> _items = new List<LearningItem>
{
new LearningItem("salut", "hello"),
new LearningItem("générer", "generate"),
new LearningItem("atteindre", new[] { "reach", "achieve" })
{
Interval = RepetitionInterval.FromValues(3, 3.0f)
}
};
public GetWordsQueryHandlerTests()
{
_options = new DbContextOptionsBuilder<LearningItemContext>()
.UseInMemoryDatabase("Get_All")
.Options;
using (var context = new LearningItemContext(_options))
{
context.AddRange(_items);
context.SaveChanges();
}
}
[Fact]
public async Task Should_Return_AllItems()
{
using (var context = new LearningItemContext(_options))
{
var handler = new FindItemsQueryHandler(context);
var result = await handler.QueryAsync(FindItemsQuery.All);
result.ToList().ShouldAllBeEquivalentTo(_items);
}
}
[Fact]
public async Task Should_Return_BasedOnQuery()
{
using (var context = new LearningItemContext(_options))
{
var handler = new FindItemsQueryHandler(context);
var result = await handler.QueryAsync(FindItemsQuery.ByWord("salut"));
var item = result.Single();
item.ShouldBeEquivalentTo(_items[0]);
}
}
}
}
|
mit
|
C#
|
a5330ddd3730d799a728009a03667ffb5eab2787
|
Set process name to "tripod".
|
rubenv/tripod,rubenv/tripod
|
src/Core/Tripod.Core/Tripod.Base/Core.cs
|
src/Core/Tripod.Core/Tripod.Base/Core.cs
|
//
// Core.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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 Gtk;
using System;
using Hyena;
using Hyena.Jobs;
using Hyena.Data.Sqlite;
using Tripod.Model;
namespace Tripod.Base
{
public class Core
{
static readonly Scheduler scheduler = new Scheduler ();
public static Scheduler Scheduler {
get { return scheduler; }
}
static readonly HyenaSqliteConnection db_connection = new TripodSqliteConnection("test.db");
public static HyenaSqliteConnection DbConnection {
get { return db_connection; }
}
static ICachingPhotoSource main_cache_photo_source;
public static ICachingPhotoSource MainCachePhotoSource {
get { return main_cache_photo_source; }
}
public static void Initialize (string name, ref string[] args)
{
Hyena.Log.Debugging = true;
GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, GLib.Log.PrintTraceLogFunction);
Hyena.Log.Debug ("Initializing Core");
ApplicationContext.TrySetProcessName ("tripod");
Application.Init (name, ref args);
main_cache_photo_source = new MainCachePhotoSource ();
main_cache_photo_source.Start ();
}
}
}
|
//
// Core.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
//
// Copyright (c) 2010 Ruben Vermeersch <ruben@savanne.be>
//
// 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 Gtk;
using System;
using Hyena.Jobs;
using Hyena.Data.Sqlite;
using Tripod.Model;
namespace Tripod.Base
{
public class Core
{
static readonly Scheduler scheduler = new Scheduler ();
public static Scheduler Scheduler {
get { return scheduler; }
}
static readonly HyenaSqliteConnection db_connection = new TripodSqliteConnection("test.db");
public static HyenaSqliteConnection DbConnection {
get { return db_connection; }
}
static ICachingPhotoSource main_cache_photo_source;
public static ICachingPhotoSource MainCachePhotoSource {
get { return main_cache_photo_source; }
}
public static void Initialize (string name, ref string[] args)
{
Hyena.Log.Debugging = true;
GLib.Log.SetLogHandler ("Gtk", GLib.LogLevelFlags.Critical, GLib.Log.PrintTraceLogFunction);
Hyena.Log.Debug ("Initializing Core");
Application.Init (name, ref args);
main_cache_photo_source = new MainCachePhotoSource ();
main_cache_photo_source.Start ();
}
}
}
|
mit
|
C#
|
b46645b9a83c5bf143dcc15e50989eb0229927ec
|
Allow reading numbers from strings in JSON
|
henkmollema/Dommel
|
src/Dommel.Json/JsonObjectTypeHandler.cs
|
src/Dommel.Json/JsonObjectTypeHandler.cs
|
using System;
using System.Data;
using System.Text.Json;
using System.Text.Json.Serialization;
using Dapper;
namespace Dommel.Json
{
internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};
public void SetValue(IDbDataParameter parameter, object? value)
{
parameter.Value = value is null || value is DBNull
? DBNull.Value
: JsonSerializer.Serialize(value, JsonOptions);
parameter.DbType = DbType.String;
}
public object? Parse(Type destinationType, object? value) =>
value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
}
}
|
using System;
using System.Data;
using System.Text.Json;
using Dapper;
namespace Dommel.Json
{
internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler
{
private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
};
public void SetValue(IDbDataParameter parameter, object? value)
{
parameter.Value = value is null || value is DBNull
? (object)DBNull.Value
: JsonSerializer.Serialize(value, JsonOptions);
parameter.DbType = DbType.String;
}
public object? Parse(Type destinationType, object? value) =>
value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null;
}
}
|
mit
|
C#
|
4953127a43468bb2542297b6339c36ef6973c472
|
Fix namespace.
|
PaulTrampert/PTrampert.Webpack.CacheBuster
|
PTrampert.Webpack.CacheBuster/ServiceCollectionExtensions.cs
|
PTrampert.Webpack.CacheBuster/ServiceCollectionExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
using PTrampert.Webpack.CacheBuster;
namespace Microsoft.Extensions.DependencyInjection
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCacheBusting(this IServiceCollection services)
{
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
return services.AddSingleton<ICacheBuster, CacheBuster>();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using PTrampert.Webpack.CacheBuster;
namespace Microsoft.Extensions.DependencyInjection.Extensions
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddCacheBusting(this IServiceCollection services)
{
services.TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
return services.AddSingleton<ICacheBuster, CacheBuster>();
}
}
}
|
mit
|
C#
|
b946e66f0310841ab8aad824d1c4d1cf2005f695
|
fix MenuItemExtensions [Wait]ChildByCondition
|
signumsoftware/framework,MehdyKarimpour/extensions,MehdyKarimpour/extensions,signumsoftware/extensions,signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions,AlejandroCano/extensions
|
Signum.Windows.Extensions.UIAutomation/MenuItemExtensions.cs
|
Signum.Windows.Extensions.UIAutomation/MenuItemExtensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using Signum.Utilities;
namespace Signum.Windows.UIAutomation
{
public static class MenuItemExtensions
{
public static AutomationElement MenuItemOpenWindow(this AutomationElement window, params string[] menuNames)
{
var menuItem = MenuItemFind(window, menuNames);
AutomationElement newWindow = window.GetWindowAfter(
() => menuItem.ButtonInvoke(),
() => "New windows opened after menu " + menuNames.ToString(" -> "));
return newWindow;
}
public static AutomationElement MenuItemFind(AutomationElement window, params string[] menuNames)
{
if (menuNames == null || menuNames.Length == 0)
throw new ArgumentNullException("menuNames");
var menuBar = window.Child(c => c.Current.ControlType == ControlType.Menu);
var menuItem = menuBar.ChildByCondition(new PropertyCondition(AutomationElement.NameProperty, menuNames[0]));
for (int i = 1; i < menuNames.Length; i++)
{
menuItem.Pattern<ExpandCollapsePattern>().Expand();
menuItem = menuItem.WaitChildByCondition(new PropertyCondition(AutomationElement.NameProperty, menuNames[i]));
}
return menuItem;
}
//static MenuItemCached[] cachedMenus;
//public static void MenuItemExploreInvoke(this WindowProxy window, Condition condition)
//{
// if (cachedMenus == null)
// {
// var menuBar = window.Owner.Child(c => c.Current.ControlType == ControlType.Menu);
// var menuItem = menuBar.ChildrenAll().Select(c=>new MenuItemCached(c));
// }
//}
}
//public class MenuItemCached
//{
// public string Name;
// public bool Expandable;
// public MenuItemCached[] childs;
// private AutomationElement c;
// public MenuItemCached(AutomationElement c)
// {
// Name = c.Current.Name;
// }
//}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Automation;
using Signum.Utilities;
namespace Signum.Windows.UIAutomation
{
public static class MenuItemExtensions
{
public static AutomationElement MenuItemOpenWindow(this AutomationElement window, params string[] menuNames)
{
var menuItem = MenuItemFind(window, menuNames);
AutomationElement newWindow = window.GetWindowAfter(
() => menuItem.ButtonInvoke(),
() => "New windows opened after menu " + menuNames.ToString(" -> "));
return newWindow;
}
public static AutomationElement MenuItemFind(AutomationElement window, params string[] menuNames)
{
if (menuNames == null || menuNames.Length == 0)
throw new ArgumentNullException("menuNames");
var menuBar = window.Child(c => c.Current.ControlType == ControlType.Menu);
var menuItem = menuBar.ChildByCondition(new PropertyCondition(AutomationElement.NameProperty, menuNames[0]));
for (int i = 1; i < menuNames.Length; i++)
{
menuItem.Pattern<ExpandCollapsePattern>().Expand();
menuItem = menuItem.ChildByCondition(new PropertyCondition(AutomationElement.NameProperty, menuNames[i]));
}
return menuItem;
}
//static MenuItemCached[] cachedMenus;
//public static void MenuItemExploreInvoke(this WindowProxy window, Condition condition)
//{
// if (cachedMenus == null)
// {
// var menuBar = window.Owner.Child(c => c.Current.ControlType == ControlType.Menu);
// var menuItem = menuBar.ChildrenAll().Select(c=>new MenuItemCached(c));
// }
//}
}
//public class MenuItemCached
//{
// public string Name;
// public bool Expandable;
// public MenuItemCached[] childs;
// private AutomationElement c;
// public MenuItemCached(AutomationElement c)
// {
// Name = c.Current.Name;
// }
//}
}
|
mit
|
C#
|
a44445cbceb6b70605ac7b8e53c3dd3668a0f576
|
Add Set method to SwitchMultiLevel
|
MiTheFreeman/ZWave4Net,roblans/ZWave4Net
|
ZWave/CommandClasses/SwitchMultiLevel.cs
|
ZWave/CommandClasses/SwitchMultiLevel.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZWave.Channel;
namespace ZWave.CommandClasses
{
public class SwitchMultiLevel : CommandClassBase
{
enum command : byte
{
Set = 0x01,
Get = 0x02,
Report = 0x03
}
public event EventHandler<ReportEventArgs<SwitchMultiLevelReport>> Changed;
public SwitchMultiLevel(Node node) : base(node, CommandClass.SwitchMultiLevel)
{
}
public async Task<SwitchMultiLevelReport> Get()
{
var response = await Channel.Send(Node, new Command(Class, command.Get), command.Report);
return new SwitchMultiLevelReport(Node, response);
}
public async Task Set(byte value)
{
await Channel.Send(Node, new Command(Class, command.Set, value));
}
protected internal override void HandleEvent(Command command)
{
base.HandleEvent(command);
var report = new SwitchMultiLevelReport(Node, command.Payload);
OnChanged(new ReportEventArgs<SwitchMultiLevelReport>(report));
}
protected virtual void OnChanged(ReportEventArgs<SwitchMultiLevelReport> e)
{
var handler = Changed;
if (handler != null)
{
handler(this, e);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using ZWave.Channel;
namespace ZWave.CommandClasses
{
public class SwitchMultiLevel : CommandClassBase
{
enum command : byte
{
//SupportedGet = 0x01,
//SupportedReport = 0x02,
Get = 0x04,
Report = 0x05
}
public event EventHandler<ReportEventArgs<SwitchMultiLevelReport>> Changed;
public SwitchMultiLevel(Node node) : base(node, CommandClass.SwitchMultiLevel)
{
}
public async Task<SwitchMultiLevelReport> Get()
{
var response = await Channel.Send(Node, new Command(Class, command.Get), command.Report);
return new SwitchMultiLevelReport(Node, response);
}
protected internal override void HandleEvent(Command command)
{
base.HandleEvent(command);
var report = new SwitchMultiLevelReport(Node, command.Payload);
OnChanged(new ReportEventArgs<SwitchMultiLevelReport>(report));
}
protected virtual void OnChanged(ReportEventArgs<SwitchMultiLevelReport> e)
{
var handler = Changed;
if (handler != null)
{
handler(this, e);
}
}
}
}
|
mit
|
C#
|
11d65208d1ca471b882562d6ec1e1f2289428b23
|
Revert "Remove unnecessary lines"
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/Behaviors/CheckMarkVisibilityBehavior.cs
|
WalletWasabi.Fluent/Behaviors/CheckMarkVisibilityBehavior.cs
|
using Avalonia;
using Avalonia.Controls;
using ReactiveUI;
using System;
using System.Reactive.Linq;
namespace WalletWasabi.Fluent.Behaviors
{
public class CheckMarkVisibilityBehavior : AttachedToVisualTreeBehavior<PathIcon>
{
public static readonly StyledProperty<bool> HasErrorsProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, bool>(nameof(HasErrors), false);
public static readonly StyledProperty<bool> IsFocusedProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, bool>(nameof(IsFocused), false);
public static readonly StyledProperty<string> TextProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, string>(nameof(Text), "");
public bool HasErrors
{
get => GetValue(HasErrorsProperty);
set => SetValue(HasErrorsProperty, value);
}
public bool IsFocused
{
get => GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
public string Text
{
get => GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly StyledProperty<TextBox> OwnerTextBoxProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, TextBox>(nameof(OwnerTextBox), null!);
public TextBox OwnerTextBox
{
get => GetValue(OwnerTextBoxProperty);
set => SetValue(OwnerTextBoxProperty, value);
}
protected override void OnAttachedToVisualTree()
{
this.WhenAnyValue(
x => x.HasErrors,
x => x.IsFocused,
x => x.Text)
.Throttle(TimeSpan.FromMilliseconds(100))
.ObserveOn(RxApp.MainThreadScheduler)
.Where(_ => AssociatedObject is { })
.Subscribe(_ => AssociatedObject!.Opacity = !HasErrors && !IsFocused && !string.IsNullOrEmpty(Text) ? 1 : 0);
Observable
.FromEventPattern<AvaloniaPropertyChangedEventArgs>(OwnerTextBox, nameof(OwnerTextBox.PropertyChanged))
.Select(x => x.EventArgs)
.Where(x => x.Property.Name == "HasErrors")
.Subscribe(x => HasErrors = (bool)x.NewValue!);
}
}
}
|
using Avalonia;
using Avalonia.Controls;
using ReactiveUI;
using System;
using System.Reactive.Linq;
namespace WalletWasabi.Fluent.Behaviors
{
public class CheckMarkVisibilityBehavior : AttachedToVisualTreeBehavior<PathIcon>
{
public static readonly StyledProperty<bool> HasErrorsProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, bool>(nameof(HasErrors), false);
public static readonly StyledProperty<bool> IsFocusedProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, bool>(nameof(IsFocused), false);
public static readonly StyledProperty<string> TextProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, string>(nameof(Text), "");
public bool HasErrors
{
get => GetValue(HasErrorsProperty);
set => SetValue(HasErrorsProperty, value);
}
public bool IsFocused
{
get => GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
public string Text
{
get => GetValue(TextProperty);
set => SetValue(TextProperty, value);
}
public static readonly StyledProperty<TextBox> OwnerTextBoxProperty =
AvaloniaProperty.Register<CheckMarkVisibilityBehavior, TextBox>(nameof(OwnerTextBox), null!);
public TextBox OwnerTextBox
{
get => GetValue(OwnerTextBoxProperty);
set => SetValue(OwnerTextBoxProperty, value);
}
protected override void OnAttachedToVisualTree()
{
this.WhenAnyValue(
x => x.HasErrors,
x => x.IsFocused,
x => x.Text)
.Subscribe(_ => AssociatedObject!.Opacity = !HasErrors && !IsFocused && !string.IsNullOrEmpty(Text) ? 1 : 0);
Observable
.FromEventPattern<AvaloniaPropertyChangedEventArgs>(OwnerTextBox, nameof(OwnerTextBox.PropertyChanged))
.Select(x => x.EventArgs)
.Where(x => x.Property.Name == "HasErrors")
.Subscribe(x => HasErrors = (bool)x.NewValue!);
}
}
}
|
mit
|
C#
|
f2390728c29c2f683c00f706dc88e01e6d5f4c2f
|
Save period configuration
|
vlastikcz/wallpaper-monster,vlastikcz/wallpaper-monster
|
WallpaperChangerApplication/WallpaperChangerConfiguration.cs
|
WallpaperChangerApplication/WallpaperChangerConfiguration.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WallpaperMonsterApplication
{
class WallpaperChangerConfiguration
{
public Double findPeriod() {
return Convert.ToDouble(findPeriodDecimal());
}
public Decimal findPeriodDecimal()
{
return Properties.Settings.Default.timer;
}
public void savePeriod(Decimal period) {
Properties.Settings.Default.timer = period;
Properties.Settings.Default.Save();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WallpaperMonsterApplication
{
class WallpaperChangerConfiguration
{
public Double findPeriod() {
return Convert.ToDouble(findPeriodDecimal());
}
public Decimal findPeriodDecimal()
{
return Properties.Settings.Default.timer;
}
public void savePeriod(Decimal period) {
Properties.Settings.Default.timer = period;
}
}
}
|
mit
|
C#
|
f1cf53d7a561744cadc8b79e7c32a8445c1f0e2d
|
Use TLS1.2 for GitHub
|
projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService
|
SimpleWAWS/Authentication/AuthUtilities.cs
|
SimpleWAWS/Authentication/AuthUtilities.cs
|
using System;
using System.IO;
using System.Net;
namespace SimpleWAWS.Authentication
{
public static class AuthUtilities
{
public static string GetContentFromUrl(string url)
{
//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "")
{
//specify to use TLS 1.2 as default connection
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.UserAgent = "x-ms-try-appservice";
if (jsonAccept)
{
request.Accept = "application/json";
}
if (addGitHubHeaders)
{
request.Accept = "application/vnd.github.v3+json";
}
if (!String.IsNullOrEmpty(AuthorizationHeader))
{
request.Headers.Add("Authorization", AuthorizationHeader);
}
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}
}
|
using System;
using System.IO;
using System.Net;
namespace SimpleWAWS.Authentication
{
public static class AuthUtilities
{
public static string GetContentFromUrl(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
public static string GetContentFromGitHubUrl(string url, string method = "GET", bool jsonAccept = false, bool addGitHubHeaders = false, string AuthorizationHeader = "")
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
request.UserAgent = "x-ms-try-appservice";
if (jsonAccept)
{
request.Accept = "application/json";
}
if (addGitHubHeaders)
{
request.Accept = "application/vnd.github.v3+json";
}
if (!String.IsNullOrEmpty(AuthorizationHeader))
{
request.Headers.Add("Authorization", AuthorizationHeader);
}
using (var response = request.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
return reader.ReadToEnd();
}
}
}
}
}
|
apache-2.0
|
C#
|
2110ba1eb03de14a6fa2218856c23bb03b8cd163
|
remove duplicate
|
molinch/FFImageLoading,luberda-molinet/FFImageLoading
|
source/FFImageLoading.Common/Helpers/PreserveAttribute.cs
|
source/FFImageLoading.Common/Helpers/PreserveAttribute.cs
|
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("FFImageLoading.Transformations"), InternalsVisibleTo("FFImageLoading.Svg.Forms")]
namespace FFImageLoading
{
sealed class PreserveAttribute : System.Attribute
{
public bool AllMembers;
public bool Conditional;
}
}
|
using System;
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("FFImageLoading.Transformations"),
InternalsVisibleTo("FFImageLoading.Svg.Forms"),
InternalsVisibleTo("FFImageLoading.Transformations")
]
namespace FFImageLoading
{
sealed class PreserveAttribute : System.Attribute
{
public bool AllMembers;
public bool Conditional;
}
}
|
mit
|
C#
|
83bcdbb4df30f16da764a5da74fd31045c28100f
|
Fix a new test name generation.
|
rsdn/nitra,JetBrains/Nitra,rsdn/nitra,JetBrains/Nitra
|
Nitra.Visualizer/AddTest.xaml.cs
|
Nitra.Visualizer/AddTest.xaml.cs
|
using System;
using System.IO;
using System.Linq;
using System.Windows;
using Nitra.Visualizer.Properties;
namespace Nitra.Visualizer
{
/// <summary>
/// Interaction logic for Test.xaml
/// </summary>
public partial class AddTest
{
readonly string _testSuitPath;
readonly string _code;
readonly string _gold;
public AddTest(string testSuitPath, string code, string gold)
{
_testSuitPath = testSuitPath;
_code = code;
_gold = gold;
InitializeComponent();
_testName.Text = MakeDefaultName();
}
private string MakeDefaultName()
{
var path = _testSuitPath;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var found = Directory.EnumerateFiles(path, "*.test").FirstOrDefault(file => File.ReadAllText(file).Equals(_code, StringComparison.Ordinal));
if (found == null)
{
const string Ext = ".test";
var fileIndex = Directory.EnumerateFiles(path, "*" + Ext).Count();
string fileName;
do
{
fileIndex++;
fileName = "test-" + fileIndex.ToString("0000");
}
while (File.Exists(Path.Combine(path, fileName + Ext)));
return fileName;
}
return Path.GetFileNameWithoutExtension(found);
}
public string TestName { get; private set; }
private void _okButton_Click(object sender, RoutedEventArgs e)
{
var path = _testSuitPath;
var filePath = Path.Combine(path, _testName.Text) + ".test";
try
{
File.WriteAllText(filePath, _code);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Nitra Visualizer",
MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.Cancel);
return;
}
var goldFilePath = Path.ChangeExtension(filePath, ".gold");
File.WriteAllText(goldFilePath, _gold);
TestName = _testName.Text;
this.DialogResult = true;
Close();
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Windows;
using Nitra.Visualizer.Properties;
namespace Nitra.Visualizer
{
/// <summary>
/// Interaction logic for Test.xaml
/// </summary>
public partial class AddTest
{
readonly string _testSuitPath;
readonly string _code;
readonly string _gold;
public AddTest(string testSuitPath, string code, string gold)
{
_testSuitPath = testSuitPath;
_code = code;
_gold = gold;
InitializeComponent();
_testName.Text = MakeDefaultName();
}
private string MakeDefaultName()
{
var path = _testSuitPath;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var found = Directory.EnumerateFiles(path, "*.test").FirstOrDefault(file => File.ReadAllText(file).Equals(_code, StringComparison.Ordinal));
if (found == null)
return "test-" + (Directory.EnumerateFiles(path, "*.test").Count() + 1).ToString("0000");
return Path.GetFileNameWithoutExtension(found);
}
public string TestName { get; private set; }
private void _okButton_Click(object sender, RoutedEventArgs e)
{
var path = _testSuitPath;
var filePath = Path.Combine(path, _testName.Text) + ".test";
try
{
File.WriteAllText(filePath, _code);
}
catch (Exception ex)
{
MessageBox.Show(this, ex.Message, "Nitra Visualizer",
MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.Cancel);
return;
}
var goldFilePath = Path.ChangeExtension(filePath, ".gold");
File.WriteAllText(goldFilePath, _gold);
TestName = _testName.Text;
this.DialogResult = true;
Close();
}
}
}
|
apache-2.0
|
C#
|
dc097700e5fed60850e4bfe641f7ae2d87bd9fd0
|
add cache for optional conversations. (C# to F#)
|
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
|
Tweek.JPad.Utils/JPadRulesParserAdapter.cs
|
Tweek.JPad.Utils/JPadRulesParserAdapter.cs
|
using Engine.Core.Context;
using Engine.Core.Rules;
using Engine.DataTypes;
using Tweek.JPad;
using System.Collections.Specialized;
using LanguageExt;
using System;
namespace Tweek.JPad.Utils
{
public class AnonymousRule : IRule
{
private readonly Func<GetContextValue, Option<ConfigurationValue>> fn;
public AnonymousRule(Func<GetContextValue, Option<ConfigurationValue>> fn)
{
this.fn = fn;
}
public Option<ConfigurationValue> GetValue(GetContextValue fullContext) => fn(fullContext);
}
public class AnonymousParser : IRuleParser
{
private readonly Func<string, IRule> fn;
public AnonymousParser(Func<string, IRule> fn)
{
this.fn = fn;
}
public IRule Parse(string source) => fn(source);
}
public class JPadRulesParserAdapter
{
public static IRuleParser Convert(JPadParser parser)
{
return new AnonymousParser((source) =>
{
var dictionary = new ListDictionary();
var compiled = parser.Parse.Invoke(source);
return new AnonymousRule(context => FSharp.fs(compiled.Invoke((s) => {
if (!dictionary.Contains(s)) {
dictionary[s] = context.Invoke(s).ToFSharp();
}
return (Microsoft.FSharp.Core.FSharpOption<string>)dictionary[s];
})).Map(ConfigurationValue.New));
});
}
}
}
|
using Engine.Core.Context;
using Engine.Core.Rules;
using Engine.DataTypes;
using Tweek.JPad;
using LanguageExt;
using System;
namespace Tweek.JPad.Utils
{
public class AnonymousRule : IRule
{
private readonly Func<GetContextValue, Option<ConfigurationValue>> fn;
public AnonymousRule(Func<GetContextValue, Option<ConfigurationValue>> fn)
{
this.fn = fn;
}
public Option<ConfigurationValue> GetValue(GetContextValue fullContext) => fn(fullContext);
}
public class AnonymousParser : IRuleParser
{
private readonly Func<string, IRule> fn;
public AnonymousParser(Func<string, IRule> fn)
{
this.fn = fn;
}
public IRule Parse(string source) => fn(source);
}
public class JPadRulesParserAdapter
{
public static IRuleParser Convert(JPadParser parser)
{
return new AnonymousParser((source) =>
{
var compiled = parser.Parse.Invoke(source);
return new AnonymousRule(context =>
FSharp.fs(compiled.Invoke((s) => context.Invoke(s).ToFSharp()))
.Map(ConfigurationValue.New));
});
}
}
}
|
mit
|
C#
|
0c1f75f63d25ecfdcfff6492dba34892ff242203
|
format OutputWindowHelper
|
jwldnr/VisualLinter
|
VisualLinter/Helpers/OutputWindowHelper.cs
|
VisualLinter/Helpers/OutputWindowHelper.cs
|
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
namespace jwldnr.VisualLinter.Helpers
{
internal static class OutputWindowHelper
{
private static IVsOutputWindowPane OutputWindowPane =>
_outputWindowPane ?? (_outputWindowPane = GetOutputWindowPane());
private static IVsOutputWindowPane _outputWindowPane;
internal static void WriteLine(string message)
{
var outputWindowPane = OutputWindowPane;
outputWindowPane?.OutputString($"[{Vsix.Name}]: {message + Environment.NewLine}");
}
private static IVsOutputWindowPane GetOutputWindowPane()
{
var outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
if (null == outputWindow)
return null;
var outputPaneGuid = new Guid(PackageGuids.GuidVisualLinterPackageOutputPane.ToByteArray());
outputWindow.CreatePane(ref outputPaneGuid, Vsix.Name, 1, 1);
outputWindow.GetPane(ref outputPaneGuid, out IVsOutputWindowPane windowPane);
return windowPane;
}
}
}
|
using System;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace jwldnr.VisualLinter.Helpers
{
internal static class OutputWindowHelper
{
private static IVsOutputWindowPane _outputWindowPane;
private static IVsOutputWindowPane OutputWindowPane =>
_outputWindowPane ?? (_outputWindowPane = GetOutputWindowPane());
private static IVsOutputWindowPane GetOutputWindowPane()
{
var outputWindow = Package.GetGlobalService(typeof(SVsOutputWindow)) as IVsOutputWindow;
if (null == outputWindow)
return null;
var outputPaneGuid = new Guid(PackageGuids.GuidVisualLinterPackageOutputPane.ToByteArray());
outputWindow.CreatePane(ref outputPaneGuid, Vsix.Name, 1, 1);
outputWindow.GetPane(ref outputPaneGuid, out IVsOutputWindowPane windowPane);
return windowPane;
}
internal static void WriteLine(string message)
{
var outputWindowPane = OutputWindowPane;
outputWindowPane?.OutputString($"[{Vsix.Name}]: {message + Environment.NewLine}");
}
}
}
|
mit
|
C#
|
b51b017005e73e4b5694547631204b74eb8d4d4b
|
Fix plugin script generator causing JS syntax error
|
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
|
Plugins/PluginScriptGenerator.cs
|
Plugins/PluginScriptGenerator.cs
|
using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("};");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
|
using System.Text;
namespace TweetDck.Plugins{
static class PluginScriptGenerator{
public static string GenerateConfig(PluginConfig config){
return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty;
}
public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){
StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150);
build.Append("(function(").Append(environment.GetScriptVariables()).Append("){");
build.Append("let tmp={");
build.Append("id:\"").Append(pluginIdentifier).Append("\",");
build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}");
build.Append("});");
build.Append("tmp.obj.$token=").Append(pluginToken).Append(";");
build.Append("window.TD_PLUGINS.install(tmp);");
build.Append("})(").Append(environment.GetScriptVariables()).Append(");");
return build.ToString();
}
}
}
|
mit
|
C#
|
37bcf85b7242c5fc2a19d5378eb8dd783786b345
|
Add empty to null check
|
FreecraftCore/FreecraftCore.Payload.Serializer,FreecraftCore/FreecraftCore.Serializer,FreecraftCore/FreecraftCore.Serializer
|
tests/FreecraftCore.Serializer.Tests/Tests/StringTests.cs
|
tests/FreecraftCore.Serializer.Tests/Tests/StringTests.cs
|
using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreecraftCore.Serializer.Tests
{
[TestFixture]
public class StringTests
{
[Test]
public static void Test_String_Serializer_Serializes()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));
//assert
Assert.AreEqual(value, "Hello!");
}
[Test]
public static void Test_String_Serializer_Can_Serialize_Empty_String()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize(""));
//assert
Assert.Null(value);
}
}
}
|
using FreecraftCore.Serializer.KnownTypes;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FreecraftCore.Serializer.Tests
{
[TestFixture]
public class StringTests
{
[Test]
public static void Test_String_Serializer_Serializes()
{
//arrange
SerializerService serializer = new SerializerService();
serializer.Compile();
//act
string value = serializer.Deserialize<string>(serializer.Serialize("Hello!"));
//assert
Assert.AreEqual(value, "Hello!");
}
}
}
|
agpl-3.0
|
C#
|
aedb18b9f21e0e98af5f3720369314658565a2aa
|
Make RulesetID non-nullable
|
ppy/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu
|
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.cs
|
osu.Game/Online/RealtimeMultiplayer/MultiplayerRoomSettings.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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int RulesetID { get; set; }
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
|
// 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.
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Game.Online.API;
namespace osu.Game.Online.RealtimeMultiplayer
{
[Serializable]
public class MultiplayerRoomSettings : IEquatable<MultiplayerRoomSettings>
{
public int BeatmapID { get; set; }
public int? RulesetID { get; set; }
public string Name { get; set; } = "Unnamed room";
[NotNull]
public IEnumerable<APIMod> Mods { get; set; } = Enumerable.Empty<APIMod>();
public bool Equals(MultiplayerRoomSettings other) => BeatmapID == other.BeatmapID && Mods.SequenceEqual(other.Mods) && RulesetID == other.RulesetID && Name.Equals(other.Name, StringComparison.Ordinal);
public override string ToString() => $"Name:{Name} Beatmap:{BeatmapID} Mods:{string.Join(',', Mods)} Ruleset:{RulesetID}";
}
}
|
mit
|
C#
|
82c7018e0e2f6863e50b3a5a3cdd4a7ca6a0387a
|
Update Patent.cs
|
whitneyhaddow/cat-patents-v2
|
Haddow_Whitney_Lab2_CP3/Haddow_Whitney_Lab2_CP3/Haddow_Whitney_Lab2_CP3/Patent.cs
|
Haddow_Whitney_Lab2_CP3/Haddow_Whitney_Lab2_CP3/Haddow_Whitney_Lab2_CP3/Patent.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Haddow_Whitney_Lab2_CP3
{
public class Patent
{
public Patent() { }
public Patent(int number, string appNumber, string description, DateTime filingDate, string inventor, string inventor2)
{
Number = number;
AppNumber = appNumber;
Description = description;
FilingDate = filingDate;
Inventor = inventor;
Inventor2 = inventor2;
}
public int Number { get; set; }
public string AppNumber { get; set; }
public string Description { get; set; }
public DateTime FilingDate { get; set; }
public string Inventor { get; set; }
public string Inventor2 { get; set; }
} //END CLASS
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Haddow_Whitney_Lab2_CP3
{
public class Patent
{
public Patent() { } //default constructor
public Patent(int number, string appNumber, string description, DateTime filingDate, string inventor, string inventor2)
{
Number = number;
AppNumber = appNumber;
Description = description;
FilingDate = filingDate;
Inventor = inventor;
Inventor2 = inventor2;
}
public int Number { get; set; }
public string AppNumber { get; set; }
public string Description { get; set; }
public DateTime FilingDate { get; set; }
public string Inventor { get; set; }
public string Inventor2 { get; set; }
} //END CLASS
}
|
mit
|
C#
|
3088e558474e80ca7ee0e51a9dfdbe44cbb84abf
|
Update _ZenDeskWidget.cshtml
|
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
|
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Shared/_ZenDeskWidget.cshtml
|
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Shared/_ZenDeskWidget.cshtml
|
@using SFA.DAS.ProviderApprenticeshipsService.Web.Extensions
@{
var label = !string.IsNullOrEmpty(ViewBag.ZenDeskLabel) ? ViewBag.ZenDeskLabel : ViewBag.PageId;
}
<script type="text/javascript">
window.zESettings = {
webWidget: {
contactForm: {
attachments: false
},
chat: {
menuOptions: {
emailTranscript: false
}
},
helpCenter: {
filter: {
section: @Html.GetZenDeskSnippetSectionId()
}
}
}
};
</script>
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=@Html.GetZenDeskSnippetKey()"></script>
<script id="co-snippet" src="https://embed-euw1.rcrsv.io/@Html.GetZenDeskCobrowsingSnippetKey()?zwwi=1"></script>
@Html.SetZendeskLabels($"matp-{label}")
|
@using SFA.DAS.ProviderApprenticeshipsService.Web.Extensions
@{
var label = !string.IsNullOrEmpty(ViewBag.ZenDeskLabel) ? ViewBag.ZenDeskLabel : ViewBag.Title;
}
<script type="text/javascript">
window.zESettings = {
webWidget: {
contactForm: {
attachments: false
},
chat: {
menuOptions: {
emailTranscript: false
}
},
helpCenter: {
filter: {
section: @Html.GetZenDeskSnippetSectionId()
}
}
}
};
</script>
<script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=@Html.GetZenDeskSnippetKey()"></script>
<script id="co-snippet" src="https://embed-euw1.rcrsv.io/@Html.GetZenDeskCobrowsingSnippetKey()?zwwi=1"></script>
@Html.SetZendeskLabels($"matp-{label}")
|
mit
|
C#
|
7ddb5346e8632660698a0d0df3e508157554f325
|
Resolve binding exception on netfx.
|
jherby2k/AudioWorks
|
AudioWorks/AudioWorks.Extensions/ExtensionContainerBase.cs
|
AudioWorks/AudioWorks.Extensions/ExtensionContainerBase.cs
|
using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Loader;
namespace AudioWorks.Extensions
{
abstract class ExtensionContainerBase
{
static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
"Extensions"));
protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
.WithAssemblies(_extensionRoot
.EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
.Select(f => f.FullName)
.Select(Assembly.LoadFrom))
.CreateContainer();
static ExtensionContainerBase()
{
// Search all extension directories for unresolved references
// Assembly.LoadFrom only works on the full framework
if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework",
StringComparison.Ordinal))
AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
Assembly.LoadFrom(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
// Use AssemblyLoadContext on .NET Core
else
UseAssemblyLoadContext();
}
static void UseAssemblyLoadContext()
{
// Workaround - this needs to reside in a separate method to avoid a binding exception with the desktop
// framework, as System.Runtime.Loader does not include a net462 library.
AssemblyLoadContext.Default.Resolving += (context, name) =>
AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
}
}
}
|
using System;
using System.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
namespace AudioWorks.Extensions
{
abstract class ExtensionContainerBase
{
static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine(
Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty,
"Extensions"));
protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration()
.WithAssemblies(_extensionRoot
.EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories)
.Select(f => f.FullName)
.Select(Assembly.LoadFrom))
.CreateContainer();
static ExtensionContainerBase()
{
// Search all extension directories for unresolved references
// .NET Core
AssemblyLoadContext.Default.Resolving += (context, name) =>
AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
// Full Framework
AppDomain.CurrentDomain.AssemblyResolve += (context, name) =>
Assembly.LoadFrom(_extensionRoot
.EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories)
.FirstOrDefault()?
.FullName);
}
}
}
|
agpl-3.0
|
C#
|
19ee344a75644b8e84fdd8269436de9d475caf2a
|
check to avoid tricky redirects
|
appharbor/AppHarbor.Web.Security
|
AuthenticationExample.Web/Controllers/SessionController.cs
|
AuthenticationExample.Web/Controllers/SessionController.cs
|
using System;
using System.Linq;
using System.Web.Mvc;
using AppHarbor.Web.Security;
using AuthenticationExample.Web.Model;
using AuthenticationExample.Web.PersistenceSupport;
using AuthenticationExample.Web.ViewModels;
namespace AuthenticationExample.Web.Controllers
{
public class SessionController : Controller
{
private readonly IAuthenticator _authenticator;
private readonly IRepository _repository;
public SessionController(IAuthenticator authenticator, IRepository repository)
{
_authenticator = authenticator;
_repository = repository;
}
[HttpGet]
public ActionResult New(string returnUrl)
{
return View(new SessionViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public ActionResult Create(SessionViewModel sessionViewModel)
{
User user = null;
if (ModelState.IsValid)
{
user = _repository.GetAll<User>().SingleOrDefault(x => x.Username == sessionViewModel.Username);
if (user == null)
{
ModelState.AddModelError("Username", "User not found");
}
}
if (ModelState.IsValid)
{
if (!BCrypt.Net.BCrypt.Verify(sessionViewModel.Password, user.Password))
{
ModelState.AddModelError("Password", "Wrong password");
}
}
if (ModelState.IsValid)
{
_authenticator.SetCookie(user.Username);
var returnUrl = sessionViewModel.ReturnUrl;
if (!string.IsNullOrEmpty(returnUrl))
{
var returnUri = new Uri(returnUrl);
if (!returnUri.IsAbsoluteUri || returnUri.Host == Request.Url.Host)
{
return Redirect(sessionViewModel.ReturnUrl);
}
}
return RedirectToAction("Index", "Home");
}
return View("New", sessionViewModel);
}
[HttpPost]
public ActionResult Destroy()
{
_authenticator.SignOut();
Session.Abandon();
return RedirectToAction("Index", "Home");
}
}
}
|
using System.Linq;
using System.Web.Mvc;
using AppHarbor.Web.Security;
using AuthenticationExample.Web.Model;
using AuthenticationExample.Web.PersistenceSupport;
using AuthenticationExample.Web.ViewModels;
namespace AuthenticationExample.Web.Controllers
{
public class SessionController : Controller
{
private readonly IAuthenticator _authenticator;
private readonly IRepository _repository;
public SessionController(IAuthenticator authenticator, IRepository repository)
{
_authenticator = authenticator;
_repository = repository;
}
[HttpGet]
public ActionResult New(string returnUrl)
{
return View(new SessionViewModel { ReturnUrl = returnUrl });
}
[HttpPost]
public ActionResult Create(SessionViewModel sessionViewModel)
{
User user = null;
if (ModelState.IsValid)
{
user = _repository.GetAll<User>().SingleOrDefault(x => x.Username == sessionViewModel.Username);
if (user == null)
{
ModelState.AddModelError("Username", "User not found");
}
}
if (ModelState.IsValid)
{
if (!BCrypt.Net.BCrypt.Verify(sessionViewModel.Password, user.Password))
{
ModelState.AddModelError("Password", "Wrong password");
}
}
if (ModelState.IsValid)
{
_authenticator.SetCookie(user.Username);
if (!string.IsNullOrEmpty(sessionViewModel.ReturnUrl))
{
return Redirect(sessionViewModel.ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
return View("New", sessionViewModel);
}
[HttpPost]
public ActionResult Destroy()
{
_authenticator.SignOut();
Session.Abandon();
return RedirectToAction("Index", "Home");
}
}
}
|
mit
|
C#
|
bc6f672f73f6a3b3923b037820fc646a1189cc2e
|
Add link to Markdown help
|
leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
|
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
|
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
|
@model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
|
@model JoinRpg.DataModel.MarkdownString
@{
var requiredMsg = new MvcHtmlString("");
var validation = false;
foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata))
{
if (attr.Key == "data-val-required")
{
requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'");
validation = true;
}
}
}
<div>
Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/>
<textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea>
</div>
@if (validation)
{
@Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" })
}
|
mit
|
C#
|
e04340538637eb0332ae80517cbc7055687fd5aa
|
Fix GTK color
|
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
|
NET/Apps/TreehopperApp/TreehopperApp/ConnectedPage.xaml.cs
|
NET/Apps/TreehopperApp/TreehopperApp/ConnectedPage.xaml.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Treehopper;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Xamarin.Forms.Xaml;
namespace TreehopperApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConnectedPage : Xamarin.Forms.TabbedPage
{
TreehopperUsb Board;
public ConnectedPage (TreehopperUsb Board)
{
this.Board = Board;
Title = Board.ToString();
On<Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false);
Children.Add(new Pages.SignalPage(Board));
Children.Add(new Pages.LibrariesPage(Board));
NavigationPage.SetHasBackButton(this, false);
this.BarBackgroundColor = Color.FromRgb(0x8b, 0xc3, 0x4a);
if(Device.RuntimePlatform != Device.GTK)
this.BarTextColor = Color.White;
InitializeComponent();
}
protected override bool OnBackButtonPressed()
{
return true;
}
protected override void OnDisappearing()
{
base.OnDisappearing();
//Board.Dispose();
//ConnectionService.Instance.Dispose();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Treehopper;
using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;
using Xamarin.Forms.Xaml;
namespace TreehopperApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ConnectedPage : Xamarin.Forms.TabbedPage
{
TreehopperUsb Board;
public ConnectedPage (TreehopperUsb Board)
{
this.Board = Board;
Title = Board.ToString();
On<Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false);
Children.Add(new Pages.SignalPage(Board));
Children.Add(new Pages.LibrariesPage(Board));
NavigationPage.SetHasBackButton(this, false);
this.BarBackgroundColor = Color.FromRgb(0x8b, 0xc3, 0x4a);
this.BarTextColor = Color.White;
InitializeComponent();
}
protected override bool OnBackButtonPressed()
{
return true;
}
protected override void OnDisappearing()
{
base.OnDisappearing();
//Board.Dispose();
//ConnectionService.Instance.Dispose();
}
}
}
|
mit
|
C#
|
1757fae0041d67d5f175ea8da19112bef0f093a3
|
Test fixed
|
dfensgmbh/biz.dfch.CS.Abiquo.Client
|
src/biz.dfch.CS.Abiquo.Client.Tests/AbiquoClientFactoryTest.cs
|
src/biz.dfch.CS.Abiquo.Client.Tests/AbiquoClientFactoryTest.cs
|
/**
* Copyright 2016 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using biz.dfch.CS.Abiquo.Client.v1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace biz.dfch.CS.Abiquo.Client.Tests
{
[TestClass]
public class AbiquoClientFactoryTest
{
[TestMethod]
public void GetByVersionReturnsCorrespondingAbiquoClient()
{
var abiquoClient = AbiquoClientFactory.GetByVersion("v1");
Assert.IsNotNull(abiquoClient);
Assert.AreEqual(typeof(AbiquoClient).FullName, abiquoClient.GetType().FullName);
}
[TestMethod]
public void GetByVersionReturnsNull()
{
var abiquoClient = AbiquoClientFactory.GetByVersion("vx");
Assert.IsNull(abiquoClient);
}
[TestMethod]
public void GetByCommitHashReturnsCorrespondingAbiquoClient()
{
var abiquoClient = AbiquoClientFactory.GetByCommitHash("hash");
Assert.IsNotNull(abiquoClient);
Assert.AreEqual(typeof(AbiquoClient).FullName, abiquoClient.GetType().FullName);
}
}
}
|
/**
* Copyright 2016 d-fens GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using biz.dfch.CS.Abiquo.Client.v1;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace biz.dfch.CS.Abiquo.Client.Tests
{
[TestClass]
public class AbiquoClientFactoryTest
{
[TestMethod]
public void GetByVersionReturnsCorrespondingAbiquoClient()
{
var abiquoClient = AbiquoClientFactory.GetByVersion("v2");
Assert.IsNotNull(abiquoClient);
Assert.AreEqual(typeof(AbiquoClient).FullName, abiquoClient.GetType().FullName);
}
[TestMethod]
public void GetByVersionReturnsNull()
{
var abiquoClient = AbiquoClientFactory.GetByVersion("vx");
Assert.IsNull(abiquoClient);
}
[TestMethod]
public void GetByCommitHashReturnsCorrespondingAbiquoClient()
{
var abiquoClient = AbiquoClientFactory.GetByCommitHash("hash");
Assert.IsNotNull(abiquoClient);
Assert.AreEqual(typeof(AbiquoClient).FullName, abiquoClient.GetType().FullName);
}
}
}
|
apache-2.0
|
C#
|
3274fa439d4240328e0c4db02feaa5e90f2086dc
|
Format +1
|
alvivar/Hasten
|
Patterns/StateMachine.cs
|
Patterns/StateMachine.cs
|
using System;
using System.Collections.Generic;
public class StateMachine<TLabel>
{
private class State
{
public readonly TLabel label;
public readonly Action onStart;
public readonly Action onStop;
public readonly Action onUpdate;
public State(TLabel label, Action onStart, Action onUpdate, Action onStop)
{
this.onStart = onStart;
this.onUpdate = onUpdate;
this.onStop = onStop;
this.label = label;
}
}
private readonly Dictionary<TLabel, State> stateDictionary;
private State currentState;
public TLabel CurrentState
{
get { return currentState.label; }
set { ChangeState(value); }
}
public StateMachine()
{
stateDictionary = new Dictionary<TLabel, State>();
}
public void Update()
{
if (currentState != null && currentState.onUpdate != null)
currentState.onUpdate();
}
public void AddState(TLabel label, Action onStart, Action onUpdate, Action onStop)
{
stateDictionary[label] = new State(label, onStart, onUpdate, onStop);
}
public void AddState(TLabel label, Action onStart, Action onUpdate)
{
AddState(label, onStart, onUpdate, null);
}
public void AddState(TLabel label, Action onStart)
{
AddState(label, onStart, null);
}
public void AddState(TLabel label)
{
AddState(label, null);
}
public void AddState<TSubStateLabel>(
TLabel label,
StateMachine<TSubStateLabel> subMachine,
TSubStateLabel subMachineStartState)
{
AddState(
label,
() => subMachine.ChangeState(subMachineStartState),
subMachine.Update);
}
private void ChangeState(TLabel newState)
{
if (currentState != null && currentState.onStop != null)
currentState.onStop();
currentState = stateDictionary[newState];
if (currentState.onStart != null)
currentState.onStart();
}
public override string ToString()
{
return CurrentState.ToString();
}
}
|
using System;
using System.Collections.Generic;
public class StateMachine<TLabel>
{
private class State
{
public readonly TLabel label;
public readonly Action onStart;
public readonly Action onStop;
public readonly Action onUpdate;
public State(TLabel label, Action onStart, Action onUpdate, Action onStop)
{
this.onStart = onStart;
this.onUpdate = onUpdate;
this.onStop = onStop;
this.label = label;
}
}
private readonly Dictionary<TLabel, State> stateDictionary;
private State currentState;
public TLabel CurrentState
{
get { return currentState.label; }
set { ChangeState(value); }
}
public StateMachine()
{
stateDictionary = new Dictionary<TLabel, State>();
}
public void Update()
{
if (currentState != null && currentState.onUpdate != null)
{
currentState.onUpdate();
}
}
public void AddState(TLabel label, Action onStart, Action onUpdate, Action onStop)
{
stateDictionary[label] = new State(label, onStart, onUpdate, onStop);
}
public void AddState(TLabel label, Action onStart, Action onUpdate)
{
AddState(label, onStart, onUpdate, null);
}
public void AddState(TLabel label, Action onStart)
{
AddState(label, onStart, null);
}
public void AddState(TLabel label)
{
AddState(label, null);
}
public void AddState<TSubStateLabel>(TLabel label, StateMachine<TSubStateLabel> subMachine,
TSubStateLabel subMachineStartState)
{
AddState(
label,
() => subMachine.ChangeState(subMachineStartState),
subMachine.Update);
}
public override string ToString()
{
return CurrentState.ToString();
}
private void ChangeState(TLabel newState)
{
if (currentState != null && currentState.onStop != null)
{
currentState.onStop();
}
currentState = stateDictionary[newState];
if (currentState.onStart != null)
{
currentState.onStart();
}
}
}
|
mit
|
C#
|
0cdd970f3d3a89f1833dcac477c72a53570d72b2
|
add JsonConstructor to ContentEncodedMessage
|
technicalpoets/producer,technicalpoets/producer
|
Producer/Producer.Domain/Messages/ContentEncodedMessage.cs
|
Producer/Producer.Domain/Messages/ContentEncodedMessage.cs
|
using System;
namespace Producer.Domain
{
public class ContentEncodedMessage : DocumentUpdatedMessage
{
public string RemoteAssetUri { get; private set; }
public ContentEncodedMessage (string documentId, string collectionId)
: base (documentId, collectionId, UserRoles.Producer)
{ }
[Newtonsoft.Json.JsonConstructor]
public ContentEncodedMessage (string documentId, string collectionId, string remoteAssetUri)
: base (documentId, collectionId, UserRoles.Producer)
{
RemoteAssetUri = remoteAssetUri;
}
public void SetRemoteAssetUri (Uri remoteAssetUri)
{
if (remoteAssetUri == null) throw new ArgumentNullException (nameof (remoteAssetUri));
var uriBuilder = new UriBuilder (remoteAssetUri)
{
Scheme = Uri.UriSchemeHttps,
Port = -1 // default port for scheme
};
RemoteAssetUri = uriBuilder.Uri.AbsoluteUri;
}
public override string ToString ()
{
var sb = new System.Text.StringBuilder ("\n\nContentEncodedMessage\n");
sb.Append (" Title".PadRight (20));
sb.Append ($"{Title}\n");
sb.Append (" Message".PadRight (20));
sb.Append ($"{Message}\n");
sb.Append (" DocumentId".PadRight (20));
sb.Append ($"{DocumentId}\n");
sb.Append (" CollectionId".PadRight (20));
sb.Append ($"{CollectionId}\n");
sb.Append (" NotificationTags".PadRight (20));
sb.Append ($"{NotificationTags}\n");
sb.Append (" RemoteAssetUri".PadRight (20));
sb.Append ($"{RemoteAssetUri}\n");
return sb.ToString ();
}
}
}
|
using System;
namespace Producer.Domain
{
public class ContentEncodedMessage : DocumentUpdatedMessage
{
public string RemoteAssetUri { get; private set; }
public ContentEncodedMessage (string documentId, string collectionId)
: base (documentId, collectionId, UserRoles.Producer)
{ }
public void SetRemoteAssetUri (Uri remoteAssetUri)
{
if (remoteAssetUri == null) throw new ArgumentNullException (nameof (remoteAssetUri));
var uriBuilder = new UriBuilder (remoteAssetUri)
{
Scheme = Uri.UriSchemeHttps,
Port = -1 // default port for scheme
};
RemoteAssetUri = uriBuilder.Uri.AbsoluteUri;
}
public override string ToString ()
{
var sb = new System.Text.StringBuilder ("\n\nContentEncodedMessage\n");
sb.Append (" Title".PadRight (20));
sb.Append ($"{Title}\n");
sb.Append (" Message".PadRight (20));
sb.Append ($"{Message}\n");
sb.Append (" DocumentId".PadRight (20));
sb.Append ($"{DocumentId}\n");
sb.Append (" CollectionId".PadRight (20));
sb.Append ($"{CollectionId}\n");
sb.Append (" NotificationTags".PadRight (20));
sb.Append ($"{NotificationTags}\n");
sb.Append (" RemoteAssetUri".PadRight (20));
sb.Append ($"{RemoteAssetUri}\n");
return sb.ToString ();
}
}
}
|
mit
|
C#
|
93b3d5bc88a161913d36ee5e576b7ef7e080fbac
|
Fix a typo in comment
|
Azure/usql
|
Examples/TweetAnalysis/TweetAnalysisClass/TweetAnalysis.cs
|
Examples/TweetAnalysis/TweetAnalysisClass/TweetAnalysis.cs
|
using Microsoft.Analytics.Interfaces;
using Microsoft.Analytics.Types.Sql;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
// TweetAnalysis Assembly
// Show the use of a U-SQL user-defined function (UDF)
//
// Register this assembly at master.TweetAnalysis either using Register Assembly on TweetAnalysisClass project in Visual Studio
// or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script.
//
namespace TweetAnalysis
{
public class Udfs
{
// SqlArray<string> get_mentions(string tweet)
//
// Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet.
//
public static SqlArray<string> get_mentions(string tweet)
{
return new SqlArray<string>(
tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@"))
);
}
}
}
|
using Microsoft.Analytics.Interfaces;
using Microsoft.Analytics.Types.Sql;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
// TweetAnalysis Assembly
// Show the use of a U-SQL user-defined function (UDF)
//
// Register this assembly at master.TweetAnalysis e`ither using Register Assembly on TweetAnalysisClass project in Visual Studio
// or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script.
//
namespace TweetAnalysis
{
public class Udfs
{
// SqlArray<string> get_mentions(string tweet)
//
// Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet.
//
public static SqlArray<string> get_mentions(string tweet)
{
return new SqlArray<string>(
tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@"))
);
}
}
}
|
mit
|
C#
|
cc8c86e192accc8c8e6cd0ce7e647a941598d4bb
|
Set version 1.1.0.0
|
OELib/ObjectEntanglementLibrary
|
ObjectEntanglementLibrary/OELib/Properties/AssemblyInfo.cs
|
ObjectEntanglementLibrary/OELib/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("OELib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("OELib")]
[assembly: AssemblyProduct("OELib")]
[assembly: AssemblyCopyright("Copyright © OELib 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("3d98bdf1-acd5-4b1b-9c45-92ada505aedd")]
// 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")]
|
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("OELib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("OELib")]
[assembly: AssemblyCopyright("Copyright © Microsoft 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("3d98bdf1-acd5-4b1b-9c45-92ada505aedd")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
b1044cb43fedd162374445ca27546ad8013d051b
|
Update Comment
|
nuitsjp/PrimerOfPrismForms
|
03.NavigationService/NavigationSample/NavigationSample/NotifyNavigationBehavior.cs
|
03.NavigationService/NavigationSample/NavigationSample/NotifyNavigationBehavior.cs
|
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace NavigationSample
{
public class NotifyNavigationBehavior : BindableBehavior<Page>
{
/// <summary>
/// アタッチ時に、対象のイベントの購読設定を行う
/// </summary>
/// <param name="bindable"></param>
protected override void OnAttachedTo(Page bindable)
{
base.OnAttachedTo(bindable);
bindable.Appearing += OnAppearing;
bindable.Disappearing += OnDisappearing;
}
/// <summary>
/// デタッチ時に、イベントの購読を解除する
/// </summary>
/// <param name="bindable"></param>
protected override void OnDetachingFrom(Page bindable)
{
bindable.Disappearing -= OnDisappearing;
bindable.Appearing -= OnAppearing;
base.OnDetachingFrom(bindable);
}
private void OnAppearing(object sender, EventArgs eventArgs)
{
// アタッチしているViewのBindingContextにバインドされているViewModelが
// IAppearingAwareを実装していた場合にイベントを通知する
(AssociatedObject.BindingContext as IAppearingAware)?.OnAppearing();
}
private void OnDisappearing(object sender, EventArgs eventArgs)
{
// アタッチしているViewのBindingContextにバインドされているViewModelが
// IDisappearingAwareを実装していた場合にイベントを通知する
(AssociatedObject.BindingContext as IDisappearingAware)?.OnDisappearing();
}
}
}
|
using System;
using System.Reflection;
using System.Windows.Input;
using Xamarin.Forms;
namespace NavigationSample
{
/// <summary>
/// アタッチしているオブジェクトで特定のイベントを購読し、イベント発行時にバインドされたコマンドを実行するビヘイビア
/// </summary>
public class NotifyNavigationBehavior : BindableBehavior<Page>
{
/// <summary>
/// アタッチ時に、対象のイベントの購読設定を行う
/// </summary>
/// <param name="bindable"></param>
protected override void OnAttachedTo(Page bindable)
{
base.OnAttachedTo(bindable);
bindable.Appearing += OnAppearing;
bindable.Disappearing += OnDisappearing;
}
/// <summary>
/// デタッチ時に、イベントの購読を解除する
/// </summary>
/// <param name="bindable"></param>
protected override void OnDetachingFrom(Page bindable)
{
bindable.Disappearing -= OnDisappearing;
bindable.Appearing -= OnAppearing;
base.OnDetachingFrom(bindable);
}
private void OnAppearing(object sender, EventArgs eventArgs)
{
(AssociatedObject.BindingContext as IAppearingAware)?.OnAppearing();
}
private void OnDisappearing(object sender, EventArgs eventArgs)
{
(AssociatedObject.BindingContext as IDisappearingAware)?.OnDisappearing();
}
}
}
|
mit
|
C#
|
7034137c2739f6130156b77ddb183fd91825ed6b
|
Remove finished TODO from PlayerFreezeCommand
|
HelloKitty/Booma.Proxy
|
src/Booma.Proxy.Packets.BlockServer/Commands/Command60/Sub60PlayerFreezeCommand.cs
|
src/Booma.Proxy.Packets.BlockServer/Commands/Command60/Sub60PlayerFreezeCommand.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Command sent by players to the server when the character is entering an operation
/// that requires it to freeze or has a start and end part of the operation.
/// Such as dropping an item, dying or chatting with an NPC.
/// </summary>
[WireDataContract]
[SubCommand60(SubCommand60OperationCode.FreezePlayer)]
public sealed class Sub60PlayerFreezeCommand : BaseSubCommand60, IMessageContextIdentifiable
{
/// <summary>
/// Enumeration of operation types.
/// According to Sylverant documentation of 0x60 subcommand packets.
/// </summary>
public enum FreezeReason : uint //TODO: Is this uint? There are 2 0 bytes afterwards for the field here but not sure
{
/// <summary>
/// Indicates the operation involves dropping an item.
/// </summary>
ItemDrop = 0x0384,
/// <summary>
///
/// </summary>
NPCChat = 0xFFFF,
}
//Client ID/Lobbyslot
/// <inheritdoc />
[WireMember(1)]
public byte Identifier { get; }
//TODO: What is this?
[WireMember(2)]
public byte Unknown1 { get; }
/// <summary>
/// Indicates reason for the reason for the freeze event.
/// </summary>
[WireMember(3)]
public FreezeReason Reason { get; } //4 bytes, last 2 usually 0x0000 but might not be apart of the enum
/// <summary>
/// The position the player with <see cref="Identifier"/> id is at.
/// Contains the X and Z component of the position.
/// </summary>
[WireMember(4)]
public Vector2<float> Position { get; }
//TODO: Do we need this? Is it ever not 0?
//TODO: Sylverant has some additional bytes here. Says they're padding. Do we need them?
[WireMember(5)]
public int Unknown2 { get; }
//Serializer ctor
private Sub60PlayerFreezeCommand()
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FreecraftCore.Serializer;
namespace Booma.Proxy
{
/// <summary>
/// Command sent by players to the server when the character is entering an operation
/// that requires it to freeze or has a start and end part of the operation.
/// Such as dropping an item, dying or chatting with an NPC.
/// </summary>
[WireDataContract]
[SubCommand60(SubCommand60OperationCode.FreezePlayer)]
public sealed class Sub60PlayerFreezeCommand : BaseSubCommand60, IMessageContextIdentifiable
{
/// <summary>
/// Enumeration of operation types.
/// According to Sylverant documentation of 0x60 subcommand packets.
/// </summary>
public enum FreezeReason : uint //TODO: Is this uint? There are 2 0 bytes afterwards for the field here but not sure
{
/// <summary>
/// Indicates the operation involves dropping an item.
/// </summary>
ItemDrop = 0x0384,
/// <summary>
///
/// </summary>
NPCChat = 0xFFFF,
}
//Client ID/Lobbyslot
/// <inheritdoc />
[WireMember(1)]
public byte Identifier { get; }
//TODO: What is this?
[WireMember(2)]
public byte Unknown1 { get; }
/// <summary>
/// Indicates reason for the reason for the freeze event.
/// </summary>
[WireMember(3)]
public FreezeReason Reason { get; } //4 bytes, last 2 usually 0x0000 but might not be apart of the enum
//TODO: Is this really a vector4?
/// <summary>
/// The position the player with <see cref="Identifier"/> id is at.
/// Contains the X and Z component of the position.
/// </summary>
[WireMember(4)]
public Vector2<float> Position { get; }
//TODO: Do we need this? Is it ever not 0?
//TODO: Sylverant has some additional bytes here. Says they're padding. Do we need them?
[WireMember(5)]
public int Unknown2 { get; }
//Serializer ctor
private Sub60PlayerFreezeCommand()
{
}
}
}
|
agpl-3.0
|
C#
|
0f744447d0e98c885091d2c5f59f041c565964ab
|
Remove unused using statements in construction comp
|
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
|
Content.Server/Construction/Components/ConstructionComponent.cs
|
Content.Server/Construction/Components/ConstructionComponent.cs
|
using System.Collections.Generic;
using Robust.Shared.Analyzers;
using Robust.Shared.GameObjects;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Construction.Components
{
[RegisterComponent, Friend(typeof(ConstructionSystem))]
public class ConstructionComponent : Component
{
public override string Name => "Construction";
[DataField("graph", required:true)]
public string Graph { get; set; } = string.Empty;
[DataField("node", required:true)]
public string Node { get; set; } = default!;
[DataField("edge")]
public int? EdgeIndex { get; set; } = null;
[DataField("step")]
public int StepIndex { get; set; } = 0;
[DataField("containers")]
public HashSet<string> Containers { get; set; } = new();
[DataField("defaultTarget")]
public string? TargetNode { get; set; } = null;
[ViewVariables]
public int? TargetEdgeIndex { get; set; } = null;
[ViewVariables]
public Queue<string>? NodePathfinding { get; set; } = null;
[DataField("deconstructionTarget")]
public string? DeconstructionNode { get; set; } = "start";
[ViewVariables]
public bool WaitingDoAfter { get; set; } = false;
[ViewVariables]
public readonly Queue<object> InteractionQueue = new();
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Content.Server.DoAfter;
using Content.Server.Stack;
using Content.Server.Tools;
using Content.Server.Tools.Components;
using Content.Shared.Construction;
using Content.Shared.Construction.Prototypes;
using Content.Shared.Construction.Steps;
using Content.Shared.Interaction;
using Content.Shared.Tools.Components;
using Robust.Shared.Analyzers;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
using Robust.Shared.Log;
using Robust.Shared.Physics;
using Robust.Shared.Prototypes;
using Robust.Shared.Serialization.Manager.Attributes;
using Robust.Shared.ViewVariables;
namespace Content.Server.Construction.Components
{
[RegisterComponent, Friend(typeof(ConstructionSystem))]
public class ConstructionComponent : Component
{
public override string Name => "Construction";
[DataField("graph", required:true)]
public string Graph { get; set; } = string.Empty;
[DataField("node", required:true)]
public string Node { get; set; } = default!;
[DataField("edge")]
public int? EdgeIndex { get; set; } = null;
[DataField("step")]
public int StepIndex { get; set; } = 0;
[DataField("containers")]
public HashSet<string> Containers { get; set; } = new();
[DataField("defaultTarget")]
public string? TargetNode { get; set; } = null;
[ViewVariables]
public int? TargetEdgeIndex { get; set; } = null;
[ViewVariables]
public Queue<string>? NodePathfinding { get; set; } = null;
[DataField("deconstructionTarget")]
public string? DeconstructionNode { get; set; } = "start";
[ViewVariables]
public bool WaitingDoAfter { get; set; } = false;
[ViewVariables]
public readonly Queue<object> InteractionQueue = new();
}
}
|
mit
|
C#
|
d4bb09ece67ec0d6bae3199beca03ffb16aa4721
|
Fix mismatching return value
|
SergeyTeplyakov/CodeContracts,hubuk/CodeContracts,SergeyTeplyakov/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,ndykman/CodeContracts,huoxudong125/CodeContracts,huoxudong125/CodeContracts,huoxudong125/CodeContracts,hubuk/CodeContracts,huoxudong125/CodeContracts,ndykman/CodeContracts,SergeyTeplyakov/CodeContracts,hubuk/CodeContracts,SergeyTeplyakov/CodeContracts,Microsoft/CodeContracts,SergeyTeplyakov/CodeContracts,huoxudong125/CodeContracts,ndykman/CodeContracts,huoxudong125/CodeContracts,hubuk/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,ndykman/CodeContracts,hubuk/CodeContracts,Microsoft/CodeContracts,Microsoft/CodeContracts,SergeyTeplyakov/CodeContracts,hubuk/CodeContracts,Microsoft/CodeContracts,ndykman/CodeContracts,hubuk/CodeContracts,huoxudong125/CodeContracts,Microsoft/CodeContracts,SergeyTeplyakov/CodeContracts
|
Microsoft.Research/Contracts/MsCorlib/System.OperatingSystem.cs
|
Microsoft.Research/Contracts/MsCorlib/System.OperatingSystem.cs
|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System
{
public class OperatingSystem: ICloneable
{
public PlatformID Platform
{
[Pure]
get
{
Contract.Ensures(Contract.Result<PlatformID>() >= PlatformID.Win32S);
Contract.Ensures(Contract.Result<PlatformID>() <= PlatformID.MacOSX);
return default(PlatformID);
}
}
public string ServicePack
{
[Pure]
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
public Version Version
{
[Pure]
get
{
Contract.Ensures(Contract.Result<Version>() != null);
return default(Version);
}
}
public string VersionString
{
get
{
Contract.Ensures(!string.IsNullOrWhitespace(Contract.Result<string>()));
return default(string);
}
}
public object Clone()
{
return default(object);
}
public OperatingSystem(PlatformID platform, Version version)
{
Contract.Requires(platform >= PlatformID.Win32S)
Contract.Requires(platform <= PlatformID.MacOSX)
Contract.Requires(version != null);
Contract.EnsuresOnThrow<ArgumentException>(true, "platform is not a PlatformID enumeration value.")
Contract.EnsuresOnThrow<ArgumentNullException>(true, "version is null.")
}
}
}
|
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System
{
public class OperatingSystem: ICloneable
{
public PlatformID Platform
{
[Pure]
get
{
Contract.Ensures(Contract.Result<PlatformID>() >= PlatformID.Win32S);
Contract.Ensures(Contract.Result<PlatformID>() <= PlatformID.MacOSX);
return default(PlatformID);
}
}
public string ServicePack
{
[Pure]
get
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
}
public Version Version
{
[Pure]
get
{
Contract.Ensures(Contract.Result<Version>() != null);
return default(Version);
}
}
public string VersionString
{
get
{
Contract.Ensures(!string.IsNullOrWhitespace(Contract.Result<string>()));
return default(Version);
}
}
public object Clone()
{
return default(object);
}
public OperatingSystem(PlatformID platform, Version version)
{
Contract.Requires(platform >= PlatformID.Win32S)
Contract.Requires(platform <= PlatformID.MacOSX)
Contract.Requires(version != null);
Contract.EnsuresOnThrow<ArgumentException>(true, "platform is not a PlatformID enumeration value.")
Contract.EnsuresOnThrow<ArgumentNullException>(true, "version is null.")
}
}
}
|
mit
|
C#
|
1535aab50608c6b0ecb22da2f5ce7bd3e37b746c
|
fix path to guiskin
|
Unity-Technologies/CodeEditor,Unity-Technologies/CodeEditor
|
src/CodeEditor.Text.UI.Unity.Editor/Implementation/TextViewAppearanceProvider.cs
|
src/CodeEditor.Text.UI.Unity.Editor/Implementation/TextViewAppearanceProvider.cs
|
using CodeEditor.Composition;
using CodeEditor.Text.UI.Unity.Engine;
using UnityEngine;
namespace CodeEditor.Text.UI.Unity.Editor.Implementation
{
[Export(typeof(ITextViewAppearanceProvider))]
class TextViewAppearanceProvider : ITextViewAppearanceProvider
{
public ITextViewAppearance AppearanceFor(ITextViewDocument document)
{
return new TextViewAppearance();
}
}
public class TextViewAppearance : ITextViewAppearance
{
private readonly GUIStyle _background;
private readonly GUIStyle _text;
private readonly GUIStyle _lineNumber;
private readonly Color _lineNumberColor;
public TextViewAppearance()
{
_background = "AnimationCurveEditorBackground";
string userSkinPath = "Assets/Editor/CodeEditor/CodeEditorSkin.guiskin";
GUISkin skin = UnityEditor.AssetDatabase.LoadAssetAtPath(userSkinPath, typeof(GUISkin)) as GUISkin;
if (skin == null)
{
//Debug.Log ("Could not find user skin at: " + userSkinPath + ". Using default skin");
skin = GUI.skin;
}
else
{
//Debug.Log ("User skin found, font: " + skin.font.name);
}
_text = new GUIStyle(skin.label)
{
richText = true,
alignment = TextAnchor.UpperLeft,
padding = { left = 0, right = 0 }
};
_text.normal.textColor = Color.white;
_lineNumber = new GUIStyle (_text)
{
richText = false,
alignment = TextAnchor.UpperRight
};
_lineNumberColor = new Color(1, 1, 1, 0.5f);
}
public GUIStyle Background
{
get { return _background; }
}
public GUIStyle Text
{
get { return _text; }
}
public GUIStyle LineNumber
{
get { return _lineNumber; }
}
public Color LineNumberColor
{
get { return _lineNumberColor; }
}
}
}
|
using CodeEditor.Composition;
using CodeEditor.Text.UI.Unity.Engine;
using UnityEngine;
namespace CodeEditor.Text.UI.Unity.Editor.Implementation
{
[Export(typeof(ITextViewAppearanceProvider))]
class TextViewAppearanceProvider : ITextViewAppearanceProvider
{
public ITextViewAppearance AppearanceFor(ITextViewDocument document)
{
return new TextViewAppearance();
}
}
public class TextViewAppearance : ITextViewAppearance
{
private readonly GUIStyle _background;
private readonly GUIStyle _text;
private readonly GUIStyle _lineNumber;
private readonly Color _lineNumberColor;
public TextViewAppearance()
{
_background = "AnimationCurveEditorBackground";
string userSkinPath = "Assets/kaizen/lib/CodeEditorSkin.guiskin";
GUISkin skin = UnityEditor.AssetDatabase.LoadAssetAtPath(userSkinPath, typeof(GUISkin)) as GUISkin;
if (skin == null)
{
//Debug.Log ("Could not find user skin at: " + userSkinPath + ". Using default skin");
skin = GUI.skin;
}
else
{
//Debug.Log ("User skin found, font: " + skin.font.name);
}
_text = new GUIStyle(skin.label)
{
richText = true,
alignment = TextAnchor.UpperLeft,
padding = { left = 0, right = 0 }
};
_text.normal.textColor = Color.white;
_lineNumber = new GUIStyle (_text)
{
richText = false,
alignment = TextAnchor.UpperRight
};
_lineNumberColor = new Color(1, 1, 1, 0.5f);
}
public GUIStyle Background
{
get { return _background; }
}
public GUIStyle Text
{
get { return _text; }
}
public GUIStyle LineNumber
{
get { return _lineNumber; }
}
public Color LineNumberColor
{
get { return _lineNumberColor; }
}
}
}
|
mit
|
C#
|
50729f1bab989d176019033d88853f53c8a46cde
|
Switch to OrdinalIgnoreCase comparison for PackageReference deduplication
|
nkolev92/sdk,nkolev92/sdk
|
src/Tasks/Microsoft.NET.Build.Tasks/CheckForImplicitPackageReferenceOverrides.cs
|
src/Tasks/Microsoft.NET.Build.Tasks/CheckForImplicitPackageReferenceOverrides.cs
|
using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Microsoft.NET.Build.Tasks
{
public class CheckForImplicitPackageReferenceOverrides : TaskBase
{
const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";
[Required]
public ITaskItem [] PackageReferenceItems { get; set; }
[Required]
public string MoreInformationLink { get; set; }
[Output]
public ITaskItem[] ItemsToRemove { get; set; }
protected override void ExecuteCore()
{
var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1);
var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));
ItemsToRemove = duplicateItemsToRemove.ToArray();
foreach (var itemToRemove in ItemsToRemove)
{
string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
itemToRemove.ItemSpec,
MoreInformationLink);
Log.LogWarning(message);
}
}
}
}
|
using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
namespace Microsoft.NET.Build.Tasks
{
public class CheckForImplicitPackageReferenceOverrides : TaskBase
{
const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined";
[Required]
public ITaskItem [] PackageReferenceItems { get; set; }
[Required]
public string MoreInformationLink { get; set; }
[Output]
public ITaskItem[] ItemsToRemove { get; set; }
protected override void ExecuteCore()
{
var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec.ToLowerInvariant()).Where(g => g.Count() > 1);
var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where(
item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase)));
ItemsToRemove = duplicateItemsToRemove.ToArray();
foreach (var itemToRemove in ItemsToRemove)
{
string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning,
itemToRemove.ItemSpec,
MoreInformationLink);
Log.LogWarning(message);
}
}
}
}
|
mit
|
C#
|
3338024c17b6febbf5aa47acc41b021e1f25c83c
|
Fix incorrect whitespace
|
UselessToucan/osu,DrabWeb/osu,johnneijzen/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,Frontear/osuKyzer,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,Nabile-Rahmani/osu,johnneijzen/osu,ppy/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,Drezi126/osu,peppy/osu,ppy/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,naoey/osu,UselessToucan/osu,DrabWeb/osu,ZLima12/osu,peppy/osu,UselessToucan/osu
|
osu.Game.Rulesets.Catch/Tests/TestCaseCatchPlayer.cs
|
osu.Game.Rulesets.Catch/Tests/TestCaseCatchPlayer.cs
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestCaseCatchPlayer : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchPlayer() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using NUnit.Framework;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Catch.Objects;
namespace osu.Game.Rulesets.Catch.Tests
{
[TestFixture]
public class TestCaseCatchPlayer : Game.Tests.Visual.TestCasePlayer
{
public TestCaseCatchPlayer() : base(typeof(CatchRuleset))
{
}
protected override Beatmap CreateBeatmap()
{
var beatmap = new Beatmap();
for (int i = 0; i < 256; i++)
beatmap.HitObjects.Add(new Fruit { X = 0.5f, StartTime = i * 100, NewCombo = i % 8 == 0 });
return beatmap;
}
}
}
|
mit
|
C#
|
ea2896a7c2a1767a030404bf8078dedab7a92341
|
Remove extra tab in the script template.
|
Damnae/storybrew
|
editor/Resources/scripttemplate.csx
|
editor/Resources/scripttemplate.csx
|
using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
|
using OpenTK;
using OpenTK.Graphics;
using StorybrewCommon.Mapset;
using StorybrewCommon.Scripting;
using StorybrewCommon.Storyboarding;
using StorybrewCommon.Storyboarding.Util;
using StorybrewCommon.Subtitles;
using StorybrewCommon.Util;
using System;
using System.Collections.Generic;
using System.Linq;
namespace StorybrewScripts
{
public class %CLASSNAME% : StoryboardObjectGenerator
{
public override void Generate()
{
}
}
}
|
mit
|
C#
|
d3919b1596a3953e8ed2b52146a75d5a9b62ee43
|
Fix line sampling (again)
|
jomar/NGraphics,praeclarum/NGraphics
|
NGraphics/Line.cs
|
NGraphics/Line.cs
|
using System;
using System.Globalization;
namespace NGraphics
{
public class Line : Element
{
protected Point start;
protected Point end;
public Line (Point start, Point end, Pen pen)
: base (pen, null)
{
this.start = start;
this.end = end;
}
protected override void DrawElement (ICanvas canvas)
{
canvas.DrawLine(start, end, Pen);
}
public override string ToString ()
{
return string.Format (CultureInfo.InvariantCulture, "Line ({0}-{1})", start, end);
}
#region implemented abstract members of Element
public override EdgeSamples[] GetEdgeSamples (double tolerance, int minSamples, int maxSamples)
{
var ps = SampleLine (start, end, true, tolerance, minSamples, maxSamples);
for (int i = 0; i < ps.Length; i++) {
var p = Transform.TransformPoint (ps [i]);
ps [i] = p;
}
return new[] { new EdgeSamples { Points = ps } };
}
public override Rect SampleableBox {
get {
var bb = new Rect (start, Size.Zero);
return Transform.TransformRect (bb.Union (end));
}
}
#endregion
}
}
|
using System;
using System.Globalization;
namespace NGraphics
{
public class Line : Element
{
protected Point start;
protected Point end;
public Line (Point start, Point end, Pen pen)
: base (pen, null)
{
this.start = start;
this.end = end;
}
protected override void DrawElement (ICanvas canvas)
{
canvas.DrawLine(start, end, Pen);
}
public override string ToString ()
{
return string.Format (CultureInfo.InvariantCulture, "Line ({0}-{1})", start, end);
}
#region implemented abstract members of Element
public override EdgeSamples[] GetEdgeSamples (double tolerance, int minSamples, int maxSamples)
{
var ps = SampleLine (start, end, true, tolerance, minSamples, maxSamples);
for (int i = 0; i < ps.Length; i++) {
var p = Transform.TransformPoint (ps [i]);
ps [i] = p;
}
return new[] { new EdgeSamples { Points = ps } };
}
public override Rect SampleableBox {
get {
var bb = new Rect (start, Size.Zero);
return bb.Union (end);
}
}
#endregion
}
}
|
mit
|
C#
|
c3ad69bf9f25fde71300e5609381703de75b149c
|
Make Paid optional
|
stripe/stripe-dotnet,richardlawley/stripe.net
|
src/Stripe.net/Services/Invoices/StripeInvoiceListOptions.cs
|
src/Stripe.net/Services/Invoices/StripeInvoiceListOptions.cs
|
using Newtonsoft.Json;
namespace Stripe
{
public class StripeInvoiceListOptions : StripeListOptions
{
/// <summary>
/// The billing mode of the invoice to retrieve. One of <see cref="StripeBilling" />.
/// </summary>
[JsonProperty("billing")]
public StripeBilling? Billing { get; set; }
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("date")]
public StripeDateFilter Date { get; set; }
/// <summary>
/// A filter on the list based on the object due_date field.
/// </summary>
[JsonProperty("due_date")]
public StripeDateFilter DueDate { get; set; }
/// <summary>
/// A filter on the list based on the object paid field.
/// </summary>
[JsonProperty("paid")]
public bool? Paid { get; set; }
[JsonProperty("subscription")]
public string SubscriptionId { get; set; }
}
}
|
using Newtonsoft.Json;
namespace Stripe
{
public class StripeInvoiceListOptions : StripeListOptions
{
/// <summary>
/// The billing mode of the invoice to retrieve. One of <see cref="StripeBilling" />.
/// </summary>
[JsonProperty("billing")]
public StripeBilling? Billing { get; set; }
[JsonProperty("customer")]
public string CustomerId { get; set; }
[JsonProperty("date")]
public StripeDateFilter Date { get; set; }
/// <summary>
/// A filter on the list based on the object due_date field.
/// </summary>
[JsonProperty("due_date")]
public StripeDateFilter DueDate { get; set; }
/// <summary>
/// A filter on the list based on the object paid field.
/// </summary>
[JsonProperty("paid")]
public bool Paid { get; set; }
[JsonProperty("subscription")]
public string SubscriptionId { get; set; }
}
}
|
apache-2.0
|
C#
|
074a1741392476b62ccdfc8bec91fff09d0dabb9
|
Update src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
|
dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS
|
src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
|
src/Umbraco.Web.Common/Extensions/LinkGeneratorExtensions.cs
|
using System;
using Umbraco.Core;
using Microsoft.AspNetCore.Routing;
using System.Reflection;
using Umbraco.Web.Common.Install;
namespace Umbraco.Extensions
{
public static class LinkGeneratorExtensions
{
/// <summary>
/// Return the back office url if the back office is installed
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetBackOfficeUrl(this LinkGenerator linkGenerator)
{
Type backOfficeControllerType;
try
{
backOfficeControllerType = Assembly.Load("Umbraco.Web.BackOffice")?.GetType("Umbraco.Web.BackOffice.Controllers.BackOfficeController");
if (backOfficeControllerType == null) return "/"; // this would indicate that the installer is installed without the back office
}
catch
{
return "/"; // this would indicate that the installer is installed without the back office
}
return linkGenerator.GetPathByAction("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea });
}
/// <summary>
/// Returns the URL for the installer
/// </summary>
/// <param name="linkGenerator"></param>
/// <returns></returns>
public static string GetInstallerUrl(this LinkGenerator linkGenerator)
{
return linkGenerator.GetPathByAction(nameof(InstallController.Index), ControllerExtensions.GetControllerName<InstallController>(), new { area = Constants.Web.Mvc.InstallArea });
}
}
}
|
using System;
using Umbraco.Core;
using Microsoft.AspNetCore.Routing;
using System.Reflection;
using Umbraco.Web.Common.Install;
namespace Umbraco.Extensions
{
public static class LinkGeneratorExtensions
{
/// <summary>
/// Return the back office url if the back office is installed
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
public static string GetBackOfficeUrl(this LinkGenerator linkGenerator)
{
Type backOfficeControllerType;
try
{
backOfficeControllerType = Assembly.Load("Umbraco.Web.BackOffice")?.GetType("Umbraco.Web.BackOffice.Controllers.BackOfficeController");
if (backOfficeControllerType == null) return "/"; // this would indicate that the installer is installed without the back office
}
catch (Exception)
{
return "/"; // this would indicate that the installer is installed without the back office
}
return linkGenerator.GetPathByAction("Default", ControllerExtensions.GetControllerName(backOfficeControllerType), new { area = Constants.Web.Mvc.BackOfficeApiArea });
}
/// <summary>
/// Returns the URL for the installer
/// </summary>
/// <param name="linkGenerator"></param>
/// <returns></returns>
public static string GetInstallerUrl(this LinkGenerator linkGenerator)
{
return linkGenerator.GetPathByAction(nameof(InstallController.Index), ControllerExtensions.GetControllerName<InstallController>(), new { area = Constants.Web.Mvc.InstallArea });
}
}
}
|
mit
|
C#
|
849d16f485b67929d05ce528d330b6b59f4b89c1
|
Fix closing tag on iframe
|
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
|
Ooui/Iframe.cs
|
Ooui/Iframe.cs
|
namespace Ooui
{
public class Iframe : Element
{
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
public Iframe ()
: base ("iframe")
{
}
protected override bool HtmlNeedsFullEndElement => true;
}
}
|
namespace Ooui
{
public class Iframe : Element
{
public string Source
{
get => GetStringAttribute ("src", null);
set => SetAttributeProperty ("src", value);
}
public Iframe ()
: base ("iframe")
{
}
}
}
|
mit
|
C#
|
4b760a978cef517e2f98295c6ba0407c33f040cf
|
fix SQ issue
|
steven-r/Oberon0Compiler
|
oberon0/Expressions/Operations/Internal/ArithmeticOpKey.cs
|
oberon0/Expressions/Operations/Internal/ArithmeticOpKey.cs
|
#region copyright
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ArithmeticOpKey.cs" company="Stephen Reindl">
// Copyright (c) Stephen Reindl. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
// </copyright>
// <summary>
// Part of oberon0 - Oberon0Compiler/ArithmeticOpKey.cs
// </summary>
// --------------------------------------------------------------------------------------------------------------------
#endregion
namespace Oberon0.Compiler.Expressions.Operations.Internal
{
using System;
using Oberon0.Compiler.Types;
/// <summary>
/// Helper class to create a dictionary of operations and it's left and right parameters
/// </summary>
internal class ArithmeticOpKey : IArithmeticOpMetadata, IEquatable<ArithmeticOpKey>
{
public ArithmeticOpKey(
int operation,
BaseType leftHandType,
BaseType rightHandType,
BaseType targetType = BaseType.AnyType)
{
Operation = operation;
LeftHandType = leftHandType;
RightHandType = rightHandType;
ResultType = targetType;
}
public BaseType LeftHandType { get; }
public int Operation { get; }
public BaseType ResultType { get; }
public BaseType RightHandType { get; }
public bool Equals(ArithmeticOpKey other)
{
if (other == null) return false;
return Operation == other.Operation && LeftHandType == other.LeftHandType
&& RightHandType == other.RightHandType;
}
public override int GetHashCode()
{
// ignore Target type
return 17 ^ Operation.GetHashCode() ^ LeftHandType.GetHashCode() ^ RightHandType.GetHashCode();
}
}
}
|
using System;
using Oberon0.Compiler.Types;
namespace Oberon0.Compiler.Expressions.Operations.Internal
{
/// <summary>
/// Helper class to create a dictionary of operations and it's left and right parameters
/// </summary>
internal class ArithmeticOpKey: IArithmeticOpMetadata, IEquatable<ArithmeticOpKey>
{
#region Constructors
public ArithmeticOpKey(int operation, BaseType leftHandType, BaseType rightHandType, BaseType targetType = BaseType.AnyType)
{
Operation = operation;
LeftHandType = leftHandType;
RightHandType = rightHandType;
ResultType = targetType;
}
#endregion
public int Operation { get; }
public BaseType LeftHandType { get; }
public BaseType RightHandType { get; }
public BaseType ResultType { get; }
#region IEquatable
public bool Equals(ArithmeticOpKey other)
{
if (other == null) throw new ArgumentNullException(nameof(other));
return Operation == other.Operation &&
LeftHandType == other.LeftHandType &&
RightHandType == other.RightHandType;
}
#endregion
public override int GetHashCode()
{
// ignore Target type
return 17 ^ Operation.GetHashCode() ^ LeftHandType.GetHashCode() ^ RightHandType.GetHashCode();
}
}
}
|
mit
|
C#
|
0d2ab550dd8c1285d94ae8991e040f06ea9a970a
|
Update SR values in tests
|
smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,ppy/osu,smoogipooo/osu,peppy/osu-new,peppy/osu,peppy/osu
|
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.cs
|
osu.Game.Rulesets.Osu.Tests/OsuDifficultyCalculatorTest.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.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.6634445062299665d, "diffcalc-test")]
[TestCase(1.0414203870195022d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.3858089051603368d, "diffcalc-test")]
[TestCase(1.2723279173428435d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
|
// 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.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Osu.Difficulty;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Osu.Tests
{
[TestFixture]
public class OsuDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Osu";
[TestCase(6.4164199087433484d, "diffcalc-test")]
[TestCase(1.0028132594779837d, "zero-length-sliders")]
public void Test(double expected, string name)
=> base.Test(expected, name);
[TestCase(8.0749334911818469d, "diffcalc-test")]
[TestCase(1.2251606765323657d, "zero-length-sliders")]
public void TestClockRateAdjusted(double expected, string name)
=> Test(expected, name, new OsuModDoubleTime());
protected override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new OsuDifficultyCalculator(new OsuRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new OsuRuleset();
}
}
|
mit
|
C#
|
9b0d1435bd72b641c3ad7b38917b47b93abcc281
|
Update AdamPedley.cs
|
beraybentesen/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,stvansolano/planetxamarin,stvansolano/planetxamarin,beraybentesen/planetxamarin,stvansolano/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,beraybentesen/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin
|
src/Firehose.Web/Authors/AdamPedley.cs
|
src/Firehose.Web/Authors/AdamPedley.cs
|
using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
namespace Firehose.Web.Authors
{
public class AdamPedley : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Pedley";
public string StateOrRegion => "Melbourne, Australia";
public string EmailAddress => "adam.pedley@gmail.com";
public string Title => "software engineer";
public Uri WebSite => new Uri("https://xamarinhelp.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://xamarinhelp.com/feed/"); }
}
public string TwitterHandle => "adpedley";
public DateTime FirstAwarded => new DateTime(2016, 10, 1);
public string GravatarHash => "";
}
}
|
using Firehose.Web.Infrastructure;
using System;
using System.Collections.Generic;
namespace Firehose.Web.Authors
{
public class AdamPedley : IAmAMicrosoftMVP
{
public string FirstName => "Adam";
public string LastName => "Pedley";
public string StateOrRegion => "Melbourne, Australia";
public string EmailAddress => "adam.pedley@gmail.com";
public string Title => "Xamarin Developer | Microsoft MVP";
public Uri WebSite => new Uri("https://xamarinhelp.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://xamarinhelp.com/feed/"); }
}
public string TwitterHandle => "adpedley";
public DateTime FirstAwarded => new DateTime(2016, 10, 1);
public string GravatarHash => "";
}
}
|
mit
|
C#
|
195a0e50f58c478dfd9327138e1cf5de19071cce
|
Update src/Bootstrap/Views/Shared/_validationSummary.cshtml
|
mohamedabdlaal/twitter.bootstrap.mvc,erichexter/twitter.bootstrap.mvc,mohamedabdlaal/twitter.bootstrap.mvc,erichexter/twitter.bootstrap.mvc
|
src/Bootstrap/Views/Shared/_validationSummary.cshtml
|
src/Bootstrap/Views/Shared/_validationSummary.cshtml
|
@if (ViewData.ModelState.Any(x => x.Value.Errors.Any()))
{
<div class="alert alert-error">
<a class="close" data-dismiss="alert">�</a>
@Html.ValidationSummary(true)
</div>
}
|
@if (ViewData.ModelState[""] != null && ViewData.ModelState[""].Errors.Any())
{
<div class="alert alert-error">
<a class="close" data-dismiss="alert"></a>
@Html.ValidationSummary(true)
</div>
}
|
apache-2.0
|
C#
|
d23e73b4ea123987c5bdf7d723f23515e0fb7265
|
Update PointShapeExtensions.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/ViewModels/Shapes/PointShapeExtensions.cs
|
src/Core2D/ViewModels/Shapes/PointShapeExtensions.cs
|
#nullable enable
using static System.Math;
namespace Core2D.ViewModels.Shapes
{
public static class PointShapeExtensions
{
public static double DistanceTo(this PointShapeViewModel point, PointShapeViewModel other)
{
var dx = point.X - other.X;
var dy = point.Y - other.Y;
// ReSharper disable once ArrangeRedundantParentheses
return Sqrt((dx * dx) + (dy * dy));
}
}
}
|
#nullable enable
using static System.Math;
namespace Core2D.ViewModels.Shapes
{
public static class PointShapeExtensions
{
public static double DistanceTo(this PointShapeViewModel point, PointShapeViewModel other)
{
var dx = point.X - other.X;
var dy = point.Y - other.Y;
return Sqrt(dx * dx + dy * dy);
}
}
}
|
mit
|
C#
|
3acf8650850e53c8b8a8ce36941a64330b565050
|
Fix path for xammac apple-doc-wizard
|
PlayScriptRedux/monomac,dlech/monomac
|
samples/macdoc/Product.cs
|
samples/macdoc/Product.cs
|
using System;
using System.Linq;
using System.Collections.Generic;
using Monodoc;
namespace macdoc
{
public enum Product
{
MonoTouch,
MonoMac
}
public static class ProductUtils
{
public static string GetFriendlyName (Product product)
{
switch (product) {
case Product.MonoTouch:
return "Xamarin.iOS";
case Product.MonoMac:
return "Xamarin.Mac";
default:
return string.Empty;
}
}
public static IEnumerable<Product> ToProducts (this IEnumerable<HelpSource> sources)
{
foreach (var hs in sources) {
if (hs.Name.StartsWith ("MonoTouch", StringComparison.InvariantCultureIgnoreCase))
yield return Product.MonoTouch;
else if (hs.Name.StartsWith ("MonoMac", StringComparison.InvariantCultureIgnoreCase))
yield return Product.MonoMac;
}
}
public static string GetDocFeedForProduct (Product product)
{
switch (product) {
case Product.MonoTouch:
return AppleDocHandler.Ios6AtomFeed;
case Product.MonoMac:
return AppleDocHandler.MacMountainLionFeed;
default:
return null;
}
}
public static string GetMergeToolForProduct (Product product)
{
switch (product) {
case Product.MonoTouch:
return "/Developer/MonoTouch/usr/share/doc/MonoTouch/apple-doc-wizard";
case Product.MonoMac:
return "/Library/Frameworks/Xamarin.Mac.framework/Versions/Current/usr/share/doc/Xamarin.Mac/apple-doc-wizard";
default:
return null;
}
}
}
}
|
using System;
using System.Linq;
using System.Collections.Generic;
using Monodoc;
namespace macdoc
{
public enum Product
{
MonoTouch,
MonoMac
}
public static class ProductUtils
{
public static string GetFriendlyName (Product product)
{
switch (product) {
case Product.MonoTouch:
return "Xamarin.iOS";
case Product.MonoMac:
return "Xamarin.Mac";
default:
return string.Empty;
}
}
public static IEnumerable<Product> ToProducts (this IEnumerable<HelpSource> sources)
{
foreach (var hs in sources) {
if (hs.Name.StartsWith ("MonoTouch", StringComparison.InvariantCultureIgnoreCase))
yield return Product.MonoTouch;
else if (hs.Name.StartsWith ("MonoMac", StringComparison.InvariantCultureIgnoreCase))
yield return Product.MonoMac;
}
}
public static string GetDocFeedForProduct (Product product)
{
switch (product) {
case Product.MonoTouch:
return AppleDocHandler.Ios6AtomFeed;
case Product.MonoMac:
return AppleDocHandler.MacMountainLionFeed;
default:
return null;
}
}
public static string GetMergeToolForProduct (Product product)
{
switch (product) {
case Product.MonoTouch:
return "/Developer/MonoTouch/usr/share/doc/MonoTouch/apple-doc-wizard";
case Product.MonoMac:
return "/Library/Frameworks/Xamarin.Mac.framework/Versions/Current/share/doc/apple-doc-wizard";
default:
return null;
}
}
}
}
|
apache-2.0
|
C#
|
a34ae13aa447e132dab3de8d0cab4fada4075e00
|
Fix 'Course' path in Startup
|
riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy
|
src/DotvvmAcademy.Web/Startup.cs
|
src/DotvvmAcademy.Web/Startup.cs
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace DotvvmAcademy.Web
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(env.WebRootPath)
});
var dotvvmConfiguration = app.UseDotVVM<DotvvmStartup>(env.ContentRootPath);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddAuthorization();
services.AddWebEncoders();
services.AddDotVVM();
services.AddCourseFormat("./Course");
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace DotvvmAcademy.Web
{
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(env.WebRootPath)
});
var dotvvmConfiguration = app.UseDotVVM<DotvvmStartup>(env.ContentRootPath);
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection();
services.AddAuthorization();
services.AddWebEncoders();
services.AddDotVVM();
services.AddCourseFormat("./course");
}
}
}
|
apache-2.0
|
C#
|
83dddb0dda1726e56675b12e8152f931e34f36f0
|
fix StateContainer test
|
appccelerate/statemachine
|
source/Appccelerate.StateMachine/Machine/StateContainer.cs
|
source/Appccelerate.StateMachine/Machine/StateContainer.cs
|
namespace Appccelerate.StateMachine.Machine
{
using System;
using System.Collections.Generic;
using Infrastructure;
using States;
public class StateContainer<TState, TEvent> :
IExtensionHost<TState, TEvent>,
IStateMachineInformation<TState, TEvent>,
ILastActiveStateModifier<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
private Dictionary<TState, IStateDefinition<TState, TEvent>> lastActiveStates = new Dictionary<TState, IStateDefinition<TState, TEvent>>();
public StateContainer()
: this(default(string))
{
}
public StateContainer(string name)
{
this.Name = name;
}
public string Name { get; }
public List<IExtension<TState, TEvent>> Extensions { get; } = new List<IExtension<TState, TEvent>>();
public Initializable<TState> InitialStateId { get; } = new Initializable<TState>();
public TState CurrentState { get; set; }
public TState CurrentStateId => this.CurrentState;
public void ForEach(Action<IExtension<TState, TEvent>> action)
{
this.Extensions.ForEach(action);
}
public IStateDefinition<TState, TEvent> GetLastActiveStateOrNullFor(TState state)
{
this.lastActiveStates.TryGetValue(state, out var lastActiveState);
return lastActiveState;
}
public void SetLastActiveStateFor(TState state, IStateDefinition<TState, TEvent> newLastActiveState)
{
if (this.lastActiveStates.ContainsKey(state))
{
this.lastActiveStates[state] = newLastActiveState;
}
else
{
this.lastActiveStates.Add(state, newLastActiveState);
}
}
}
}
|
namespace Appccelerate.StateMachine.Machine
{
using System;
using System.Collections.Generic;
using Infrastructure;
using States;
public class StateContainer<TState, TEvent> :
IExtensionHost<TState, TEvent>,
IStateMachineInformation<TState, TEvent>,
ILastActiveStateModifier<TState, TEvent>
where TState : IComparable
where TEvent : IComparable
{
public StateContainer()
: this(default(string))
{
}
public StateContainer(string name)
{
this.Name = name;
}
public string Name { get; }
public List<IExtension<TState, TEvent>> Extensions { get; } = new List<IExtension<TState, TEvent>>();
public Initializable<TState> InitialStateId { get; } = new Initializable<TState>();
public TState CurrentState { get; set; }
public TState CurrentStateId => this.CurrentState;
public void ForEach(Action<IExtension<TState, TEvent>> action)
{
this.Extensions.ForEach(action);
}
public IStateDefinition<TState, TEvent> GetLastActiveStateOrNullFor(TState state)
{
throw new NotImplementedException();
}
public void SetLastActiveStateFor(TState state, IStateDefinition<TState, TEvent> newLastActiveState)
{
throw new NotImplementedException();
}
}
}
|
apache-2.0
|
C#
|
cb98bdcfdf91d205738f04267c725d2f319f8513
|
Update FrontEndCookieAuthenticationOptions.cs
|
Shazwazza/UmbracoIdentity,Shazwazza/UmbracoIdentity,Shazwazza/UmbracoIdentity
|
src/UmbracoIdentity/FrontEndCookieAuthenticationOptions.cs
|
src/UmbracoIdentity/FrontEndCookieAuthenticationOptions.cs
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security.Cookies;
using System;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
namespace UmbracoIdentity
{
/// <summary>
/// Cookie authentication options for Umbraco front-end authentication
/// </summary>
public class FrontEndCookieAuthenticationOptions : CookieAuthenticationOptions
{
public FrontEndCookieAuthenticationOptions(
FrontEndCookieManager frontEndCookieManager,
ISecuritySection securitySection,
IGlobalSettings globalSettings)
{
CookieManager = frontEndCookieManager;
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
SlidingExpiration = true;
ExpireTimeSpan = TimeSpan.FromMinutes(globalSettings.TimeOutInMinutes);
CookieDomain = securitySection.AuthCookieDomain;
CookieName = securitySection.AuthCookieName + "_MEMBERS";
CookieHttpOnly = true;
CookieSecure = globalSettings.UseHttps ? CookieSecureOption.Always : CookieSecureOption.SameAsRequest;
CookiePath = "/";
}
[Obsolete("Use FrontEndCookieAuthenticationOptions constructor with extended parameters")]
public FrontEndCookieAuthenticationOptions(FrontEndCookieManager frontEndCookieManager)
{
CookieManager = frontEndCookieManager;
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
}
}
}
|
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security.Cookies;
using System;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
namespace UmbracoIdentity
{
/// <summary>
/// Cookie authentication options for Umbraco front-end authentication
/// </summary>
public class FrontEndCookieAuthenticationOptions : CookieAuthenticationOptions
{
public FrontEndCookieAuthenticationOptions(
FrontEndCookieManager frontEndCookieManager,
ISecuritySection securitySection,
IGlobalSettings globalSettings)
{
CookieManager = frontEndCookieManager;
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie;
SlidingExpiration = true;
ExpireTimeSpan = TimeSpan.FromMinutes(globalSettings.TimeOutInMinutes);
CookieDomain = securitySection.AuthCookieDomain;
CookieName = securitySection.AuthCookieName + "_MEMBERS";
CookieHttpOnly = true;
CookieSecure = globalSettings.UseHttps ? CookieSecureOption.Always : CookieSecureOption.SameAsRequest;
CookiePath = "/";
}
}
}
|
mit
|
C#
|
523fa51d9598fe02f4034652a05b90067f2a1736
|
Remove "broken" tag from CompareTo tests
|
Ruhrpottpatriot/SemanticVersion
|
test/SemanticVersionTest/SemanticVersion/CompareToTests.cs
|
test/SemanticVersionTest/SemanticVersion/CompareToTests.cs
|
namespace SemanticVersionTest
{
using SemVersion;
using Xunit;
public class CompareToTests
{
[Fact]
public void CompareToInvaildObject()
{
SemanticVersion version = new SemanticVersion(1,0,0);
Assert.Equal(1,version.CompareTo(new object()));
}
[Fact]
public void CompareToValidObject()
{
SemanticVersion version = new SemanticVersion(1,0,0);
SemanticVersion other = new SemanticVersion(1,0,0);
Assert.Equal(0, version.CompareTo((object)other));
}
[Fact]
public void CompareTo()
{
SemanticVersion version = new SemanticVersion(1, 0, 0);
Assert.Equal(0, version.CompareTo(version));
}
[Fact]
public void CompareToNull()
{
SemanticVersion version = new SemanticVersion(1, 0, 0);
Assert.Equal(1, version.CompareTo(null));
}
[Fact]
public void CompareToMinor()
{
SemanticVersion left = new SemanticVersion(1, 0, 0);
SemanticVersion right = new SemanticVersion(1, 1, 0);
Assert.Equal(-1, left.CompareTo(right));
}
[Fact]
public void CompareToPatch()
{
SemanticVersion left = new SemanticVersion(1, 1, 0);
SemanticVersion right = new SemanticVersion(1, 1, 1);
Assert.Equal(-1, left.CompareTo(right));
}
[Fact]
public void CompareToBuildRightEmpty()
{
SemanticVersion left = new SemanticVersion(1, 1, 0, build:"abc");
SemanticVersion right = new SemanticVersion(1, 1, 0);
Assert.Equal(0, left.CompareTo(right));
}
[Fact]
public void CompareToBuildLeftEmpty()
{
SemanticVersion left = new SemanticVersion(1, 1, 0);
SemanticVersion right = new SemanticVersion(1, 1, 0, build: "abc");
Assert.Equal(0, left.CompareTo(right));
}
}
}
|
namespace SemanticVersionTest
{
using SemVersion;
using Xunit;
public class CompareToTests
{
[Fact]
public void CompareToInvaildObject()
{
SemanticVersion version = new SemanticVersion(1,0,0);
Assert.Equal(1,version.CompareTo(new object()));
}
[Fact]
public void CompareToValidObject()
{
SemanticVersion version = new SemanticVersion(1,0,0);
SemanticVersion other = new SemanticVersion(1,0,0);
Assert.Equal(0, version.CompareTo((object)other));
}
[Fact]
public void CompareTo()
{
SemanticVersion version = new SemanticVersion(1, 0, 0);
Assert.Equal(0, version.CompareTo(version));
}
[Fact]
public void CompareToNull()
{
SemanticVersion version = new SemanticVersion(1, 0, 0);
Assert.Equal(1, version.CompareTo(null));
}
[Fact]
public void CompareToMinor()
{
SemanticVersion left = new SemanticVersion(1, 0, 0);
SemanticVersion right = new SemanticVersion(1, 1, 0);
Assert.Equal(-1, left.CompareTo(right));
}
[Fact]
public void CompareToPatch()
{
SemanticVersion left = new SemanticVersion(1, 1, 0);
SemanticVersion right = new SemanticVersion(1, 1, 1);
Assert.Equal(-1, left.CompareTo(right));
}
[Fact(Skip="Broken")]
public void CompareToBuildRightEmpty()
{
SemanticVersion left = new SemanticVersion(1, 1, 0, build:"abc");
SemanticVersion right = new SemanticVersion(1, 1, 0);
Assert.Equal(1, left.CompareTo(right));
}
[Fact(Skip="Broken")]
public void CompareToBuildLeftEmpty()
{
SemanticVersion left = new SemanticVersion(1, 1, 0);
SemanticVersion right = new SemanticVersion(1, 1, 0, build: "abc");
Assert.Equal(-1, left.CompareTo(right));
}
}
}
|
mit
|
C#
|
306cf771debe797987d4d6d8f59b763727fbbf48
|
build 7.1.15.0
|
agileharbor/channelAdvisorAccess
|
src/Global/GlobalAssemblyInfo.cs
|
src/Global/GlobalAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor 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( "7.1.15.0" ) ]
|
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor 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( "7.1.14.0" ) ]
|
bsd-3-clause
|
C#
|
9a28a61b165cb0669b04219380ffb5fb63bb23ee
|
Update AmigoCloudRestSharpOauth2Authenticator.cs
|
amigocloud/amigocloud_samples,amigocloud/amigocloud_samples,amigocloud/amigocloud_samples,amigocloud/amigocloud_samples,amigocloud/amigocloud_samples
|
CSharp/AmigoCloudSample/AmigoCloudSample/AmigoCloudRestSharpOauth2Authenticator.cs
|
CSharp/AmigoCloudSample/AmigoCloudSample/AmigoCloudRestSharpOauth2Authenticator.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmigoCloudSample
{
public class AmigoCloudRestSharpOAuth2Authenticator : RestSharp.Authenticators.OAuth2Authenticator
{
public AmigoCloudRestSharpOAuth2Authenticator(string access_token)
: base(access_token)
{
}
public override void Authenticate(RestSharp.IRestClient client, RestSharp.IRestRequest request)
{
bool foundAuthorizationHeader = false;
for (int i = 0; i < request.Parameters.Count; i++)
{
if (request.Parameters[i].Name == "Authorization")
{
foundAuthorizationHeader = true;
break;
// do nothing
}
}
if (foundAuthorizationHeader)
{
// do nothing
}
else
{
request.AddHeader("Authorization", "Bearer " + base.AccessToken);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AmigoCloudSample
{
public class AmigoCloudRestSharpOAuth2Authenticator : RestSharp.Authenticators.OAuth2Authenticator
{
public AmigoCloudRestSharpOAuth2Authenticator(string access_token)
: base(access_token)
{
}
public override void Authenticate(RestSharp.IRestClient client, RestSharp.IRestRequest request)
{
bool foundAuthorizationHeader = false;
for (int i = 0; i < request.Parameters.Count; i++)
{
if (request.Parameters[i].Name == "Authorization")
{
foundAuthorizationHeader = true;
break;
// do nothing
}
}
if (foundAuthorizationHeader)
{
// do nothing
}
else
{
request.AddHeader("Authorization", "Bearer " + base.AccessToken);
}
// curl --header "Authorization: Bearer tDmfUNoKehyiIH2JK2inUCySzM8AWu" http://qa-amigocloud.urbanfootprint.net/footprint/amigocloud/gptool_data/
}
}
}
|
mit
|
C#
|
ba7b36c8bedad937b291aaf112e9cfea84f8e7dd
|
make sure to flush logs when job is done
|
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
|
Anlab.Jobs.Core/Logging/LogHelper.cs
|
Anlab.Jobs.Core/Logging/LogHelper.cs
|
using System;
using Microsoft.Extensions.Configuration;
using Serilog;
using StackifyLib;
namespace Anlab.Jobs.Core.Logging
{
public static class LogHelper {
public static LoggerConfiguration LogConfiguration;
public static bool _loggingSetup = false;
public static void ConfigureLogging(IConfigurationRoot configuration) {
if (_loggingSetup) return;
configuration.ConfigureStackifyLogging(); // use the config setting keys
LogConfiguration = new LoggerConfiguration()
.WriteTo.Stackify()
.WriteTo.Console();
Log.Logger = LogConfiguration.CreateLogger();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Log.Fatal(e.ExceptionObject as Exception, e.ExceptionObject.ToString());
AppDomain.CurrentDomain.ProcessExit += (sender, e) => Log.CloseAndFlush();
_loggingSetup = true;
}
}
}
|
using System;
using Microsoft.Extensions.Configuration;
using Serilog;
using StackifyLib;
namespace Anlab.Jobs.Core.Logging
{
public static class LogHelper {
public static LoggerConfiguration LogConfiguration;
public static bool _loggingSetup = false;
public static void ConfigureLogging(IConfigurationRoot configuration) {
if (_loggingSetup) return;
configuration.ConfigureStackifyLogging(); // use the config setting keys
LogConfiguration = new LoggerConfiguration()
.WriteTo.Stackify()
.WriteTo.Console();
Log.Logger = LogConfiguration.CreateLogger();
AppDomain.CurrentDomain.UnhandledException += (sender, e) => Log.Fatal(e.ExceptionObject as Exception, e.ExceptionObject.ToString());
_loggingSetup = true;
}
}
}
|
mit
|
C#
|
44924e40e4052eb9cdd5939f5ce4dd8aa9f5fa5b
|
Convert tabs to spaces because, you know, ...
|
Over17/UnityOBBDownloader,Over17/UnityOBBDownloader
|
Assets/Scripts/DownloadObbExample.cs
|
Assets/Scripts/DownloadObbExample.cs
|
using UnityEngine;
using System.Collections;
public class DownloadObbExample : MonoBehaviour
{
private IGooglePlayObbDownloader m_obbDownloader;
void Start()
{
m_obbDownloader = GooglePlayObbDownloadManager.GetGooglePlayObbDownloader();
m_obbDownloader.PublicKey = "YOUR PUBLIC KEY HERE";
}
void OnGUI()
{
if (!GooglePlayObbDownloadManager.IsRunningOnAndroid())
{
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "Use GooglePlayDownloader only on Android device!");
return;
}
string expPath = m_obbDownloader.GetExpansionFilePath();
if (expPath == null)
{
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "External storage is not available!");
}
else
{
var mainPath = m_obbDownloader.GetMainOBBPath();
var patchPath = m_obbDownloader.GetPatchOBBPath();
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "Main = ..." + ( mainPath == null ? " NOT AVAILABLE" : mainPath.Substring(expPath.Length)));
GUI.Label(new Rect(10, 25, Screen.width-10, 20), "Patch = ..." + (patchPath == null ? " NOT AVAILABLE" : patchPath.Substring(expPath.Length)));
if (mainPath == null || patchPath == null)
if (GUI.Button(new Rect(10, 100, 100, 100), "Fetch OBBs"))
m_obbDownloader.FetchOBB();
}
}
}
|
using UnityEngine;
using System.Collections;
public class DownloadObbExample : MonoBehaviour
{
private IGooglePlayObbDownloader m_obbDownloader;
void Start()
{
m_obbDownloader = GooglePlayObbDownloadManager.GetGooglePlayObbDownloader();
m_obbDownloader.PublicKey = "YOUR PUBLIC KEY HERE";
}
void OnGUI()
{
if (!GooglePlayObbDownloadManager.IsRunningOnAndroid())
{
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "Use GooglePlayDownloader only on Android device!");
return;
}
string expPath = m_obbDownloader.GetExpansionFilePath();
if (expPath == null)
{
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "External storage is not available!");
}
else
{
var mainPath = m_obbDownloader.GetMainOBBPath();
var patchPath = m_obbDownloader.GetPatchOBBPath();
GUI.Label(new Rect(10, 10, Screen.width-10, 20), "Main = ..." + ( mainPath == null ? " NOT AVAILABLE" : mainPath.Substring(expPath.Length)));
GUI.Label(new Rect(10, 25, Screen.width-10, 20), "Patch = ..." + (patchPath == null ? " NOT AVAILABLE" : patchPath.Substring(expPath.Length)));
if (mainPath == null || patchPath == null)
if (GUI.Button(new Rect(10, 100, 100, 100), "Fetch OBBs"))
m_obbDownloader.FetchOBB();
}
}
}
|
apache-2.0
|
C#
|
57041f8c4468a8cdc8ff5dc1fc6e5340c591cd7f
|
add page for resource detail and partially implement it
|
anobleperson/allReady,MisterJames/allReady,HTBox/allReady,HamidMosalla/allReady,jonatwabash/allReady,HamidMosalla/allReady,gitChuckD/allReady,dpaquette/allReady,gitChuckD/allReady,gitChuckD/allReady,anobleperson/allReady,binaryjanitor/allReady,VishalMadhvani/allReady,binaryjanitor/allReady,BillWagner/allReady,bcbeatty/allReady,jonatwabash/allReady,stevejgordon/allReady,BillWagner/allReady,dpaquette/allReady,HTBox/allReady,jonatwabash/allReady,MisterJames/allReady,MisterJames/allReady,HamidMosalla/allReady,stevejgordon/allReady,mgmccarthy/allReady,dpaquette/allReady,mgmccarthy/allReady,GProulx/allReady,GProulx/allReady,binaryjanitor/allReady,c0g1t8/allReady,jonatwabash/allReady,HamidMosalla/allReady,VishalMadhvani/allReady,stevejgordon/allReady,mgmccarthy/allReady,VishalMadhvani/allReady,bcbeatty/allReady,bcbeatty/allReady,anobleperson/allReady,bcbeatty/allReady,VishalMadhvani/allReady,c0g1t8/allReady,BillWagner/allReady,HTBox/allReady,BillWagner/allReady,c0g1t8/allReady,dpaquette/allReady,stevejgordon/allReady,gitChuckD/allReady,HTBox/allReady,MisterJames/allReady,binaryjanitor/allReady,GProulx/allReady,GProulx/allReady,mgmccarthy/allReady,anobleperson/allReady,c0g1t8/allReady
|
AllReadyApp/Web-App/AllReady/Areas/Admin/ViewModels/Resource/ResourceEditViewModel.cs
|
AllReadyApp/Web-App/AllReady/Areas/Admin/ViewModels/Resource/ResourceEditViewModel.cs
|
using System;
using System.ComponentModel.DataAnnotations;
namespace AllReady.Areas.Admin.ViewModels.Resource
{
public class ResourceEditViewModel
{
public int Id { get; set; }
public int CampaignId { get; set; }
public string CampaignName { get; set; }
[Display(Name = "Resource name")]
[Required]
public string Name { get; set; }
[Display(Name = "Resource description")]
public string Description { get; set; }
[Required]
[Url]
[Display(Name = "Resource URL")]
public string ResourceUrl { get; set; }
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace AllReady.Areas.Admin.ViewModels.Resource
{
public class ResourceEditViewModel
{
public int Id { get; set; }
public int CampaignId { get; set; }
[Display(Name = "Resource name")]
[Required]
public string Name { get; set; }
[Display(Name = "Resource description")]
public string Description { get; set; }
[Required]
[Url]
[Display(Name = "Resource URL")]
public string ResourceUrl { get; set; }
}
}
|
mit
|
C#
|
5c02290245cdf8c840a20e60c1f0bcf135c8d7e1
|
Bump version to 0.5.2
|
quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot,sqt/cactbot
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
CactbotOverlay/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.5.2.0")]
[assembly: AssemblyFileVersion("0.5.2.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("CactbotOverlay")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CactbotOverlay")]
[assembly: AssemblyCopyright("Copyright 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("a7324717-0785-49ac-95e9-dc01bd7fbe7c")]
// Version:
// - Major Version
// - Minor Version
// - Build Number
// - Revision
// GitHub has only 3 version components, so Revision should always be 0.
[assembly: AssemblyVersion("0.5.1.0")]
[assembly: AssemblyFileVersion("0.5.1.0")]
|
apache-2.0
|
C#
|
92300d011c48b4142c62f5b237812f04c18d31f9
|
Make decal on despawn script use void.
|
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
|
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/ProjectileDecalOnDespawn.cs
|
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/ProjectileDecalOnDespawn.cs
|
using UnityEngine;
namespace Weapons.Projectiles.Behaviours
{
/// <summary>
/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
/// </summary>
public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
{
[SerializeField] private GameObject decal = null;
[Tooltip("Living time of decal.")]
[SerializeField] private float animationTime = 0;
[Tooltip("Spawn decal on collision?")]
[SerializeField] private bool isTriggeredOnHit = true;
public void OnDespawn(RaycastHit2D hit, Vector2 point)
{
if (isTriggeredOnHit && hit.collider != null)
{
OnBeamEnd(hit.point);
}
else
{
OnBeamEnd(point);
}
}
private void OnBeamEnd(Vector2 position)
{
var newDecal = Spawn.ClientPrefab(decal.name,
position).GameObject;
var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
timeLimitedDecal.SetUpDecal(animationTime);
}
}
}
|
using UnityEngine;
namespace Weapons.Projectiles.Behaviours
{
/// <summary>
/// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something.
/// </summary>
public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn
{
[SerializeField] private GameObject decal = null;
[Tooltip("Living time of decal.")]
[SerializeField] private float animationTime = 0;
[Tooltip("Spawn decal on collision?")]
[SerializeField] private bool isTriggeredOnHit = true;
public void OnDespawn(RaycastHit2D hit, Vector2 point)
{
if (isTriggeredOnHit && hit.collider != null)
{
OnBeamEnd(hit.point);
}
else
{
OnBeamEnd(point);
}
}
private bool OnBeamEnd(Vector2 position)
{
var newDecal = Spawn.ClientPrefab(decal.name,
position).GameObject;
var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>();
timeLimitedDecal.SetUpDecal(animationTime);
return false;
}
}
}
|
agpl-3.0
|
C#
|
983c90af5262d9e027f6a26d79c718a4eabec2e7
|
Fix harmony ambiguity
|
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
|
LmpClient/Harmony/ScenarioDiscoverableObjects_SpawnComet.cs
|
LmpClient/Harmony/ScenarioDiscoverableObjects_SpawnComet.cs
|
using Harmony;
using LmpClient.Systems.AsteroidComet;
using LmpClient.Systems.Lock;
using LmpClient.Systems.SettingsSys;
using LmpCommon.Enums;
// ReSharper disable All
namespace LmpClient.Harmony
{
/// <summary>
/// This harmony patch is intended to skip the spawn of a comet if we don't have the lock or the server doesn't allow them
/// </summary>
[HarmonyPatch(typeof(ScenarioDiscoverableObjects))]
[HarmonyPatch("SpawnComet")]
[HarmonyPatch(new[] { typeof(string) })]
public class ScenarioDiscoverableObjects_SpawnComet
{
[HarmonyPrefix]
private static bool PrefixSpawnComet()
{
if (MainSystem.NetworkState < ClientState.Connected) return true;
if (!LockSystem.LockQuery.AsteroidCometLockBelongsToPlayer(SettingsSystem.CurrentSettings.PlayerName))
return false;
var currentComets = AsteroidCometSystem.Singleton.GetCometCount();
if (currentComets >= SettingsSystem.ServerSettings.MaxNumberOfComets)
{
return false;
}
return true;
}
}
}
|
using Harmony;
using LmpClient.Systems.AsteroidComet;
using LmpClient.Systems.Lock;
using LmpClient.Systems.SettingsSys;
using LmpCommon.Enums;
// ReSharper disable All
namespace LmpClient.Harmony
{
/// <summary>
/// This harmony patch is intended to skip the spawn of a comet if we don't have the lock or the server doesn't allow them
/// </summary>
[HarmonyPatch(typeof(ScenarioDiscoverableObjects))]
[HarmonyPatch("SpawnComet")]
public class ScenarioDiscoverableObjects_SpawnComet
{
[HarmonyPrefix]
private static bool PrefixSpawnComet()
{
if (MainSystem.NetworkState < ClientState.Connected) return true;
if (!LockSystem.LockQuery.AsteroidCometLockBelongsToPlayer(SettingsSystem.CurrentSettings.PlayerName))
return false;
var currentComets = AsteroidCometSystem.Singleton.GetCometCount();
if (currentComets >= SettingsSystem.ServerSettings.MaxNumberOfComets)
{
return false;
}
return true;
}
}
}
|
mit
|
C#
|
f612700a1ad38bfe1be307408e25cd176c1b8701
|
Format changes
|
castleproject/Castle.Facilities.Wcf-READONLY,castleproject/Castle.Facilities.Wcf-READONLY,castleproject/castle-READONLY-SVN-dump,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump,codereflection/Castle.Components.Scheduler,carcer/Castle.Components.Validator
|
ActiveRecord/Castle.ActiveRecord.Tests/NullablesTestCase.cs
|
ActiveRecord/Castle.ActiveRecord.Tests/NullablesTestCase.cs
|
// Copyright 2004-2006 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ActiveRecord.Tests
{
using NUnit.Framework;
using Castle.ActiveRecord.Tests.Model;
[TestFixture]
public class NullablesTestCase : AbstractActiveRecordTest
{
[SetUp]
public new void Init()
{
base.Init();
ActiveRecordStarter.Initialize(GetConfigSource(), typeof(NullableModel));
Recreate();
}
[Test]
public void Usage()
{
NullableModel model = new NullableModel();
model.Save();
Assert.AreEqual(1, NullableModel.FindAll().Length);
model = NullableModel.FindAll()[0];
Assert.AreEqual(Nullables.NullableInt32.Default, model.Age);
Assert.AreEqual(Nullables.NullableDateTime.Default, model.Completion);
Assert.AreEqual(Nullables.NullableBoolean.Default, model.Accepted);
}
}
}
|
// Copyright 2004-2006 Castle Project - http://www.castleproject.org/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Castle.ActiveRecord.Tests
{
using System;
using NUnit.Framework;
using Castle.ActiveRecord.Tests.Model;
[TestFixture]
public class NullablesTestCase : AbstractActiveRecordTest
{
[SetUp]
public new void Init()
{
base.Init();
ActiveRecordStarter.Initialize( GetConfigSource(), typeof(NullableModel) );
Recreate();
}
[Test]
public void Usage()
{
NullableModel model = new NullableModel();
model.Save();
Assert.AreEqual(1, NullableModel.FindAll().Length);
model = NullableModel.FindAll()[0];
Assert.AreEqual(Nullables.NullableInt32.Default, model.Age);
Assert.AreEqual(Nullables.NullableDateTime.Default, model.Completion);
Assert.AreEqual(Nullables.NullableBoolean.Default, model.Accepted);
}
}
}
|
apache-2.0
|
C#
|
e0ec5525bd72d87eb592745ac48dad6b993c73a2
|
Fix comparison logic
|
rvhuang/heuristic-suite
|
AlgorithmForce.Example.CoinsFlipping/PuzzleStateComparer.cs
|
AlgorithmForce.Example.CoinsFlipping/PuzzleStateComparer.cs
|
using System.Linq;
namespace AlgorithmForce.Example.CoinsFlipping
{
using HeuristicSuite;
class PuzzleStateComparer : HeuristicComparer<bool[]>
{
public PuzzleStateComparer()
: base(Estimation)
{
}
private static double Estimation(bool[] coins)
{
return 0 - (coins.Count(coin => coin) + GetContinuity(coins));
}
private static int GetContinuity(bool[] coins)
{
var finalScore = 0;
var currentScore = 0;
for (var i = 1; i < coins.Length; i++)
{
if (coins[i - 1] && coins[i])
currentScore += 1;
else
{
if (finalScore < currentScore)
finalScore = currentScore;
currentScore = 0;
}
}
if (finalScore < currentScore)
finalScore = currentScore;
return finalScore;
}
}
}
|
using System.Linq;
namespace AlgorithmForce.Example.CoinsFlipping
{
using HeuristicSuite;
class PuzzleStateComparer : HeuristicComparer<bool[]>
{
public PuzzleStateComparer()
: base(Estimation)
{
}
private static double Estimation(bool[] coins)
{
return 0 - coins.Count(coin => coin) + GetContinuity(coins);
}
private static int GetContinuity(bool[] coins)
{
var finalScore = 0;
var currentScore = 0;
for (var i = 1; i < coins.Length; i++)
{
if (coins[i - 1] && coins[i])
currentScore += 1;
else
{
if (finalScore < currentScore)
finalScore = currentScore;
currentScore = 0;
}
}
if (finalScore < currentScore)
finalScore = currentScore;
return finalScore;
}
}
}
|
mit
|
C#
|
968463912ab548808ff87bc58760b2b2bc7bb45e
|
Include CheckBoxList in ValueListPreValueMigrator
|
mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,madsoulswe/Umbraco-CMS
|
src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/DataTypes/ValueListPreValueMigrator.cs
|
src/Umbraco.Core/Migrations/Upgrade/V_8_0_0/DataTypes/ValueListPreValueMigrator.cs
|
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0.DataTypes
{
class ValueListPreValueMigrator : IPreValueMigrator
{
private readonly string[] _editors =
{
"Umbraco.RadioButtonList",
"Umbraco.CheckBoxList",
"Umbraco.DropDown",
"Umbraco.DropdownlistPublishingKeys",
"Umbraco.DropDownMultiple",
"Umbraco.DropdownlistMultiplePublishKeys"
};
public bool CanMigrate(string editorAlias)
=> _editors.Contains(editorAlias);
public virtual string GetNewAlias(string editorAlias)
=> null;
public object GetConfiguration(int dataTypeId, string editorAlias, Dictionary<string, PreValueDto> preValues)
{
var config = new ValueListConfiguration();
foreach (var preValue in preValues.Values)
config.Items.Add(new ValueListConfiguration.ValueListItem { Id = preValue.Id, Value = preValue.Value });
return config;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.PropertyEditors;
namespace Umbraco.Core.Migrations.Upgrade.V_8_0_0.DataTypes
{
class ValueListPreValueMigrator : IPreValueMigrator
{
private readonly string[] _editors =
{
"Umbraco.RadioButtonList",
"Umbraco.DropDown",
"Umbraco.DropdownlistPublishingKeys",
"Umbraco.DropDownMultiple",
"Umbraco.DropdownlistMultiplePublishKeys"
};
public bool CanMigrate(string editorAlias)
=> _editors.Contains(editorAlias);
public virtual string GetNewAlias(string editorAlias)
=> null;
public object GetConfiguration(int dataTypeId, string editorAlias, Dictionary<string, PreValueDto> preValues)
{
var config = new ValueListConfiguration();
foreach (var preValue in preValues.Values)
config.Items.Add(new ValueListConfiguration.ValueListItem { Id = preValue.Id, Value = preValue.Value });
return config;
}
}
}
|
mit
|
C#
|
bc3d2378f69eef44ccfd44111ea51faa10e84d7b
|
Fix uwp comiple. Sample scene passes.
|
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MixedRealityToolkit.Examples/Demos/HandTracking/Script/OpenSystemKeyboard.cs
|
Assets/MixedRealityToolkit.Examples/Demos/HandTracking/Script/OpenSystemKeyboard.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Experimental.UI;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
public class OpenSystemKeyboard : MonoBehaviour
{
private MixedRealityKeyboard wmrKeyboard;
private TouchScreenKeyboard touchscreenKeyboard;
public static string keyboardText = "";
public TextMesh debugMessage;
private void Start()
{
#if !UNITY_EDITOR && UNITY_WSA
// Windows mixed reality keyboard initialization goes here
wmrKeyboard = gameObject.AddComponent<MixedRealityKeyboard>();
wmrKeyboard.TextChanged.AddListener((eventData) => debugMessage.text = "typing... " + wmrKeyboard.Text);
wmrKeyboard.KeyboardHidden.AddListener(() => debugMessage.text = "typed " + wmrKeyboard.Text);
#else
// non-Windows mixed reality keyboard initialization goes here
#endif
}
public void Open()
{
#if !UNITY_EDITOR && UNITY_WSA
wmrKeyboard.ShowKeyboard();
#else
touchscreenKeyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, false, false);
#endif
}
private void Update()
{
#if !UNITY_EDITOR && UNITY_WSA
// Windows mixed reality keyboard update goes here
#else
// non-Windows mixed reality keyboard initialization goes here
// for non-Windows mixed reality keyboards just use Unity's default
// touchscreenkeyboard.
// We will use touchscreenkeyboard once Unity bug is fixed
// Unity bug tracking the issue https://fogbugz.unity3d.com/default.asp?1137074_rttdnt8t1lccmtd3
if (touchscreenKeyboard != null)
{
keyboardText = touchscreenKeyboard.text;
if (TouchScreenKeyboard.visible)
{
debugMessage.text = "typing... " + keyboardText;
}
else
{
debugMessage.text = "typed " + keyboardText;
touchscreenKeyboard = null;
}
}
#endif
}
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Experimental.UI;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Examples.Demos
{
public class OpenSystemKeyboard : MonoBehaviour
{
private MixedRealityKeyboard wmrKeyboard;
private TouchScreenKeyboard touchscreenKeyboard;
public static string keyboardText = "";
public TextMesh debugMessage;
private void Start()
{
#if !UNITY_EDITOR && UNITY_WSA
// Windows mixed reality keyboard initialization goes here
wmrKeyboard = gameObject.AddComponent<MixedRealityKeyboard>();
wmrKeyboard.TextChanged.AddListener((eventData) => debugMessage.text = "typing... " + keyboard.Text);
wmrKeyboard.KeyboardHidden.AddListener(() => debugMessage.text = "typed " + keyboard.Text);
#else
// non-Windows mixed reality keyboard initialization goes here
#endif
}
public void Open()
{
#if !UNITY_EDITOR && UNITY_WSA
wmrKeyboard.ShowKeyboard();
#else
touchscreenKeyboard = TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, false, false);
#endif
}
private void Update()
{
#if !UNITY_EDITOR && UNITY_WSA
// Windows mixed reality keyboard update goes here
#else
// non-Windows mixed reality keyboard initialization goes here
// for non-Windows mixed reality keyboards just use Unity's default
// touchscreenkeyboard.
// We will use touchscreenkeyboard once Unity bug is fixed
// Unity bug tracking the issue https://fogbugz.unity3d.com/default.asp?1137074_rttdnt8t1lccmtd3
if (touchscreenKeyboard != null)
{
keyboardText = touchscreenKeyboard.text;
if (TouchScreenKeyboard.visible)
{
debugMessage.text = "typing... " + keyboardText;
}
else
{
debugMessage.text = "typed " + keyboardText;
touchscreenKeyboard = null;
}
}
#endif
}
}
}
|
mit
|
C#
|
bd792bbed35e26c0bed80922753080da250bcefa
|
Improve tests
|
carbon/Amazon
|
src/Amazon.Ssm.Tests/CommandTests.cs
|
src/Amazon.Ssm.Tests/CommandTests.cs
|
using System;
using System.Text.Json;
using Xunit;
namespace Amazon.Ssm.Tests
{
public class CommandTests
{
[Fact]
public void ParseCommand()
{
var text = @"{ ""CommandId"":""id"",""Comment"":"""",""CompletedCount"":0,""DocumentName"":""update_app4"",""ErrorCount"":0,""ExpiresAfter"":1.494832672676E9,""InstanceIds"":[],""MaxConcurrency"":""50"",""MaxErrors"":""0"",""NotificationConfig"":{""NotificationArn"":"""",""NotificationEvents"":[],""NotificationType"":""""},""OutputS3BucketName"":"""",""OutputS3KeyPrefix"":"""",""Parameters"":{""appName"":[""platform""]},""RequestedDateTime"":1.494825472676E9,""ServiceRole"":"""",""Status"":""Pending"",""StatusDetails"":""Pending"",""TargetCount"":0,""Targets"":[{""Key"":""tag: envId"",""Values"":[""1""]}]}";
var command = JsonSerializer.Deserialize<Command>(text);
Assert.Equal("id", command.CommandId);
Assert.Equal("update_app4", command.DocumentName);
Assert.Empty(command.Comment);
Assert.Equal(0, command.CompletedCount);
Assert.Equal(CommandStatus.Pending, command.Status);
Assert.Equal("Pending", command.StatusDetails);
Assert.Equal(1494825472676, ((DateTimeOffset)command.RequestedDateTime).ToUnixTimeMilliseconds());
}
[InlineData("InProgress", CommandStatus.InProgress)]
[InlineData("Cancelled", CommandStatus.Cancelled)]
[Theory]
public void ParseStatus(string text, CommandStatus status)
{
var command = JsonSerializer.Deserialize<Command>(@$"{{ ""Status"":""{text}"" }}");
Assert.Equal(status, command.Status);
Assert.Null(command.RequestedDateTime);
}
}
}
|
using System;
using Carbon.Json;
using Xunit;
namespace Amazon.Ssm.Tests
{
public class CommandTests
{
[Fact]
public void ParseCommand()
{
var text = @"{ ""CommandId"":""id"",""Comment"":"""",""CompletedCount"":0,""DocumentName"":""update_app4"",""ErrorCount"":0,""ExpiresAfter"":1.494832672676E9,""InstanceIds"":[],""MaxConcurrency"":""50"",""MaxErrors"":""0"",""NotificationConfig"":{""NotificationArn"":"""",""NotificationEvents"":[],""NotificationType"":""""},""OutputS3BucketName"":"""",""OutputS3KeyPrefix"":"""",""Parameters"":{""appName"":[""platform""]},""RequestedDateTime"":1.494825472676E9,""ServiceRole"":"""",""Status"":""Pending"",""StatusDetails"":""Pending"",""TargetCount"":0,""Targets"":[{""Key"":""tag: envId"",""Values"":[""1""]}]}";
var command = JsonObject.Parse(text).As<Command>();
Assert.Equal(1494825472676, new DateTimeOffset(command.RequestedDateTime).ToUnixTimeMilliseconds());
}
}
}
|
mit
|
C#
|
8f14afc3fb2d0bef209940d27123f42481137b03
|
Fix search result when returning multiple results
|
sboulema/Hops,sboulema/Hops,sboulema/Hops
|
src/Hops/Views/Search/Results.cshtml
|
src/Hops/Views/Search/Results.cshtml
|
@using Hops.Models;
@model ListModel<HopModel>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Search results - Hops";
}
@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{
<h3>Search results for "@Model.Pagination.SearchTerm":</h3>
}
@Html.Partial("~/Views/Hop/List.cshtml", Model)
|
@using Hops.Models;
@model ListModel<HopModel>
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
@{
ViewBag.Title = "Search results - Hops";
}
@if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm))
{
<h3>Search results for "@Model.Pagination.SearchTerm":</h3>
}
@Html.Partial("~/Views/Hop/List", Model)
|
mit
|
C#
|
28b53d8acf53a19faca7609e57fb1a46e981bd42
|
Add some extensions to ScriptCommand I should get on writing some tests.
|
PhoenixBound/b2w2-scripts
|
gen5_parse_compile/ScriptCommand.cs
|
gen5_parse_compile/ScriptCommand.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gen5_parse_compile
{
public class ScriptCommand
{
// ID of the command, like 0x0002 or 0x017A
ushort id;
// The name that matches with that ID
string name;
// Size of the whole command in bytes, including the command itself
byte size;
public ushort ID
{
get
{
return id;
}
set
{
id = value;
name = GetCommandName(id);
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
id = GetCommandID(name);
}
}
public ScriptCommand()
{
// Initialize to "nop" by default
id = 0;
name = GetCommandName(id);
}
// UNTESTED (but so simple it should work, right?)
private string GetCommandName(ushort id)
{
// Something something XML parsing...I'm gonna save that for later.
return $"cmd{id:X}";
}
// UNTESTED AS HECK, WRITE A TEST FOR THIS OR SOMETHIGN
private ushort GetCommandID(string name)
{
ushort commandID = 0x0000;
// First, check if it's one of the hardcoded "cmdAB"-type names.
if (name.Length >= 4)
{
bool parsingBool = true;
if (name[0].ToString().ToLower() == "c" &&
name[1].ToString().ToLower() == "m" &&
name[2].ToString().ToLower() == "d")
{
string stringID = name.TrimStart("cmd".ToCharArray());
parsingBool = ushort.TryParse(stringID, out commandID);
}
if (!parsingBool)
{
Console.WriteLine("WARNING: Invalid command {0}. Er...that's not good.", name);
// This will probably be used to compile scripts in the future, so it makes the
// most sense to me to have the script end early.
commandID = 0x0002;
}
}
// Otherwise, something something XML parsing...I'm gonna save that for later.
return commandID;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace gen5_parse_compile
{
public class ScriptCommand
{
ushort id;
string name;
public ushort ID
{
get
{
return id;
}
set
{
id = value;
name = GetCommandName(id);
}
}
public ScriptCommand()
{
id = 0;
name = GetCommandName(id);
}
private string GetCommandName(ushort id)
{
// Something something XML parsing...I'm gonna save that for later.
return $"cmd{id:X}";
}
}
}
|
mit
|
C#
|
459cea6a650489f4a917212240a8bbb5049276c2
|
Update First Page.
|
nuitsjp/PrimerOfPrismForms
|
NavigationEventSequence/NavigationEventSequence/NavigationEventSequence/App.xaml.cs
|
NavigationEventSequence/NavigationEventSequence/NavigationEventSequence/App.xaml.cs
|
using Prism.Unity;
using NavigationEventSequence.Views;
using Xamarin.Forms;
namespace NavigationEventSequence
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("MyNavigationPage/ViewA");
//NavigationService.NavigateAsync("MyTabbedPage/MyNavigationPage/ViewC");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<ViewA>();
Container.RegisterTypeForNavigation<ViewB>();
Container.RegisterTypeForNavigation<ViewC>();
Container.RegisterTypeForNavigation<MyNavigationPage>();
Container.RegisterTypeForNavigation<MyTabbedPage>();
Container.RegisterTypeForNavigation<MyTabNavigationPage>();
}
}
}
|
using Prism.Unity;
using NavigationEventSequence.Views;
using Xamarin.Forms;
namespace NavigationEventSequence
{
public partial class App : PrismApplication
{
public App(IPlatformInitializer initializer = null) : base(initializer) { }
protected override void OnInitialized()
{
InitializeComponent();
//NavigationService.NavigateAsync("MyNavigationPage/ViewA");
NavigationService.NavigateAsync("MyTabbedPage/MyNavigationPage/ViewC");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<NavigationPage>();
Container.RegisterTypeForNavigation<ViewA>();
Container.RegisterTypeForNavigation<ViewB>();
Container.RegisterTypeForNavigation<ViewC>();
Container.RegisterTypeForNavigation<MyNavigationPage>();
Container.RegisterTypeForNavigation<MyTabbedPage>();
Container.RegisterTypeForNavigation<MyTabNavigationPage>();
}
}
}
|
mit
|
C#
|
c2ee8da283b2d3a6b500059d6a261ffcef0950e3
|
Disable 35736 test for Android
|
Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms
|
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla35736.cs
|
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla35736.cs
|
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 35736, "[iOS] Editor does not update Text value from autocorrect when losing focus", PlatformAffected.iOS)]
public class Bugzilla35736 : TestContentPage
{
protected override void Init()
{
var editor = new Editor
{
AutomationId = "Bugzilla35736Editor"
};
var label = new Label
{
AutomationId = "Bugzilla35736Label",
Text = ""
};
Content = new StackLayout
{
Children =
{
editor,
label,
new Button
{
AutomationId = "Bugzilla35736Button",
Text = "Click to set label text",
Command = new Command(() => { label.Text = editor.Text; })
}
}
};
}
#if UITEST && __IOS__
[Test]
public void Bugzilla35736Test()
{
RunningApp.WaitForElement(q => q.Marked("Bugzilla35736Editor"));
RunningApp.EnterText(q => q.Marked("Bugzilla35736Editor"), "Testig");
RunningApp.Tap(q => q.Marked("Bugzilla35736Button"));
Assert.AreEqual("Testing", RunningApp.Query(q => q.Marked("Bugzilla35736Label"))[0].Text);
}
#endif
}
}
|
using Xamarin.Forms.CustomAttributes;
using Xamarin.Forms.Internals;
#if UITEST
using Xamarin.UITest;
using NUnit.Framework;
#endif
namespace Xamarin.Forms.Controls.Issues
{
[Preserve(AllMembers = true)]
[Issue(IssueTracker.Bugzilla, 35736, "[iOS] Editor does not update Text value from autocorrect when losing focus", PlatformAffected.iOS)]
public class Bugzilla35736 : TestContentPage
{
protected override void Init()
{
var editor = new Editor
{
AutomationId = "Bugzilla35736Editor"
};
var label = new Label
{
AutomationId = "Bugzilla35736Label",
Text = ""
};
Content = new StackLayout
{
Children =
{
editor,
label,
new Button
{
AutomationId = "Bugzilla35736Button",
Text = "Click to set label text",
Command = new Command(() => { label.Text = editor.Text; })
}
}
};
}
#if UITEST
[Test]
public void Bugzilla35736Test()
{
RunningApp.WaitForElement(q => q.Marked("Bugzilla35736Editor"));
RunningApp.EnterText(q => q.Marked("Bugzilla35736Editor"), "Testig");
RunningApp.Tap(q => q.Marked("Bugzilla35736Button"));
Assert.AreEqual("Testing", RunningApp.Query(q => q.Marked("Bugzilla35736Label"))[0].Text);
}
#endif
}
}
|
mit
|
C#
|
02d5eed6dcc25e6894837c6c2dfcc3adb9e0ffdd
|
Update ExceptionlessTraceTelemeter.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Analytics/Telemetry/ExceptionlessTraceTelemeter.cs
|
TIKSN.Core/Analytics/Telemetry/ExceptionlessTraceTelemeter.cs
|
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessTraceTelemeter : ExceptionlessTelemeterBase, ITraceTelemeter
{
public Task TrackTraceAsync(string message)
{
try
{
ExceptionlessClient.Default.CreateLog(message).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return Task.CompletedTask;
}
public Task TrackTraceAsync(string message, TelemetrySeverityLevel severityLevel)
{
try
{
ExceptionlessClient.Default.CreateLog(message).SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
return Task.CompletedTask;
}
}
}
|
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Exceptionless;
namespace TIKSN.Analytics.Telemetry
{
public class ExceptionlessTraceTelemeter : ExceptionlessTelemeterBase, ITraceTelemeter
{
public async Task TrackTrace(string message)
{
try
{
ExceptionlessClient.Default.CreateLog(message).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel)
{
try
{
ExceptionlessClient.Default.CreateLog(message).SetType(severityLevel.ToString()).Submit();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
}
}
|
mit
|
C#
|
22f8d3ac4af34584f14999e36adcad6270055a94
|
Fix warnings.
|
JohanLarsson/Gu.Localization
|
Gu.Wpf.Localization/MarkupExtensions/CurrentCultureProxy.cs
|
Gu.Wpf.Localization/MarkupExtensions/CurrentCultureProxy.cs
|
namespace Gu.Wpf.Localization
{
using System.ComponentModel;
using System.Globalization;
using Gu.Localization;
internal class CurrentCultureProxy : INotifyPropertyChanged
{
internal static readonly CurrentCultureProxy Instance = new CurrentCultureProxy();
private CurrentCultureProxy()
{
Translator.CurrentCultureChanged += (_, __) => this.OnPropertyChanged(nameof(this.Value));
}
public event PropertyChangedEventHandler PropertyChanged;
public CultureInfo Value => Translator.CurrentCulture;
protected virtual void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
|
namespace Gu.Wpf.Localization
{
using System.ComponentModel;
using System.Globalization;
using Gu.Localization;
internal class CurrentCultureProxy : INotifyPropertyChanged
{
internal static readonly CurrentCultureProxy Instance = new CurrentCultureProxy();
private CurrentCultureProxy()
{
Translator.CurrentCultureChanged += (_, __) => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(this.Value)));
}
public event PropertyChangedEventHandler PropertyChanged;
public CultureInfo Value => Translator.CurrentCulture;
}
}
|
mit
|
C#
|
d0c50f9d0b3b7b76a0533a3eb181de07980928e2
|
Fix description a little
|
joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net
|
Joinrpg/Views/Shared/DisplayTemplates/MarkdownString.cshtml
|
Joinrpg/Views/Shared/DisplayTemplates/MarkdownString.cshtml
|
@using JoinRpg.Web.Helpers
@model JoinRpg.DataModel.MarkdownString
@Model.ToHtmlString()
|
@using JoinRpg.Web.Helpers
@model JoinRpg.DataModel.MarkdownString
<p>@Model.ToHtmlString()</p>
|
mit
|
C#
|
d3ca07c04a7ea74bc76a93c7b55e28207c594bd0
|
Fix extra assembly info attributes since they are generated by nuget
|
kthompson/csharp-glob,kthompson/glob,kthompson/glob
|
src/Glob/Properties/AssemblyInfo.cs
|
src/Glob/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("Glob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Glob")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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: InternalsVisibleTo("Glob.Tests")]
[assembly: InternalsVisibleTo("Glob.Benchmarks")]
|
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("Glob")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Glob")]
[assembly: AssemblyCopyright("Copyright © 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// 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: InternalsVisibleTo("Glob.Tests")]
[assembly: InternalsVisibleTo("Glob.Benchmarks")]
|
mit
|
C#
|
6408705f82979db60e2a7d1ec81fb56a2f81c3df
|
Return an empty string for / on markdig webapi
|
lunet-io/markdig
|
src/Markdig.WebApp/ApiController.cs
|
src/Markdig.WebApp/ApiController.cs
|
using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;
namespace Markdig.WebApp
{
public class ApiController : Controller
{
[HttpGet()]
[Route("")]
public string Empty()
{
return string.Empty;
}
// GET api/to_html?text=xxx&extensions=advanced
[Route("api/to_html")]
[HttpGet()]
public object Get([FromQuery] string text, [FromQuery] string extension)
{
try
{
if (text == null)
{
text = string.Empty;
}
if (text.Length > 1000)
{
text = text.Substring(0, 1000);
}
var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
var result = Markdown.ToHtml(text, pipeline);
return new {name = "markdig", html = result, version = Markdown.Version};
}
catch (Exception ex)
{
return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
}
}
private static string GetPrettyMessageFromException(Exception exception)
{
var builder = new StringBuilder();
while (exception != null)
{
builder.Append(exception.Message);
exception = exception.InnerException;
}
return builder.ToString();
}
}
}
|
using System;
using System.Text;
using Microsoft.AspNetCore.Mvc;
namespace Markdig.WebApp
{
public class ApiController : Controller
{
// GET api/to_html?text=xxx&extensions=advanced
[Route("api/to_html")]
[HttpGet()]
public object Get([FromQuery] string text, [FromQuery] string extension)
{
try
{
if (text == null)
{
text = string.Empty;
}
if (text.Length > 1000)
{
text = text.Substring(0, 1000);
}
var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build();
var result = Markdown.ToHtml(text, pipeline);
return new {name = "markdig", html = result, version = Markdown.Version};
}
catch (Exception ex)
{
return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version };
}
}
private static string GetPrettyMessageFromException(Exception exception)
{
var builder = new StringBuilder();
while (exception != null)
{
builder.Append(exception.Message);
exception = exception.InnerException;
}
return builder.ToString();
}
}
}
|
bsd-2-clause
|
C#
|
0eaf450204c397fa58c7b310ccefe574f9e851cc
|
Make field readonly
|
peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu
|
osu.Game/Beatmaps/Drawables/Cards/Buttons/DownloadButton.cs
|
osu.Game/Beatmaps/Drawables/Cards/Buttons/DownloadButton.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.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Configuration;
using osu.Game.Online;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
private readonly Bindable<DownloadState> downloadState = new Bindable<DownloadState>();
private Bindable<bool> preferNoVideo = null!;
[Resolved]
private BeatmapManager beatmaps { get; set; } = null!;
public DownloadButton(APIBeatmapSet beatmapSet)
{
Icon.Icon = FontAwesome.Solid.Download;
this.beatmapSet = beatmapSet;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, BeatmapDownloadTracker downloadTracker)
{
preferNoVideo = config.GetBindable<bool>(OsuSetting.PreferNoVideo);
((IBindable<DownloadState>)downloadState).BindTo(downloadTracker.State);
}
protected override void LoadComplete()
{
base.LoadComplete();
preferNoVideo.BindValueChanged(_ => updateState());
downloadState.BindValueChanged(_ => updateState(), true);
FinishTransforms(true);
}
private void updateState()
{
this.FadeTo(downloadState.Value != DownloadState.LocallyAvailable ? 1 : 0, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
if (beatmapSet.Availability.DownloadDisabled)
{
Enabled.Value = false;
TooltipText = BeatmapsetsStrings.AvailabilityDisabled;
return;
}
if (!beatmapSet.HasVideo)
TooltipText = BeatmapsetsStrings.PanelDownloadAll;
else
TooltipText = preferNoVideo.Value ? BeatmapsetsStrings.PanelDownloadNoVideo : BeatmapsetsStrings.PanelDownloadVideo;
Action = () => beatmaps.Download(beatmapSet, preferNoVideo.Value);
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable enable
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Game.Online.API.Requests.Responses;
using osu.Game.Configuration;
using osu.Game.Online;
using osu.Game.Resources.Localisation.Web;
namespace osu.Game.Beatmaps.Drawables.Cards.Buttons
{
public class DownloadButton : BeatmapCardIconButton
{
private readonly APIBeatmapSet beatmapSet;
private Bindable<bool> preferNoVideo = null!;
private Bindable<DownloadState> downloadState = new Bindable<DownloadState>();
[Resolved]
private BeatmapManager beatmaps { get; set; } = null!;
public DownloadButton(APIBeatmapSet beatmapSet)
{
Icon.Icon = FontAwesome.Solid.Download;
this.beatmapSet = beatmapSet;
}
[BackgroundDependencyLoader]
private void load(OsuConfigManager config, BeatmapDownloadTracker downloadTracker)
{
preferNoVideo = config.GetBindable<bool>(OsuSetting.PreferNoVideo);
((IBindable<DownloadState>)downloadState).BindTo(downloadTracker.State);
}
protected override void LoadComplete()
{
base.LoadComplete();
preferNoVideo.BindValueChanged(_ => updateState());
downloadState.BindValueChanged(_ => updateState(), true);
FinishTransforms(true);
}
private void updateState()
{
this.FadeTo(downloadState.Value != DownloadState.LocallyAvailable ? 1 : 0, BeatmapCard.TRANSITION_DURATION, Easing.OutQuint);
if (beatmapSet.Availability.DownloadDisabled)
{
Enabled.Value = false;
TooltipText = BeatmapsetsStrings.AvailabilityDisabled;
return;
}
if (!beatmapSet.HasVideo)
TooltipText = BeatmapsetsStrings.PanelDownloadAll;
else
TooltipText = preferNoVideo.Value ? BeatmapsetsStrings.PanelDownloadNoVideo : BeatmapsetsStrings.PanelDownloadVideo;
Action = () => beatmaps.Download(beatmapSet, preferNoVideo.Value);
}
}
}
|
mit
|
C#
|
80fbb44ea980d77046904404f4b6758e1350b706
|
Fix build (#1447)
|
space-wizards/space-station-14-content,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14-content,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
|
Content.Shared/Physics/MoverController.cs
|
Content.Shared/Physics/MoverController.cs
|
#nullable enable
using Content.Shared.GameObjects.Components.Movement;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
namespace Content.Shared.Physics
{
public class MoverController : VirtualController
{
private Vector2 _velocity;
private ICollidableComponent? _component;
public Vector2 Velocity
{
get => _velocity;
set => _velocity = value;
}
public override ICollidableComponent? ControlledComponent
{
set => _component = value;
}
public MoverController()
{
_velocity = Vector2.Zero;
}
public void Move(Vector2 velocityDirection, float speed)
{
if (_component?.Owner.HasComponent<MovementIgnoreGravityComponent>() == false
&& IoCManager.Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition)) return;
Push(velocityDirection, speed);
}
public void Push(Vector2 velocityDirection, float speed)
{
Velocity = velocityDirection * speed;
}
public void StopMoving()
{
Velocity = Vector2.Zero;
}
public override void UpdateBeforeProcessing()
{
base.UpdateBeforeProcessing();
if (_component == null)
{
return;
}
if (Velocity == Vector2.Zero)
{
// Try to stop movement
_component.LinearVelocity = Vector2.Zero;
}
else
{
_component.LinearVelocity = Velocity;
}
}
}
}
|
using Content.Shared.GameObjects.Components.Movement;
using Robust.Shared.GameObjects.Components;
using Robust.Shared.Interfaces.Physics;
using Robust.Shared.IoC;
using Robust.Shared.Maths;
using Robust.Shared.Physics;
namespace Content.Shared.Physics
{
public class MoverController : VirtualController
{
private Vector2 _velocity;
private ICollidableComponent _component = null;
public Vector2 Velocity
{
get => _velocity;
set => _velocity = value;
}
public override ICollidableComponent? ControlledComponent
{
set => _component = value;
}
public MoverController()
{
_velocity = Vector2.Zero;
}
public void Move(Vector2 velocityDirection, float speed)
{
if (!_component.Owner.HasComponent<MovementIgnoreGravityComponent>() && IoCManager
.Resolve<IPhysicsManager>().IsWeightless(_component.Owner.Transform.GridPosition)) return;
Push(velocityDirection, speed);
}
public void Push(Vector2 velocityDirection, float speed)
{
Velocity = velocityDirection * speed;
}
public void StopMoving()
{
Velocity = Vector2.Zero;
}
public override void UpdateBeforeProcessing()
{
base.UpdateBeforeProcessing();
if (Velocity == Vector2.Zero)
{
// Try to stop movement
_component.LinearVelocity = Vector2.Zero;
}
else
{
_component.LinearVelocity = Velocity;
}
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.