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 |
|---|---|---|---|---|---|---|---|---|
c35ff713c44194a901e7b744832fb23d5a8c6131 | Add precision and scale to avatar zoom scale | MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure | src/GRA.Data/Model/AvatarLayer.cs | src/GRA.Data/Model/AvatarLayer.cs | using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
[Column(TypeName = "decimal(4,2)")]
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
| using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace GRA.Data.Model
{
public class AvatarLayer : Abstract.BaseDbEntity
{
[Required]
public int SiteId { get; set; }
[Required]
[MaxLength(255)]
public string Name { get; set; }
[Required]
public int Position { get; set; }
public bool CanBeEmpty { get; set; }
public int GroupId { get; set; }
public int SortOrder { get; set; }
public bool DefaultLayer { get; set; }
public bool ShowItemSelector { get; set; }
public bool ShowColorSelector { get; set; }
[MaxLength(255)]
public string Icon { get; set; }
public decimal ZoomScale { get; set; }
public int ZoomYOffset { get; set; }
public ICollection<AvatarColor> AvatarColors { get; set; }
public ICollection<AvatarItem> AvatarItems { get; set; }
}
}
| mit | C# |
cb60e3abf6ae0213ba071340b4dd264796406445 | Test requires longer to run on slower aws build agents | Intelliflo/JustSaying,eric-davis/JustSaying,Intelliflo/JustSaying | JustEat.Simples.AwsTools.UnitTests/SqsNotificationListener/WhenThereAreExceptionsInSqsCalling.cs | JustEat.Simples.AwsTools.UnitTests/SqsNotificationListener/WhenThereAreExceptionsInSqsCalling.cs | using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 1000;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
} | using System;
using Amazon.SQS.Model;
using JustEat.Testing;
using NSubstitute;
using NUnit.Framework;
namespace AwsTools.UnitTests.SqsNotificationListener
{
public class WhenThereAreExceptionsInSqsCalling : BaseQueuePollingTest
{
private int _sqsCallCounter;
protected override void Given()
{
TestWaitTime = 50;
base.Given();
Sqs.ReceiveMessage(Arg.Any<ReceiveMessageRequest>())
.Returns(x => { throw new Exception(); })
.AndDoes(x => { _sqsCallCounter++; });
}
[Then]
public void QueueIsPolledMoreThanOnce()
{
Assert.Greater(_sqsCallCounter, 1);
}
}
} | apache-2.0 | C# |
2251bf3bcbdb82f706ba81624faf6a943b60324a | Use lambda spec for method | peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,smoogipoo/osu,ppy/osu | osu.Game/Overlays/Profile/Sections/Historical/UserHistoryGraph.cs | osu.Game/Overlays/Profile/Sections/Historical/UserHistoryGraph.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount) =>
new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Extensions.LocalisationExtensions;
using osu.Framework.Localisation;
using static osu.Game.Users.User;
namespace osu.Game.Overlays.Profile.Sections.Historical
{
public class UserHistoryGraph : UserGraph<DateTime, long>
{
private readonly LocalisableString tooltipCounterName;
[CanBeNull]
public UserHistoryCount[] Values
{
set => Data = value?.Select(v => new KeyValuePair<DateTime, long>(v.Date, v.Count)).ToArray();
}
public UserHistoryGraph(LocalisableString tooltipCounterName)
{
this.tooltipCounterName = tooltipCounterName;
}
protected override float GetDataPointHeight(long playCount) => playCount;
protected override UserGraphTooltipContent GetTooltipContent(DateTime date, long playCount)
{
return new UserGraphTooltipContent(
tooltipCounterName,
playCount.ToLocalisableString("N0"),
date.ToLocalisableString("MMMM yyyy"));
}
}
}
| mit | C# |
58319bf299ac0643bd38222dadc103eea7269763 | Fix typing of Clock.GlobalClock. | wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia | src/Avalonia.Animation/Clock.cs | src/Avalonia.Animation/Clock.cs | using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Text;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
public class Clock : ClockBase
{
public static IClock GlobalClock => AvaloniaLocator.Current.GetService<IGlobalClock>();
private IDisposable _parentSubscription;
public Clock()
:this(GlobalClock)
{
}
public Clock(IClock parent)
{
_parentSubscription = parent.Subscribe(Pulse);
}
protected override void Stop()
{
_parentSubscription?.Dispose();
}
}
}
| using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Text;
using Avalonia.Reactive;
namespace Avalonia.Animation
{
public class Clock : ClockBase
{
public static IClock GlobalClock => AvaloniaLocator.Current.GetService<IClock>();
private IDisposable _parentSubscription;
public Clock()
:this(GlobalClock)
{
}
public Clock(IClock parent)
{
_parentSubscription = parent.Subscribe(Pulse);
}
protected override void Stop()
{
_parentSubscription?.Dispose();
}
}
}
| mit | C# |
c1837df4f6a17c7e326b13dd7ea248159ac6f628 | Update SendResult.cs | lishewen/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,wanddy/WeiXinMPSDK,down4u/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/GroupMessage/GroupMessageJson/SendResult.cs | src/Senparc.Weixin.MP/Senparc.Weixin.MP/AdvancedAPIs/GroupMessage/GroupMessageJson/SendResult.cs | /*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:SendResult.cs
文件功能描述:群发结果
创建标识:Senparc - 20150211
修改标识:Senparc - 20150303
修改描述:整理接口
----------------------------------------------------------------*/
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.MP.AdvancedAPIs.GroupMessage
{
/// <summary>
/// 发送信息后的结果
/// </summary>
public class SendResult : WxJsonResult
{
/// <summary>
/// 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),图文消息为news
/// </summary>
public UploadMediaFileType type { get; set; }
/// <summary>
/// 消息ID
/// </summary>
public string msg_id { get; set; }
/// <summary>
/// 消息数据ID
/// </summary>
public string msg_data_id { get; set; }
}
public class GetSendResult:WxJsonResult
{
/// <summary>
/// 消息ID
/// </summary>
public string msg_id { get; set; }
/// <summary>
/// 消息发送后的状态,SEND_SUCCESS表示发送成功
/// </summary>
public string msg_status { get; set; }
}
}
| /*----------------------------------------------------------------
Copyright (C) 2017 Senparc
文件名:SendResult.cs
文件功能描述:群发结果
创建标识:Senparc - 20150211
修改标识:Senparc - 20150303
修改描述:整理接口
----------------------------------------------------------------*/
using Senparc.Weixin.Entities;
namespace Senparc.Weixin.MP.AdvancedAPIs.GroupMessage
{
/// <summary>
/// 发送信息后的结果
/// </summary>
public class SendResult : WxJsonResult
{
/// <summary>
/// 媒体文件类型,分别有图片(image)、语音(voice)、视频(video)和缩略图(thumb),图文消息为news
/// </summary>
public UploadMediaFileType type { get; set; }
/// <summary>
/// 消息ID
/// </summary>
public string msg_id { get; set; }
}
public class GetSendResult:WxJsonResult
{
/// <summary>
/// 消息ID
/// </summary>
public string msg_id { get; set; }
/// <summary>
/// 消息发送后的状态,SEND_SUCCESS表示发送成功
/// </summary>
public string msg_status { get; set; }
}
} | apache-2.0 | C# |
f621c9da5ec63f8e01eb68d0ac202ab510559279 | Fix Cryptic Password not giving an unsubmittable penalty | samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/CrypticPasswordComponentSolver.cs | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/CrypticPasswordComponentSolver.cs | using System;
using System.Collections;
using System.Collections.Generic;
public class CrypticPasswordComponentSolver : ComponentSolver
{
public CrypticPasswordComponentSolver(TwitchModule module) :
base(module)
{
component = Module.BombComponent.GetComponent(componentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "!{0} submit answer [submit an answer] | !{0} toggle [move all columns down one character]");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] split = inputCommand.ToLowerInvariant().SplitFull(" ,;");
if (split.Length == 1 && split[0] == "toggle")
{
yield return null;
for (int i = 0; i < 6; i++)
{
yield return DoInteractionClick(selectables[i + 6]);
}
}
else if (split.Length == 2 && split[0].EqualsAny("press", "hit", "enter", "push", "submit") && split[1].Length == 6)
{
yield return null;
var word = split[1].ToUpperInvariant();
var displayLetters = component.GetValue<List<char>[]>("displayLetters");
for (int i = 0; i < 6; i++)
{
if (!displayLetters[i].Contains(word[i]))
{
yield return "unsubmittablepenalty";
yield break;
}
}
var displayIndices = component.GetValue<int[]>("displayIndices");
for (int i = 0; i < 6; i++)
{
yield return SelectIndex(displayIndices[i], displayLetters[i].IndexOf(word[i]), 5, selectables[i], selectables[i + 6]);
}
yield return DoInteractionClick(selectables[12]);
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal(component.GetValue<string>("solutionWord"));
}
private static Type componentType = ReflectionHelper.FindType("CrypticPassword");
private readonly object component;
private readonly KMSelectable[] selectables;
}
| using System;
using System.Collections;
using System.Collections.Generic;
public class CrypticPasswordComponentSolver : ComponentSolver
{
public CrypticPasswordComponentSolver(TwitchModule module) :
base(module)
{
component = Module.BombComponent.GetComponent(componentType);
selectables = Module.BombComponent.GetComponent<KMSelectable>().Children;
ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "!{0} submit answer [submit an answer] | !{0} toggle [move all columns down one character]");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] split = inputCommand.ToLowerInvariant().SplitFull(" ,;");
if (split.Length == 1 && split[0] == "toggle")
{
yield return null;
for (int i = 0; i < 6; i++)
{
yield return DoInteractionClick(selectables[i + 6]);
}
}
else if (split.Length == 2 && split[0].EqualsAny("press", "hit", "enter", "push", "submit") && split[1].Length == 6)
{
var word = split[1].ToUpperInvariant();
var displayLetters = component.GetValue<List<char>[]>("displayLetters");
for (int i = 0; i < 6; i++)
{
if (!displayLetters[i].Contains(word[i]))
{
yield return "unsubmittablepenalty";
yield break;
}
}
yield return null;
var displayIndices = component.GetValue<int[]>("displayIndices");
for (int i = 0; i < 6; i++)
{
yield return SelectIndex(displayIndices[i], displayLetters[i].IndexOf(word[i]), 5, selectables[i], selectables[i + 6]);
}
yield return DoInteractionClick(selectables[12]);
}
}
protected override IEnumerator ForcedSolveIEnumerator()
{
yield return null;
yield return RespondToCommandInternal(component.GetValue<string>("solutionWord"));
}
private static Type componentType = ReflectionHelper.FindType("CrypticPassword");
private readonly object component;
private readonly KMSelectable[] selectables;
}
| mit | C# |
d905e2d2aeaf900049da17e2fd22b2262732f099 | Correct Add-AzurePHPWorkerRole cmdlet class name | johnkors/azure-sdk-tools,markcowl/azure-sdk-tools,antonba/azure-sdk-tools,DinoV/azure-sdk-tools,johnkors/azure-sdk-tools,antonba/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,johnkors/azure-sdk-tools,Madhukarc/azure-sdk-tools,DinoV/azure-sdk-tools,markcowl/azure-sdk-tools,johnkors/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,antonba/azure-sdk-tools,antonba/azure-sdk-tools,akromm/azure-sdk-tools,akromm/azure-sdk-tools,Madhukarc/azure-sdk-tools,akromm/azure-sdk-tools,markcowl/azure-sdk-tools,markcowl/azure-sdk-tools,antonba/azure-sdk-tools,akromm/azure-sdk-tools,johnkors/azure-sdk-tools,DinoV/azure-sdk-tools,DinoV/azure-sdk-tools,Madhukarc/azure-sdk-tools,Madhukarc/azure-sdk-tools | WindowsAzurePowershell/src/Management.CloudService/PHP/Cmdlet/AddAzurePHPWorkerRole.cs | WindowsAzurePowershell/src/Management.CloudService/PHP/Cmdlet/AddAzurePHPWorkerRole.cs | // ----------------------------------------------------------------------------------
//
// Copyright 2011 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.CloudService.PHP.Cmdlet
{
using System;
using System.Management.Automation;
using Model;
using Properties;
/// <summary>
/// Create scaffolding for a new PHP worker role, change cscfg file and csdef to include the added worker role
/// </summary>
[Cmdlet(VerbsCommon.Add, "AzurePHPWorkerRole")]
public class AddAzurePHPWorkerRoleCommand : AddRole
{
internal string AddAzureNodeWorkerRoleProcess(string workerRoleName, int instances, string rootPath)
{
string result;
AzureService service = new AzureService(rootPath, null);
RoleInfo workerRole = service.AddWorkerRole(Resources.PHPScaffolding, workerRoleName, instances);
try
{
service.ChangeRolePermissions(workerRole);
}
catch (UnauthorizedAccessException)
{
SafeWriteObject(Resources.AddRoleMessageInsufficientPermissions);
SafeWriteObject(Environment.NewLine);
}
result = string.Format(Resources.AddRoleMessageCreate, rootPath, workerRole.Name);
return result;
}
protected override void ProcessRecord()
{
try
{
SkipChannelInit = true;
base.ProcessRecord();
string result = AddAzureNodeWorkerRoleProcess(Name, Instances, base.GetServiceRootPath());
SafeWriteObject(result);
}
catch (Exception ex)
{
SafeWriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
}
}
}
} | // ----------------------------------------------------------------------------------
//
// Copyright 2011 Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Management.CloudService.PHP.Cmdlet
{
using System;
using System.Management.Automation;
using Model;
using Properties;
/// <summary>
/// Create scaffolding for a new PHP worker role, change cscfg file and csdef to include the added worker role
/// </summary>
[Cmdlet(VerbsCommon.Add, "AzurePHPWorkerRole")]
public class AddAzureNodeWorkerRoleCommand : AddRole
{
internal string AddAzureNodeWorkerRoleProcess(string workerRoleName, int instances, string rootPath)
{
string result;
AzureService service = new AzureService(rootPath, null);
RoleInfo workerRole = service.AddWorkerRole(Resources.PHPScaffolding, workerRoleName, instances);
try
{
service.ChangeRolePermissions(workerRole);
}
catch (UnauthorizedAccessException)
{
SafeWriteObject(Resources.AddRoleMessageInsufficientPermissions);
SafeWriteObject(Environment.NewLine);
}
result = string.Format(Resources.AddRoleMessageCreate, rootPath, workerRole.Name);
return result;
}
protected override void ProcessRecord()
{
try
{
SkipChannelInit = true;
base.ProcessRecord();
string result = AddAzureNodeWorkerRoleProcess(Name, Instances, base.GetServiceRootPath());
SafeWriteObject(result);
}
catch (Exception ex)
{
SafeWriteError(new ErrorRecord(ex, string.Empty, ErrorCategory.CloseError, null));
}
}
}
} | apache-2.0 | C# |
f949bd443947b588772af700f8c4660ff174f51e | Remove dot net core dependency | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/GetApprenticeshipRequest.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2.Api.Types/Requests/GetApprenticeshipRequest.cs |
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
public long? AccountId { get; set; }
public long? ProviderId { get; set; }
public int PageNumber { get; set; }
public int PageItemCount { get; set; }
public string SortField { get; set; }
public bool ReverseSort { get; set; }
}
} | using Microsoft.AspNetCore.Mvc;
namespace SFA.DAS.CommitmentsV2.Api.Types.Requests
{
public class GetApprenticeshipRequest
{
[FromQuery]
public long? AccountId { get; set; }
[FromQuery]
public long? ProviderId { get; set; }
[FromQuery]
public int PageNumber { get; set; }
[FromQuery]
public int PageItemCount { get; set; }
[FromQuery]
public string SortField { get; set; }
[FromQuery]
public bool ReverseSort { get; set; }
}
} | mit | C# |
5fb41ba8b610a22830cb972407d14ad477966654 | Add a 'close enough' parameter and tweak for NecrophageBehavior | futurechris/zombai | Assets/Scripts/Behaviors/NecrophageBehavior.cs | Assets/Scripts/Behaviors/NecrophageBehavior.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NecrophageBehavior : AgentBehavior
{
// this value * arbiter's convert distance = radius inside which
// the necrophage won't continue to move towards the corpse
private static float necrophageRadiusMultiplier = 0.5f;
// "pursue" nearest corpse
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
Action newMoveAction;
Action newLookAction;
Agent tempAgent;
bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent);
if(found && !myself.getMoveInUse() && !myself.getLookInUse())
{
float distance = Vector2.Distance(myself.getLocation(),tempAgent.getLocation());
if(distance < ActionArbiter.Instance.getConvertDistance()*necrophageRadiusMultiplier)
{
newMoveAction = new Action(Action.ActionType.STAY);
}
else
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.setTargetPoint(tempAgent.getLocation());
}
newLookAction = new Action(Action.ActionType.TURN_TOWARDS);
newLookAction.setTargetPoint(tempAgent.getLocation());
currentPlans.Clear();
this.currentPlans.Add(newMoveAction);
this.currentPlans.Add(newLookAction);
return true;
}
return false;
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NecrophageBehavior : AgentBehavior
{
// "pursue" nearest corpse
public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits)
{
Action newMoveAction;
Action newLookAction;
Agent tempAgent;
bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent);
if(found && !myself.getMoveInUse() && !myself.getLookInUse())
{
newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS);
newMoveAction.setTargetPoint(tempAgent.getLocation());
newLookAction = new Action(Action.ActionType.TURN_TOWARDS);
newLookAction.setTargetPoint(tempAgent.getLocation());
currentPlans.Clear();
this.currentPlans.Add(newMoveAction);
this.currentPlans.Add(newLookAction);
return true;
}
return false;
}
}
| mit | C# |
bcb78f4835af606627a8b33c83d560eccd396867 | Handle play/pause | bartlomiejwolk/AnimationPathAnimator | AudioSourceController/AudioSourceController.cs | AudioSourceController/AudioSourceController.cs | using UnityEngine;
using System.Collections;
namespace ATP.AnimationPathTools.AudioSourceControllerComponent {
/// <summary>
/// Allows controlling <c>AudioSource</c> component from inspector
/// and with keyboard shortcuts.
/// </summary>
// todo add menu option to create component
public sealed class AudioSourceController : MonoBehaviour {
[SerializeField]
private AudioSource audioSource;
public AudioSource AudioSource {
get { return audioSource; }
}
private void Start() {
}
private void Update() {
// Play/Pause.
if (Input.GetKeyDown(KeyCode.Space)) {
// Pause
if (AudioSource.isPlaying) {
AudioSource.Pause();
}
// Play
else {
AudioSource.Play();
}
}
}
}
}
| using UnityEngine;
using System.Collections;
namespace ATP.AnimationPathTools.AudioSourceControllerComponent {
/// <summary>
/// Allows controlling <c>AudioSource</c> component from inspector
/// and with keyboard shortcuts.
/// </summary>
// todo add menu option to create component
public sealed class AudioSourceController : MonoBehaviour {
[SerializeField]
private AudioSource audioSource;
private void Start() {
}
private void Update() {
}
}
}
| mit | C# |
9f4a0257be105d24629782905c49749f5870f863 | Reduce array allocations during frame parsing | jennings/Turbocharged.NSQ | src/Turbocharged.NSQ/Message.cs | src/Turbocharged.NSQ/Message.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Turbocharged.NSQ
{
/// <summary>
/// A message delivered from NSQ.
/// </summary>
public class Message
{
public string Id { get; private set; }
public short Attempts { get; private set; }
public long Timestamp { get; private set; }
public MessageBody Body { get; private set; }
readonly NsqTcpConnection _connection;
const int TIMESTAMP_START = 0;
const int TIMESTAMP_COUNT = 8;
const int ATTEMPTS_START = 8;
const int ATTEMPTS_COUNT = 2;
const int ID_START = 10;
const int ID_COUNT = 16;
const int DATA_START = TIMESTAMP_COUNT + ATTEMPTS_COUNT + ID_COUNT;
internal Message(Frame frame, NsqTcpConnection connection)
{
_connection = connection;
if (frame.Type != FrameType.Message)
throw new ArgumentException("Frame must have FrameType 'Message'", "frame");
if (BitConverter.IsLittleEndian)
{
Array.Reverse(frame.Data, TIMESTAMP_START, TIMESTAMP_COUNT);
Array.Reverse(frame.Data, ATTEMPTS_START, ATTEMPTS_COUNT);
}
Timestamp = BitConverter.ToInt64(frame.Data, TIMESTAMP_START);
Attempts = BitConverter.ToInt16(frame.Data, ATTEMPTS_START);
Id = Encoding.ASCII.GetString(frame.Data, ID_START, ID_COUNT);
// Data
var dataLength = frame.Data.Length - DATA_START;
Body = new byte[dataLength];
Array.ConstrainedCopy(frame.Data, DATA_START, Body, 0, dataLength);
}
public Task FinishAsync()
{
return _connection.SendCommandAsync(new Finish(this));
}
public Task RequeueAsync()
{
throw new NotImplementedException();
}
public Task TouchAsync()
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Turbocharged.NSQ
{
/// <summary>
/// A message delivered from NSQ.
/// </summary>
public class Message
{
public string Id { get; private set; }
public short Attempts { get; private set; }
public long Timestamp { get; private set; }
public MessageBody Body { get; private set; }
readonly NsqTcpConnection _connection;
internal Message(Frame frame, NsqTcpConnection connection)
{
_connection = connection;
if (frame.Type != FrameType.Message)
throw new ArgumentException("Frame must have FrameType 'Message'", "frame");
byte[] timestampBuffer = new byte[8];
byte[] attemptsBuffer = new byte[2];
byte[] idBuffer = new byte[16];
Array.ConstrainedCopy(frame.Data, 0, timestampBuffer, 0, 8);
Array.ConstrainedCopy(frame.Data, 8, attemptsBuffer, 0, 2);
Array.ConstrainedCopy(frame.Data, 10, idBuffer, 0, 16);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(timestampBuffer);
Array.Reverse(attemptsBuffer);
}
Timestamp = BitConverter.ToInt64(timestampBuffer, 0);
Attempts = BitConverter.ToInt16(attemptsBuffer, 0);
Id = Encoding.ASCII.GetString(idBuffer);
// Data
const int DATA_OFFSET = 8 + 2 + 16;
var dataLength = frame.Data.Length - DATA_OFFSET;
Body = new byte[dataLength];
Array.ConstrainedCopy(frame.Data, DATA_OFFSET, Body, 0, dataLength);
}
public Task FinishAsync()
{
return _connection.SendCommandAsync(new Finish(this));
}
public Task RequeueAsync()
{
throw new NotImplementedException();
}
public Task TouchAsync()
{
throw new NotImplementedException();
}
}
}
| mit | C# |
c57dd4ca1510471000f17a3dac08d19e63125790 | Update the unit control (power on\off, temp, fan speed, etc) | eric-winkler/MyAir3Api | MyAir3Api/UnitControl.cs | MyAir3Api/UnitControl.cs | using System.Threading.Tasks;
using System.Xml.Linq;
namespace Winkler.MyAir3Api
{
public class UnitControl
{
private readonly IAirconWebClient _aircon;
public bool Power { get; private set; }
public FanSpeed FanSpeed { get; set; }
public InverterMode InverterMode { get; set; }
public bool TempsSetting { get; private set; }
public decimal CentralActualTemp { get; private set; }
public decimal CentralDesiredTemp { get; set; }
public string ErrorCode { get; private set; }
public string ActivationCodeStatus { get; private set; }
public int NumberOfZones { get; private set; }
public decimal MaxUserTemp { get; private set; }
public decimal MinUserTemp { get; private set; }
public int NumberOfSchedules { get; private set; }
public UnitControl(IAirconWebClient aircon, XElement data)
{
_aircon = aircon;
Power = int.Parse(data.Element("airconOnOff").Value) == 1;
FanSpeed = (FanSpeed) int.Parse(data.Element("fanSpeed").Value);
InverterMode = (InverterMode) int.Parse(data.Element("mode").Value);
TempsSetting = int.Parse(data.Element("unitControlTempsSetting").Value) == 1;
CentralActualTemp = decimal.Parse(data.Element("centralActualTemp").Value);
CentralDesiredTemp = decimal.Parse(data.Element("centralDesiredTemp").Value);
ErrorCode = data.Element("airConErrorCode").Value;
ActivationCodeStatus = data.Element("activationCodeStatus").Value;
NumberOfZones = int.Parse(data.Element("numberOfZones").Value);
MaxUserTemp = decimal.Parse(data.Element("maxUserTemp").Value);
MinUserTemp = decimal.Parse(data.Element("minUserTemp").Value);
NumberOfSchedules = int.Parse(data.Element("availableSchedules").Value);
}
public async Task<AirconWebResponse> UpdateAsync()
{
return await _aircon.GetAsync("setSystemData?"
+ "airconOnOff=" + (Power ? "1" : "0")
+ "&fanSpeed=" + (int) FanSpeed
+ "&mode=" + (int) InverterMode
+ "¢ralDesiredTemp=" + CentralDesiredTemp);
}
}
} | using System.Xml.Linq;
namespace Winkler.MyAir3Api
{
public class UnitControl
{
private readonly IAirconWebClient _aircon;
public bool Power { get; private set; }
public FanSpeed FanSpeed { get; private set; }
public InverterMode InverterMode { get; private set; }
public bool TempsSetting { get; private set; }
public decimal CentralActualTemp { get; private set; }
public decimal CentralDesiredTemp { get; private set; }
public string ErrorCode { get; private set; }
public string ActivationCodeStatus { get; private set; }
public int NumberOfZones { get; private set; }
public decimal MaxUserTemp { get; private set; }
public decimal MinUserTemp { get; private set; }
public int NumberOfSchedules { get; private set; }
public UnitControl(IAirconWebClient aircon, XElement data)
{
_aircon = aircon;
Power = int.Parse(data.Element("airconOnOff").Value) == 1;
FanSpeed = (FanSpeed) int.Parse(data.Element("fanSpeed").Value);
InverterMode = (InverterMode) int.Parse(data.Element("mode").Value);
TempsSetting = int.Parse(data.Element("unitControlTempsSetting").Value) == 1;
CentralActualTemp = decimal.Parse(data.Element("centralActualTemp").Value);
CentralDesiredTemp = decimal.Parse(data.Element("centralDesiredTemp").Value);
ErrorCode = data.Element("airConErrorCode").Value;
ActivationCodeStatus = data.Element("activationCodeStatus").Value;
NumberOfZones = int.Parse(data.Element("numberOfZones").Value);
MaxUserTemp = decimal.Parse(data.Element("maxUserTemp").Value);
MinUserTemp = decimal.Parse(data.Element("minUserTemp").Value);
NumberOfSchedules = int.Parse(data.Element("availableSchedules").Value);
}
}
} | apache-2.0 | C# |
fe9f0d8de55dfdded1d6640ccace919cfbbd0605 | Move REcttransform scaler into mrtk namespace | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/Utilities/RectTransformCubeScaler.cs | Assets/MixedRealityToolkit.SDK/Features/UX/Scripts/Utilities/RectTransformCubeScaler.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Utilities
{
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
/// <summary>
/// RectTransforms do not scale 3d objects (such as unit cubes) to fit within their bounds.
/// This helper class will apply a scale to fit a unit cube into the bounds specified by the RectTransform.
/// The Z component is scaled to the min of the X and Y components.
/// </summary>
[ExecuteInEditMode]
[RequireComponent(typeof(RectTransform))]
public class RectTransformCubeScaler : MonoBehaviour
{
private RectTransform rectTransform;
private Vector2 prevRectSize = default;
private void Start()
{
rectTransform = GetComponent<RectTransform>();
}
private void Update()
{
var size = rectTransform.rect.size;
if (prevRectSize != size)
{
prevRectSize = size;
this.transform.localScale = new Vector3(size.x, size.y, Mathf.Min(size.x, size.y));
}
}
}
| mit | C# |
2d3debdee48349b482e5130bbc16b851afa21422 | Remove empty test setup method from VsoAgentBuildNumberTests | asbjornu/GitVersion,asbjornu/GitVersion,ParticularLabs/GitVersion,GitTools/GitVersion,dazinator/GitVersion,JakeGinnivan/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,ermshiperete/GitVersion,JakeGinnivan/GitVersion,gep13/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,ParticularLabs/GitVersion,JakeGinnivan/GitVersion,JakeGinnivan/GitVersion | src/GitVersionCore.Tests/BuildServers/VsoAgentBuildNumberTests.cs | src/GitVersionCore.Tests/BuildServers/VsoAgentBuildNumberTests.cs | using System;
using GitVersion;
using GitVersionCore.Tests;
using NUnit.Framework;
using Shouldly;
[TestFixture]
public class VsoAgentBuildNumberTests
{
string key = "BUILD_BUILDNUMBER";
string logPrefix = "##vso[build.updatebuildnumber]";
VsoAgent versionBuilder = new VsoAgent();
[TearDown]
public void TearDownVsoAgentBuildNumberTest()
{
Environment.SetEnvironmentVariable(key, null, EnvironmentVariableTarget.Process);
}
[TestCase("$(GitVersion.FullSemVer)", "1.0.0", "1.0.0")]
[TestCase("$(GITVERSION_FULLSEMVER)", "1.0.0", "1.0.0")]
[TestCase("$(GitVersion.FullSemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
[TestCase("$(GITVERSION_FULLSEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
public void VsoAgentBuildNumberWithFullSemVer(string buildNumberFormat, string myFullSemVer, string expectedBuildNumber)
{
Environment.SetEnvironmentVariable(key, buildNumberFormat, EnvironmentVariableTarget.Process);
var vars = new TestableVersionVariables(fullSemVer: myFullSemVer);
var logMessage = versionBuilder.GenerateSetVersionMessage(vars);
logMessage.ShouldBe(logPrefix + expectedBuildNumber);
}
[TestCase("$(GitVersion.SemVer)", "1.0.0", "1.0.0")]
[TestCase("$(GITVERSION_SEMVER)", "1.0.0", "1.0.0")]
[TestCase("$(GitVersion.SemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
[TestCase("$(GITVERSION_SEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
public void VsoAgentBuildNumberWithSemVer(string buildNumberFormat, string mySemVer, string expectedBuildNumber)
{
Environment.SetEnvironmentVariable(key, buildNumberFormat, EnvironmentVariableTarget.Process);
var vars = new TestableVersionVariables(semVer: mySemVer);
var logMessage = versionBuilder.GenerateSetVersionMessage(vars);
logMessage.ShouldBe(logPrefix + expectedBuildNumber);
}
} | using System;
using GitVersion;
using GitVersionCore.Tests;
using NUnit.Framework;
using Shouldly;
[TestFixture]
public class VsoAgentBuildNumberTests
{
string key = "BUILD_BUILDNUMBER";
string logPrefix = "##vso[build.updatebuildnumber]";
VsoAgent versionBuilder = new VsoAgent();
[SetUp]
public void SetUpVsoAgentBuildNumberTest()
{
}
[TearDown]
public void TearDownVsoAgentBuildNumberTest()
{
Environment.SetEnvironmentVariable(key, null, EnvironmentVariableTarget.Process);
}
[TestCase("$(GitVersion.FullSemVer)", "1.0.0", "1.0.0")]
[TestCase("$(GITVERSION_FULLSEMVER)", "1.0.0", "1.0.0")]
[TestCase("$(GitVersion.FullSemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
[TestCase("$(GITVERSION_FULLSEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
public void VsoAgentBuildNumberWithFullSemVer(string buildNumberFormat, string myFullSemVer, string expectedBuildNumber)
{
Environment.SetEnvironmentVariable(key, buildNumberFormat, EnvironmentVariableTarget.Process);
var vars = new TestableVersionVariables(fullSemVer: myFullSemVer);
var logMessage = versionBuilder.GenerateSetVersionMessage(vars);
logMessage.ShouldBe(logPrefix + expectedBuildNumber);
}
[TestCase("$(GitVersion.SemVer)", "1.0.0", "1.0.0")]
[TestCase("$(GITVERSION_SEMVER)", "1.0.0", "1.0.0")]
[TestCase("$(GitVersion.SemVer)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
[TestCase("$(GITVERSION_SEMVER)-Build.1234", "1.0.0", "1.0.0-Build.1234")]
public void VsoAgentBuildNumberWithSemVer(string buildNumberFormat, string mySemVer, string expectedBuildNumber)
{
Environment.SetEnvironmentVariable(key, buildNumberFormat, EnvironmentVariableTarget.Process);
var vars = new TestableVersionVariables(semVer: mySemVer);
var logMessage = versionBuilder.GenerateSetVersionMessage(vars);
logMessage.ShouldBe(logPrefix + expectedBuildNumber);
}
} | mit | C# |
55c84cc58bd014f3fbd72183c45d6403ff76ace0 | Move js files to project root | nosami/XSTerm,nosami/XSTerm,nosami/XSTerm | XSTerm/XSTerm.cs | XSTerm/XSTerm.cs | using System;
using MonoDevelop.Components;
using MonoDevelop.Components.Mac;
using WebKit;
using AppKit;
using CoreGraphics;
using Foundation;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Diagnostics;
using MonoDevelop.Core;
using Mono.Addins;
namespace XSTerm
{
public class XSTerm : MonoDevelop.Ide.Gui.PadContent
{
readonly Terminal terminal;
public XSTerm()
{
terminal = new Terminal();
}
public override Control Control => terminal;
}
class Terminal : Control
{
readonly WebView webView;
protected override object CreateNativeWidget<T>()
{
return webView;
}
public Terminal()
{
webView = new WebView();
webView.SetValueForKey(NSObject.FromObject(false), new NSString("drawsBackground"));
var rootPath = AddinManager.CurrentAddin.GetFilePath("..", "..");
var pathToNode = Path.Combine(rootPath, "node");
var pathToApp = Path.Combine(rootPath, "xterm.js", "demo", "app.js");
var port = FreeTcpPort();
var psi = new ProcessStartInfo
{
UseShellExecute = false,
CreateNoWindow = true,
FileName = pathToNode,
RedirectStandardOutput = true,
Arguments = $"{pathToApp} {port}"
};
var process = Process.Start(psi);
process.BeginOutputReadLine();
process.EnableRaisingEvents = true;
process.OutputDataReceived += (s, e) => {
LoggingService.LogInfo(e.Data);
if (e.Data.StartsWith("App listening")) Runtime.RunInMainThread(() => webView.MainFrameUrl = $"http://0.0.0.0:{port}");
};
}
static int FreeTcpPort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
}
}
| using System;
using MonoDevelop.Components;
using MonoDevelop.Components.Mac;
using WebKit;
using AppKit;
using CoreGraphics;
using Foundation;
using System.Net.Sockets;
using System.Net;
using System.IO;
using System.Diagnostics;
using MonoDevelop.Core;
using Mono.Addins;
namespace XSTerm
{
public class XSTerm : MonoDevelop.Ide.Gui.PadContent
{
readonly Terminal terminal;
public XSTerm()
{
terminal = new Terminal();
}
public override Control Control => terminal;
}
class Terminal : Control
{
readonly WebView webView;
protected override object CreateNativeWidget<T>()
{
return webView;
}
public Terminal()
{
webView = new WebView();
webView.SetValueForKey(NSObject.FromObject(false), new NSString("drawsBackground"));
var rootPath = AddinManager.CurrentAddin.GetFilePath("..", "..", "..");
var pathToNode = Path.Combine(rootPath, "node");
var pathToApp = Path.Combine(rootPath, "xterm.js", "demo", "app.js");
var port = FreeTcpPort();
var psi = new ProcessStartInfo
{
UseShellExecute = false,
CreateNoWindow = true,
FileName = pathToNode,
RedirectStandardOutput = true,
Arguments = $"{pathToApp} {port}"
};
var process = Process.Start(psi);
process.BeginOutputReadLine();
process.EnableRaisingEvents = true;
process.OutputDataReceived += (s, e) => {
LoggingService.LogInfo(e.Data);
if (e.Data.StartsWith("App listening")) Runtime.RunInMainThread(() => webView.MainFrameUrl = $"http://0.0.0.0:{port}");
};
}
static int FreeTcpPort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
}
}
| mit | C# |
941c29c2be579c3d2177130736b21ba470e9e31e | Mark test windows only | svick/cli,ravimeda/cli,dasMulli/cli,livarcocc/cli-1,svick/cli,harshjain2/cli,harshjain2/cli,harshjain2/cli,johnbeisner/cli,ravimeda/cli,svick/cli,Faizan2304/cli,livarcocc/cli-1,dasMulli/cli,dasMulli/cli,johnbeisner/cli,livarcocc/cli-1,Faizan2304/cli,Faizan2304/cli,ravimeda/cli,johnbeisner/cli | test/dotnet.Tests/TelemetryCommandTest.cs | test/dotnet.Tests/TelemetryCommandTest.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using FluentAssertions;
namespace Microsoft.DotNet.Tests
{
public class MockTelemetry : ITelemetry
{
public bool Enabled { get; set; }
public string EventName { get; set; }
public IDictionary<string, string> Properties { get; set; }
public void TrackEvent(string eventName, IDictionary<string, string> properties, IDictionary<string, double> measurements)
{
EventName = eventName;
Properties = properties;
}
}
public class TelemetryCommandTests : TestBase
{
[Fact]
public void TestProjectDependencyIsNotAvailableThroughDriver()
{
MockTelemetry mockTelemetry = new MockTelemetry();
string[] args = { "help" };
Microsoft.DotNet.Cli.Program.ProcessArgs(args, mockTelemetry);
Assert.Equal(mockTelemetry.EventName, args[0]);
}
[WindowsOnlyFact]
public void InternalreportinstallsuccessCommandCollectExeNameWithEventname()
{
MockTelemetry mockTelemetry = new MockTelemetry();
string[] args = { "c:\\mypath\\dotnet-sdk-latest-win-x64.exe" };
InternalReportinstallsuccess.ProcessInputAndSendTelemetry(args, mockTelemetry);
mockTelemetry.EventName.Should().Be("reportinstallsuccess");
mockTelemetry.Properties["exeName"].Should().Be("dotnet-sdk-latest-win-x64.exe");
}
[Fact]
public void InternalreportinstallsuccessCommandIsRegistedInBuiltIn()
{
BuiltInCommandsCatalog.Commands.Should().ContainKey("internal-reportinstallsuccess");
}
}
}
| // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Collections.Generic;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Tools.Test.Utilities;
using Xunit;
using FluentAssertions;
namespace Microsoft.DotNet.Tests
{
public class MockTelemetry : ITelemetry
{
public bool Enabled { get; set; }
public string EventName { get; set; }
public IDictionary<string, string> Properties { get; set; }
public void TrackEvent(string eventName, IDictionary<string, string> properties, IDictionary<string, double> measurements)
{
EventName = eventName;
Properties = properties;
}
}
public class TelemetryCommandTests : TestBase
{
[Fact]
public void TestProjectDependencyIsNotAvailableThroughDriver()
{
MockTelemetry mockTelemetry = new MockTelemetry();
string[] args = { "help" };
Microsoft.DotNet.Cli.Program.ProcessArgs(args, mockTelemetry);
Assert.Equal(mockTelemetry.EventName, args[0]);
}
[Fact]
public void InternalreportinstallsuccessCommandCollectExeNameWithEventname()
{
MockTelemetry mockTelemetry = new MockTelemetry();
string[] args = { "c:\\mypath\\dotnet-sdk-latest-win-x64.exe" };
InternalReportinstallsuccess.ProcessInputAndSendTelemetry(args, mockTelemetry);
mockTelemetry.EventName.Should().Be("reportinstallsuccess");
mockTelemetry.Properties["exeName"].Should().Be("dotnet-sdk-latest-win-x64.exe");
}
[Fact]
public void InternalreportinstallsuccessCommandIsRegistedInBuiltIn()
{
BuiltInCommandsCatalog.Commands.Should().ContainKey("internal-reportinstallsuccess");
}
}
}
| mit | C# |
fafc80818cf5ec090e67d23210cf71ee9d5fc5e2 | Fix typo | ZLima12/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,peppy/osu-new,2yangk23/osu,smoogipooo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,DrabWeb/osu,ppy/osu,UselessToucan/osu,EVAST9919/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,DrabWeb/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu | osu.Game/Screens/Play/GameplayClock.cs | osu.Game/Screens/Play/GameplayClock.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Timing;
namespace osu.Game.Screens.Play
{
/// <summary>
/// A clock which is used for gameplay elements that need to follow audio time 1:1.
/// Exposed via DI by <see cref="PauseContainer"/>.
/// <remarks>
/// The main purpose of this clock is to stop components using it from accidentally processing the main
/// <see cref="IFrameBasedClock"/>, as this should only be done once to ensure accuracy.
/// </remarks>
/// </summary>
public class GameplayClock : IFrameBasedClock
{
private readonly IFrameBasedClock underlyingClock;
public GameplayClock(IFrameBasedClock underlyingClock)
{
this.underlyingClock = underlyingClock;
}
public double CurrentTime => underlyingClock.CurrentTime;
public double Rate => underlyingClock.Rate;
public bool IsRunning => underlyingClock.IsRunning;
public void ProcessFrame()
{
// we do not want to process the underlying clock.
// this is handled by PauseContainer.
}
public double ElapsedFrameTime => underlyingClock.ElapsedFrameTime;
public double FramesPerSecond => underlyingClock.FramesPerSecond;
public FrameTimeInfo TimeInfo => underlyingClock.TimeInfo;
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Timing;
namespace osu.Game.Screens.Play
{
/// <summary>
/// A clock which is used for gameplay elements that need to follow audio time 1:1.
/// Exposed via DI by <see cref="PauseContainer"/>.
/// <remarks>
/// THe main purpose of this clock is to stop components using it from accidentally processing the main
/// <see cref="IFrameBasedClock"/>, as this should only be done once to ensure accuracy.
/// </remarks>
/// </summary>
public class GameplayClock : IFrameBasedClock
{
private readonly IFrameBasedClock underlyingClock;
public GameplayClock(IFrameBasedClock underlyingClock)
{
this.underlyingClock = underlyingClock;
}
public double CurrentTime => underlyingClock.CurrentTime;
public double Rate => underlyingClock.Rate;
public bool IsRunning => underlyingClock.IsRunning;
public void ProcessFrame()
{
// we do not want to process the underlying clock.
// this is handled by PauseContainer.
}
public double ElapsedFrameTime => underlyingClock.ElapsedFrameTime;
public double FramesPerSecond => underlyingClock.FramesPerSecond;
public FrameTimeInfo TimeInfo => underlyingClock.TimeInfo;
}
} | mit | C# |
99803c323d1251e9a597920f136d713423cc1f5c | Update CompositeHttpControllerTypeResolver.cs | Bocami/webapi | src/Bocami.Practices.WebApi/CompositeHttpControllerTypeResolver.cs | src/Bocami.Practices.WebApi/CompositeHttpControllerTypeResolver.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dispatcher;
namespace Bocami.Practices.WebApi
{
public class CompositeHttpControllerTypeResolver : IHttpControllerTypeResolver
{
private readonly IHttpControllerTypeResolver[] httpControllerTypeResolvers;
public CompositeHttpControllerTypeResolver(params IHttpControllerTypeResolver[] httpControllerTypeResolvers)
{
if (httpControllerTypeResolvers == null)
throw new ArgumentNullException("httpControllerTypeResolvers");
this.httpControllerTypeResolvers = httpControllerTypeResolvers;
}
public ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
{
return this.httpControllerTypeResolvers
.SelectMany(a => a.GetControllerTypes(assembliesResolver))
.Distinct()
.ToList();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http.Dispatcher;
namespace Bocami.Practices.WebApi
{
public class CompositeHttpControllerTypeResolver : IHttpControllerTypeResolver
{
private readonly IHttpControllerTypeResolver[] httpControllerTypeResolvers;
public CompositeHttpControllerTypeResolver(params IHttpControllerTypeResolver[] httpControllerTypeResolvers)
{
this.httpControllerTypeResolvers = httpControllerTypeResolvers;
}
public ICollection<Type> GetControllerTypes(IAssembliesResolver assembliesResolver)
{
return this.httpControllerTypeResolvers
.SelectMany(a => a.GetControllerTypes(assembliesResolver))
.Distinct()
.ToList();
}
}
} | mit | C# |
cbec83c55978d18a00b1a62b51ffbe144a1ff02f | Remove unused using statements from AddMonsterCardCommandHandler | fablecode/ygo-api | src/Application/ygo.application/Commands/AddMonsterCard/AddMonsterCardCommandHandler.cs | src/Application/ygo.application/Commands/AddMonsterCard/AddMonsterCardCommandHandler.cs | using FluentValidation;
using MediatR;
using System.Linq;
using System.Threading.Tasks;
using ygo.application.Repository;
namespace ygo.application.Commands.AddMonsterCard
{
public class AddMonsterCardCommandHandler : IAsyncRequestHandler<AddMonsterCardCommand, CommandResult>
{
private readonly ICardRepository _repository;
private readonly IValidator<AddMonsterCardCommand> _validator;
public AddMonsterCardCommandHandler(ICardRepository repository, IValidator<AddMonsterCardCommand> validator)
{
_repository = repository;
_validator = validator;
}
public async Task<CommandResult> Handle(AddMonsterCardCommand message)
{
var commandResult = new CommandResult();
var validateResults = _validator.Validate(message);
if (validateResults.IsValid)
{
var newMonsterCard = message.MapToCard();
var newMonsterCardResult = await _repository.Add(newMonsterCard);
commandResult.Data = newMonsterCardResult.Id;
commandResult.IsSuccessful = true;
}
else
commandResult.Errors = validateResults.Errors.Select(err => err.ErrorMessage).ToList();
return commandResult;
}
}
} | using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using FluentValidation;
using MediatR;
using ygo.application.Ioc;
using ygo.application.Repository;
namespace ygo.application.Commands.AddMonsterCard
{
public class AddMonsterCardCommandHandler : IAsyncRequestHandler<AddMonsterCardCommand, CommandResult>
{
private readonly ICardRepository _repository;
private readonly IValidator<AddMonsterCardCommand> _validator;
public AddMonsterCardCommandHandler(ICardRepository repository, IValidator<AddMonsterCardCommand> validator)
{
_repository = repository;
_validator = validator;
}
public async Task<CommandResult> Handle(AddMonsterCardCommand message)
{
var commandResult = new CommandResult();
var validateResults = _validator.Validate(message);
if (validateResults.IsValid)
{
var newMonsterCard = message.MapToCard();
var newMonsterCardResult = await _repository.Add(newMonsterCard);
commandResult.Data = newMonsterCardResult.Id;
commandResult.IsSuccessful = true;
}
else
commandResult.Errors = validateResults.Errors.Select(err => err.ErrorMessage).ToList();
return commandResult;
}
}
} | mit | C# |
07151935a14a305a898533bff8231765b0db77e2 | Use 'var' | mattwar/roslyn,gafter/roslyn,michalhosala/roslyn,AlekseyTs/roslyn,budcribar/roslyn,natidea/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,natgla/roslyn,pdelvo/roslyn,TyOverby/roslyn,natidea/roslyn,thomaslevesque/roslyn,mattscheffer/roslyn,swaroop-sridhar/roslyn,jeffanders/roslyn,managed-commons/roslyn,shyamnamboodiripad/roslyn,michalhosala/roslyn,HellBrick/roslyn,ErikSchierboom/roslyn,DustinCampbell/roslyn,orthoxerox/roslyn,SeriaWei/roslyn,KirillOsenkov/roslyn,a-ctor/roslyn,khyperia/roslyn,Giftednewt/roslyn,vslsnap/roslyn,orthoxerox/roslyn,abock/roslyn,natidea/roslyn,jamesqo/roslyn,managed-commons/roslyn,mattscheffer/roslyn,vcsjones/roslyn,dotnet/roslyn,mseamari/Stuff,amcasey/roslyn,KirillOsenkov/roslyn,rgani/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,Hosch250/roslyn,physhi/roslyn,VSadov/roslyn,akrisiun/roslyn,jaredpar/roslyn,genlu/roslyn,balajikris/roslyn,Giftednewt/roslyn,leppie/roslyn,KiloBravoLima/roslyn,panopticoncentral/roslyn,AArnott/roslyn,reaction1989/roslyn,xoofx/roslyn,bbarry/roslyn,OmarTawfik/roslyn,leppie/roslyn,mmitche/roslyn,cston/roslyn,gafter/roslyn,jcouv/roslyn,weltkante/roslyn,xasx/roslyn,Maxwe11/roslyn,lorcanmooney/roslyn,mavasani/roslyn,cston/roslyn,Giftednewt/roslyn,paulvanbrenk/roslyn,yeaicc/roslyn,jasonmalinowski/roslyn,jhendrixMSFT/roslyn,davkean/roslyn,mseamari/Stuff,AnthonyDGreen/roslyn,ValentinRueda/roslyn,jhendrixMSFT/roslyn,vcsjones/roslyn,antonssonj/roslyn,dotnet/roslyn,robinsedlaczek/roslyn,HellBrick/roslyn,antonssonj/roslyn,Maxwe11/roslyn,khyperia/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,weltkante/roslyn,CaptainHayashi/roslyn,abock/roslyn,weltkante/roslyn,ljw1004/roslyn,khellang/roslyn,mattscheffer/roslyn,jamesqo/roslyn,yeaicc/roslyn,xoofx/roslyn,jhendrixMSFT/roslyn,antonssonj/roslyn,panopticoncentral/roslyn,nguerrera/roslyn,SeriaWei/roslyn,HellBrick/roslyn,physhi/roslyn,bartdesmet/roslyn,pdelvo/roslyn,natgla/roslyn,KiloBravoLima/roslyn,ljw1004/roslyn,CaptainHayashi/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,balajikris/roslyn,tmeschter/roslyn,jkotas/roslyn,jaredpar/roslyn,panopticoncentral/roslyn,ericfe-ms/roslyn,Pvlerick/roslyn,vslsnap/roslyn,srivatsn/roslyn,CyrusNajmabadi/roslyn,mmitche/roslyn,Pvlerick/roslyn,eriawan/roslyn,balajikris/roslyn,stephentoub/roslyn,a-ctor/roslyn,VPashkov/roslyn,bartdesmet/roslyn,ValentinRueda/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,robinsedlaczek/roslyn,AmadeusW/roslyn,pdelvo/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,KevinH-MS/roslyn,managed-commons/roslyn,vslsnap/roslyn,basoundr/roslyn,dpoeschl/roslyn,AmadeusW/roslyn,tmat/roslyn,Shiney/roslyn,bartdesmet/roslyn,genlu/roslyn,genlu/roslyn,kelltrick/roslyn,jkotas/roslyn,MichalStrehovsky/roslyn,zooba/roslyn,khellang/roslyn,MatthieuMEZIL/roslyn,TyOverby/roslyn,MatthieuMEZIL/roslyn,michalhosala/roslyn,drognanar/roslyn,MattWindsor91/roslyn,DustinCampbell/roslyn,ericfe-ms/roslyn,MatthieuMEZIL/roslyn,jcouv/roslyn,cston/roslyn,eriawan/roslyn,agocke/roslyn,VSadov/roslyn,tmeschter/roslyn,a-ctor/roslyn,yeaicc/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,KevinH-MS/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,sharadagrawal/Roslyn,sharadagrawal/Roslyn,Hosch250/roslyn,kelltrick/roslyn,KevinH-MS/roslyn,MichalStrehovsky/roslyn,mattwar/roslyn,khellang/roslyn,sharwell/roslyn,KevinRansom/roslyn,aelij/roslyn,ErikSchierboom/roslyn,bkoelman/roslyn,zooba/roslyn,robinsedlaczek/roslyn,drognanar/roslyn,stephentoub/roslyn,xoofx/roslyn,jamesqo/roslyn,agocke/roslyn,jmarolf/roslyn,TyOverby/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,physhi/roslyn,zooba/roslyn,shyamnamboodiripad/roslyn,SeriaWei/roslyn,xasx/roslyn,diryboy/roslyn,agocke/roslyn,dpoeschl/roslyn,thomaslevesque/roslyn,AnthonyDGreen/roslyn,amcasey/roslyn,jeffanders/roslyn,akrisiun/roslyn,Shiney/roslyn,dpoeschl/roslyn,mseamari/Stuff,jkotas/roslyn,drognanar/roslyn,OmarTawfik/roslyn,bbarry/roslyn,tmat/roslyn,ValentinRueda/roslyn,heejaechang/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,heejaechang/roslyn,srivatsn/roslyn,diryboy/roslyn,ljw1004/roslyn,brettfo/roslyn,Maxwe11/roslyn,Pvlerick/roslyn,AlekseyTs/roslyn,mattwar/roslyn,paulvanbrenk/roslyn,tmat/roslyn,akrisiun/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,KirillOsenkov/roslyn,MattWindsor91/roslyn,eriawan/roslyn,sharwell/roslyn,tvand7093/roslyn,tannergooding/roslyn,VSadov/roslyn,paulvanbrenk/roslyn,leppie/roslyn,rgani/roslyn,VPashkov/roslyn,swaroop-sridhar/roslyn,VPashkov/roslyn,gafter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,amcasey/roslyn,jaredpar/roslyn,sharadagrawal/Roslyn,kelltrick/roslyn,basoundr/roslyn,vcsjones/roslyn,davkean/roslyn,jcouv/roslyn,srivatsn/roslyn,jasonmalinowski/roslyn,tmeschter/roslyn,khyperia/roslyn,dotnet/roslyn,aelij/roslyn,DustinCampbell/roslyn,heejaechang/roslyn,basoundr/roslyn,wvdd007/roslyn,Shiney/roslyn,bkoelman/roslyn,diryboy/roslyn,abock/roslyn,reaction1989/roslyn,AArnott/roslyn,aelij/roslyn,lorcanmooney/roslyn,ericfe-ms/roslyn,nguerrera/roslyn,AnthonyDGreen/roslyn,rgani/roslyn,brettfo/roslyn,KevinRansom/roslyn,reaction1989/roslyn,Hosch250/roslyn,wvdd007/roslyn,lorcanmooney/roslyn,AArnott/roslyn,tvand7093/roslyn,shyamnamboodiripad/roslyn,jmarolf/roslyn,OmarTawfik/roslyn,budcribar/roslyn,CaptainHayashi/roslyn,KiloBravoLima/roslyn,thomaslevesque/roslyn,jmarolf/roslyn,budcribar/roslyn,bkoelman/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,tvand7093/roslyn,natgla/roslyn,bbarry/roslyn,mmitche/roslyn,tannergooding/roslyn,KevinRansom/roslyn,jeffanders/roslyn,brettfo/roslyn,AmadeusW/roslyn,xasx/roslyn | src/Workspaces/Core/Portable/Utilities/ForegroundThreadDataKind.cs | src/Workspaces/Core/Portable/Utilities/ForegroundThreadDataKind.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Utilities
{
internal enum ForegroundThreadDataKind
{
Wpf,
StaUnitTest,
Unknown
}
internal static class ForegroundThreadDataInfo
{
private static readonly ForegroundThreadDataKind s_fallbackForegroundThreadDataKind;
private static ForegroundThreadDataKind? s_currentForegroundThreadDataKind;
static ForegroundThreadDataInfo()
{
s_fallbackForegroundThreadDataKind = CreateDefault();
}
internal static ForegroundThreadDataKind CreateDefault()
{
var kind = SynchronizationContext.Current?.GetType().FullName == "System.Windows.Threading.DispatcherSynchronizationContext"
? ForegroundThreadDataKind.Wpf
: ForegroundThreadDataKind.Unknown;
return kind;
}
internal static ForegroundThreadDataKind CurrentForegroundThreadDataKind
{
get { return s_currentForegroundThreadDataKind ?? s_fallbackForegroundThreadDataKind; }
}
internal static void SetCurrentForegroundThreadDataKind(ForegroundThreadDataKind? kind)
{
s_currentForegroundThreadDataKind = kind;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Utilities
{
internal enum ForegroundThreadDataKind
{
Wpf,
StaUnitTest,
Unknown
}
internal static class ForegroundThreadDataInfo
{
private static readonly ForegroundThreadDataKind s_fallbackForegroundThreadDataKind;
private static ForegroundThreadDataKind? s_currentForegroundThreadDataKind;
static ForegroundThreadDataInfo()
{
s_fallbackForegroundThreadDataKind = CreateDefault();
}
internal static ForegroundThreadDataKind CreateDefault()
{
ForegroundThreadDataKind kind = SynchronizationContext.Current?.GetType().FullName == "System.Windows.Threading.DispatcherSynchronizationContext"
? ForegroundThreadDataKind.Wpf
: ForegroundThreadDataKind.Unknown;
return kind;
}
internal static ForegroundThreadDataKind CurrentForegroundThreadDataKind
{
get { return s_currentForegroundThreadDataKind ?? s_fallbackForegroundThreadDataKind; }
}
internal static void SetCurrentForegroundThreadDataKind(ForegroundThreadDataKind? kind)
{
s_currentForegroundThreadDataKind = kind;
}
}
} | mit | C# |
83294b65941d8bd4e846a7ace0cbce358997270f | bump version | leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,base33/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,aaronpowell/Umbraco-CMS,aaronpowell/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,robertjf/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,NikRimington/Umbraco-CMS,tompipe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,rasmuseeg/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,aaronpowell/Umbraco-CMS,abryukhov/Umbraco-CMS,tcmorris/Umbraco-CMS,NikRimington/Umbraco-CMS,dawoe/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,WebCentrum/Umbraco-CMS,arknu/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,umbraco/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,base33/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,tompipe/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,aadfPT/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,aadfPT/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,aadfPT/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,robertjf/Umbraco-CMS,base33/Umbraco-CMS,arknu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,lars-erik/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS | src/SolutionInfo.cs | src/SolutionInfo.cs | using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("7.8.0")]
[assembly: AssemblyInformationalVersion("7.8.0-beta005")] | using System.Reflection;
using System.Resources;
[assembly: AssemblyCompany("Umbraco")]
[assembly: AssemblyCopyright("Copyright © Umbraco 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguageAttribute("en-US")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("7.8.0")]
[assembly: AssemblyInformationalVersion("7.8.0-beta004")] | mit | C# |
400690b84523541226b51676d393882015da20ae | Fix bug with query after json ignoring user doc contact challenges. | danludwig/eventsourced.net,grrizzly/eventsourced.net,danludwig/eventsourced.net,danludwig/eventsourced.net,grrizzly/eventsourced.net,grrizzly/eventsourced.net | src/EventSourced.Net.ReadModel/ReadModel/Users/Internal/Queries/UserDocumentByContactChallengeCorrelationId.cs | src/EventSourced.Net.ReadModel/ReadModel/Users/Internal/Queries/UserDocumentByContactChallengeCorrelationId.cs | using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x =>
AQL.In(query.CorrelationId, x.ContactEmailChallenges.Select(y => y.CorrelationId)) ||
AQL.In(query.CorrelationId, x.ContactSmsChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
| using System;
using System.Linq;
using System.Threading.Tasks;
using ArangoDB.Client;
using EventSourced.Net.ReadModel.Users.Internal.Documents;
namespace EventSourced.Net.ReadModel.Users.Internal.Queries
{
public class UserDocumentByContactChallengeCorrelationId : IQuery<Task<UserDocument>>
{
public Guid CorrelationId { get; }
internal UserDocumentByContactChallengeCorrelationId(Guid correlationId) {
CorrelationId = correlationId;
}
}
public class HandleUserDocumentByContactChallengeCorrelationId : IHandleQuery<UserDocumentByContactChallengeCorrelationId, Task<UserDocument>>
{
private IArangoDatabase Db { get; }
public HandleUserDocumentByContactChallengeCorrelationId(IArangoDatabase db) {
Db = db;
}
public Task<UserDocument> Handle(UserDocumentByContactChallengeCorrelationId query) {
UserDocument user = Db.Query<UserDocument>()
.SingleOrDefault(x => AQL.In(query.CorrelationId, x.ContactChallenges.Select(y => y.CorrelationId)));
return Task.FromResult(user);
}
}
}
| mit | C# |
20f91106d9988154252a681d15841e3683594f47 | Fix failing test | UselessToucan/osu,naoey/osu,ZLima12/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,peppy/osu,peppy/osu-new,naoey/osu,DrabWeb/osu,DrabWeb/osu,ZLima12/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,johnneijzen/osu,naoey/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu | osu.Game.Rulesets.Catch.Tests/CatchDifficultyCalculatorTest.cs | osu.Game.Rulesets.Catch.Tests/CatchDifficultyCalculatorTest.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.Catch.Difficulty;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Catch.Tests
{
public class CatchDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Catch";
[TestCase(3.8701854263563118d, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override LegacyDifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new CatchDifficultyCalculator(new CatchRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new CatchRuleset();
}
}
| // 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.Catch.Difficulty;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Tests.Beatmaps;
namespace osu.Game.Rulesets.Catch.Tests
{
public class CatchDifficultyCalculatorTest : DifficultyCalculatorTest
{
protected override string ResourceAssembly => "osu.Game.Rulesets.Catch";
[TestCase(3.8664391043534758, "diffcalc-test")]
public void Test(double expected, string name)
=> base.Test(expected, name);
protected override LegacyDifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => new CatchDifficultyCalculator(new CatchRuleset(), beatmap);
protected override Ruleset CreateRuleset() => new CatchRuleset();
}
}
| mit | C# |
7b43730fe61791017693d058a101487057d218a3 | add QuoteBackground in OsuMarkdownQuoteBlock | NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,peppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu | osu.Game/Graphics/Containers/Markdown/OsuMarkdownQuoteBlock.cs | osu.Game/Graphics/Containers/Markdown/OsuMarkdownQuoteBlock.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 Markdig.Syntax;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Framework.Graphics.Shapes;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownQuoteBlock : MarkdownQuoteBlock
{
public OsuMarkdownQuoteBlock(QuoteBlock quoteBlock)
: base(quoteBlock)
{
}
protected override Drawable CreateBackground() => new QuoteBackground();
public override MarkdownTextFlowContainer CreateTextFlow()
{
return base.CreateTextFlow().With(f => f.Margin = new MarginPadding
{
Vertical = 10,
Horizontal = 20,
});
}
private class QuoteBackground : Box
{
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.CentreLeft;
RelativeSizeAxes = Axes.Y;
Width = 2;
Colour = colourProvider.Content2;
}
}
}
}
| // 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 Markdig.Syntax;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers.Markdown;
using osu.Game.Overlays;
namespace osu.Game.Graphics.Containers.Markdown
{
public class OsuMarkdownQuoteBlock : MarkdownQuoteBlock
{
private Drawable background;
public OsuMarkdownQuoteBlock(QuoteBlock quoteBlock)
: base(quoteBlock)
{
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
background.Colour = colourProvider.Content2;
}
protected override Drawable CreateBackground()
{
background = base.CreateBackground();
background.Width = 2;
return background;
}
public override MarkdownTextFlowContainer CreateTextFlow()
{
return base.CreateTextFlow().With(f => f.Margin = new MarginPadding
{
Vertical = 10,
Horizontal = 20,
});
}
}
}
| mit | C# |
9d26080ce9f8329180a7ccc086fc9fe3d9a287ee | Update Start.cs | DYanis/UniversalNumeralSystems | ConvertorFromBaseToDecimalNumeralSystem/ConvertorFromBaseToDecimalNumeralSystem/Start.cs | ConvertorFromBaseToDecimalNumeralSystem/ConvertorFromBaseToDecimalNumeralSystem/Start.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
internal class Start
{
internal static void Main()
{
// Add numeral system keys.
List<string> keys = new List<string>();
keys.Add("KKK0"); // 1
keys.Add("KKK1"); // 2
keys.Add("KKK2"); // 3
keys.Add("KKK3"); // 4
keys.Add("KKK4"); // 5
keys.Add("KKK5"); // 6
keys.Add("KKK6"); // 7
keys.Add("KKK7"); // 8
keys.Add("KKK8"); // 9
string baseNumber = Console.ReadLine();
ulong convertedNumber = ConvertFromBaseToDecimal(keys, baseNumber);
Console.WriteLine(convertedNumber);
}
internal static ulong ConvertFromBaseToDecimal(List<string> keys, string baseNumber)
{
List<ulong> numL = new List<ulong>();
string currentKey = string.Empty;
for (int i = 0; i < baseNumber.Length; i++)
{
currentKey += baseNumber[i].ToString();
if (keys.IndexOf(currentKey) > -1)
{
numL.Add((ulong)keys.IndexOf(currentKey));
currentKey = string.Empty;
}
}
ulong[] decimalNumbers = numL.ToArray();
Array.Reverse(decimalNumbers);
ulong result = 0;
for (int i = 0; i < numL.Count; i++)
{
result += (decimalNumbers[i] * Pow((ulong)keys.Count, (ulong)i));
}
return result;
}
internal static ulong Pow(ulong number, ulong pow)
{
ulong result = 1;
for (ulong i = 0; i < pow; i++)
{
result *= number;
}
return result;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
internal class Start
{
internal static void Main()
{
// Add numeral system keys.
List<string> keys = new List<string>();
keys.Add("KKK0");
keys.Add("KKK1");
keys.Add("KKK2");
keys.Add("KKK3");
keys.Add("KKK4");
keys.Add("KKK5");
keys.Add("KKK6");
keys.Add("KKK7");
keys.Add("KKK8");
string baseNumber = Console.ReadLine();
ulong convertedNumber = ConvertorFromBaseToDecimal(keys, baseNumber);
Console.WriteLine(convertedNumber);
}
internal static ulong ConvertorFromBaseToDecimal(List<string> keys, string baseNumber)
{
List<ulong> numL = new List<ulong>();
string currentKey = string.Empty;
for (int i = 0; i < baseNumber.Length; i++)
{
currentKey += baseNumber[i].ToString();
if (keys.IndexOf(currentKey) > -1)
{
numL.Add((ulong)keys.IndexOf(currentKey));
currentKey = string.Empty;
}
}
ulong[] decimalNumbers = numL.ToArray();
Array.Reverse(decimalNumbers);
ulong result = 0;
for (int i = 0; i < numL.Count; i++)
{
result += (decimalNumbers[i] * Pow((ulong)keys.Count, (ulong)i));
}
return result;
}
internal static ulong Pow(ulong number, ulong pow)
{
ulong result = 1;
for (ulong i = 0; i < pow; i++)
{
result *= number;
}
return result;
}
}
| mit | C# |
9748c37e17249f947c984d1ddb00538ba82fd963 | add untested PeriodicTimerSystemClockMonitor code. | atsushieno/mono-reactive,paulcbetts/mono-reactive | System.Reactive.Core/System.Reactive.PlatformServices/PeriodicTimerSystemClockMonitor.cs | System.Reactive.Core/System.Reactive.PlatformServices/PeriodicTimerSystemClockMonitor.cs | using System;
using System.ComponentModel;
using System.Threading;
namespace System.Reactive.PlatformServices
{
[EditorBrowsable (EditorBrowsableState.Advanced)]
public class PeriodicTimerSystemClockMonitor : INotifySystemClockChanged
{
public PeriodicTimerSystemClockMonitor (TimeSpan period)
{
this.period = period;
thread = new Thread (Loop) { IsBackground = true };
thread.Start ();
}
Thread thread;
TimeSpan period;
DateTimeOffset now;
public event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;
void Loop ()
{
now = SystemClock.UtcNow;
while (true) {
Thread.Sleep (period);
var delta = SystemClock.UtcNow - now - period;
if (SystemClockChanged != null && Math.Abs (delta.Ticks) > TimeSpan.TicksPerSecond)
SystemClockChanged (this, new SystemClockChangedEventArgs ());
now = SystemClock.UtcNow;
}
}
}
}
| using System;
using System.ComponentModel;
namespace System.Reactive.PlatformServices
{
[EditorBrowsable (EditorBrowsableState.Advanced)]
public class PeriodicTimerSystemClockMonitor : INotifySystemClockChanged
{
public PeriodicTimerSystemClockMonitor (TimeSpan period)
{
this.period = period;
}
TimeSpan period;
public event EventHandler<SystemClockChangedEventArgs> SystemClockChanged;
}
}
| mit | C# |
aabc8da9638cb4fd338a4b9aa3faa1caffcd86c9 | Fix whitespace | octokit/octokit.net,thedillonb/octokit.net,TattsGroup/octokit.net,editor-tools/octokit.net,gdziadkiewicz/octokit.net,editor-tools/octokit.net,devkhan/octokit.net,dampir/octokit.net,shiftkey-tester/octokit.net,octokit/octokit.net,SmithAndr/octokit.net,adamralph/octokit.net,rlugojr/octokit.net,Sarmad93/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,dampir/octokit.net,shiftkey-tester/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,alfhenrik/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,ivandrofly/octokit.net,TattsGroup/octokit.net,M-Zuber/octokit.net,ivandrofly/octokit.net,shiftkey/octokit.net,M-Zuber/octokit.net,shana/octokit.net,khellang/octokit.net,shiftkey/octokit.net,rlugojr/octokit.net,eriawan/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,alfhenrik/octokit.net,eriawan/octokit.net,shana/octokit.net | Octokit.Tests.Integration/Helpers/TeamContext.cs | Octokit.Tests.Integration/Helpers/TeamContext.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Octokit.Tests.Integration.Helpers
{
internal sealed class TeamContext : IDisposable
{
internal TeamContext(IConnection connection, Team team)
{
_connection = connection;
Team = team;
TeamId = team.Id;
TeamName = team.Name;
}
private IConnection _connection;
internal int TeamId { get; private set; }
internal string TeamName { get; private set; }
internal Team Team { get; private set; }
public void Dispose()
{
Helper.DeleteTeam(_connection, Team);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Octokit.Tests.Integration.Helpers
{
internal sealed class TeamContext : IDisposable
{
internal TeamContext(IConnection connection, Team team)
{
_connection = connection;
Team = team;
TeamId = team.Id;
TeamName = team.Name;
}
private IConnection _connection;
internal int TeamId { get; private set; }
internal string TeamName { get; private set; }
internal Team Team { get; private set; }
public void Dispose()
{
Helper.DeleteTeam(_connection, Team);
}
}
}
| mit | C# |
901f53cf092b0ae8d528a5ea4c977d8841d0288b | Fix typo | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/Clients/SingleInstanceCheckerTests.cs | WalletWasabi.Tests/UnitTests/Clients/SingleInstanceCheckerTests.cs | using NBitcoin;
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Services;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.Clients
{
/// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/>
[Collection("Serial unit tests collection")]
public class SingleInstanceCheckerTests
{
private static Random Random { get; } = new();
/// <summary>
/// Global port may collide when several PRs are being tested on CI at the same time,
/// so we need some sort of non-determinism here (e.g. random numbers).
/// </summary>
private static int GenerateRandomPort()
{
return Random.Next(37128, 37168);
}
[Fact]
public async Task SingleInstanceTestsAsync()
{
int mainNetPort = GenerateRandomPort();
int testNetPort = GenerateRandomPort();
int regTestPort = GenerateRandomPort();
// Disposal test.
await using (SingleInstanceChecker sic = new(mainNetPort))
{
await sic.CheckAsync();
}
// Check different networks.
await using (SingleInstanceChecker sic = new(mainNetPort))
{
await sic.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sic.CheckAsync());
await using SingleInstanceChecker sicMainNet2 = new(mainNetPort);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicMainNet2.CheckAsync());
await using SingleInstanceChecker sicTestNet = new(testNetPort);
await sicTestNet.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicTestNet.CheckAsync());
await using SingleInstanceChecker sicRegTest = new(regTestPort);
await sicRegTest.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicRegTest.CheckAsync());
}
}
[Fact]
public async Task OtherInstanceStartedTestsAsync()
{
int mainNetPort = GenerateRandomPort();
// Disposal test.
await using SingleInstanceChecker sic = new(mainNetPort);
long eventCalled = 0;
sic.OtherInstanceStarted += SetCalled;
try
{
// I am the first instance this should be fine.
await sic.CheckAsync();
await using SingleInstanceChecker secondInstance = new(mainNetPort);
for (int i = 0; i < 3; i++)
{
// I am the second one.
await Assert.ThrowsAsync<InvalidOperationException>(async () => await secondInstance.CheckAsync());
}
// There should be the same number of events as the number of tries from the second instance.
Assert.Equal(3, Interlocked.Read(ref eventCalled));
}
finally
{
sic.OtherInstanceStarted -= SetCalled;
}
void SetCalled(object? sender, EventArgs args)
{
Interlocked.Increment(ref eventCalled);
}
}
}
}
| using NBitcoin;
using System;
using System.Threading;
using System.Threading.Tasks;
using WalletWasabi.Services;
using Xunit;
namespace WalletWasabi.Tests.UnitTests.Clients
{
/// <seealso cref="XunitConfiguration.SerialCollectionDefinition"/>
[Collection("Serial unit tests collection")]
public class SingleInstanceCheckerTests
{
private static Random Random { get; } = new();
/// <summary>
/// Global port may collide when several PRs are being tested on CI at the same time,
/// so we need some sort of non-determinism here (e.g. random numbers).
/// </summary>
private static int GenerateRandomPort()
{
return Random.Next(37128, 37168);
}
[Fact]
public async Task SingleInstanceTestsAsync()
{
int mainNetPort = GenerateRandomPort();
int testNetPort = GenerateRandomPort();
int regTestPort = GenerateRandomPort();
// Disposal test.
await using (SingleInstanceChecker sic = new(mainNetPort))
{
await sic.CheckAsync();
}
// Check different networks.
await using (SingleInstanceChecker sic = new(mainNetPort))
{
await sic.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sic.CheckAsync());
await using SingleInstanceChecker sicMainNet2 = new(mainNetPort);
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicMainNet2.CheckAsync());
await using SingleInstanceChecker sicTestNet = new(testNetPort);
await sicTestNet.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicTestNet.CheckAsync());
await using SingleInstanceChecker sicRegTest = new(regTestPort);
await sicRegTest.CheckAsync();
await Assert.ThrowsAsync<InvalidOperationException>(async () => await sicRegTest.CheckAsync());
}
}
[Fact]
public async Task OtherInstanceStartedTestsAsync()
{
int mainNetPort = GenerateRandomPort();
// Disposal test.
await using SingleInstanceChecker sic = new(mainNetPort);
long eventCalled = 0;
sic.OtherInstanceStarted += SetCalled;
try
{
// I am the first instance this should be fine.
await sic.CheckAsync();
await using SingleInstanceChecker secondInstance = new(mainNetPort);
for (int i = 0; i < 3; i++)
{
// I am the second one.
await Assert.ThrowsAsync<InvalidOperationException>(async () => await secondInstance.CheckAsync());
}
// There should be the same number of event as the number of tries from the second instance.
Assert.Equal(3, Interlocked.Read(ref eventCalled));
}
finally
{
sic.OtherInstanceStarted -= SetCalled;
}
void SetCalled(object? sender, EventArgs args)
{
Interlocked.Increment(ref eventCalled);
}
}
}
}
| mit | C# |
de658c932e6ef23ce6511d15cabf28b836f94416 | Fix test regression | peppy/osu,UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,ppy/osu,ppy/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu-new,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,UselessToucan/osu,ZLima12/osu,UselessToucan/osu | osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.cs | osu.Game.Tests/Visual/SongSelect/TestSceneBeatmapOptionsOverlay.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.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Screens.Select.Options;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null, Key.Number1);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null, Key.Number2);
overlay.AddButton(@"Delete", @"all difficulties", FontAwesome.Solid.Trash, Color4.Pink, null, Key.Number3);
overlay.AddButton(@"Edit", @"beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null, Key.Number4);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
| // 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.ComponentModel;
using osu.Framework.Graphics.Sprites;
using osu.Game.Screens.Select.Options;
using osuTK.Graphics;
using osuTK.Input;
namespace osu.Game.Tests.Visual.SongSelect
{
[Description("bottom beatmap details")]
public class TestSceneBeatmapOptionsOverlay : OsuTestScene
{
public TestSceneBeatmapOptionsOverlay()
{
var overlay = new BeatmapOptionsOverlay();
overlay.AddButton(@"Remove", @"from unplayed", FontAwesome.Regular.TimesCircle, Color4.Purple, null, Key.Number1);
overlay.AddButton(@"Clear", @"local scores", FontAwesome.Solid.Eraser, Color4.Purple, null, Key.Number2);
overlay.AddButton(@"Edit", @"Beatmap", FontAwesome.Solid.PencilAlt, Color4.Yellow, null, Key.Number3);
overlay.AddButton(@"Delete", @"Beatmap", FontAwesome.Solid.Trash, Color4.Pink, null, Key.Number4, float.MaxValue);
Add(overlay);
AddStep(@"Toggle", overlay.ToggleVisibility);
}
}
}
| mit | C# |
61cd881db97eff7423f79ca2aecf7be69e4214e2 | バージョン 0.4.0 に更新 | shibayan/iisexpress-testkit,shibayan/iisexpress-testkit | src/IisExpressTestKit/Properties/AssemblyInfo.cs | src/IisExpressTestKit/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("IisExpressTestKit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IisExpressTestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("c22c6598-6b1c-4d74-a49c-85ed2a329f6f")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.0")] | using System.Reflection;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("IisExpressTestKit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IisExpressTestKit")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
[assembly: Guid("c22c6598-6b1c-4d74-a49c-85ed2a329f6f")]
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
//
// メジャー バージョン
// マイナー バージョン
// ビルド番号
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0")] | apache-2.0 | C# |
9d001587bfe16feae036c00799ed77af4a7f2aba | Remove nullable | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/CrashReport/CrashReporter.cs | WalletWasabi.Fluent/CrashReport/CrashReporter.cs | using System;
using System.Diagnostics;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.CrashReport
{
public class CrashReporter
{
private const int MaxRecursiveCalls = 5;
public int Attempts { get; private set; }
public string? Base64ExceptionString { get; private set; } = null;
public bool HadException { get; private set; }
public SerializableException? SerializedException { get; private set; }
public void TryInvokeIfRequired()
{
if (!HadException)
{
return;
}
try
{
if (Attempts >= MaxRecursiveCalls)
{
throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors.");
}
var args = ToCliArguments();
var path = Process.GetCurrentProcess().MainModule?.FileName;
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"Invalid path: '{path}'");
}
ProcessStartInfo startInfo = ProcessStartInfoFactory.Make(path, args);
using Process? p = Process.Start(startInfo);
}
catch (Exception ex)
{
Logger.LogWarning($"There was a problem while invoking crash report:{ex.ToUserFriendlyString()}.");
}
}
public string ToCliArguments()
{
if (string.IsNullOrEmpty(Base64ExceptionString))
{
throw new InvalidOperationException($"The crash report exception message is empty.");
}
return $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\"";
}
public bool TryProcessCliArgs(string[] args)
{
if (args.Length < 3)
{
return false;
}
if (args[0].Contains("crashreport") && args[1].Contains("-attempt=") && args[2].Contains("-exception="))
{
var attemptString = args[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1].Trim('"');
var exceptionString = args[2].Split("=", StringSplitOptions.RemoveEmptyEntries)[1].Trim('"');
Attempts = int.Parse(attemptString);
Base64ExceptionString = exceptionString;
SerializedException = SerializableException.FromBase64String(exceptionString);
return true;
}
return false;
}
/// <summary>
/// Sets the exception when it occurs the first time and should be reported to the user.
/// </summary>
public void SetException(Exception ex)
{
SerializedException = ex.ToSerializableException();
Base64ExceptionString = SerializableException.ToBase64String(SerializedException);
HadException = true;
}
}
}
| using System;
using System.Diagnostics;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.CrashReport
{
public class CrashReporter
{
private const int MaxRecursiveCalls = 5;
public int Attempts { get; private set; }
public string? Base64ExceptionString { get; private set; } = null;
public bool HadException { get; private set; }
public SerializableException? SerializedException { get; private set; }
public void TryInvokeIfRequired()
{
if (!HadException)
{
return;
}
try
{
if (Attempts >= MaxRecursiveCalls)
{
throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors.");
}
var args = ToCliArguments();
var path = Process.GetCurrentProcess()?.MainModule?.FileName;
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"Invalid path: '{path}'");
}
ProcessStartInfo startInfo = ProcessStartInfoFactory.Make(path, args);
using Process? p = Process.Start(startInfo);
}
catch (Exception ex)
{
Logger.LogWarning($"There was a problem while invoking crash report:{ex.ToUserFriendlyString()}.");
}
}
public string ToCliArguments()
{
if (string.IsNullOrEmpty(Base64ExceptionString))
{
throw new InvalidOperationException($"The crash report exception message is empty.");
}
return $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\"";
}
public bool TryProcessCliArgs(string[] args)
{
if (args.Length < 3)
{
return false;
}
if (args[0].Contains("crashreport") && args[1].Contains("-attempt=") && args[2].Contains("-exception="))
{
var attemptString = args[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1].Trim('"');
var exceptionString = args[2].Split("=", StringSplitOptions.RemoveEmptyEntries)[1].Trim('"');
Attempts = int.Parse(attemptString);
Base64ExceptionString = exceptionString;
SerializedException = SerializableException.FromBase64String(exceptionString);
return true;
}
return false;
}
/// <summary>
/// Sets the exception when it occurs the first time and should be reported to the user.
/// </summary>
public void SetException(Exception ex)
{
SerializedException = ex.ToSerializableException();
Base64ExceptionString = SerializableException.ToBase64String(SerializedException);
HadException = true;
}
}
}
| mit | C# |
6f7c7faac92339a46c0ff222967ab8d96221a041 | Add Hello world! | mk-dev-team/mk-world-of-imagination | WorldOfImagination/WorldOfImagination/Program.cs | WorldOfImagination/WorldOfImagination/Program.cs | using System;
namespace WorldOfImagination
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WorldOfImagination
{
class Program
{
static void Main(string[] args)
{
}
}
}
| mit | C# |
d8714dd7d18a9df0ee5bce7780846b3fe9ec955b | Add a missing event type | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/Syncthing/ApiClient/EventType.cs | src/SyncTrayzor/Syncthing/ApiClient/EventType.cs | using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
ListenAddressesChanged,
}
}
| using Newtonsoft.Json;
namespace SyncTrayzor.Syncthing.ApiClient
{
[JsonConverter(typeof(DefaultingStringEnumConverter))]
public enum EventType
{
Unknown,
Starting,
StartupComplete,
Ping,
DeviceDiscovered,
DeviceConnected,
DeviceDisconnected,
RemoteIndexUpdated,
LocalIndexUpdated,
ItemStarted,
ItemFinished,
// Not quite sure which it's going to be, so play it safe...
MetadataChanged,
ItemMetadataChanged,
StateChanged,
FolderRejected,
DeviceRejected,
ConfigSaved,
DownloadProgress,
FolderSummary,
FolderCompletion,
FolderErrors,
FolderScanProgress,
DevicePaused,
DeviceResumed,
LoginAttempt,
ListenAddressChanged,
RelayStateChanged,
ExternalPortMappingChanged,
}
}
| mit | C# |
1b5047541dbf3e99ba7e118056b2b03184b5b44a | Add limiter to JsonArrayField min and max properties | Ackara/Mockaroo.NET | src/Mockaroo.Core/Fields/JSONArrayField.cs | src/Mockaroo.Core/Fields/JSONArrayField.cs | namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min
{
get { return _min; }
set { _min = value.Between(0, 100); }
}
public int Max
{
get { return _max; }
set { _max = value.Between(0, 100); }
}
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
#region Private Members
private int _min = 1, _max = 5;
#endregion Private Members
}
} | namespace Gigobyte.Mockaroo.Fields
{
public partial class JSONArrayField
{
public int Min { get; set; } = 1;
public int Max { get; set; } = 5;
public override string ToJson()
{
return $"{base.BaseJson()},\"minItems\":{Min},\"maxItems\":{Max}}}";
}
}
} | mit | C# |
b3c447b812ff64fa56f8ba41f27a732dbbead067 | Refresh template cache when template.json file is renamed | mrward/monodevelop-template-creator-addin,mrward/monodevelop-template-creator-addin | src/MonoDevelop.TemplateCreator/MonoDevelop.Templating/TemplateJsonFileChangedMonitor.cs | src/MonoDevelop.TemplateCreator/MonoDevelop.Templating/TemplateJsonFileChangedMonitor.cs | //
// TemplateJsonFileChangedMonitor.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2017 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using MonoDevelop.Core;
namespace MonoDevelop.Templating
{
class TemplateJsonFileChangedMonitor
{
public TemplateJsonFileChangedMonitor()
{
FileService.FileChanged += FileChanged;
FileService.FileRemoved += FileRemoved;
FileService.FileRenamed += FileRenamed;
}
void FileChanged (object sender, FileEventArgs e)
{
foreach (FileEventInfo file in e) {
OnFileChanged (file);
}
}
/// <summary>
/// Refresh the template folders if a template.json file has changed.
/// </summary>
void OnFileChanged (FileEventInfo file)
{
if (file.FileName.IsTemplateJsonFile ()) {
TemplatingServices.EventsService.OnTemplateFoldersChanged ();
}
}
void FileRemoved (object sender, FileEventArgs e)
{
foreach (FileEventInfo file in e) {
OnFileRemoved (file);
}
}
/// <summary>
/// Refresh the template folders if a template.json file is removed or a
/// .template.config folder is removed.
/// </summary>
void OnFileRemoved (FileEventInfo file)
{
if (file.FileName.IsTemplateJsonFile () || file.FileName.IsTemplateConfigDirectory ()) {
TemplatingServices.EventsService.OnTemplateFoldersChanged ();
}
}
void FileRenamed (object sender, FileCopyEventArgs e)
{
foreach (FileCopyEventInfo file in e) {
FileRenamed (file);
}
}
void FileRenamed (FileCopyEventInfo file)
{
if (file.SourceFile.IsTemplateJsonFile () || file.TargetFile.IsTemplateJsonFile ()) {
TemplatingServices.EventsService.OnTemplateFoldersChanged ();
}
}
}
}
| //
// TemplateJsonFileChangedMonitor.cs
//
// Author:
// Matt Ward <matt.ward@xamarin.com>
//
// Copyright (c) 2017 Xamarin Inc. (http://xamarin.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using MonoDevelop.Core;
namespace MonoDevelop.Templating
{
class TemplateJsonFileChangedMonitor
{
public TemplateJsonFileChangedMonitor()
{
FileService.FileChanged += FileChanged;
FileService.FileRemoved += FileRemoved;
}
void FileChanged (object sender, FileEventArgs e)
{
foreach (FileEventInfo file in e) {
OnFileChanged (file);
}
}
/// <summary>
/// Refresh the template folders if a template.json file has changed.
/// </summary>
void OnFileChanged (FileEventInfo file)
{
if (file.FileName.IsTemplateJsonFile ()) {
TemplatingServices.EventsService.OnTemplateFoldersChanged ();
}
}
void FileRemoved (object sender, FileEventArgs e)
{
foreach (FileEventInfo file in e) {
OnFileRemoved (file);
}
}
/// <summary>
/// Refresh the template folders if a template.json file is removed or a
/// .template.config folder is removed.
/// </summary>
void OnFileRemoved (FileEventInfo file)
{
if (file.FileName.IsTemplateJsonFile () || file.FileName.IsTemplateConfigDirectory ()) {
TemplatingServices.EventsService.OnTemplateFoldersChanged ();
}
}
}
}
| mit | C# |
f8d186e87bcc219d4c16cb6c8c1b9e301316b188 | move oauth configuration in its own method | aoancea/practice-web-api-security,aoancea/practice-web-api-security,aoancea/practice-web-api-security | src/Api/Startup.cs | src/Api/Startup.cs | using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Phobos.Api.App_Start;
using Phobos.Api.Infrastructure;
using System;
using System.Web.Http;
[assembly: OwinStartup(typeof(Phobos.Api.Startup))]
namespace Phobos.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new SimpleOAuthAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
} | using Microsoft.Owin;
using Microsoft.Owin.Security.OAuth;
using Owin;
using Phobos.Api.App_Start;
using Phobos.Api.Infrastructure;
using System;
using System.Web.Http;
[assembly: OwinStartup(typeof(Phobos.Api.Startup))]
namespace Phobos.Api
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888
HttpConfiguration config = new HttpConfiguration();
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new SimpleOAuthAuthorizationServerProvider()
};
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
WebApiConfig.Register(config);
app.UseWebApi(config);
}
}
} | mit | C# |
8b0b90801306a80e68e0b3e3ce6c0088460aa9b1 | update RealFileWriter. (#1121) | superyyrrzz/docfx,LordZoltan/docfx,dotnet/docfx,LordZoltan/docfx,LordZoltan/docfx,hellosnow/docfx,DuncanmaMSFT/docfx,hellosnow/docfx,LordZoltan/docfx,928PJY/docfx,pascalberger/docfx,superyyrrzz/docfx,pascalberger/docfx,pascalberger/docfx,dotnet/docfx,DuncanmaMSFT/docfx,hellosnow/docfx,928PJY/docfx,dotnet/docfx,superyyrrzz/docfx,928PJY/docfx | src/Microsoft.DocAsCode.Common/FileAbstractLayer/RealFileWriter.cs | src/Microsoft.DocAsCode.Common/FileAbstractLayer/RealFileWriter.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Common
{
using System;
using System.Collections.Immutable;
using System.IO;
public class RealFileWriter : FileWriterBase
{
public RealFileWriter(string outputFolder)
: base(outputFolder) { }
#region Overrides
public override void Copy(PathMapping sourceFileName, RelativePath destFileName)
{
var dest = Path.Combine(ExpandedOutputFolder, destFileName.RemoveWorkingFolder());
Directory.CreateDirectory(Path.GetDirectoryName(dest));
var source = Environment.ExpandEnvironmentVariables(sourceFileName.PhysicalPath);
if (!FilePathComparer.OSPlatformSensitiveStringComparer.Equals(source, dest))
{
File.Copy(source, dest, true);
}
File.SetAttributes(dest, FileAttributes.Normal);
}
public override Stream Create(RelativePath file)
{
var f = Path.Combine(ExpandedOutputFolder, file.RemoveWorkingFolder());
Directory.CreateDirectory(Path.GetDirectoryName(f));
return File.Create(f);
}
public override IFileReader CreateReader()
{
return new RealFileReader(OutputFolder, ImmutableDictionary<string, string>.Empty);
}
#endregion
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Common
{
using System;
using System.Collections.Immutable;
using System.IO;
public class RealFileWriter : FileWriterBase
{
public RealFileWriter(string outputFolder)
: base(outputFolder) { }
#region Overrides
public override void Copy(PathMapping sourceFileName, RelativePath destFileName)
{
var f = Path.Combine(ExpandedOutputFolder, destFileName.RemoveWorkingFolder());
Directory.CreateDirectory(Path.GetDirectoryName(f));
File.Copy(Environment.ExpandEnvironmentVariables(sourceFileName.PhysicalPath), f, true);
File.SetAttributes(f, FileAttributes.Normal);
}
public override Stream Create(RelativePath file)
{
var f = Path.Combine(ExpandedOutputFolder, file.RemoveWorkingFolder());
Directory.CreateDirectory(Path.GetDirectoryName(f));
return File.Create(f);
}
public override IFileReader CreateReader()
{
return new RealFileReader(OutputFolder, ImmutableDictionary<string, string>.Empty);
}
#endregion
}
}
| mit | C# |
74a66f8bafb2a750dd9a946f985d24f2eeef55b9 | Fix bug in DataDirectoryDeriver | x97mdr/pickles,magicmonty/pickles,blorgbeard/pickles,irfanah/pickles,ppnrao/pickles,irfanah/pickles,dirkrombauts/pickles,irfanah/pickles,picklesdoc/pickles,dirkrombauts/pickles,x97mdr/pickles,dirkrombauts/pickles,blorgbeard/pickles,irfanah/pickles,picklesdoc/pickles,magicmonty/pickles,ppnrao/pickles,picklesdoc/pickles,magicmonty/pickles,magicmonty/pickles,dirkrombauts/pickles,picklesdoc/pickles,blorgbeard/pickles,ppnrao/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles | src/Pickles/Pickles.UserInterface/Settings/DataDirectoryDeriver.cs | src/Pickles/Pickles.UserInterface/Settings/DataDirectoryDeriver.cs | // #region License
//
//
// /*
// Copyright [2011] [Jeffrey Cameron]
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// */
// #endregion
using System;
using System.Deployment.Application;
using System.IO;
using System.Reflection;
namespace Pickles.UserInterface.Settings
{
public static class DataDirectoryDeriver
{
public static string DeriveDataDirectory()
{
if (ApplicationDeployment.IsNetworkDeployed)
{
return ApplicationDeployment.CurrentDeployment.DataDirectory;
}
else
{
Assembly entryAssembly = Assembly.GetEntryAssembly();
if (entryAssembly != null)
{
return Path.GetDirectoryName(entryAssembly.Location);
}
return string.Empty;
}
}
}
} | // #region License
//
//
// /*
// Copyright [2011] [Jeffrey Cameron]
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// */
// #endregion
using System;
using System.Deployment.Application;
using System.IO;
using System.Reflection;
namespace Pickles.UserInterface.Settings
{
public static class DataDirectoryDeriver
{
public static string DeriveDataDirectory()
{
if (ApplicationDeployment.IsNetworkDeployed)
{
return ApplicationDeployment.CurrentDeployment.DataDirectory;
}
else
{
return Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
}
}
}
} | apache-2.0 | C# |
9f9cefb773bdbb8a8a21e9dce61d39c88ba78795 | Add edit / remove buttons to each file on experience page | ucdavis/Badges,ucdavis/Badges | Badges/Views/Shared/_ExperienceWork.cshtml | Badges/Views/Shared/_ExperienceWork.cshtml | @model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description<br />
<a href="#edit">
<i class="icon-edit"></i>
</a>
<a href="#delete">
<i class="icon-remove"></i>
</a>
</p>
<div></div>
</div>
@* </div> *@
}
</div>
</div>
| @model Badges.Models.Shared.ExperienceViewModel
<div id="work-container" class="container work">
<div class="row">
@foreach (var work in @Model.SupportingWorks)
{
@* <div class="col-md-4"> *@
<div class="@work.Type work-item-box">
@Html.Partial("_ViewWork", work)
<p>@work.Description</p>
</div>
@* </div> *@
}
</div>
</div>
| mpl-2.0 | C# |
3019cd7c9fa49c329acbb76813b7b251ddcb93a6 | Remove nasty stuff | rolltechrick/PushSharp,yuejunwu/PushSharp,richardvaldivieso/PushSharp,chaoscope/PushSharp,ingljo/PushSharp,profporridge/PushSharp,cafeburger/PushSharp,wanglj7525/PushSharp,mao1350848579/PushSharp,agran/PushSharp,ingljo/PushSharp,rucila/PushSharp,bobqian1130/PushSharp,cafeburger/PushSharp,18098924759/PushSharp,codesharpdev/PushSharp,cnbin/PushSharp,profporridge/PushSharp,rolltechrick/PushSharp,mao1350848579/PushSharp,sumalla/PushSharp,agran/PushSharp,SuPair/PushSharp,bberak/PushSharp,sskodje/PushSharp,chaoscope/PushSharp,richardvaldivieso/PushSharp,bberak/PushSharp,fanpan26/PushSharp,richardvaldivieso/PushSharp,mao1350848579/PushSharp,JeffCertain/PushSharp,yuejunwu/PushSharp,ZanoMano/PushSharp,kouweizhong/PushSharp,cnbin/PushSharp,JeffCertain/PushSharp,zoser0506/PushSharp,zoser0506/PushSharp,wanglj7525/PushSharp,sumalla/PushSharp,kouweizhong/PushSharp,JeffCertain/PushSharp,FragCoder/PushSharp,tianhang/PushSharp,fanpan26/PushSharp,volkd/PushSharp,18098924759/PushSharp,profporridge/PushSharp,fhchina/PushSharp,fhchina/PushSharp,chaoscope/PushSharp,codesharpdev/PushSharp,ZanoMano/PushSharp,cafeburger/PushSharp,sskodje/PushSharp,18098924759/PushSharp,wanglj7525/PushSharp,sumalla/PushSharp,fhchina/PushSharp,volkd/PushSharp,SuPair/PushSharp,ZanoMano/PushSharp,rucila/PushSharp,volkd/PushSharp,bobqian1130/PushSharp,FragCoder/PushSharp,yuejunwu/PushSharp,kouweizhong/PushSharp,fanpan26/PushSharp,rolltechrick/PushSharp,SuPair/PushSharp,tianhang/PushSharp,agran/PushSharp,tianhang/PushSharp,codesharpdev/PushSharp,sskodje/PushSharp,bobqian1130/PushSharp,zoser0506/PushSharp,ingljo/PushSharp,cnbin/PushSharp,rucila/PushSharp,FragCoder/PushSharp | Client.Samples/PushSharp.ClientSample.MonoTouch/PushSharp.ClientSample.MonoTouch/AppDelegate.cs | Client.Samples/PushSharp.ClientSample.MonoTouch/PushSharp.ClientSample.MonoTouch/AppDelegate.cs | using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.ObjCRuntime;
namespace PushSharp.ClientSample.AppleMonoTouch
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UINavigationController navController;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
navController = new UINavigationController();
// If you have defined a view, add it here:
window.AddSubview (navController.View);
// make the window visible
window.MakeKeyAndVisible ();
//Register for remote notifications
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(UIRemoteNotificationType.Alert
| UIRemoteNotificationType.Badge
| UIRemoteNotificationType.Sound);
return true;
}
public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
{
var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
var newDeviceToken = deviceToken.ToString().Replace("<", "").Replace(">", "").Replace(" ", "");
if (string.IsNullOrEmpty(oldDeviceToken) || !oldDeviceToken.Equals(newDeviceToken))
{
//TODO: Put your own logic here to notify your server that the device token has changed/been created!
}
//Save device token now
NSUserDefaults.StandardUserDefaults.SetString(newDeviceToken, "PushDeviceToken");
Console.WriteLine("Device Token: " + newDeviceToken);
}
public override void FailedToRegisterForRemoteNotifications (UIApplication application, NSError error)
{
Console.WriteLine("Failed to register for notifications");
}
public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
{
Console.WriteLine("Received Remote Notification!");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using MonoTouch.ObjCRuntime;
namespace PushSharp.ClientSample.AppleMonoTouch
{
// The UIApplicationDelegate for the application. This class is responsible for launching the
// User Interface of the application, as well as listening (and optionally responding) to
// application events from iOS.
[Register ("AppDelegate")]
public partial class AppDelegate : UIApplicationDelegate
{
// class-level declarations
UIWindow window;
UINavigationController navController;
//
// This method is invoked when the application has loaded and is ready to run. In this
// method you should instantiate the window, load the UI into it and then make the window
// visible.
//
// You have 17 seconds to return from this method, or iOS will terminate your application.
//
public override bool FinishedLaunching (UIApplication app, NSDictionary options)
{
// create a new window instance based on the screen size
window = new UIWindow (UIScreen.MainScreen.Bounds);
navController = new UINavigationController();
// If you have defined a view, add it here:
window.AddSubview (navController.View);
// make the window visible
window.MakeKeyAndVisible ();
//Register for remote notifications
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(UIRemoteNotificationType.Alert
| UIRemoteNotificationType.Badge
| UIRemoteNotificationType.Sound);
return true;
}
public override void RegisteredForRemoteNotifications (UIApplication application, NSData deviceToken)
{
var oldDeviceToken = NSUserDefaults.StandardUserDefaults.StringForKey("PushDeviceToken");
//There's probably a better way to do this
var strFormat = new NSString("%@");
var dt = new NSString(MonoTouch.ObjCRuntime.Messaging.IntPtr_objc_msgSend_IntPtr_IntPtr(new MonoTouch.ObjCRuntime.Class("NSString").Handle, new MonoTouch.ObjCRuntime.Selector("stringWithFormat:").Handle, strFormat.Handle, deviceToken.Handle));
var newDeviceToken = dt.ToString().Replace("<", "").Replace(">", "").Replace(" ", "");
if (string.IsNullOrEmpty(oldDeviceToken) || !deviceToken.Equals(newDeviceToken))
{
//TODO: Put your own logic here to notify your server that the device token has changed/been created!
}
//Save device token now
NSUserDefaults.StandardUserDefaults.SetString(newDeviceToken, "PushDeviceToken");
Console.WriteLine("Device Token: " + newDeviceToken);
}
public override void FailedToRegisterForRemoteNotifications (UIApplication application, NSError error)
{
Console.WriteLine("Failed to register for notifications");
}
public override void ReceivedRemoteNotification (UIApplication application, NSDictionary userInfo)
{
Console.WriteLine("Received Remote Notification!");
}
}
}
| apache-2.0 | C# |
05463364468de3cec8b8e7d45f4634f781607410 | Remove Dead Code in Peer | HelloKitty/GladNet2,HelloKitty/GladNet2.0,HelloKitty/GladNet2,HelloKitty/GladNet2.0 | src/GladNet.Common/Network/Peer/Peer.cs | src/GladNet.Common/Network/Peer/Peer.cs | using Logging.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace GladNet.Common
{
public abstract class Peer : INetPeer, IClassLogger
{
/// <summary>
/// Peer's service for sending network messages.
/// Use Extension methods or specific types for an neater API.
/// </summary>
public INetworkMessageSender NetworkSendService { get; private set; }
/// <summary>
/// Provides access to various connection related details for a this given Pee's connection.
/// </summary>
public IConnectionDetails PeerDetails { get; private set; }
public ILogger Logger { get; private set; }
protected Peer(ILogger logger, INetworkMessageSender messageSender, IConnectionDetails details)
{
logger.ThrowIfNull(nameof(logger));
messageSender.ThrowIfNull(nameof(messageSender));
details.ThrowIfNull(nameof(details));
PeerDetails = details;
NetworkSendService = messageSender;
Logger = logger;
}
protected abstract void OnStatusChanged(NetStatus status);
public virtual bool CanSend(OperationType opType)
{
return false;
}
}
}
| using Logging.Services;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
namespace GladNet.Common
{
public abstract class Peer : INetPeer, IClassLogger
{
public INetworkMessageSender NetworkSendService { get; private set; }
/// <summary>
/// Provides access to various connection related details for a this given Pee's connection.
/// </summary>
public IConnectionDetails PeerDetails { get; private set; }
public ILogger Logger { get; private set; }
protected Peer(ILogger logger, INetworkMessageSender messageSender, IConnectionDetails details)
{
logger.ThrowIfNull(nameof(logger));
messageSender.ThrowIfNull(nameof(messageSender));
details.ThrowIfNull(nameof(details));
PeerDetails = details;
NetworkSendService = messageSender;
Logger = logger;
}
/*#region Message Senders
//The idea here is we return invalids because sometimes a Peer can't send a certain message type.
//In most cases external classes shouldn't be interfacing with this class in this fashion.
//They should instead used more explict send methods. However, this exists to allow for
//users to loosely couple their senders as best they can though they really shouldn't since
//it can't be known if the runetime Peer type offers that functionality.
[SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")]
public virtual SendResult TrySendMessage(OperationType opType, PacketPayload payload, DeliveryMethod deliveryMethod, bool encrypt = false, byte channel = 0)
{
payload.ThrowIfNull(nameof(payload));
//TODO: Implement logging.
if (!CanSend(opType))
return SendResult.Invalid;
return NetworkSendService.TrySendMessage(opType, payload, deliveryMethod, encrypt, channel); //ncrunch: no coverage Reason: The line doesn't have to be tested. This is abstract and can be overidden.
}
//This is non-virtual because it should mirror non-generic methods functionality. It makes no sense to change them individually.
public SendResult TrySendMessage<TPacketType>(OperationType opType, TPacketType payload) where TPacketType : PacketPayload, IStaticPayloadParameters
{
payload.ThrowIfNull(nameof(payload));
return TrySendMessage(opType, payload, payload.DeliveryMethod, payload.Encrypted, payload.Channel);
}
#endregion*/
protected abstract void OnStatusChanged(NetStatus status);
public virtual bool CanSend(OperationType opType)
{
return false;
}
}
}
| bsd-3-clause | C# |
63ff8d4a4d1319caf43ae8afefb54ea7e7285cf2 | Make Shuffle() returns IList to avoid delayed execution. | AIWolfSharp/AIWolf_NET | AIWolfLib/ShuffleExtensions.cs | AIWolfLib/ShuffleExtensions.cs | //
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたIListを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたTのIList</returns>
#else
/// <summary>
/// Returns shuffled IList of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IList of T.</returns>
#endif
public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList();
}
}
| //
// ShuffleExtensions.cs
//
// Copyright (c) 2017 Takashi OTSUKI
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
using System;
using System.Collections.Generic;
using System.Linq;
namespace AIWolf.Lib
{
#if JHELP
/// <summary>
/// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義
/// </summary>
#else
/// <summary>
/// Defines extension method to shuffle what implements IEnumerable interface.
/// </summary>
#endif
public static class ShuffleExtensions
{
#if JHELP
/// <summary>
/// IEnumerableをシャッフルしたものを返す
/// </summary>
/// <typeparam name="T">IEnumerableの要素の型</typeparam>
/// <param name="s">TのIEnumerable</param>
/// <returns>シャッフルされたIEnumerable</returns>
#else
/// <summary>
/// Returns shuffled IEnumerable of T.
/// </summary>
/// <typeparam name="T">Type of element of IEnumerable.</typeparam>
/// <param name="s">IEnumerable of T.</param>
/// <returns>Shuffled IEnumerable of T.</returns>
#endif
public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid());
}
}
| mit | C# |
650ae83222c393d4ef266875e58324dfaa45241f | Fix tests | sboulema/CodeNav,sboulema/CodeNav | CodeNav.Tests/MapperTests/TestInterface.cs | CodeNav.Tests/MapperTests/TestInterface.cs | using System;
using System.IO;
using System.Linq;
using CodeNav.Mappers;
using CodeNav.Models;
using NUnit.Framework;
namespace CodeNav.Tests.MapperTests
{
[TestFixture]
public class TestInterface
{
[Test]
public void TestInterfaceShouldBeOk()
{
var document = SyntaxMapper.MapDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\Files\\TestInterface.cs"));
Assert.IsTrue(document.Any());
// First item should be a namespace
Assert.AreEqual(CodeItemKindEnum.Namespace, document.First().Kind);
// Namespace item should have 2 members
Assert.AreEqual(2, (document.First() as IMembers).Members.Count);
// First item should be an interface
var innerInterface = (document.First() as IMembers).Members.First() as CodeInterfaceItem;
Assert.AreEqual(3, innerInterface.Members.Count);
Assert.IsTrue(innerInterface.IconPath.Contains("Interface"));
// Second item should be the implementing class
var implementingClass = (document.First() as IMembers).Members.Last() as CodeClassItem;
Assert.AreEqual(CodeItemKindEnum.Class, implementingClass.Kind);
Assert.AreEqual(3, implementingClass.Members.Count);
var implementedInterface = implementingClass.Members.Last() as CodeImplementedInterfaceItem;
Assert.AreEqual(CodeItemKindEnum.ImplementedInterface, implementedInterface.Kind);
Assert.AreEqual(3, implementedInterface.Members.Count);
// Items shoud be properly replaced
Assert.AreEqual(12, implementedInterface.Members[0].StartLine);
Assert.AreEqual(17, implementedInterface.Members[1].StartLine);
Assert.AreEqual(34, implementedInterface.Members[2].StartLine);
}
}
}
| using System;
using System.IO;
using System.Linq;
using CodeNav.Mappers;
using CodeNav.Models;
using NUnit.Framework;
namespace CodeNav.Tests.MapperTests
{
[TestFixture]
public class TestInterface
{
[Test]
public void TestInterfaceShouldBeOk()
{
var document = SyntaxMapper.MapDocument(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..\\..\\Files\\TestInterface.cs"));
Assert.IsTrue(document.Any());
// First item should be a namespace
Assert.AreEqual(CodeItemKindEnum.Namespace, document.First().Kind);
// Namespace item should have 2 members
Assert.AreEqual(2, (document.First() as IMembers).Members.Count);
// First item should be an interface
var innerInterface = (document.First() as IMembers).Members.First() as CodeInterfaceItem;
Assert.AreEqual(3, innerInterface.Members.Count);
Assert.IsTrue(innerInterface.IconPath.Contains("Interface"));
// Second item should be the implementing class
var implementingClass = (document.First() as IMembers).Members.Last() as CodeClassItem;
Assert.AreEqual(CodeItemKindEnum.Class, implementingClass.Kind);
Assert.AreEqual(3, implementingClass.Members.Count);
var implementedInterface = implementingClass.Members.Last() as CodeInterfaceItem;
Assert.AreEqual(CodeItemKindEnum.ImplementedInterface, implementedInterface.Kind);
Assert.AreEqual(3, implementedInterface.Members.Count);
// Items shoud be properly replaced
Assert.AreEqual(12, implementedInterface.Members[0].StartLine);
Assert.AreEqual(17, implementedInterface.Members[1].StartLine);
Assert.AreEqual(34, implementedInterface.Members[2].StartLine);
}
}
}
| mit | C# |
56eb272a7e6de491cfef8b4bd35a67f33bb0556a | Break the build | webcanvas/ConfigLoader | ConfigLoader.UnitTests/AppSettingsTests.cs | ConfigLoader.UnitTests/AppSettingsTests.cs | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfigLoader.UnitTests
{
[TestFixture]
public class AppSettingsTests
{
[Test]
public void CanLoadFromAppConfig()
{
// We have some conventions at play.
// IE.. if it looks like a database then load it from the connection strings.
// lets get the configuration values.
var config = ConfigLoader.LoadConfig<TestConfig>();
Assert.IsNotNull(config);
Assert.AreEqual("something!", config.DB);
Assert.AreEqual("something!!", config.DBDriver);
}
}
}
| using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConfigLoader.UnitTests
{
//[TestFixture]
//public class AppSettingsTests
//{
// [Test]
// public void CanLoadFromAppConfig()
// {
// // We have some conventions at play.
// // IE.. if it looks like a database then load it from the connection strings.
// // lets get the configuration values.
// var config = ConfigLoader.LoadConfig<TestConfig>();
// Assert.IsNotNull(config);
// Assert.AreEqual("something!", config.DB);
// Assert.AreEqual("something!!", config.DBDriver);
// }
//}
}
| mit | C# |
c60481f655c11b75b8eb74bf66076e951f12c7c2 | Add comments for internal API. | msgpack/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,scopely/msgpack-cli,scopely/msgpack-cli,modulexcite/msgpack-cli | cli/src/MsgPack/Serialization/SerializationMethodGeneratorOption.cs | cli/src/MsgPack/Serialization/SerializationMethodGeneratorOption.cs | #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
using System.ComponentModel;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// It is intended for the runtime, you cannot use this option.
/// </summary>
[EditorBrowsable( EditorBrowsableState.Never )]
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
| #region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
using System;
namespace MsgPack.Serialization
{
/// <summary>
/// Define options of <see cref="SerializationMethodGeneratorManager"/>
/// </summary>
public enum SerializationMethodGeneratorOption
{
#if !SILVERLIGHT
/// <summary>
/// The generated method IL can be dumped to the current directory.
/// </summary>
CanDump,
/// <summary>
/// The entire generated method can be collected by GC when it is no longer used.
/// </summary>
CanCollect,
#endif
/// <summary>
/// Prefer performance. This options is default.
/// </summary>
Fast
}
}
| apache-2.0 | C# |
2a3986fb75b415a33db560951d72f994d12bf5ac | Define private method Game#LetterWasGuessed | 12joan/hangman | game.cs | game.cs | using System;
using System.Collections.Generic;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
}
public string ShownWord() {
return Word;
}
private bool LetterWasGuessed(char letter) {
return GuessedLetters.Contains(letter);
}
}
}
| using System;
using System.Collections.Generic;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
}
public string ShownWord() {
return Word;
}
}
}
| unlicense | C# |
df980ec10930485d6a200077add66be4d87ccdbf | fix crash | Tlaster/iHentai | src/iHentai/Platform/PlatformService.cs | src/iHentai/Platform/PlatformService.cs | using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.AccessCache;
namespace iHentai.Platform
{
internal class PlatformService : IPlatformService
{
public string LocalPath => ApplicationData.Current.LocalFolder.Path;
public async Task<IFolderItem?> GetFolder(string token)
{
var folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
if (folder == null)
{
return null;
}
return new PathFolderItem(folder.Path, token, folder.DateCreated.DateTime);
}
public async Task<IFolderItem?> GetFolderFromPath(string path, string token)
{
var folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
if (folder == null)
{
return null;
}
return new PathFolderItem(path, token, folder.DateCreated.DateTime);
}
public async Task<IFolderItem?> GetFolderFromPath(string path)
{
try
{
var folder = await StorageFolder.GetFolderFromPathAsync(path);
return new FolderItem(folder, "");
}
catch (Exception)
{
return null;
}
}
}
} | using System;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.AccessCache;
namespace iHentai.Platform
{
internal class PlatformService : IPlatformService
{
public string LocalPath => ApplicationData.Current.LocalFolder.Path;
public async Task<IFolderItem?> GetFolder(string token)
{
var folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
if (folder == null)
{
return null;
}
return new PathFolderItem(folder.Path, token, folder.DateCreated.DateTime);
}
public async Task<IFolderItem?> GetFolderFromPath(string path, string token)
{
var folder = await StorageApplicationPermissions.FutureAccessList.GetFolderAsync(token);
if (folder == null)
{
return null;
}
return new PathFolderItem(path, token, folder.DateCreated.DateTime);
}
public async Task<IFolderItem?> GetFolderFromPath(string path)
{
var folder = await StorageFolder.GetFolderFromPathAsync(path);
return new FolderItem(folder, "");
}
}
} | mit | C# |
d1c9c242c1b531a626569615a9eeb7235db91f40 | Add method for getting Language from tag | api-ai/api-ai-net,IntranetFactory/api-ai-net,dialogflow/dialogflow-dotnet-client,api-ai/api-ai-net,dialogflow/dialogflow-dotnet-client | ApiAiSDK/SupportedLanguage.cs | ApiAiSDK/SupportedLanguage.cs | //
// API.AI .NET SDK - client-side libraries for API.AI
// =================================================
//
// Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
// https://www.api.ai
//
// ***********************************************************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
// ***********************************************************************************************************************
using System;
namespace ApiAiSDK
{
/// <summary>
/// List of the the languages, supported by API.AI service
/// </summary>
public class SupportedLanguage
{
public static readonly SupportedLanguage English = new SupportedLanguage("en");
public static readonly SupportedLanguage Russian = new SupportedLanguage("ru");
public static readonly SupportedLanguage German = new SupportedLanguage("de");
public static readonly SupportedLanguage Portuguese = new SupportedLanguage("pt");
public static readonly SupportedLanguage PortugueseBrazil = new SupportedLanguage("pt-BR");
public static readonly SupportedLanguage Spanish = new SupportedLanguage("es");
public static readonly SupportedLanguage French = new SupportedLanguage("fr");
public static readonly SupportedLanguage Italian = new SupportedLanguage("it");
public static readonly SupportedLanguage Japanese = new SupportedLanguage("ja");
public static readonly SupportedLanguage ChineseChina = new SupportedLanguage("zh-CN");
public static readonly SupportedLanguage ChineseHongKong = new SupportedLanguage("zh-HK");
public static readonly SupportedLanguage ChineseTaiwan = new SupportedLanguage("zh-TW");
private static readonly SupportedLanguage[] AllLangs =
{
English,
Russian,
German,
Portuguese,
PortugueseBrazil,
Spanish,
French,
Italian,
Japanese,
ChineseChina,
ChineseHongKong,
ChineseTaiwan
};
public readonly string code;
private SupportedLanguage(string code)
{
this.code = code;
}
public static SupportedLanguage FromLanguageTag(string languageTag)
{
foreach (var item in AllLangs)
{
if (string.Equals(item.code, languageTag, StringComparison.InvariantCultureIgnoreCase))
{
return item;
}
}
return English;
}
}
}
| //
// API.AI .NET SDK - client-side libraries for API.AI
// =================================================
//
// Copyright (C) 2015 by Speaktoit, Inc. (https://www.speaktoit.com)
// https://www.api.ai
//
// ***********************************************************************************************************************
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
// an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//
// ***********************************************************************************************************************
using System;
namespace ApiAiSDK
{
/// <summary>
/// List of the the languages, supported by API.AI service
/// </summary>
public class SupportedLanguage
{
public static readonly SupportedLanguage English = new SupportedLanguage("en");
public static readonly SupportedLanguage Russian = new SupportedLanguage("ru");
public static readonly SupportedLanguage German = new SupportedLanguage("de");
public static readonly SupportedLanguage Portuguese = new SupportedLanguage("pt");
public static readonly SupportedLanguage PortugueseBrazil = new SupportedLanguage("pt-BR");
public static readonly SupportedLanguage Spanish = new SupportedLanguage("es");
public static readonly SupportedLanguage French = new SupportedLanguage("fr");
public static readonly SupportedLanguage Italian = new SupportedLanguage("it");
public static readonly SupportedLanguage Japanese = new SupportedLanguage("ja");
public static readonly SupportedLanguage ChineseChina = new SupportedLanguage("zh-CN");
public static readonly SupportedLanguage ChineseHongKong = new SupportedLanguage("zh-HK");
public static readonly SupportedLanguage ChineseTaiwan = new SupportedLanguage("zh-TW");
public readonly string code;
private SupportedLanguage(string code)
{
this.code = code;
}
}
}
| apache-2.0 | C# |
d4e3a2ae0897c6cd24ce061ce8713334c7369f02 | update trigger text to fade based on time and not number of frames | spencewenski/Vision | Assets/Scripts/TriggerText.cs | Assets/Scripts/TriggerText.cs | using UnityEngine;
using System.Collections;
public class TriggerText : MonoBehaviour {
public float displaySec = 5f;
public float fadeSec = 1f;
public bool _______________;
public enum DisplayState_e { FADE_IN, VISIBLE, FADE_OUT };
public DisplayState_e state;
public float displayTimeRemaining;
public float fadeTimeRemaining;
public CanvasRenderer textRenderer;
// Use this for initialization
void Start () {
textRenderer = GetComponent<CanvasRenderer>();
fadeTimeRemaining = fadeSec;
state = DisplayState_e.FADE_IN;
textRenderer.SetAlpha(0);
}
// Update is called once per frame
void Update () {
switch (state) {
case DisplayState_e.FADE_IN:
fadeIn();
return;
case DisplayState_e.VISIBLE:
visible();
return;
case DisplayState_e.FADE_OUT:
fadeOut();
return;
default:
print("TriggerText.Update(): invalid state");
return;
}
}
private void fadeIn() {
fadeTimeRemaining = Utility.updateTimeRemaining(fadeTimeRemaining);
if (fadeTimeRemaining <= 0) {
displayTimeRemaining = displaySec;
state = DisplayState_e.VISIBLE;
textRenderer.SetAlpha(1);
return;
}
textRenderer.SetAlpha((fadeSec - fadeTimeRemaining) / fadeSec);
}
private void visible() {
displayTimeRemaining = Utility.updateTimeRemaining(displayTimeRemaining);
if (displayTimeRemaining <= 0) {
fadeTimeRemaining = fadeSec;
state = DisplayState_e.FADE_OUT;
return;
}
}
private void fadeOut() {
fadeTimeRemaining = Utility.updateTimeRemaining(fadeTimeRemaining);
if (fadeTimeRemaining <= 0) {
Destroy(gameObject);
}
textRenderer.SetAlpha(fadeTimeRemaining / fadeSec);
}
}
| using UnityEngine;
using System.Collections;
public class TriggerText : MonoBehaviour {
public float displaySec = 5f;
public float fadeSec = 1f;
private float displayFrames;
private float fadeInFrames = 0;
private float fadeOutFrames;
private float fadeTotalFrames;
private CanvasRenderer textRenderer;
// Use this for initialization
void Start () {
displayFrames = displaySec / Time.fixedDeltaTime;
fadeOutFrames = fadeSec / Time.fixedDeltaTime;
fadeTotalFrames = fadeSec / Time.fixedDeltaTime;
textRenderer = GetComponent<CanvasRenderer>();
textRenderer.SetAlpha(0);
}
// Update is called once per frame
void Update () {
++fadeInFrames;
if (fadeInFrames <= fadeTotalFrames)
{
textRenderer.SetAlpha(fadeInFrames / fadeTotalFrames);
}
--displayFrames;
if (displayFrames <= 0)
{
--fadeOutFrames;
textRenderer.SetAlpha(fadeOutFrames / fadeTotalFrames);
if (fadeOutFrames <= 0)
{
Destroy(gameObject);
}
}
}
}
| mit | C# |
3ea31d1ac99c6d14d7e8bd77294b7094af07c2d6 | Update DateTimeExtensions.cs | keith-hall/Extensions,keith-hall/Extensions | src/DateTimeExtensions.cs | src/DateTimeExtensions.cs | using System;
namespace HallLibrary.Extensions
{
/// <summary>
/// Contains extension methods for working with <see cref="DateTime" />s.
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in ISO-8601 format.
/// </summary>
/// <param name="dt">The date to convert.</param>
/// <param name="withT">Whether or not to include the 'T' in the output. If false, a space will be used instead.</param>
/// <returns>An ISO-8601 formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns>
public static string ToISO8601String(this DateTime dt, bool withT)
{
return dt.ToString(
dt.ToSortableDateTime()
.Replace(@" ", withT ? @"'T'" : @" ")
+ @"'" + TimeZoneString(dt) + @"'"
, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in a universal sortable format.
/// </summary>
/// <param name="dt">The date to convert.</param>
/// <returns>A sortable formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns>
public static string ToSortableDateTime (this DateTime dt) {
return Thread.CurrentThread.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern
.Replace(@"Z'", @".'fff");
}
/// <summary>
/// Gets the local time zone offset <see cref="String"/> from UTC for the specified <see cref="DateTime"/>.
/// </summary>
/// <param name="dt">The date to get the local timezone offset <see cref="String"/> for.</param>
/// <returns>A <see cref="String"/> representation of the local timezone offset for the specified <see cref="DateTime"/>.</returns>
public static string TimeZoneString (this DateTime dt) {
if (dt.Kind == DateTimeKind.Utc)
return @"Z";
var diff = System.TimeZoneInfo.Local.BaseUtcOffset;
var hours = diff.Hours;
if (System.TimeZoneInfo.Local.IsDaylightSavingTime(dt))
hours += 1;
return (hours > 0 ? @"+" : string.Empty) + hours.ToString(@"00")
+ @":" + diff.Minutes.ToString(@"00");
}
/// <summary>
/// Convert the specified <see cref="DateTime"/> from UTC to the Local timezone.
/// </summary>
/// <param name="dt">The date to convert to local time.</param>
/// <returns>The specified UTC <see cref="DateTime"/> converted to the Local timezone.</returns>
public static DateTime FromUniversalTime (this DateTime dt) {
if (dt.Kind == DateTimeKind.Local)
return dt;
return System.TimeZoneInfo.ConvertTimeFromUtc(dt, System.TimeZoneInfo.Local);
}
}
}
| /// <summary>
/// Contains extension methods for working with <see cref="DateTime" />s.
/// </summary>
public static class DateTimeExtensions
{
/// <summary>
/// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in ISO-8601 format.
/// </summary>
/// <param name="dt">The date to convert.</param>
/// <param name="withT">Whether or not to include the 'T' in the output. If false, a space will be used instead.</param>
/// <returns>An ISO-8601 formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns>
public static string ToISO8601String(this DateTime dt, bool withT)
{
return dt.ToString(
dt.ToSortableDateTime()
.Replace(@" ", withT ? @"'T'" : @" ")
+ @"'" + TimeZoneString(dt) + @"'"
, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts the specified <see cref="DateTime"/> to a <see cref="String"/>, in a universal sortable format.
/// </summary>
/// <param name="dt">The date to convert.</param>
/// <returns>A sortable formatted <see cref="String"/> representation of the specified <see cref="DateTime"/>.</returns>
public static string ToSortableDateTime (this DateTime dt) {
return Thread.CurrentThread.CurrentCulture.DateTimeFormat.UniversalSortableDateTimePattern
.Replace(@"Z'", @".'fff");
}
/// <summary>
/// Gets the local time zone offset <see cref="String"/> from UTC for the specified <see cref="DateTime"/>.
/// </summary>
/// <param name="dt">The date to get the local timezone offset <see cref="String"/> for.</param>
/// <returns>A <see cref="String"/> representation of the local timezone offset for the specified <see cref="DateTime"/>.</returns>
public static string TimeZoneString (this DateTime dt) {
if (dt.Kind == DateTimeKind.Utc)
return @"Z";
var diff = System.TimeZoneInfo.Local.BaseUtcOffset;
var hours = diff.Hours;
if (System.TimeZoneInfo.Local.IsDaylightSavingTime(dt))
hours += 1;
return (hours > 0 ? @"+" : string.Empty) + hours.ToString(@"00")
+ @":" + diff.Minutes.ToString(@"00");
}
/// <summary>
/// Convert the specified <see cref="DateTime"/> from UTC to the Local timezone.
/// </summary>
/// <param name="dt">The date to convert to local time.</param>
/// <returns>The specified UTC <see cref="DateTime"/> converted to the Local timezone.</returns>
public static DateTime FromUniversalTime (this DateTime dt) {
if (dt.Kind == DateTimeKind.Local)
return dt;
return System.TimeZoneInfo.ConvertTimeFromUtc(dt, System.TimeZoneInfo.Local);
}
}
| apache-2.0 | C# |
9900d747bf250ebd0728c7c8c9c02643908689da | Fix build error | InfiniteSoul/Azuria | Azuria/ProxerClientOptions.cs | Azuria/ProxerClientOptions.cs | using System;
using Autofac;
using Azuria.Connection;
namespace Azuria
{
/// <summary>
///
/// </summary>
public class ProxerClientOptions
{
/// <summary>
///
/// </summary>
public ProxerClientOptions()
{
RegisterComponents(this.ContainerBuilder);
}
#region Properties
internal ContainerBuilder ContainerBuilder { get; set; } = new ContainerBuilder();
#endregion
#region Methods
private static void RegisterComponents(ContainerBuilder builder)
{
builder.RegisterInstance(new HttpClient()).As<IHttpClient>();
//builder.RegisterInstance(new LoginManager()).As<ILoginManager>();
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public ProxerClientOptions WithCustomHttpClient(IHttpClient client)
{
if (client == null) throw new ArgumentNullException(nameof(client));
this.ContainerBuilder.RegisterInstance(client);
return this;
}
/// <summary>
///
/// </summary>
/// <param name="timeout"></param>
/// <param name="userAgentExtra"></param>
/// <returns></returns>
public ProxerClientOptions WithCustomHttpClient(int timeout = 5000, string userAgentExtra = "")
{
this.ContainerBuilder.RegisterInstance(new HttpClient(timeout, userAgentExtra)).As<IHttpClient>();
return this;
}
#endregion
}
} | using System;
using Autofac;
using Azuria.Authentication;
using Azuria.Connection;
namespace Azuria
{
/// <summary>
///
/// </summary>
public class ProxerClientOptions
{
/// <summary>
///
/// </summary>
public ProxerClientOptions()
{
RegisterComponents(this.ContainerBuilder);
}
#region Properties
internal ContainerBuilder ContainerBuilder { get; set; } = new ContainerBuilder();
#endregion
#region Methods
private static void RegisterComponents(ContainerBuilder builder)
{
builder.RegisterInstance(new HttpClient()).As<IHttpClient>();
builder.RegisterInstance(new LoginManager()).As<ILoginManager>();
}
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <returns></returns>
public ProxerClientOptions WithCustomHttpClient(IHttpClient client)
{
if (client == null) throw new ArgumentNullException(nameof(client));
this.ContainerBuilder.RegisterInstance(client);
return this;
}
/// <summary>
///
/// </summary>
/// <param name="timeout"></param>
/// <param name="userAgentExtra"></param>
/// <returns></returns>
public ProxerClientOptions WithCustomHttpClient(int timeout = 5000, string userAgentExtra = "")
{
this.ContainerBuilder.RegisterInstance(new HttpClient(timeout, userAgentExtra)).As<IHttpClient>();
return this;
}
#endregion
}
} | mit | C# |
8e3eaf9266c3e84f68dc0e07c472ffeb0a9b2c60 | Fix proper charset value in html part of message. | mios-fi/mios.mail.templating | Library/RazorEmailTemplate.cs | Library/RazorEmailTemplate.cs | using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
namespace Mios.Mail.Templating {
public class RazorEmailTemplate<T> : IEmailTemplate<T> {
private readonly RazorTemplate<T> subjectTemplate;
private readonly RazorTemplate<T> textTemplate;
private readonly RazorTemplate<T> htmlTemplate;
public RazorEmailTemplate(RazorTemplate<T> subjectTemplate, RazorTemplate<T> textTemplate, RazorTemplate<T> htmlTemplate) {
if(subjectTemplate == null) throw new ArgumentNullException("subjectTemplate");
if(textTemplate == null) throw new ArgumentNullException("textTemplate");
this.subjectTemplate = subjectTemplate;
this.textTemplate = textTemplate;
this.htmlTemplate = htmlTemplate;
}
public MailMessage Transform(T model) {
var message = new MailMessage {
Subject = subjectTemplate.Execute(model),
Body = textTemplate.Execute(model)
};
if(htmlTemplate!=null) {
var htmlBody = htmlTemplate.Execute(model);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlBody));
var htmlView = new AlternateView(stream, new ContentType("text/html") { CharSet = "utf-8" });
message.AlternateViews.Add(htmlView);
}
return message;
}
public MailMessage Transform(T model, MailAddress to, MailAddress from) {
var message = Transform(model);
message.To.Add(to);
message.From = from;
return message;
}
}
} | using System;
using System.IO;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
namespace Mios.Mail.Templating {
public class RazorEmailTemplate<T> : IEmailTemplate<T> {
private readonly RazorTemplate<T> subjectTemplate;
private readonly RazorTemplate<T> textTemplate;
private readonly RazorTemplate<T> htmlTemplate;
public RazorEmailTemplate(RazorTemplate<T> subjectTemplate, RazorTemplate<T> textTemplate, RazorTemplate<T> htmlTemplate) {
if(subjectTemplate == null) throw new ArgumentNullException("subjectTemplate");
if(textTemplate == null) throw new ArgumentNullException("textTemplate");
this.subjectTemplate = subjectTemplate;
this.textTemplate = textTemplate;
this.htmlTemplate = htmlTemplate;
}
public MailMessage Transform(T model) {
var message = new MailMessage {
Subject = subjectTemplate.Execute(model),
Body = textTemplate.Execute(model)
};
if(htmlTemplate!=null) {
var htmlBody = htmlTemplate.Execute(model);
var stream = new MemoryStream(Encoding.UTF8.GetBytes(htmlBody));
var htmlView = new AlternateView(stream, new ContentType("text/html") { CharSet = "utf8" });
message.AlternateViews.Add(htmlView);
}
return message;
}
public MailMessage Transform(T model, MailAddress to, MailAddress from) {
var message = Transform(model);
message.To.Add(to);
message.From = from;
return message;
}
}
} | bsd-2-clause | C# |
7d92d542e9f218240f967b0c8b461dd25839e583 | Change to use UIScreen.Scale to detect HD content. | hig-ag/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,zmaruo/CocosSharp,MSylvia/CocosSharp,hig-ag/CocosSharp,mono/CocosSharp,netonjm/CocosSharp,netonjm/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp | Samples/GoneBananasiOS/GoneBananasiOS/GoneBananasApplication.cs | Samples/GoneBananasiOS/GoneBananasiOS/GoneBananasApplication.cs | using CocosDenshion;
using CocosSharp;
using Microsoft.Xna.Framework;
using MonoTouch.UIKit;
namespace GoneBananas
{
public class GoneBananasApplication : CCApplication
{
public GoneBananasApplication (Game game, GraphicsDeviceManager graphics = null)
: base (game, graphics)
{
// Set our supported orientations for those that can use them
SupportedOrientations = CCDisplayOrientation.Portrait;
}
public override bool ApplicationDidFinishLaunching ()
{
//initialize director
CCDirector director = CCDirector.SharedDirector;
// turn on display FPS
director.DisplayStats = true;
// set FPS. the default value is 1.0/60 if you don't call this
director.AnimationInterval = 1.0 / 60;
// We will setup our Design Resolution here
if (UIScreen.MainScreen.Scale > 1.0)
{
CCContentManager.SharedContentManager.SearchPaths.Add("hd");
}
CCScene scene = GameStartLayer.Scene;
director.RunWithScene (scene);
// returning true indicates the app initialized successfully and can continue
return true;
}
public override void ApplicationDidEnterBackground ()
{
// stop all of the animation actions that are running.
CCDirector.SharedDirector.Pause ();
// if you use SimpleAudioEngine, your music must be paused
CCSimpleAudioEngine.SharedEngine.PauseBackgroundMusic ();
}
public override void ApplicationWillEnterForeground ()
{
CCDirector.SharedDirector.Resume ();
// if you use SimpleAudioEngine, your background music track must resume here.
CCSimpleAudioEngine.SharedEngine.ResumeBackgroundMusic ();
}
}
} | using Microsoft.Xna.Framework;
using CocosDenshion;
using CocosSharp;
namespace GoneBananas
{
public class GoneBananasApplication : CCApplication
{
public GoneBananasApplication (Game game, GraphicsDeviceManager graphics = null)
: base (game, graphics)
{
// Set our supported orientations for those that can use them
SupportedOrientations = CCDisplayOrientation.Portrait;
}
public override bool ApplicationDidFinishLaunching ()
{
//initialize director
CCDirector director = CCDirector.SharedDirector;
// turn on display FPS
director.DisplayStats = true;
// set FPS. the default value is 1.0/60 if you don't call this
director.AnimationInterval = 1.0 / 60;
// We will setup our Design Resolution here
if (CCDrawManager.FrameSize.Height > 480)
{
CCContentManager.SharedContentManager.SearchPaths.Add("hd");
}
CCScene scene = GameStartLayer.Scene;
director.RunWithScene (scene);
// returning true indicates the app initialized successfully and can continue
return true;
}
public override void ApplicationDidEnterBackground ()
{
// stop all of the animation actions that are running.
CCDirector.SharedDirector.Pause ();
// if you use SimpleAudioEngine, your music must be paused
CCSimpleAudioEngine.SharedEngine.PauseBackgroundMusic ();
}
public override void ApplicationWillEnterForeground ()
{
CCDirector.SharedDirector.Resume ();
// if you use SimpleAudioEngine, your background music track must resume here.
CCSimpleAudioEngine.SharedEngine.ResumeBackgroundMusic ();
}
}
} | mit | C# |
9529440fd09cf3074d7914b770a99948492356c2 | add graphic | Syntronian/cbabb,Syntronian/cbabb | source/CBA/Views/Home/Results.cshtml | source/CBA/Views/Home/Results.cshtml | @model CBA.Models.BuyBuddie.Search
@{
ViewBag.Title = "CBA Travel Companion";
}
<header class="bar bar-nav">
@{ Html.BeginForm("Index", "Home", FormMethod.Get); }
<button class="btn btn-link btn-nav pull-left">
<span class="icon icon-left-nav"></span>
</button>
@{ Html.EndForm(); }
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")" /></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
@if (ViewBag.Error != null)
{
<p>ViewBag.Error</p>
}
<div class="content-padded">
<div class="pull-left">
<img src="http://buybuddie.com.au/Content/bb/img/bb-gray.gif" alt="0">
</div>
<div class="pull-left" style="margin-left: 40px;">
<h3>
Issues
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Message))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Message))</p> }
}
<h3 style="margin-top: 40px;">
Solutions
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Solution))
{ <p>@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Solution))</p> }
}
</div>
</div>
</div>
| @model CBA.Models.BuyBuddie.Search
@{
ViewBag.Title = "CBA Travel Companion";
}
<header class="bar bar-nav">
@{ Html.BeginForm("Index", "Home", FormMethod.Get); }
<button class="btn btn-link btn-nav pull-left">
<span class="icon icon-left-nav"></span>
</button>
@{ Html.EndForm(); }
<h1 class="title"><img src="@Url.Content("~/assets/img/cba-logo.png")" /></h1>
</header>
<nav class="bar bar-tab">
<a class="tab-item" href="@Url.Action("Index")">
<span class="icon icon-home"></span>
<span class="tab-label">Home</span>
</a>
<a class="tab-item" href="#">
<span class="icon icon-gear"></span>
<span class="tab-label">Settings</span>
</a>
</nav>
<div class="content">
@if (ViewBag.Error != null)
{
<p>ViewBag.Error</p>
}
<h3 class="content-padded">
Issues
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Message))
{ <p class="content-padded">@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Message))</p> }
}
<h3 class="content-padded" style="margin-top: 40px;">
Solutions
</h3>
@foreach (var issue in Model.Issues)
{
if (!string.IsNullOrEmpty(issue.Solution))
{ <p class="content-padded">@Html.Raw(CBA.Helpers.HTML.WithActiveLinks(issue.Solution))</p> }
}
</div>
| mit | C# |
362780159ccd141f59fae2226c1c4df5fd41fb36 | build fix | DigDes/SoapCore | src/SoapCore.Tests/Models.cs | src/SoapCore.Tests/Models.cs | using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace SoapCore.Tests
{
[DataContract]
public class ComplexModelInput
{
[DataMember]
public string StringProperty { get; set; }
[DataMember]
public int IntProperty { get; set; }
[DataMember]
public List<string> ListProperty { get; set; }
[DataMember]
public DateTimeOffset DateTimeOffsetProperty { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace SoapCore.Tests
{
[DataContract]
public class ComplexModelInput
{
[DataMember]
public string StringProperty { get; set; }
[DataMember]
public int IntProperty { get; set; }
[DataMember]
public List<string> ListProperty { get; set; }
}
}
| mit | C# |
8cf59a74df6467dca844019b681eb7be21999b6b | update version number | hillin/ue4launcher | ProjectLauncher/Properties/AssemblyInfo.cs | ProjectLauncher/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("ProjectLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProjectLauncher")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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.170")]
[assembly: AssemblyFileVersion("1.5.0.170")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("ProjectLauncher")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ProjectLauncher")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.4.2.148")]
[assembly: AssemblyFileVersion("1.4.2.148")]
| apache-2.0 | C# |
66c0e101d7e02d859629e9ea62737bf23d358bd0 | set output folder | PaintLab/SaveAsPdf | src/TestHelloDom1/Program.cs | src/TestHelloDom1/Program.cs | //Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
using System.IO;
using Fonet;
using PixelFarm.Drawing.Pdf;
namespace FonetExample
{
//hello dom sample
class HelloWorld
{
static void Main(string[] args)
{
MyPdfDocument pdfdoc = new MyPdfDocument();
//1. create new page and append to doc
MyPdfPage page = pdfdoc.CreatePage();
pdfdoc.Pages.Add(page);
//2. set page property
MyPdfCanvas canvas = page.Canvas;
canvas.DrawString("Hello World!, from PixelFarm", 20, 20);
//
FonetDriver driver = FonetDriver.Make();
driver.ImageHandler += str =>
{
return null;
};
string outputFilename = "bin\\output.pdf";
using (FileStream outputStream = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
{
driver.Render(pdfdoc, outputStream);
outputStream.Flush();
outputStream.Close();
}
}
}
} | //Apache2, 2017, WinterDev
//Apache2, 2009, griffm, FO.NET
using System.IO;
using Fonet;
using PixelFarm.Drawing.Pdf;
namespace FonetExample
{
//hello dom sample
class HelloWorld
{
static void Main(string[] args)
{
MyPdfDocument pdfdoc = new MyPdfDocument();
//1. create new page and append to doc
MyPdfPage page = pdfdoc.CreatePage();
pdfdoc.Pages.Add(page);
//2. set page property
//
MyPdfCanvas canvas = page.Canvas;
canvas.DrawString("Hello World!, from PixelFarm", 20, 20);
//
FonetDriver driver = FonetDriver.Make();
driver.ImageHandler += str =>
{
return null;
};
string outputFilename = "hello.pdf";
using (FileStream outputStream = new FileStream(outputFilename, FileMode.Create, FileAccess.Write))
{
driver.Render(pdfdoc, outputStream);
outputStream.Flush();
outputStream.Close();
}
}
}
} | apache-2.0 | C# |
52ec220aa6e13b18afa9279868a57ce19d750c08 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.59")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2018 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.0.58")] | mit | C# |
5125a8cd49fd886df9f8923a0b539e2fc26a41d0 | bump ver | AntonyCorbett/OnlyT,AntonyCorbett/OnlyT | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.3")] | using System.Reflection;
[assembly: AssemblyCompany("SoundBox")]
[assembly: AssemblyProduct("OnlyT")]
[assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.3.0.2")] | mit | C# |
bcf84e00a11b171773c7938dc79e316f34cb7b93 | Update _ZenDeskWidget.cshtml | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web/Views/Shared/_ZenDeskWidget.cshtml | src/SFA.DAS.EmployerAccounts.Web/Views/Shared/_ZenDeskWidget.cshtml | @using SFA.DAS.EmployerAccounts.Web.Extensions
<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>
@Html.SetZenDeskLabels(new string[] { ViewBag.ZenDeskLabel })
| @using SFA.DAS.EmployerAccounts.Web.Extensions
<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>
@Html.SetZenDeskLabels(new string[] { ViewBag.ZenDeskLabel })
@using SFA.DAS.EmployerAccounts.Web.Extensions
<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>
@Html.SetZenDeskLabels(!string.IsNullOrWhiteSpace(ViewBag.Title) ? new[] {$"reg-{ViewBag.Title}"} : new string[] {ViewBag.ZenDeskLabel})
<script type="text/javascript">
zE(function() {
zE.identify({
name: '@ViewBag.GaData.UserName',
email: '@ViewBag.GaData.UserEmail',
organization: '@ViewBag.GaData.Acc'
});
});
</script>
| mit | C# |
2a57171ea82b22ccbae0e005ec8b0940aeb46295 | Use new auth API | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | testapps/RazorPagesApp/Startup.cs | testapps/RazorPagesApp/Startup.cs | using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace RazorPagesApp
{
public class Startup : IDesignTimeMvcBuilderConfiguration
{
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.AddAuthentication().AddCookie(options => options.LoginPath = "/Login");
ConfigureMvc(builder);
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseAuthentication();
app.UseMvc();
}
public void ConfigureMvc(IMvcBuilder builder)
{
builder.AddRazorPagesOptions(options =>
{
options.RootDirectory = "/Pages";
options.Conventions.AuthorizeFolder("/Auth");
});
}
}
}
| using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace RazorPagesApp
{
public class Startup : IDesignTimeMvcBuilderConfiguration
{
public void ConfigureServices(IServiceCollection services)
{
var builder = services.AddMvc();
services.AddCookieAuthentication(options => options.LoginPath = "/Login");
ConfigureMvc(builder);
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
app.UseAuthentication();
app.UseMvc();
}
public void ConfigureMvc(IMvcBuilder builder)
{
builder.AddRazorPagesOptions(options =>
{
options.RootDirectory = "/Pages";
options.Conventions.AuthorizeFolder("/Auth");
});
}
}
}
| apache-2.0 | C# |
41022f519259eaa16e66c45154b5b858003a5091 | Update unit test | synel/syndll2 | Syndll2.FunctionalTests/BasicTests/ServerTests.cs | Syndll2.FunctionalTests/BasicTests/ServerTests.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Syndll2.FunctionalTests.BasicTests
{
[TestClass]
public class ServerTests
{
[TestMethod]
//[Ignore] // run this manually, when appropriate
public async Task Can_Receive_Inbound_Messages_From_Terminal()
{
var cts = new CancellationTokenSource();
var server = new SynelServer();
server.AsyncMessageReceivedHandler = async notification =>
{
if (notification.Type == NotificationType.Data)
{
Console.WriteLine(notification.Data);
await notification.AcknowledegeAsync();
}
if (notification.Type == NotificationType.Query)
{
Console.WriteLine(notification.Data);
await notification.ReplyAsync(true, 0, "Success");
}
cts.Cancel();
};
await server.ListenAsync(cts.Token);
}
}
} | using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Syndll2.FunctionalTests.BasicTests
{
[TestClass]
public class ServerTests
{
[TestMethod]
//[Ignore] // run this manually, when appropriate
public async Task Can_Receive_Inbound_Messages_From_Terminal()
{
var cts = new CancellationTokenSource();
var server = new SynelServer();
server.MessageReceived += (sender, args) =>
{
var notification = args.Notification;
if (notification.Type == NotificationType.Data)
{
Console.WriteLine(notification.Data);
notification.Acknowledege();
}
if (notification.Type == NotificationType.Query)
{
Console.WriteLine(notification.Data);
notification.Reply(true, 0, "Success");
}
cts.Cancel();
};
await server.ListenAsync(cts.Token);
}
}
} | mit | C# |
9eb215b94f11f9ecdee3da96c8de920315fe21ca | delete comment | AlexanderMazaletskiy/ProceduralBuildings,tkaretsos/ProceduralBuildings | Scripts/BuildingController.cs | Scripts/BuildingController.cs | using Thesis;
using UnityEngine;
using System.Collections.Generic;
public class BuildingController : MonoBehaviour
{
void Start ()
{
MaterialManager.Instance.Init();
NeoManager.Instance.Init();
NeoManager.Instance.CreateNeoclassical(BuildMode.Three);
}
void Update ()
{
if (Input.GetKeyUp(KeyCode.Alpha1))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Many);
}
if (Input.GetKeyUp(KeyCode.Alpha2))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Two);
}
if (Input.GetKeyUp(KeyCode.Alpha3))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Three);
}
if (Input.GetKeyUp(KeyCode.Alpha4))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Four);
}
if (Input.GetKeyUp(KeyCode.Alpha5))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Five);
}
}
}
| using Thesis;
using UnityEngine;
using System.Collections.Generic;
public class BuildingController : MonoBehaviour
{
void Start ()
{
MaterialManager.Instance.Init();
NeoManager.Instance.Init();
NeoManager.Instance.CreateNeoclassical(BuildMode.Three);
}
void Update ()
{
if (Input.GetKeyUp(KeyCode.Alpha1))
{
NeoManager.Instance.DestroyBuildings();
//StartCoroutine("NeoclassicalManager.Instance.CreateNeoclassical", BuildMode.Many);
NeoManager.Instance.CreateNeoclassical(BuildMode.Many);
}
if (Input.GetKeyUp(KeyCode.Alpha2))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Two);
}
if (Input.GetKeyUp(KeyCode.Alpha3))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Three);
}
if (Input.GetKeyUp(KeyCode.Alpha4))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Four);
}
if (Input.GetKeyUp(KeyCode.Alpha5))
{
NeoManager.Instance.DestroyBuildings();
NeoManager.Instance.CreateNeoclassical(BuildMode.Five);
}
}
}
| mit | C# |
4d2636d341139a493bbb1157a8b84902d03461e9 | Fix compiler warning for ParserException | mdileep/NFugue | src/NFugue/Parser/ParserException.cs | src/NFugue/Parser/ParserException.cs | using System;
namespace NFugue.Parser
{
public class ParserException : Exception
{
public ParserException()
{
}
public ParserException(string message) : base(message)
{
}
public int Position { get; set; } = -1;
}
}
| using System;
namespace NFugue.Parser
{
public class ParserException : Exception
{
public ParserException(string message) : base(message)
{
}
public int Position { get; set; } = -1;
}
}
| apache-2.0 | C# |
f787ce367ca2064db9685ffadd4134b0764e8321 | Move all Eco setting types to the Eco namespace | lukyad/Eco | Eco/Properties/AssemblyInfo.cs | Eco/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// 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("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible 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("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// 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.*")]
[assembly:SettingsAssembly("Eco")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Eco;
// 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("Eco")]
[assembly: AssemblyDescription("Yet another configuration library for .NET")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Eco")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// SettingsComVisible 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("bfdd8cf1-3e3b-4120-8d3a-68bd506ec4b3")]
// 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.*")]
[assembly:SettingsAssembly("Eco.Elements")]
| apache-2.0 | C# |
bfdc8aa1e8b20e388905824b03892c3ffebc80d5 | Update CoreCLR version in DependencyVersions.cs | wtgodbe/core-setup,ramarag/core-setup,ellismg/core-setup,gkhanna79/core-setup,steveharter/core-setup,rakeshsinghranchi/core-setup,karajas/core-setup,zamont/core-setup,chcosta/core-setup,ericstj/core-setup,crummel/dotnet_core-setup,cakine/core-setup,ericstj/core-setup,chcosta/core-setup,janvorli/core-setup,ellismg/core-setup,chcosta/core-setup,ravimeda/core-setup,joperezr/core-setup,wtgodbe/core-setup,janvorli/core-setup,vivmishra/core-setup,ramarag/core-setup,karajas/core-setup,schellap/core-setup,cakine/core-setup,weshaggard/core-setup,steveharter/core-setup,schellap/core-setup,ellismg/core-setup,zamont/core-setup,MichaelSimons/core-setup,chcosta/core-setup,crummel/dotnet_core-setup,janvorli/core-setup,gkhanna79/core-setup,MichaelSimons/core-setup,crummel/dotnet_core-setup,wtgodbe/core-setup,zamont/core-setup,rakeshsinghranchi/core-setup,vivmishra/core-setup,zamont/core-setup,vivmishra/core-setup,rakeshsinghranchi/core-setup,weshaggard/core-setup,gkhanna79/core-setup,gkhanna79/core-setup,MichaelSimons/core-setup,cakine/core-setup,ravimeda/core-setup,rakeshsinghranchi/core-setup,chcosta/core-setup,chcosta/core-setup,weshaggard/core-setup,weshaggard/core-setup,steveharter/core-setup,zamont/core-setup,crummel/dotnet_core-setup,ravimeda/core-setup,gkhanna79/core-setup,weshaggard/core-setup,steveharter/core-setup,ericstj/core-setup,karajas/core-setup,joperezr/core-setup,rakeshsinghranchi/core-setup,ramarag/core-setup,MichaelSimons/core-setup,ellismg/core-setup,ramarag/core-setup,joperezr/core-setup,crummel/dotnet_core-setup,rakeshsinghranchi/core-setup,steveharter/core-setup,vivmishra/core-setup,janvorli/core-setup,schellap/core-setup,ericstj/core-setup,cakine/core-setup,karajas/core-setup,MichaelSimons/core-setup,joperezr/core-setup,ellismg/core-setup,zamont/core-setup,janvorli/core-setup,karajas/core-setup,joperezr/core-setup,ravimeda/core-setup,steveharter/core-setup,schellap/core-setup,weshaggard/core-setup,ellismg/core-setup,wtgodbe/core-setup,vivmishra/core-setup,ramarag/core-setup,joperezr/core-setup,ericstj/core-setup,karajas/core-setup,ravimeda/core-setup,schellap/core-setup,janvorli/core-setup,crummel/dotnet_core-setup,ravimeda/core-setup,wtgodbe/core-setup,schellap/core-setup,MichaelSimons/core-setup,ramarag/core-setup,ericstj/core-setup,cakine/core-setup,cakine/core-setup,wtgodbe/core-setup,gkhanna79/core-setup,vivmishra/core-setup | build_projects/shared-build-targets-utils/DependencyVersions.cs | build_projects/shared-build-targets-utils/DependencyVersions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.DotNet.Cli.Build
{
public class DependencyVersions
{
public static readonly string CoreCLRVersion = "1.2.0-beta-24619-01";
public static readonly string JitVersion = "1.2.0-beta-24619-01";
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.DotNet.Cli.Build
{
public class DependencyVersions
{
public static readonly string CoreCLRVersion = "1.2.0-beta-24522-03";
public static readonly string JitVersion = "1.2.0-beta-24522-03";
}
}
| mit | C# |
38f6fc3d812b8052bc32ce7d8a7757701ffb39b5 | Clear Region in exit. | ResourceHunter/BaiduPanDownloadWpf | Source/Accelerider.Windows/ViewModels/MainWindow.vm.cs | Source/Accelerider.Windows/ViewModels/MainWindow.vm.cs | using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Input;
using Accelerider.Windows.Infrastructure;
using Accelerider.Windows.Infrastructure.Commands;
using Accelerider.Windows.Resources.I18N;
using Accelerider.Windows.Views.AppStore;
using Microsoft.Practices.Unity;
using Prism.Regions;
using System.Linq;
namespace Accelerider.Windows.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
private ICommand _feedbackCommand;
private bool _appStoreIsDisplayed;
public MainWindowViewModel(IUnityContainer container, IRegionManager regionManager) : base(container)
{
RegionManager = regionManager;
FeedbackCommand = new RelayCommand(() => Process.Start(ConstStrings.IssueUrl));
GlobalMessageQueue.Enqueue(UiStrings.Message_Welcome);
}
public IRegionManager RegionManager { get; }
public ICommand FeedbackCommand
{
get => _feedbackCommand;
set => SetProperty(ref _feedbackCommand, value);
}
public bool AppStoreIsDisplayed
{
get => _appStoreIsDisplayed;
set
{
if (_appStoreIsDisplayed) return;
if (!SetProperty(ref _appStoreIsDisplayed, value)) return;
var region = RegionManager.Regions[RegionNames.MainTabRegion];
foreach (var activeView in region.ActiveViews)
{
region.Deactivate(activeView);
}
}
}
public override void OnLoaded(object view)
{
var region = RegionManager.Regions[RegionNames.MainTabRegion];
region.ActiveViews.CollectionChanged += OnActiveViewsChanged;
}
private void OnActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add) return;
_appStoreIsDisplayed = false;
RaisePropertyChanged(nameof(AppStoreIsDisplayed));
}
public override void OnUnloaded(object view)
{
var regionNames = RegionManager.Regions.Select(item => item.Name).ToArray();
foreach (var regionName in regionNames)
{
RegionManager.Regions.Remove(regionName);
}
AcceleriderUser.OnExit();
}
}
}
| using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Input;
using Accelerider.Windows.Infrastructure;
using Accelerider.Windows.Infrastructure.Commands;
using Accelerider.Windows.Resources.I18N;
using Accelerider.Windows.Views.AppStore;
using Microsoft.Practices.Unity;
using Prism.Regions;
namespace Accelerider.Windows.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
private ICommand _feedbackCommand;
private bool _appStoreIsDisplayed;
public MainWindowViewModel(IUnityContainer container, IRegionManager regionManager) : base(container)
{
RegionManager = regionManager;
FeedbackCommand = new RelayCommand(() => Process.Start(ConstStrings.IssueUrl));
GlobalMessageQueue.Enqueue(UiStrings.Message_Welcome);
}
public IRegionManager RegionManager { get; }
public ICommand FeedbackCommand
{
get => _feedbackCommand;
set => SetProperty(ref _feedbackCommand, value);
}
public bool AppStoreIsDisplayed
{
get => _appStoreIsDisplayed;
set
{
if (_appStoreIsDisplayed) return;
if (!SetProperty(ref _appStoreIsDisplayed, value)) return;
var region = RegionManager.Regions[RegionNames.MainTabRegion];
foreach (var activeView in region.ActiveViews)
{
region.Deactivate(activeView);
}
}
}
public override void OnLoaded(object view)
{
var region = RegionManager.Regions[RegionNames.MainTabRegion];
region.ActiveViews.CollectionChanged += OnActiveViewsChanged;
}
private void OnActiveViewsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action != NotifyCollectionChangedAction.Add) return;
_appStoreIsDisplayed = false;
RaisePropertyChanged(nameof(AppStoreIsDisplayed));
}
public override void OnUnloaded(object view)
{
AcceleriderUser.OnExit();
}
}
}
| mit | C# |
f978386c8636e7ee897d041464da404b6e4c3b34 | Fix indent. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Controls/LockScreen/LockScreenImpl.cs | WalletWasabi.Gui/Controls/LockScreen/LockScreenImpl.cs | using Avalonia.Controls;
namespace WalletWasabi.Gui.Controls.LockScreen
{
internal class LockScreenImpl : UserControl
{
internal virtual void Reset()
{
IsHitTestVisible = true;
}
}
}
| using Avalonia.Controls;
namespace WalletWasabi.Gui.Controls.LockScreen
{
internal class LockScreenImpl : UserControl
{
internal virtual void Reset()
{
IsHitTestVisible = true;
}
}
}
| mit | C# |
a679e9a86b79b9e0c45b76dc5b5fc745c72f03dd | Add support for Authenticated on 3DS Charges | stripe/stripe-dotnet | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsCardThreeDSecure.cs | src/Stripe.net/Entities/Charges/ChargePaymentMethodDetails/ChargePaymentMethodDetailsCardThreeDSecure.cs | namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
/// <summary>
/// Whether or not authentication was performed. 3D Secure will succeed without
/// authentication when the card is not enrolled.
/// </summary>
[JsonProperty("authenticated")]
public bool Authenticated { get; set; }
/// <summary>
/// Whether or not 3D Secure succeeded.
/// </summary>
[JsonProperty("succeeded")]
public bool Succeeded { get; set; }
/// <summary>
/// The version of 3D Secure that was used for this payment.
/// </summary>
[JsonProperty("version")]
public string Version { get; set; }
}
}
| namespace Stripe
{
using Newtonsoft.Json;
using Stripe.Infrastructure;
public class ChargePaymentMethodDetailsCardThreeDSecure : StripeEntity
{
[JsonProperty("succeeded")]
public bool Succeeded { get; set; }
[JsonProperty("version")]
public string Version { get; set; }
}
}
| apache-2.0 | C# |
e65f311b42b0661dd09c289d163a0d4f414da91b | Update assembly copyright notice to 2017 | HangfireIO/Hangfire.Azure.ServiceBusQueue | src/HangFire.Azure.ServiceBusQueue/Properties/SharedAssemblyInfo.cs | src/HangFire.Azure.ServiceBusQueue/Properties/SharedAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Hangfire")]
[assembly: AssemblyCopyright("Copyright © 2013-2017 Sergey Odinokov, Adam Barclay")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// Don't edit manually! Use `build.bat version` command instead!
[assembly: AssemblyVersion("0.1.0")]
| using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyProduct("Hangfire")]
[assembly: AssemblyCopyright("Copyright © 2013-2015 Sergey Odinokov, Adam Barclay")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
// Don't edit manually! Use `build.bat version` command instead!
[assembly: AssemblyVersion("0.1.0")]
| mit | C# |
85a47231bcd424f4d3ecd974f0804e357270a0be | Update Program.cs (#708) | anjdreas/UnitsNet,anjdreas/UnitsNet | UnitsNet.Benchmark/Program.cs | UnitsNet.Benchmark/Program.cs | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using UnitsNet.Units;
namespace UnitsNet.Benchmark
{
[MemoryDiagnoser]
public class UnitsNetBenchmarks
{
private Length length = Length.FromMeters(3.0);
private IQuantity lengthIQuantity = Length.FromMeters(3.0);
[Benchmark]
public Length Constructor() => new Length(3.0, LengthUnit.Meter);
[Benchmark]
public Length Constructor_SI() => new Length(3.0, UnitSystem.SI);
[Benchmark]
public Length FromMethod() => Length.FromMeters(3.0);
[Benchmark]
public double ToProperty() => length.Centimeters;
[Benchmark]
public double As() => length.As(LengthUnit.Centimeter);
[Benchmark]
public double As_SI() => length.As(UnitSystem.SI);
[Benchmark]
public Length ToUnit() => length.ToUnit(LengthUnit.Centimeter);
[Benchmark]
public Length ToUnit_SI() => length.ToUnit(UnitSystem.SI);
[Benchmark]
public string ToStringTest() => length.ToString();
[Benchmark]
public Length Parse() => Length.Parse("3.0 m");
[Benchmark]
public bool TryParseValid() => Length.TryParse("3.0 m", out var l);
[Benchmark]
public bool TryParseInvalid() => Length.TryParse("3.0 zoom", out var l);
[Benchmark]
public IQuantity QuantityFrom() => Quantity.From(3.0, LengthUnit.Meter);
[Benchmark]
public double IQuantity_As() => lengthIQuantity.As(LengthUnit.Centimeter);
[Benchmark]
public double IQuantity_As_SI() => lengthIQuantity.As(UnitSystem.SI);
[Benchmark]
public IQuantity IQuantity_ToUnit() => lengthIQuantity.ToUnit(LengthUnit.Centimeter);
[Benchmark]
public string IQuantity_ToStringTest() => lengthIQuantity.ToString();
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<UnitsNetBenchmarks>();
}
}
}
| using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using UnitsNet.Units;
namespace UnitsNet.Benchmark
{
[MemoryDiagnoser]
public class UnitsNetBenchmarks
{
private Length length = Length.FromMeters(3.0);
private IQuantity lengthIQuantity = Length.FromMeters(3.0);
[Benchmark]
public Length Constructor() => new Length(3.0, LengthUnit.Meter);
[Benchmark]
public Length FromMethod() => Length.FromMeters(3.0);
[Benchmark]
public double ToProperty() => length.Centimeters;
[Benchmark]
public double As() => length.As(LengthUnit.Centimeter);
[Benchmark]
public Length ToUnit() => length.ToUnit(LengthUnit.Centimeter);
[Benchmark]
public string ToStringTest() => length.ToString();
[Benchmark]
public Length Parse() => Length.Parse("3.0 m");
[Benchmark]
public bool TryParseValid() => Length.TryParse("3.0 m", out var l);
[Benchmark]
public bool TryParseInvalid() => Length.TryParse("3.0 zoom", out var l);
[Benchmark]
public IQuantity QuantityFrom() => Quantity.From(3.0, LengthUnit.Meter);
[Benchmark]
public double IQuantity_As() => lengthIQuantity.As(LengthUnit.Centimeter);
[Benchmark]
public IQuantity IQuantity_ToUnit() => lengthIQuantity.ToUnit(LengthUnit.Centimeter);
[Benchmark]
public string IQuantity_ToStringTest() => lengthIQuantity.ToString();
}
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<UnitsNetBenchmarks>();
}
}
}
| mit | C# |
b52cbc80396ceb85cf81ddf71d1d21c9e88ec54c | Add automatic placement for Prizes. | cmilr/Unity2D-Components,jguarShark/Unity2D-Components | Entities/InteractiveEntity.cs | Entities/InteractiveEntity.cs | using UnityEngine;
using System;
using System.Collections;
using Matcha.Game.Tweens;
public class InteractiveEntity : MonoBehaviour
{
public enum EntityType { none, prize, weapon };
public EntityType entityType;
[HideInInspector]
public bool alreadyCollided = false;
public bool disableIfOffScreen = true;
public int worth;
void Start()
{
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
// still buggy
// needs to be more succint
transform.position = new Vector3(transform.position.x, (float)(Math.Ceiling(transform.position.y) - .623f), transform.position.z);
break;
case EntityType.weapon:
break;
}
}
void OnBecameInvisible()
{
if(disableIfOffScreen)
gameObject.SetActive(false);
}
void OnBecameVisible()
{
if(disableIfOffScreen)
gameObject.SetActive(true);
}
public void React()
{
alreadyCollided = true;
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
MTween.PickupPrize(gameObject);
break;
case EntityType.weapon:
MTween.PickupWeapon(gameObject);
break;
}
}
public void SelfDestruct(int inSeconds)
{
Destroy(gameObject, inSeconds);
}
}
| using UnityEngine;
using System.Collections;
using Matcha.Game.Tweens;
public class InteractiveEntity : MonoBehaviour
{
public enum EntityType { none, prize, weapon };
public EntityType entityType;
[HideInInspector]
public bool alreadyCollided = false;
public bool disableIfOffScreen = true;
public int worth;
void OnBecameInvisible()
{
if(disableIfOffScreen)
gameObject.SetActive(false);
}
void OnBecameVisible()
{
if(disableIfOffScreen)
gameObject.SetActive(true);
}
public void React()
{
alreadyCollided = true;
switch (entityType)
{
case EntityType.none:
break;
case EntityType.prize:
MTween.PickupPrize(gameObject);
break;
case EntityType.weapon:
MTween.PickupWeapon(gameObject);
break;
}
}
public void SelfDestruct(int inSeconds)
{
Destroy(gameObject, inSeconds);
}
}
| mit | C# |
9d2dff2cb871403637511e2d7545dfad89d59c68 | Add scale to allow legacy icons to display correctly sized | UselessToucan/osu,NeoAdonis/osu,ppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu | osu.Game/Beatmaps/BeatmapStatistic.cs | osu.Game/Beatmaps/BeatmapStatistic.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osuTK;
namespace osu.Game.Beatmaps
{
public class BeatmapStatistic
{
[Obsolete("Use CreateIcon instead")] // can be removed 20210203
public IconUsage Icon = FontAwesome.Regular.QuestionCircle;
/// <summary>
/// A function to create the icon for display purposes.
/// </summary>
public Func<Drawable> CreateIcon;
public string Content;
public string Name;
public BeatmapStatistic()
{
#pragma warning disable 618
CreateIcon = () => new SpriteIcon { Icon = Icon, Scale = new Vector2(0.6f) };
#pragma warning restore 618
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
namespace osu.Game.Beatmaps
{
public class BeatmapStatistic
{
[Obsolete("Use CreateIcon instead")] // can be removed 20210203
public IconUsage Icon = FontAwesome.Regular.QuestionCircle;
/// <summary>
/// A function to create the icon for display purposes.
/// </summary>
public Func<Drawable> CreateIcon;
public string Content;
public string Name;
public BeatmapStatistic()
{
#pragma warning disable 618
CreateIcon = () => new SpriteIcon { Icon = Icon };
#pragma warning restore 618
}
}
}
| mit | C# |
1caab78bdc38dcc512831a88809749db334837f7 | Update ModAutoplay.cs | peppy/osu,ppy/osu,ppy/osu,ppy/osu,peppy/osu,peppy/osu | osu.Game/Rulesets/Mods/ModAutoplay.cs | osu.Game/Rulesets/Mods/ModAutoplay.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 disable
using System;
using System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Replays;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModAutoplay : Mod, IApplicableFailOverride, ICreateReplayData
{
public override string Name => "Autoplay";
public override string Acronym => "AT";
public override IconUsage? Icon => OsuIcon.ModAuto;
public override ModType Type => ModType.Automation;
public override string Description => "Watch a perfect automated play through the song.";
public override double ScoreMultiplier => 1;
public bool PerformFail() => false;
public bool RestartOnFail => false;
public override bool UserPlayable => false;
public override bool ValidForMultiplayer => false;
public override bool ValidForMultiplayerAsFreeMod => false;
public override Type[] IncompatibleMods => new[] { typeof(ModCinema), typeof(ModRelax), typeof(ModFailCondition), typeof(ModNoFail), typeof(ModAdaptiveSpeed) };
public override bool HasImplementation => GetType().GenericTypeArguments.Length == 0;
[Obsolete("Override CreateReplayData(IBeatmap, IReadOnlyList<Mod>) instead")] // Can be removed 20220929
public virtual Score CreateReplayScore(IBeatmap beatmap, IReadOnlyList<Mod> mods) => new Score { Replay = new Replay() };
public virtual ModReplayData CreateReplayData(IBeatmap beatmap, IReadOnlyList<Mod> mods)
{
#pragma warning disable CS0618
var replayScore = CreateReplayScore(beatmap, mods);
#pragma warning restore CS0618
return new ModReplayData(replayScore.Replay, new ModCreatedUser { Username = replayScore.ScoreInfo.User.Username });
}
}
}
| // 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 disable
using System;
using System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Beatmaps;
using osu.Game.Graphics;
using osu.Game.Replays;
using osu.Game.Scoring;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModAutoplay : Mod, IApplicableFailOverride, ICreateReplayData
{
public override string Name => "Autoplay";
public override string Acronym => "AT";
public override IconUsage? Icon => OsuIcon.ModAuto;
public override ModType Type => ModType.Automation;
public override string Description => "Watch a perfect automated play through the song.";
public override double ScoreMultiplier => 1;
public bool PerformFail() => false;
public bool RestartOnFail => false;
public override bool UserPlayable => false;
public override bool ValidForMultiplayer => false;
public override bool ValidForMultiplayerAsFreeMod => false;
public override Type[] IncompatibleMods => new[] { typeof(ModCinema), typeof(ModRelax), typeof(ModFailCondition), typeof(ModNoFail) };
public override bool HasImplementation => GetType().GenericTypeArguments.Length == 0;
[Obsolete("Override CreateReplayData(IBeatmap, IReadOnlyList<Mod>) instead")] // Can be removed 20220929
public virtual Score CreateReplayScore(IBeatmap beatmap, IReadOnlyList<Mod> mods) => new Score { Replay = new Replay() };
public virtual ModReplayData CreateReplayData(IBeatmap beatmap, IReadOnlyList<Mod> mods)
{
#pragma warning disable CS0618
var replayScore = CreateReplayScore(beatmap, mods);
#pragma warning restore CS0618
return new ModReplayData(replayScore.Replay, new ModCreatedUser { Username = replayScore.ScoreInfo.User.Username });
}
}
}
| mit | C# |
5bc316f2f0c1b7ae647e3b27ba018b04135cb9d2 | Fix import | RehanSaeed/ASP.NET-MVC-Boilerplate,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates | Source/MVC6/Boilerplate.AspNetCore.Sample/Views/_ViewImports.cshtml | Source/MVC6/Boilerplate.AspNetCore.Sample/Views/_ViewImports.cshtml | @using MvcBoilerplate
@using MvcBoilerplate.Constants
@using MvcBoilerplate.Settings;
@using Boilerplate.AspNetCore
@using Boilerplate.AspNetCore.TagHelpers
@using Boilerplate.AspNetCore.TagHelpers.OpenGraph
@using Boilerplate.AspNetCore.TagHelpers.Twitter
@* $Start-ApplicationInsights$ *@
@using Microsoft.ApplicationInsights.Extensibility
@* $End-ApplicationInsights$ *@
@using Microsoft.AspNetCore.Hosting
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Options
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Boilerplate.AspNetCore.TagHelpers | @using MvcBoilerplate
@using MvcBoilerplate.Constants
@using MvcBoilerplate.Settings;
@using Boilerplate.AspNetCore
@using Boilerplate.AspNetCore.TagHelpers
@using Boilerplate.AspNetCore.TagHelpers.OpenGraph
@using Boilerplate.AspNetCore.TagHelpers.Twitter
@* $Start-ApplicationInsights$ *@
@using Microsoft.ApplicationInsights.Extensibility
@* $End-ApplicationInsights$ *@
@using Microsoft.AspNetCore.Hosting
@using Microsoft.AspNetCore.Http
@using Microsoft.Extensions.Options
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
@addTagHelper *, Boilerplate.AspNetCore.Mvc.TagHelpers | mit | C# |
d120678e306e9dc85cfb0e8d2fd82efd96c3a7cb | Fix redundant default value | smoogipooo/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,ppy/osu | osu.Game/Screens/Play/GameplayState.cs | osu.Game/Screens/Play/GameplayState.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.Collections.Generic;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
#nullable enable
namespace osu.Game.Screens.Play
{
/// <summary>
/// The state of an active gameplay session, generally constructed and exposed by <see cref="Player"/>.
/// </summary>
public class GameplayState
{
/// <summary>
/// The final post-convert post-mod-application beatmap.
/// </summary>
public readonly IBeatmap Beatmap;
/// <summary>
/// The ruleset used in gameplay.
/// </summary>
public readonly Ruleset Ruleset;
/// <summary>
/// The mods applied to the gameplay.
/// </summary>
public readonly IReadOnlyList<Mod> Mods;
/// <summary>
/// The gameplay score.
/// </summary>
public Score? Score { get; set; }
/// <summary>
/// A bindable tracking the last judgement result applied to any hit object.
/// </summary>
public IBindable<JudgementResult> LastJudgementResult => lastJudgementResult;
private readonly Bindable<JudgementResult> lastJudgementResult = new Bindable<JudgementResult>();
public GameplayState(IBeatmap beatmap, Ruleset ruleset, IReadOnlyList<Mod> mods)
{
Beatmap = beatmap;
Ruleset = ruleset;
Mods = mods;
}
/// <summary>
/// Applies the score change of a <see cref="JudgementResult"/> to this <see cref="GameplayState"/>.
/// </summary>
/// <param name="result">The <see cref="JudgementResult"/> to apply.</param>
public void ApplyResult(JudgementResult result) => lastJudgementResult.Value = result;
}
}
| // 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.Collections.Generic;
using osu.Framework.Bindables;
using osu.Game.Beatmaps;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Mods;
using osu.Game.Scoring;
#nullable enable
namespace osu.Game.Screens.Play
{
/// <summary>
/// The state of an active gameplay session, generally constructed and exposed by <see cref="Player"/>.
/// </summary>
public class GameplayState
{
/// <summary>
/// The final post-convert post-mod-application beatmap.
/// </summary>
public readonly IBeatmap Beatmap;
/// <summary>
/// The ruleset used in gameplay.
/// </summary>
public readonly Ruleset Ruleset;
/// <summary>
/// The mods applied to the gameplay.
/// </summary>
public readonly IReadOnlyList<Mod> Mods;
/// <summary>
/// The gameplay score.
/// </summary>
public Score? Score { get; set; } = null;
/// <summary>
/// A bindable tracking the last judgement result applied to any hit object.
/// </summary>
public IBindable<JudgementResult> LastJudgementResult => lastJudgementResult;
private readonly Bindable<JudgementResult> lastJudgementResult = new Bindable<JudgementResult>();
public GameplayState(IBeatmap beatmap, Ruleset ruleset, IReadOnlyList<Mod> mods)
{
Beatmap = beatmap;
Ruleset = ruleset;
Mods = mods;
}
/// <summary>
/// Applies the score change of a <see cref="JudgementResult"/> to this <see cref="GameplayState"/>.
/// </summary>
/// <param name="result">The <see cref="JudgementResult"/> to apply.</param>
public void ApplyResult(JudgementResult result) => lastJudgementResult.Value = result;
}
}
| mit | C# |
d8cbb6110374fc37268486ff33e568a0391f1b8a | Add ignoreCase switch to enum parsers | Tyrrrz/Extensions | Extensions/Ext.Enums.cs | Extensions/Ext.Enums.cs | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Tyrrrz.Extensions
{
public static partial class Ext
{
/// <summary>
/// Returns true if the enum value has all of the given flags set
/// </summary>
[Pure]
public static bool HasFlags(this Enum enumValue, params Enum[] flags)
{
return flags.All(enumValue.HasFlag);
}
/// <summary>
/// Parses string to enum
/// </summary>
[Pure]
public static TEnum ParseEnum<TEnum>([NotNull] this string str, bool ignoreCase = true) where TEnum : struct
{
if (IsBlank(str))
throw new ArgumentNullException(nameof(str));
return (TEnum) Enum.Parse(typeof (TEnum), str, ignoreCase);
}
/// <summary>
/// Parses string to enum or default value
/// </summary>
[Pure]
public static TEnum ParseEnumOrDefault<TEnum>(this string str, bool ignoreCase = true, TEnum defaultValue = default(TEnum)) where TEnum : struct
{
if (IsBlank(str)) return defaultValue;
TEnum result;
return Enum.TryParse(str, ignoreCase, out result) ? result : defaultValue;
}
/// <summary>
/// Gets all possible values of an enumeration
/// </summary>
[Pure]
public static IEnumerable<TEnum> GetAllEnumValues<TEnum>(this Type enumType) where TEnum : struct
{
return Enum.GetValues(enumType).Cast<TEnum>();
}
/// <summary>
/// Returns the path of the given special folder
/// </summary>
[Pure]
public static string GetPath(this Environment.SpecialFolder specialFolder,
Environment.SpecialFolderOption option = Environment.SpecialFolderOption.None)
{
return Environment.GetFolderPath(specialFolder, option);
}
/// <summary>
/// Returns a random bool
/// </summary>
[Pure]
public static TEnum RandomEnum<TEnum>() where TEnum : struct
{
var values = GetAllEnumValues<TEnum>(typeof(TEnum));
return GetRandom(values);
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Tyrrrz.Extensions
{
public static partial class Ext
{
/// <summary>
/// Returns true if the enum value has all of the given flags set
/// </summary>
[Pure]
public static bool HasFlags(this Enum enumValue, params Enum[] flags)
{
return flags.All(enumValue.HasFlag);
}
/// <summary>
/// Parses string to enum
/// </summary>
[Pure]
public static TEnum ParseEnum<TEnum>([NotNull] this string str) where TEnum : struct
{
if (IsBlank(str))
throw new ArgumentNullException(nameof(str));
return (TEnum) Enum.Parse(typeof (TEnum), str, true);
}
/// <summary>
/// Parses string to enum or default value
/// </summary>
[Pure]
public static TEnum ParseEnumOrDefault<TEnum>(this string str, TEnum defaultValue = default(TEnum)) where TEnum : struct
{
if (IsBlank(str)) return defaultValue;
TEnum result;
return Enum.TryParse(str, true, out result) ? result : defaultValue;
}
/// <summary>
/// Gets all possible values of an enumeration
/// </summary>
[Pure]
public static IEnumerable<TEnum> GetAllEnumValues<TEnum>(this Type enumType) where TEnum : struct
{
return Enum.GetValues(enumType).Cast<TEnum>();
}
/// <summary>
/// Returns the path of the given special folder
/// </summary>
[Pure]
public static string GetPath(this Environment.SpecialFolder specialFolder,
Environment.SpecialFolderOption option = Environment.SpecialFolderOption.None)
{
return Environment.GetFolderPath(specialFolder, option);
}
/// <summary>
/// Returns a random bool
/// </summary>
[Pure]
public static TEnum RandomEnum<TEnum>() where TEnum : struct
{
var values = GetAllEnumValues<TEnum>(typeof(TEnum));
return GetRandom(values);
}
}
} | mit | C# |
f434f085ead4361d5965396e6f4aecaf6a2f8f64 | fix RIDER-49316 | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/ShaderLab/Psi/Formatting/ShaderLabCppCustomFormattingInfoProvider.cs | resharper/resharper-unity/src/ShaderLab/Psi/Formatting/ShaderLabCppCustomFormattingInfoProvider.cs | using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Cpp.CodeStyle;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel;
using JetBrains.ReSharper.Psi.Cpp.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi.Formatting
{
[ProjectFileType(typeof(ShaderLabProjectFileType))]
public class ShaderLabCppCustomFormattingInfoProvider : ICppCustomFormattingInfoProvider
{
public bool DefaultAdjustLeadingAndTrailingWhitespaces => false;
public void AdjustLeadingAndTrailingWhitespaces(CppCodeFormatter cppCodeFormatter, CppFile cppFile)
{
var cgProgram = (cppFile.Parent as IInjectedFileHolder)?.OriginalNode.PrevSibling;
var s = ShaderLabCppFormatterExtension.GetIndentInCgProgram(cgProgram);
cppCodeFormatter.RemoveLeadingSpacesInFile(cppFile);
cppCodeFormatter.RemoveTrailingSpaces( cppFile);
var lineEnding = cppFile.DetectLineEnding(cppFile.GetPsiServices());
LowLevelModificationUtil.AddChildBefore(cppFile.firstChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
LowLevelModificationUtil.AddChildAfter(cppFile.lastChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
}
}
} | using JetBrains.ProjectModel;
using JetBrains.ReSharper.Feature.Services.Cpp.CodeStyle;
using JetBrains.ReSharper.Plugins.Unity.ShaderLab.ProjectModel;
using JetBrains.ReSharper.Psi.Cpp.Tree;
using JetBrains.ReSharper.Psi.ExtensionsAPI;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.ShaderLab.Psi.Formatting
{
[ProjectFileType(typeof(ShaderLabProjectFileType))]
public class ShaderLabCppCustomFormattingInfoProvider : ICppCustomFormattingInfoProvider
{
public bool DefaultAdjustLeadingAndTrailingWhitespaces => false;
public void AdjustLeadingAndTrailingWhitespaces(CppCodeFormatter cppCodeFormatter, CppFile cppFile)
{
var cgProgram = (cppFile.Parent as IInjectedFileHolder)?.OriginalNode.PrevSibling;
var s = ShaderLabCppFormatterExtension.GetIndentInCgProgram(cgProgram);
cppCodeFormatter.RemoveLeadingSpacesInFile(cppFile);
cppCodeFormatter.RemoveTrailingSpaces( cppFile);
var lineEnding = cppFile.DetectLineEnding(cppFile.GetPsiServices());
LowLevelModificationUtil.AddChildBefore(cppFile.firstChild, cppCodeFormatter.CreateNewLine(lineEnding));
LowLevelModificationUtil.AddChildAfter(cppFile.lastChild, cppCodeFormatter.CreateNewLine(lineEnding), cppCodeFormatter.CreateSpace(s, null));
}
}
} | apache-2.0 | C# |
e0c84c3a1c43fca24bcdd5a974b6402864917cb4 | Fix typo | rucila/FileHelpers,jbparker/FileHelpers,phaufe/FileHelpers,tablesmit/FileHelpers,senthilmsv/FileHelpers,MarcosMeli/FileHelpers,rucila/FileHelpers,CarbonEdge/FileHelpers,mcavigelli/FileHelpers,regisbsb/FileHelpers,p07r0457/FileHelpers,regisbsb/FileHelpers,jawn/FileHelpers,merkt/FileHelpers,phaufe/FileHelpers,xavivars/FileHelpers,aim00ver/FileHelpers,tablesmit/FileHelpers,neildobson71/FileHelpers,jawn/FileHelpers,guillaumejay/FileHelpers,modulexcite/FileHelpers | FileHelpers.Analyzer/FileHelpers.Analyzer/FileHelpers.Analyzer/UseGenericEngine/UseGenericEngineAnalyzer.cs | FileHelpers.Analyzer/FileHelpers.Analyzer/FileHelpers.Analyzer/UseGenericEngine/UseGenericEngineAnalyzer.cs | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace FileHelpersAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UseGenericEngineAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "UseGenericEngine";
private static readonly string Title = "FileHelpers: You can use the generic engine";
private static readonly string MessageFormat = "FileHelpers: You can use the generic engine";
private static readonly string Description = "It is recommended to use the generic version of the engine";
private const string Category = "Usage";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ObjectCreationExpression);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var creation = (ObjectCreationExpressionSyntax)context.Node;
var engineType = creation.Type.ToString();
if (engineType == "FileHelperEngine" ||
engineType == "FileHelpers.FileHelperEngine" ||
engineType == "FileHelperAsyncEngine" ||
engineType == "FileHelpers.FileHelperAsyncEngine"
)
{
if (creation.ArgumentList.Arguments.Count > 0 &&
creation.ArgumentList.Arguments[0].Expression is TypeOfExpressionSyntax)
{
var diagnostic = Diagnostic.Create(Rule, creation.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace FileHelpersAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class UseGenericEngineAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "UseGenericEngine";
private static readonly string Title = "FileHelpers: You can use the generic engine";
private static readonly string MessageFormat = "FileHelpers: You can use the generic engine";
private static readonly string Description = "Is recommended to use the generic version of the engine";
private const string Category = "Usage";
private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule);
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.ObjectCreationExpression);
}
private void AnalyzeNode(SyntaxNodeAnalysisContext context)
{
var creation = (ObjectCreationExpressionSyntax)context.Node;
var engineType = creation.Type.ToString();
if (engineType == "FileHelperEngine" ||
engineType == "FileHelpers.FileHelperEngine" ||
engineType == "FileHelperAsyncEngine" ||
engineType == "FileHelpers.FileHelperAsyncEngine"
)
{
if (creation.ArgumentList.Arguments.Count > 0 &&
creation.ArgumentList.Arguments[0].Expression is TypeOfExpressionSyntax)
{
var diagnostic = Diagnostic.Create(Rule, creation.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}
}
}
}
| mit | C# |
4b88fb6f2d53ff305e5ac7b247bf3f093b35580f | Update PolyCubicBezierSegmentTests.cs | Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D | tests/Core2D.UnitTests/Path/Segments/PolyCubicBezierSegmentTests.cs | tests/Core2D.UnitTests/Path/Segments/PolyCubicBezierSegmentTests.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class PolyCubicBezierSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void Points_Not_Null()
{
var target = new PolyCubicBezierSegment();
Assert.False(target.Points.IsDefault);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new PolyCubicBezierSegment();
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
var target = segment.GetPoints();
Assert.Equal(5, target.Count());
Assert.Equal(segment.Points, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new PolyCubicBezierSegment();
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
var actual = target.ToString();
Assert.Equal("C0,0 0,0 0,0 0,0 0,0", actual);
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Core2D.Path.Segments;
using Core2D.Shapes;
using System.Linq;
using Xunit;
namespace Core2D.UnitTests
{
public class PolyCubicBezierSegmentTests
{
[Fact]
[Trait("Core2D.Path", "Segments")]
public void Points_Not_Null()
{
var target = new PolyCubicBezierSegment();
Assert.NotNull(target.Points);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void GetPoints_Should_Return_All_Segment_Points()
{
var segment = new PolyCubicBezierSegment();
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
segment.Points = segment.Points.Add(new PointShape());
var target = segment.GetPoints();
Assert.Equal(5, target.Count());
Assert.Equal(segment.Points, target);
}
[Fact]
[Trait("Core2D.Path", "Segments")]
public void ToString_Should_Return_Path_Markup()
{
var target = new PolyCubicBezierSegment();
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
target.Points = target.Points.Add(new PointShape());
var actual = target.ToString();
Assert.Equal("C0,0 0,0 0,0 0,0 0,0", actual);
}
}
}
| mit | C# |
933e8a46955c0564fd80b191addcb2efb0abf3d6 | fix version check | jasonmalinowski/roslyn,mavasani/roslyn,dotnet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/LanguageVersionExtensions.cs | src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/LanguageVersionExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp.Shared.Extensions
{
internal static class LanguageVersionExtensions
{
public static bool IsCSharp11OrAbove(this LanguageVersion languageVersion)
=> languageVersion >= LanguageVersion.CSharp11;
public static bool HasConstantInterpolatedStrings(this LanguageVersion languageVersion)
=> languageVersion >= LanguageVersion.CSharp10;
/// <remarks>
/// Corresponds to Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts.CSharpNext.
/// </remarks>
internal const LanguageVersion CSharpNext = LanguageVersion.Preview;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.CSharp.Shared.Extensions
{
internal static class LanguageVersionExtensions
{
public static bool IsCSharp11OrAbove(this LanguageVersion languageVersion)
=> languageVersion >= LanguageVersion.Preview;
public static bool HasConstantInterpolatedStrings(this LanguageVersion languageVersion)
=> languageVersion >= LanguageVersion.CSharp10;
/// <remarks>
/// Corresponds to Microsoft.CodeAnalysis.CSharp.LanguageVersionFacts.CSharpNext.
/// </remarks>
internal const LanguageVersion CSharpNext = LanguageVersion.Preview;
}
}
| mit | C# |
a01149d1f074fc22c1d2c4319565a54933e978b4 | Add test for cache hit | vanashimko/MPP.Mapper | MapperTests/DtoMapperTests.cs | MapperTests/DtoMapperTests.cs | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
Destination expected = new Destination
{
FirstProperty = 1,
SecondProperty = "a",
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
mockCache.Setup(mock => mock.HasCacheFor(It.IsAny<MappingEntryInfo>())).Returns(true);
mockCache.Setup(mock => mock.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>())).Returns(x => x);
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Once);
}
}
} | using System;
using Xunit;
using Mapper;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Moq;
namespace Mapper.Tests
{
public class DtoMapperTests
{
[Fact]
public void Map_NullPassed_ExceptionThrown()
{
IMapper mapper = new DtoMapper();
Assert.Throws<ArgumentNullException>(() => mapper.Map<object, object>(null));
}
[Fact]
public void Map_TwoCompatibleFields_TwoFieldsAssigned()
{
IMapper mapper = new DtoMapper();
var source = new Source
{
FirstProperty = 1,
SecondProperty = "a",
ThirdProperty = 3.14,
FourthProperty = 2
};
Destination expected = new Destination
{
FirstProperty = 1,
SecondProperty = "a",
};
Destination actual = mapper.Map<Source, Destination>(source);
Assert.Equal(expected, actual);
}
[Fact]
public void Map_CacheMiss_GetCacheForDidNotCalled()
{
var mockCache = new Mock<IMappingFunctionsCache>();
IMapper mapper = new DtoMapper(mockCache.Object);
mapper.Map<object, object>(new object());
mockCache.Verify(cache => cache.GetCacheFor<object, object>(It.IsAny<MappingEntryInfo>()), Times.Never);
}
[Fact]
public void Map_CacheHit_GetCacheForCalled()
{
Assert.True(false, "Not implemented");
}
}
} | mit | C# |
0ab5d39adce0aa1e63ece7a56275a13d71dd8a70 | Improve dependency resolver regex | TheBerkin/Rant | Rant/RantDependencyResolver.cs | Rant/RantDependencyResolver.cs | using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rant
{
/// <summary>
/// Default class for package depdendency resolving.
/// </summary>
public class RantDependencyResolver
{
/// <summary>
/// Attempts to resolve a depdendency to the appropriate package.
/// </summary>
/// <param name="depdendency">The depdendency to resolve.</param>
/// <param name="package">The package loaded from the depdendency.</param>
/// <returns></returns>
public virtual bool TryResolvePackage(RantPackageDependency depdendency, out RantPackage package)
{
package = null;
var path = Path.Combine(Environment.CurrentDirectory, $"{depdendency.ID}.rantpkg");
if (!File.Exists(path))
{
RantPackageVersion version;
// Fallback to name with version appended
path = Directory.GetFiles(Environment.CurrentDirectory, $"{depdendency.ID}*.rantpkg").FirstOrDefault(p =>
{
var match = Regex.Match(Path.GetFileNameWithoutExtension(p), depdendency.ID + @"[\s\-_.]*[vV]?(?<version>\d+(\.\d+){0,2})$", RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture);
if (!match.Success) return false;
version = RantPackageVersion.Parse(match.Groups["version"].Value);
return (depdendency.AllowNewer && version >= depdendency.Version) || depdendency.Version == version;
});
if (path == null) return false;
}
try
{
var pkg = RantPackage.Load(path);
if (pkg.ID != depdendency.ID) return false;
if ((depdendency.AllowNewer && package.Version >= depdendency.Version) || package.Version == depdendency.Version)
{
package = pkg;
return true;
}
return false;
}
catch
{
return false;
}
}
}
} | using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rant
{
/// <summary>
/// Default class for package depdendency resolving.
/// </summary>
public class RantDependencyResolver
{
/// <summary>
/// Attempts to resolve a depdendency to the appropriate package.
/// </summary>
/// <param name="depdendency">The depdendency to resolve.</param>
/// <param name="package">The package loaded from the depdendency.</param>
/// <returns></returns>
public virtual bool TryResolvePackage(RantPackageDependency depdendency, out RantPackage package)
{
package = null;
var path = $"{depdendency.ID}.rantpkg";
if (!File.Exists(path))
{
RantPackageVersion version;
// Fallback to name with version appended
path = Directory.GetFiles(Environment.CurrentDirectory, $"{depdendency.ID}*.rantpkg").FirstOrDefault(p =>
{
var match = Regex.Match(Path.GetFileNameWithoutExtension(p), depdendency.ID + @"[\s\-_.]+v?(?<version>\d+(\.\d+){1,2})");
if (!match.Success) return false;
version = RantPackageVersion.Parse(match.Groups["version"].Value);
return (depdendency.AllowNewer && version >= depdendency.Version) || depdendency.Version == version;
});
if (path == null) return false;
}
try
{
var pkg = RantPackage.Load(path);
if (pkg.ID != depdendency.ID) return false;
if ((depdendency.AllowNewer && package.Version >= depdendency.Version) || package.Version == depdendency.Version)
{
package = pkg;
return true;
}
return false;
}
catch
{
return false;
}
}
}
} | mit | C# |
8d576a9cbbdf7a20ca564b5118b7c65fda0db948 | Make sure a ball can't happen while a goal has already happened! | markmandel/paddle-soccer,markmandel/paddle-soccer,markmandel/paddle-soccer,markmandel/paddle-soccer | Assets/Client/Controllers/BallController.cs | Assets/Client/Controllers/BallController.cs | using System;
using Client.Common;
using Client.Game;
using UnityEngine;
namespace Client.Controllers
{
// Create a ball. Once there is a Goal, create a new
// ball at the given time frame.
public class BallController : MonoBehaviour
{
[SerializeField]
[Tooltip("The soccer ball prefab")]
private GameObject prefabBall;
private GameObject currentBall;
// property to ensure we don't try and create a ball while
// creating a ball
private bool isGoal;
// --- Messages ---
private void Start()
{
if(prefabBall == null)
{
throw new Exception("Prefab should not be null!");
}
isGoal = false;
var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>();
var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>();
p1Goal.TriggerEnter += OnGoal;
p2Goal.TriggerEnter += OnGoal;
CreateBall();
}
// --- Functions ---
// Create a ball. Removes the old one if there is one.
private void OnGoal(Collider _)
{
if(!isGoal)
{
isGoal = true;
Invoke("CreateBall", 5);
}
}
private void CreateBall()
{
if(currentBall != null)
{
Destroy(currentBall);
}
currentBall = Instantiate(prefabBall);
currentBall.name = Ball.Name;
isGoal = false;
}
}
} | using System;
using Client.Common;
using Client.Game;
using UnityEngine;
namespace Client.Controllers
{
// Create a ball. Once there is a Goal, create a new
// ball at the given time frame.
public class BallController : MonoBehaviour
{
[SerializeField]
[Tooltip("The soccer ball prefab")]
private GameObject prefabBall;
private GameObject currentBall;
// --- Messages ---
private void Start()
{
if(prefabBall == null)
{
throw new Exception("Prefab should not be null!");
}
CreateBall();
var p1Goal = Goals.FindPlayerOneGoal().GetComponent<TriggerObservable>();
var p2Goal = Goals.FindPlayerTwoGoal().GetComponent<TriggerObservable>();
p1Goal.TriggerEnter += OnGoal;
p2Goal.TriggerEnter += OnGoal;
}
// --- Functions ---
// Create a ball. Removes the old one if there is one.
private void CreateBall()
{
if(currentBall != null)
{
Destroy(currentBall);
}
currentBall = Instantiate(prefabBall);
currentBall.name = Ball.Name;
}
private void OnGoal(Collider _)
{
Invoke("CreateBall", 5);
}
}
} | apache-2.0 | C# |
a871b6807982d05d0ef14163e00a4a654a6d977e | Remove redundant code | arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5 | src/Arkivverket.Arkade/Core/Archive.cs | src/Arkivverket.Arkade/Core/Archive.cs | using System.IO;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core
{
public class Archive
{
public Uuid Uuid { get; }
public WorkingDirectory WorkingDirectory { get; }
public ArchiveType ArchiveType { get; }
public Archive(ArchiveType archiveType, Uuid uuid, WorkingDirectory workingDirectory)
{
ArchiveType = archiveType;
Uuid = uuid;
WorkingDirectory = workingDirectory;
}
public string GetContentDescriptionFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.ArkivstrukturXmlFileName).FullName;
}
public string GetStructureDescriptionFileName()
{
return WorkingDirectory.AdministrativeMetadata().WithFile(ArkadeConstants.AddmlXmlFileName).FullName;
}
public string GetContentDescriptionXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.ArkivstrukturXsdFileName).FullName;
}
public string GetStructureDescriptionXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.AddmlXsdFileName).FullName;
}
public string GetMetadataCatalogXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.MetadatakatalogXsdFileName).FullName;
}
public bool HasStructureDescriptionXmlSchema()
{
return File.Exists(GetStructureDescriptionXmlSchemaFileName());
}
public bool HasContentDescriptionXmlSchema()
{
return File.Exists(GetContentDescriptionXmlSchemaFileName());
}
public bool HasMetadataCatalogXmlSchema()
{
return File.Exists(GetMetadataCatalogXmlSchemaFileName());
}
public FileInfo GetInformationPackageFileName()
{
return WorkingDirectory.Root().WithFile(Uuid + ".tar");
}
}
public enum ArchiveType
{
Noark3,
Noark4,
Noark5,
Fagsystem,
}
} | using System.IO;
using Arkivverket.Arkade.Util;
namespace Arkivverket.Arkade.Core
{
public class Archive
{
public Uuid Uuid { get; private set; }
public WorkingDirectory WorkingDirectory { get; private set; }
public ArchiveType ArchiveType { get; private set; }
public Archive(ArchiveType archiveType, Uuid uuid, WorkingDirectory workingDirectory)
{
ArchiveType = archiveType;
Uuid = uuid;
WorkingDirectory = workingDirectory;
}
public string GetContentDescriptionFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.ArkivstrukturXmlFileName).FullName;
}
public string GetStructureDescriptionFileName()
{
return WorkingDirectory.AdministrativeMetadata().WithFile(ArkadeConstants.AddmlXmlFileName).FullName;
}
public string GetContentDescriptionXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.ArkivstrukturXsdFileName).FullName;
}
public string GetStructureDescriptionXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.AddmlXsdFileName).FullName;
}
public string GetMetadataCatalogXmlSchemaFileName()
{
return WorkingDirectory.Content().WithFile(ArkadeConstants.MetadatakatalogXsdFileName).FullName;
}
public bool HasStructureDescriptionXmlSchema()
{
return File.Exists(GetStructureDescriptionXmlSchemaFileName());
}
public bool HasContentDescriptionXmlSchema()
{
return File.Exists(GetContentDescriptionXmlSchemaFileName());
}
public bool HasMetadataCatalogXmlSchema()
{
return File.Exists(GetMetadataCatalogXmlSchemaFileName());
}
public FileInfo GetInformationPackageFileName()
{
return WorkingDirectory.Root().WithFile(Uuid.ToString() + ".tar");
}
}
public enum ArchiveType
{
Noark3,
Noark4,
Noark5,
Fagsystem,
}
} | agpl-3.0 | C# |
90217fdb0607ea62e228ac847736d26fad205508 | Update HmacHashGenerator.cs | rileywhite/Bix | src/Bix/Http.Hmac/HmacHashGenerator.cs | src/Bix/Http.Hmac/HmacHashGenerator.cs | /***************************************************************************/
// Copyright 2013-2019 Riley White
//
// 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 Bix.Core;
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace Bix.Http.Hmac
{
public static class HmacHashGenerator
{
public static string Generate(
HmacAuthenticationParameter parameter,
Guid secretKey,
string endpointUri,
string jsonContent = null)
{
if (endpointUri == null)
{
throw new ArgumentNullException(nameof(endpointUri));
}
if (endpointUri == string.Empty)
{
throw new ArgumentException("Cannot be empty", nameof(endpointUri));
}
// normalize any URL encoded characters
endpointUri = WebUtility.UrlDecode(endpointUri);
// exclude the endpointUri scheme if it exists because reverse proxies will sometimes changing the scheme
var slashSlashIndex = endpointUri.IndexOf("//");
if (slashSlashIndex >= 0)
{
endpointUri = endpointUri.Substring(slashSlashIndex + 1);
}
var parameterContainer = new
{
EndpointUri = endpointUri,
JsonContent = jsonContent ?? string.Empty,
Parameter = parameter.CloneWithoutHash(),
};
using (var generator = new HMACSHA512 { Key = secretKey.ToByteArray() })
{
return Convert.ToBase64String(
generator.ComputeHash(
Encoding.UTF8.GetBytes(parameterContainer.ToJson())));
}
}
}
}
| /***************************************************************************/
// Copyright 2013-2019 Riley White
//
// 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 Bix.Core;
using System;
using System.Net;
using System.Security.Cryptography;
using System.Text;
namespace Bix.Http.Hmac
{
public static class HmacHashGenerator
{
public static string Generate(
HmacAuthenticationParameter parameter,
Guid secretKey,
string endpointUri,
string jsonContent = null)
{
if (endpointUri == null)
{
throw new ArgumentNullException(nameof(endpointUri));
}
if (endpointUri == string.Empty)
{
throw new ArgumentException("Cannot be empty", nameof(endpointUri));
}
// normalize any URL encoded characters
endpointUri = WebUtility.UrlDecode(endpointUri);
// exclude the endpointUri scheme if it exists because reverse proxies will sometimes changing the scheme
var slashSlashIndex = endpointUri.IndexOf("//");
if (slashSlashIndex >= 0)
{
endpointUri = endpointUri.Substring(slashSlashIndex);
}
endpointUri = endpointUri.Substring(slashSlashIndex + 1);
var parameterContainer = new
{
EndpointUri = endpointUri,
JsonContent = jsonContent ?? string.Empty,
Parameter = parameter.CloneWithoutHash(),
};
using (var generator = new HMACSHA512 { Key = secretKey.ToByteArray() })
{
return Convert.ToBase64String(
generator.ComputeHash(
Encoding.UTF8.GetBytes(parameterContainer.ToJson())));
}
}
}
}
| apache-2.0 | C# |
ed1ad561e4838a41e157fc73e0da19a970614634 | fix build | RPCS3/discord-bot,Nicba1010/discord-bot | CompatBot/EventHandlers/NewBuildsMonitor.cs | CompatBot/EventHandlers/NewBuildsMonitor.cs | using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CompatBot.Commands;
using DSharpPlus.EventArgs;
namespace CompatBot.EventHandlers
{
internal static class NewBuildsMonitor
{
private static readonly Regex BuildResult = new Regex("build (succeed|pass)ed", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
public static Task OnMessageCreated(MessageCreateEventArgs args)
{
OnMessageCreatedInternal(args);
return Task.CompletedTask;
}
public static async void OnMessageCreatedInternal(MessageCreateEventArgs args)
{
if (!args.Author.IsBot)
return;
if (!"github".Equals(args.Channel.Name, StringComparison.InvariantCultureIgnoreCase))
return;
if (string.IsNullOrEmpty(args.Message.Content) || args.Message.Content.StartsWith(Config.CommandPrefix))
return;
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
if (BuildResult.IsMatch(args.Message.Content))
if (!await CompatList.UpdatesCheck.CheckForRpcs3Updates(args.Client, null).ConfigureAwait(false))
{
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
await CompatList.UpdatesCheck.CheckForRpcs3Updates(args.Client, null).ConfigureAwait(false);
}
}
}
}
| using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using CompatBot.Commands;
using DSharpPlus.EventArgs;
namespace CompatBot.EventHandlers
{
internal static class NewBuildsMonitor
{
private static readonly Regex BuildResult = new Regex("build (succeed|pass)ed", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
public static async void OnMessageCreated(MessageCreateEventArgs args)
{
if (!args.Author.IsBot)
return;
if (!"github".Equals(args.Channel.Name, StringComparison.InvariantCultureIgnoreCase))
return;
if (string.IsNullOrEmpty(args.Message.Content) || args.Message.Content.StartsWith(Config.CommandPrefix))
return;
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
if (BuildResult.IsMatch(args.Message.Content))
if (!await CompatList.UpdatesCheck.CheckForRpcs3Updates(args.Client, null).ConfigureAwait(false))
{
await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);
await CompatList.UpdatesCheck.CheckForRpcs3Updates(args.Client, null).ConfigureAwait(false);
}
}
}
}
| lgpl-2.1 | C# |
fe0e26602975f9f8209c6abd2f9de3f18a65ea61 | Fix issues with wordwrap string extension method | msoler8785/ExoMail | ExoMail.Smtp/Extensions/StringExtensions.cs | ExoMail.Smtp/Extensions/StringExtensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Extensions
{
public static class StringExtensions
{
public static Stream ToStream(this string str)
{
return new MemoryStream(Encoding.ASCII.GetBytes(str));
}
public static string WordWrap(this string str, int cols)
{
return WordWrap(str, cols, string.Empty);
}
public static string WordWrap(this string str, int cols, string indent)
{
string[] words = str.Split(' ');
var sb = new StringBuilder();
int colIndex = 0;
string space = string.Empty;
string newLine = "\r\n";
for (int i = 0; i < words.Count(); i++)
{
space = i == (words.Count() - 1) ? newLine : " ";
colIndex += words[i].Length + space.Length + newLine.Length;
if (colIndex <= cols)
{
sb.AppendFormat("{0}{1}", words[i], space);
}
else
{
colIndex = 0;
sb.AppendFormat("\r\n{0}{1}{2}", indent, words[i], space);
}
if (words[i].Contains(';'))
{
colIndex = 0;
sb.Append(newLine);
sb.Append(indent);
}
}
return sb.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExoMail.Smtp.Extensions
{
public static class StringExtensions
{
public static Stream ToStream(this string str)
{
return new MemoryStream(Encoding.ASCII.GetBytes(str));
}
public static string WordWrap(this string str, int cols)
{
return WordWrap(str, cols, string.Empty);
}
public static string WordWrap(this string str, int cols, string indent)
{
string[] words = str.Split(' ');
var sb = new StringBuilder();
int colIndex = 0;
string space = string.Empty;
for (int i = 0; i < words.Count(); i++)
{
space = i == words.Count() ? string.Empty : " ";
colIndex += words[i].Length + space.Length;
if (colIndex <= cols)
{
sb.Append(string.Format("{0}{1}", words[i], space));
}
else
{
colIndex = 0;
sb.Append(string.Format("\r\n{0}{1}{2}", indent, words[i], space));
}
}
return sb.ToString();
}
}
}
| mit | C# |
34f3fb3fdb9b1853b54f9c338932e9cbd409d235 | Add children node argument | GGG-KILLER/GUtils.NET | GUtils.Parsing.BBCode/Tree/BBNodeFactory.cs | GUtils.Parsing.BBCode/Tree/BBNodeFactory.cs | using System;
namespace GUtils.Parsing.BBCode.Tree
{
/// <summary>
/// A factory for <see cref="BBTextNode" /> and <see cref="BBTagNode" />
/// </summary>
public static class BBNodeFactory
{
/// <summary>
/// Initializes a new <see cref="BBTextNode" /> with the provided <paramref name="text" />.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static BBTextNode Text ( String text ) =>
new BBTextNode ( text );
/// <summary>
/// Initializes a new self-closing <see cref="BBTagNode" /> with the provided
/// <paramref name="name" />.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static BBTagNode SelfClosingTag ( String name ) =>
new BBTagNode ( name );
/// <summary>
/// Initializes a new <see cref="BBTagNode" /> with the provided <paramref name="name" />.
/// </summary>
/// <param name="name"></param>
/// <param name="children"></param>
/// <returns></returns>
public static BBTagNode Tag ( String name, params BBNode[] children )
{
var tag = new BBTagNode ( name, null );
foreach ( BBNode child in children )
tag.AddChild ( child );
return tag;
}
/// <summary>
/// Initializes a new <see cref="BBTagNode" /> with the provided <paramref name="name" /> and
/// <paramref name="value" />.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="children"></param>
/// <returns></returns>
public static BBTagNode Tag ( String name, String value, params BBNode[] children )
{
var tag = new BBTagNode ( name, value );
foreach ( BBNode child in children )
tag.AddChild ( child );
return tag;
}
}
}
| using System;
namespace GUtils.Parsing.BBCode.Tree
{
/// <summary>
/// A factory for <see cref="BBTextNode" /> and <see cref="BBTagNode" />
/// </summary>
public static class BBNodeFactory
{
/// <summary>
/// Initializes a new <see cref="BBTextNode" /> with the provided <paramref name="text" />.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public static BBTextNode Text ( String text ) =>
new BBTextNode ( text );
/// <summary>
/// Initializes a new self-closing <see cref="BBTagNode" /> with the provided
/// <paramref name="name" />.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static BBTagNode SelfClosingTag ( String name ) =>
new BBTagNode ( name );
/// <summary>
/// Initializes a new <see cref="BBTagNode" /> with the provided <paramref name="name" />.
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static BBTagNode Tag ( String name ) =>
new BBTagNode ( name, null );
/// <summary>
/// Initializes a new <see cref="BBTagNode" /> with the provided <paramref name="name" /> and
/// <paramref name="value" />.
/// </summary>
/// <param name="name"></param>
/// <param name="value"></param>
/// <returns></returns>
public static BBTagNode Tag ( String name, String value ) =>
new BBTagNode ( name, value );
}
}
| mit | C# |
fbcac7b2df3ffc204cea2831e9b5131d21afc9a9 | Remove broken out of bounds item | lukecahill/NutritionTracker | food_tracker/NutritionItem.cs | food_tracker/NutritionItem.cs | using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace food_tracker {
public class NutritionItem {
[Key]
public int NutritionItemId { get; set; }
public string name { get; set; }
public double amount { get; set; }
public string dayId { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
[ForeignKey("dayId")]
public WholeDay wholeDay { get; set; }
[Obsolete("Only needed for serialization and materialization", true)]
public NutritionItem() { }
public NutritionItem(string name, string day, List<double> values, double amount) {
this.name = name;
this.dayId = day;
this.calories = values[0];
this.fats = values[1];
this.saturatedFats = values[2];
this.carbohydrates = values[3];
this.sugars = values[4];
this.fibre = values[5];
this.protein = values[6];
this.salt = values[7];
this.amount = amount;
}
public override string ToString() {
return this.name;
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace food_tracker {
public class NutritionItem {
[Key]
public int NutritionItemId { get; set; }
public string name { get; set; }
public double amount { get; set; }
public string dayId { get; set; }
public double calories { get; set; }
public double carbohydrates { get; set; }
public double sugars { get; set; }
public double fats { get; set; }
public double saturatedFats { get; set; }
public double protein { get; set; }
public double salt { get; set; }
public double fibre { get; set; }
[ForeignKey("dayId")]
public WholeDay wholeDay { get; set; }
[Obsolete("Only needed for serialization and materialization", true)]
public NutritionItem() { }
public NutritionItem(string name, string day, List<double> values, double amount) {
this.name = name;
this.dayId = day;
this.calories = values[0];
this.fats = values[1];
this.saturatedFats = values[2];
this.carbohydrates = values[3];
this.sugars = values[4];
this.fibre = values[5];
this.protein = values[6];
this.salt = values[7];
this.amount = values[8];
this.amount = amount;
}
public override string ToString() {
return this.name;
}
}
}
| mit | C# |
b23972f46411358ede5fe40ee677cb0f51cdd66b | Remove Console.out.WriteLine | Seddryck/NBi,Seddryck/NBi | NBi.Testing.Core/ConnectionExceptionTest.cs | NBi.Testing.Core/ConnectionExceptionTest.cs | using System;
using System.Data.OleDb;
using System.Linq;
using NBi.Core;
using NBi.Extensibility;
using NUnit.Framework;
namespace NBi.Testing.Core
{
[TestFixture]
public class ConnectionExceptionTest
{
#region SetUp & TearDown
//Called only at instance creation
[OneTimeSetUp]
public void SetupMethods()
{
}
//Called only at instance destruction
[OneTimeTearDown]
public void TearDownMethods()
{
}
//Called before each test
[SetUp]
public void SetupTest()
{
}
//Called after each test
[TearDown]
public void TearDownTest()
{
}
#endregion
[Test]
public void Ctor_ExceptionCreated_ContainsConnectionString()
{
NBiException nbiEx = null;
// Open the connection
using (var connection = new OleDbConnection())
{
var connectionString = "CONNECTION STRING TO DISPLAY";
try
{ connection.ConnectionString = connectionString; }
catch (ArgumentException ex)
{
nbiEx = Assert.Catch<NBiException>(delegate { throw new ConnectionException(ex, connectionString); });
}
if (nbiEx == null)
Assert.Fail("An exception should have been thrown");
else
{
Assert.That(nbiEx.Message, Does.Contain(connectionString));
}
}
}
}
}
| using System;
using System.Data.OleDb;
using System.Linq;
using NBi.Core;
using NBi.Extensibility;
using NUnit.Framework;
namespace NBi.Testing.Core
{
[TestFixture]
public class ConnectionExceptionTest
{
#region SetUp & TearDown
//Called only at instance creation
[OneTimeSetUp]
public void SetupMethods()
{
}
//Called only at instance destruction
[OneTimeTearDown]
public void TearDownMethods()
{
}
//Called before each test
[SetUp]
public void SetupTest()
{
}
//Called after each test
[TearDown]
public void TearDownTest()
{
}
#endregion
[Test]
public void Ctor_ExceptionCreated_ContainsConnectionString()
{
NBiException nbiEx = null;
// Open the connection
using (var connection = new OleDbConnection())
{
var connectionString = "CONNECTION STRING TO DISPLAY";
try
{ connection.ConnectionString = connectionString; }
catch (ArgumentException ex)
{
nbiEx = Assert.Catch<NBiException>(delegate { throw new ConnectionException(ex, connectionString); });
}
if (nbiEx == null)
Assert.Fail("An exception should have been thrown");
else
{
//Test can continue
Console.Out.WriteLine(nbiEx.Message);
Assert.That(nbiEx.Message, Does.Contain(connectionString));
}
}
}
}
}
| apache-2.0 | C# |
e6d2199b224307fea2817096706fd15ca8d9571b | Use the generic AbstractKeywordHighlighter<TNode> as base class. | jmarolf/roslyn,stephentoub/roslyn,aelij/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,agocke/roslyn,mgoertz-msft/roslyn,gafter/roslyn,jasonmalinowski/roslyn,aelij/roslyn,davkean/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,genlu/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,mavasani/roslyn,tmat/roslyn,diryboy/roslyn,diryboy/roslyn,sharwell/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,reaction1989/roslyn,heejaechang/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,sharwell/roslyn,reaction1989/roslyn,wvdd007/roslyn,abock/roslyn,abock/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,brettfo/roslyn,physhi/roslyn,brettfo/roslyn,jmarolf/roslyn,KirillOsenkov/roslyn,physhi/roslyn,jasonmalinowski/roslyn,aelij/roslyn,weltkante/roslyn,bartdesmet/roslyn,davkean/roslyn,physhi/roslyn,jmarolf/roslyn,genlu/roslyn,tmat/roslyn,heejaechang/roslyn,weltkante/roslyn,tmat/roslyn,gafter/roslyn,eriawan/roslyn,tannergooding/roslyn,stephentoub/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,agocke/roslyn,bartdesmet/roslyn,davkean/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,reaction1989/roslyn,dotnet/roslyn,brettfo/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,gafter/roslyn,eriawan/roslyn,dotnet/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,mavasani/roslyn,panopticoncentral/roslyn,dotnet/roslyn,abock/roslyn,wvdd007/roslyn,KevinRansom/roslyn,genlu/roslyn,agocke/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn | src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/DiscardParameterHighlighter.cs | src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/DiscardParameterHighlighter.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Highlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp)]
internal class DiscardParameterHighlighter : AbstractKeywordHighlighter<ArgumentSyntax>
{
[ImportingConstructor]
public DiscardParameterHighlighter()
{
}
protected override IEnumerable<TextSpan> GetHighlights(ArgumentSyntax node, CancellationToken cancellationToken)
{
if (node.Expression.IsKind(SyntaxKind.IdentifierName))
{
var syntax = (IdentifierNameSyntax)node.Expression;
if(syntax.Identifier.Text == "_")
{
return ImmutableArray.Create(syntax.Identifier.Span);
}
}
if (node.Expression.IsKind(SyntaxKind.DeclarationExpression))
{
var syntax = (DeclarationExpressionSyntax)node.Expression;
if (syntax.Designation.IsKind(SyntaxKind.DiscardDesignation))
{
return ImmutableArray.Create(syntax.Designation.Span);
}
}
return SpecializedCollections.EmptyEnumerable<TextSpan>();
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.CSharp.Highlighting.KeywordHighlighters
{
[ExportHighlighter(LanguageNames.CSharp)]
internal class DiscardParameterHighlighter : AbstractKeywordHighlighter
{
[ImportingConstructor]
public DiscardParameterHighlighter()
{
}
protected override bool IsHighlightableNode(SyntaxNode node)
{
if (!node.IsKind(CodeAnalysis.CSharp.SyntaxKind.Argument) || !(node is ArgumentSyntax syntax))
{
return false;
}
if (!syntax.RefOrOutKeyword.IsKind(SyntaxKind.OutKeyword))
{
return false;
}
if (syntax.Expression.IsKind(SyntaxKind.IdentifierName) && syntax.Expression is IdentifierNameSyntax name)
{
return name.Identifier.Text == "_";
}
if (syntax.Expression.IsKind(SyntaxKind.DeclarationExpression) && syntax.Expression is DeclarationExpressionSyntax declaration)
{
return declaration.Designation.IsKind(SyntaxKind.DiscardDesignation);
}
return false;
}
protected override IEnumerable<TextSpan> GetHighlightsForNode(SyntaxNode node, CancellationToken cancellationToken)
{
var argument = (ArgumentSyntax)node;
if (argument.Expression.IsKind(SyntaxKind.IdentifierName))
{
return ImmutableArray.Create(((IdentifierNameSyntax)argument.Expression).Identifier.Span);
}
if (argument.Expression.IsKind(SyntaxKind.DeclarationExpression))
{
return ImmutableArray.Create(((DeclarationExpressionSyntax)argument.Expression).Designation.Span);
}
return SpecializedCollections.EmptyEnumerable<TextSpan>();
}
}
}
| mit | C# |
4f7af51199cfeaadea3ba743925a7b3f84dea571 | Add update to serializedObject in diagnostic inspector so changes actually apply | killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity,vladkol/MixedRealityToolkit-Unity,StephenHodgson/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,vladkol/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity | Assets/MixedRealityToolkit/_Core/Inspectors/Profiles/MixedRealityDiagnosticsSystemProfileInspector.cs | Assets/MixedRealityToolkit/_Core/Inspectors/Profiles/MixedRealityDiagnosticsSystemProfileInspector.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.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.Definitions.Diagnostics;
using Microsoft.MixedReality.Toolkit.Core.Managers;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Core.Inspectors.Profiles
{
[CustomEditor(typeof(MixedRealityDiagnosticsProfile))]
public class MixedRealityDiagnosticsSystemProfileInspector : MixedRealityBaseConfigurationProfileInspector
{
private SerializedProperty showCpu;
private SerializedProperty showFps;
private SerializedProperty showMemory;
private SerializedProperty visible;
private void OnEnable()
{
if (!CheckMixedRealityManager(false))
{
return;
}
showCpu = serializedObject.FindProperty("showCpu");
showFps = serializedObject.FindProperty("showFps");
showMemory = serializedObject.FindProperty("showMemory");
visible = serializedObject.FindProperty("visible");
}
public override void OnInspectorGUI()
{
RenderMixedRealityToolkitLogo();
if (!CheckMixedRealityManager())
{
return;
}
if (GUILayout.Button("Back to Configuration Profile"))
{
Selection.activeObject = MixedRealityManager.Instance.ActiveProfile;
}
if (MixedRealityPreferences.LockProfiles && !((BaseMixedRealityProfile)target).IsCustomProfile)
{
GUI.enabled = false;
}
serializedObject.Update();
EditorGUILayout.Space();
EditorGUILayout.LabelField("Diagnostic Visualization Options", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("Diagnostic visualizations can help monitor system resources and performance inside an application.", MessageType.Info);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(visible);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(showCpu);
EditorGUILayout.PropertyField(showFps);
EditorGUILayout.PropertyField(showMemory);
serializedObject.ApplyModifiedProperties();
}
}
}
| // 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.Core.Definitions;
using Microsoft.MixedReality.Toolkit.Core.Definitions.Diagnostics;
using Microsoft.MixedReality.Toolkit.Core.Managers;
using UnityEditor;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Core.Inspectors.Profiles
{
[CustomEditor(typeof(MixedRealityDiagnosticsProfile))]
public class MixedRealityDiagnosticsSystemProfileInspector : MixedRealityBaseConfigurationProfileInspector
{
private SerializedProperty showCpu;
private SerializedProperty showFps;
private SerializedProperty showMemory;
private SerializedProperty visible;
private void OnEnable()
{
if (!CheckMixedRealityManager(false))
{
return;
}
showCpu = serializedObject.FindProperty("showCpu");
showFps = serializedObject.FindProperty("showFps");
showMemory = serializedObject.FindProperty("showMemory");
visible = serializedObject.FindProperty("visible");
}
public override void OnInspectorGUI()
{
RenderMixedRealityToolkitLogo();
if (!CheckMixedRealityManager())
{
return;
}
if (GUILayout.Button("Back to Configuration Profile"))
{
Selection.activeObject = MixedRealityManager.Instance.ActiveProfile;
}
if (MixedRealityPreferences.LockProfiles && !((BaseMixedRealityProfile)target).IsCustomProfile)
{
GUI.enabled = false;
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Diagnostic Visualization Options", EditorStyles.boldLabel);
EditorGUILayout.HelpBox("Diagnostic visualizations can help monitor system resources and performance inside an application.", MessageType.Info);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(visible);
EditorGUILayout.Space();
EditorGUILayout.PropertyField(showCpu);
EditorGUILayout.PropertyField(showFps);
EditorGUILayout.PropertyField(showMemory);
}
}
}
| mit | C# |
8bc85e0a34fb02ed3eb92cccfa59054fbfec6067 | Set AssemblyVersion and AssemblyFileVersion to 1.0.0.0 | mehrandvd/Tralus,mehrandvd/Tralus | Shell/Source/Tralus.Shell.WorkflowService/Properties/AssemblyInfo.cs | Shell/Source/Tralus.Shell.WorkflowService/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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 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("Tralus.Shell.WorkflowService")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Tralus.Shell.WorkflowService")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
[assembly: AssemblyVersion("1.0.*")]
| apache-2.0 | C# |
79c3eb4662a7c1d55dec82398236352ea2cd1542 | move YamlOptions to Halforbit.DataStores namespace | halforbit/data-stores | FileStores/Serialization/Yaml/Halforbit.DataStores.FileStores.Serialization.Yaml/Model/YamlOptions.cs | FileStores/Serialization/Yaml/Halforbit.DataStores.FileStores.Serialization.Yaml/Model/YamlOptions.cs | using System;
namespace Halforbit.DataStores
{
[Flags]
public enum YamlOptions
{
None = 0,
CamelCaseEnumValues = 1,
CamelCasePropertyNames = 2,
RemoveDefaultValues = 4,
OmitGuidDashes = 8,
Default = CamelCasePropertyNames | CamelCaseEnumValues | RemoveDefaultValues | OmitGuidDashes
}
}
| using System;
namespace Halforbit.DataStores.FileStores.Serialization.Yaml.Model
{
[Flags]
public enum YamlOptions
{
None = 0,
CamelCaseEnumValues = 1,
CamelCasePropertyNames = 2,
RemoveDefaultValues = 4,
OmitGuidDashes = 8,
Default = CamelCasePropertyNames | CamelCaseEnumValues | RemoveDefaultValues | OmitGuidDashes
}
}
| mit | C# |
ebdeb7b1f4e533100225307f4faf6060d826f7a1 | Update Time.cs | dimmpixeye/Unity3dTools | Runtime/LibTime/Time.cs | Runtime/LibTime/Time.cs | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
namespace Pixeye.Actors
{
public class time : IKernel
{
protected const float fps = 60;
/// <summary>
/// <para> Default Framework Time. Use it for independent timing</para>
/// </summary>
internal static time Default = new time();
public static int frame => UnityEngine.Time.frameCount;
/// <summary>
/// <para> The scale at which the time is passing. This can be used for slow motion effects.</para>
/// </summary>
public float timeScale = 1.0f;
protected float deltaTimeFixed;
protected float deltaTime;
internal float timeScaleCached = 1.0f;
public static float scale => Default.timeScale;
/// <summary>
/// <para> The time in seconds it took to complete the last frame</para>
/// </summary>
public static float delta => Default.deltaTime;
/// <summary>
/// <para> 1 / 60 constant time</para>
/// </summary>
public static float deltaFixed => Default.deltaTimeFixed;
public time()
{
ProcessorUpdate.times.Add(this);
ProcessorUpdate.timesLen++;
deltaTimeFixed = 1 / fps;
deltaTime = deltaTimeFixed;
}
public void Tick()
{
deltaTime = UnityEngine.Time.deltaTime * timeScale;
deltaTimeFixed *= timeScale;
}
}
} | // Project : ACTORS
// Contacts : Pixeye - ask@pixeye.games
namespace Pixeye.Actors
{
public class time : IKernel
{
protected const float fps = 60;
/// <summary>
/// <para> Default Framework Time. Use it for independent timing</para>
/// </summary>
internal static time Default = new time();
public static int frame => UnityEngine.Time.frameCount;
/// <summary>
/// <para> The scale at which the time is passing. This can be used for slow motion effects.</para>
/// </summary>
public float timeScale = 1.0f;
protected float deltaTimeFixed;
protected float deltaTime;
internal float timeScaleCached = 1.0f;
/// <summary>
/// <para> The time in seconds it took to complete the last frame</para>
/// </summary>
public static float delta => Default.deltaTime;
/// <summary>
/// <para> 1 / 60 constant time</para>
/// </summary>
public static float deltaFixed => Default.deltaTimeFixed;
public time()
{
ProcessorUpdate.times.Add(this);
ProcessorUpdate.timesLen++;
deltaTimeFixed = 1 / fps;
deltaTime = deltaTimeFixed;
}
public void Tick()
{
deltaTime = UnityEngine.Time.deltaTime * timeScale;
deltaTimeFixed *= timeScale;
}
}
} | mit | C# |
f343c503d79df0e0264c7340a16322edff52d972 | add Standard to IsDigits benchmark | maxhauser/semver | Semver.Benchmarks/IsDigits.cs | Semver.Benchmarks/IsDigits.cs | using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using Semver.Utility;
namespace Semver.Benchmarks
{
[SimpleJob(RuntimeMoniker.Net461)]
[SimpleJob(RuntimeMoniker.NetCoreApp21)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
public class IsDigits
{
private const string Value = "245413548946516575165756156751323245451984";
[Benchmark]
public bool Standard() => Value.IsDigits();
[Benchmark]
public bool ForeachLoop() => ForeachIsDigits(Value);
[Benchmark]
public bool ForLoop() => ForIsDigits(Value);
public static bool ForeachIsDigits(string value)
{
foreach (var c in value)
if (!c.IsDigit())
return false;
return true;
}
public static bool ForIsDigits(string value)
{
for (var i = 0; i < value.Length; i++)
if (!value[i].IsDigit())
return false;
return true;
}
}
}
| using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using Semver.Utility;
namespace Semver.Benchmarks
{
[SimpleJob(RuntimeMoniker.Net461)]
[SimpleJob(RuntimeMoniker.NetCoreApp21)]
[SimpleJob(RuntimeMoniker.NetCoreApp31)]
public class IsDigits
{
private const string Value = "245413548946516575165756156751323245451984";
[Benchmark]
public bool ForeachLoop() => ForeachIsDigit(Value);
[Benchmark]
public bool ForLoop() => ForIsDigit(Value);
public static bool ForeachIsDigit(string value)
{
foreach (var c in value)
if (!c.IsDigit())
return false;
return true;
}
public static bool ForIsDigit(string value)
{
for (var i = 0; i < value.Length; i++)
if (!value[i].IsDigit())
return false;
return true;
}
}
}
| mit | C# |
dfb482d31a395d1d1657616072fec7a78d431073 | Disable the trace listener as too many people have it on and forget... (#219) | nkdAgility/vsts-sync-migration | src/VstsSyncMigrator.Core/Telemetry.cs | src/VstsSyncMigrator.Core/Telemetry.cs | using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
using Microsoft.ApplicationInsights.TraceListener;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VstsSyncMigrator.Engine
{
public static class Telemetry
{
private const string applicationInsightsKey = "4b9bb17b-c7ee-43e5-b220-ec6db2c33373";
private static TelemetryClient telemetryClient;
private static bool enableTrace = false;
public static bool EnableTrace { get { return enableTrace; } set { enableTrace = value; } }
public static TelemetryClient Current { get {
if (telemetryClient == null)
{
InitiliseTelemetry();
}
return telemetryClient;
// No change
} }
public static void InitiliseTelemetry()
{
//if (enableTrace) { Trace.Listeners.Add(new ApplicationInsightsTraceListener(applicationInsightsKey)); }
TelemetryConfiguration.Active.InstrumentationKey = applicationInsightsKey;
telemetryClient = new TelemetryClient();
telemetryClient.InstrumentationKey = applicationInsightsKey;
telemetryClient.Context.User.Id = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
telemetryClient.Context.Component.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
Trace.WriteLine(string.Format("SessionID: {0}", telemetryClient.Context.Session.Id));
AddModules();
telemetryClient.TrackEvent("ApplicationStarted");
}
public static void AddModules()
{
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
string.Format(@"\.NET CLR Memory({0})\# GC Handles", System.AppDomain.CurrentDomain.FriendlyName), "GC Handles"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
}
}
}
| using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.PerfCounterCollector;
using Microsoft.ApplicationInsights.TraceListener;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VstsSyncMigrator.Engine
{
public static class Telemetry
{
private const string applicationInsightsKey = "4b9bb17b-c7ee-43e5-b220-ec6db2c33373";
private static TelemetryClient telemetryClient;
private static bool enableTrace = false;
public static bool EnableTrace { get { return enableTrace; } set { enableTrace = value; } }
public static TelemetryClient Current { get {
if (telemetryClient == null)
{
InitiliseTelemetry();
}
return telemetryClient;
// No change
} }
public static void InitiliseTelemetry()
{
if (enableTrace) { Trace.Listeners.Add(new ApplicationInsightsTraceListener(applicationInsightsKey)); }
TelemetryConfiguration.Active.InstrumentationKey = applicationInsightsKey;
telemetryClient = new TelemetryClient();
telemetryClient.InstrumentationKey = applicationInsightsKey;
telemetryClient.Context.User.Id = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
telemetryClient.Context.Session.Id = Guid.NewGuid().ToString();
telemetryClient.Context.Device.OperatingSystem = Environment.OSVersion.ToString();
telemetryClient.Context.Component.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
Trace.WriteLine(string.Format("SessionID: {0}", telemetryClient.Context.Session.Id));
AddModules();
telemetryClient.TrackEvent("ApplicationStarted");
}
public static void AddModules()
{
var perfCollectorModule = new PerformanceCollectorModule();
perfCollectorModule.Counters.Add(new PerformanceCounterCollectionRequest(
string.Format(@"\.NET CLR Memory({0})\# GC Handles", System.AppDomain.CurrentDomain.FriendlyName), "GC Handles"));
perfCollectorModule.Initialize(TelemetryConfiguration.Active);
}
}
}
| mit | C# |
06a2774e2580457a3da278fdeeb4353f5b929cc2 | create file on save if not exists | feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,edewit/fh-dotnet-sdk,feedhenry/fh-dotnet-sdk | FHSDKPortable/Services/Data/IOService.cs | FHSDKPortable/Services/Data/IOService.cs | using System;
using Windows.Storage;
namespace FHSDK.Services.Data
{
internal class IOService : IIOService
{
public string ReadFile(string fullPath)
{
var file = GetFile(fullPath);
return FileIO.ReadTextAsync(file).AsTask().Result;
}
public void WriteFile(string fullPath, string content)
{
var file = CreateIfNotExists(fullPath);
FileIO.WriteTextAsync(file, content).AsTask().Wait();
}
public bool Exists(string fullPath)
{
try
{
GetFile(fullPath);
return true;
}
catch (Exception)
{
return false;
}
}
public string GetDataPersistDir()
{
return ApplicationData.Current.LocalFolder.Path;
}
private static StorageFile GetFile(string fullPath)
{
return StorageFile.GetFileFromPathAsync(fullPath).AsTask().Result;
}
private StorageFile CreateIfNotExists(string fullPath)
{
if (!Exists(fullPath))
{
var path = fullPath.Substring(GetDataPersistDir().Length);
return ApplicationData.Current.LocalFolder.CreateFileAsync(path, CreationCollisionOption.OpenIfExists).AsTask().Result;
}
return StorageFile.GetFileFromPathAsync(fullPath).AsTask().Result;
}
}
} | using System;
using System.IO;
using Windows.Storage;
namespace FHSDK.Services.Data
{
internal class IOService : IIOService
{
public string ReadFile(string fullPath)
{
var file = GetFile(fullPath);
return FileIO.ReadTextAsync(file).AsTask().Result;
}
public void WriteFile(string fullPath, string content)
{
var file = GetFile(fullPath);
FileIO.WriteTextAsync(file, content).AsTask().Wait();
}
public bool Exists(string fullPath)
{
try
{
GetFile(fullPath);
return true;
}
catch (FileNotFoundException)
{
return false;
}
}
public string GetDataPersistDir()
{
var local = ApplicationData.Current.LocalFolder;
return local.Path;
}
private static StorageFile GetFile(string fullPath)
{
return StorageFile.GetFileFromPathAsync(fullPath).AsTask().Result;
}
}
} | apache-2.0 | C# |
fe60dd60125d4d716b456038aa231a88e40e514e | Fix version result | Thulur/GitStatisticsAnalyzer,Thulur/GitDataExplorer | GitDataExplorer/Results/VersionResult.cs | GitDataExplorer/Results/VersionResult.cs | using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace GitDataExplorer.Results
{
class VersionResult : IResult
{
public override bool Equals(object obj)
{
VersionResult versionResult = obj as VersionResult;
if (versionResult == null) return false;
return Major == versionResult.Major && Minor == versionResult.Minor && Bugfix == versionResult.Bugfix;
}
public override int GetHashCode() => Major.GetHashCode() ^ Minor.GetHashCode() ^ Bugfix.GetHashCode();
public override string ToString() => Major.ToString() + "." + Minor.ToString() + "." + Bugfix.ToString();
public void ParseResult(IList<string> lines)
{
string versionLine = lines[0];
if (Regex.IsMatch(versionLine, @"git version [0-9]\.[0-9]\.[0-9][\s\S]*"))
{
string versionString = Regex.Match(versionLine, @"[0-9]\.[0-9]\.[0-9]").ToString();
IList<string> versionNumbers = versionString.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
Major = Convert.ToByte(versionNumbers[0]);
Minor = Convert.ToByte(versionNumbers[1]);
Bugfix = Convert.ToByte(versionNumbers[2]);
ExecutionResult = ExecutionResult.Success;
}
}
public byte Major { get; private set; }
public byte Minor { get; private set; }
public byte Bugfix { get; private set; }
public ExecutionResult ExecutionResult { get; private set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace GitDataExplorer.Results
{
class VersionResult : IResult
{
public override bool Equals(object obj)
{
VersionResult versionResult = obj as VersionResult;
if (versionResult == null) return false;
return Major == versionResult.Major && Minor == versionResult.Minor && Bugfix == versionResult.Bugfix;
}
public override int GetHashCode() => Major.GetHashCode() ^ Minor.GetHashCode() ^ Bugfix.GetHashCode();
public override string ToString() => Major.ToString() + "." + Minor.ToString() + "." + Bugfix.ToString();
public void ParseResult(IList<string> lines)
{
string versionLine = lines[0];
if (Regex.IsMatch(versionLine, @"git version [0-9]\.[0-9]\.[0-9]"))
{
string versionString = Regex.Match(versionLine, @"[0-9]\.[0-9]\.[0-9]").ToString();
IList<string> versionNumbers = versionString.Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
Major = Convert.ToByte(versionNumbers[0]);
Minor = Convert.ToByte(versionNumbers[1]);
Bugfix = Convert.ToByte(versionNumbers[2]);
ExecutionResult = ExecutionResult.Success;
}
}
public byte Major { get; private set; }
public byte Minor { get; private set; }
public byte Bugfix { get; private set; }
public ExecutionResult ExecutionResult { get; private set; }
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.