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
3df3086c2794c7b8829a0c9a662ca3e6a3c215c9
Add TilePOI to list of tile names
fistak/MaterialColor
MaterialColor.Core/State.cs
MaterialColor.Core/State.cs
using MaterialColor.Common.Data; using System.Collections.Generic; using UnityEngine; namespace MaterialColor.Core { public static class State { public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>(); public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>(); public static ConfiguratorState ConfiguratorState = new ConfiguratorState(); public static bool Disabled = false; public static readonly List<string> TileNames = new List<string> { "Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane", "TilePOI" }; } }
using MaterialColor.Common.Data; using System.Collections.Generic; using UnityEngine; namespace MaterialColor.Core { public static class State { public static Dictionary<string, Color32> TypeColorOffsets = new Dictionary<string, Color32>(); public static Dictionary<SimHashes, ElementColorInfo> ElementColorInfos = new Dictionary<SimHashes, ElementColorInfo>(); public static ConfiguratorState ConfiguratorState = new ConfiguratorState(); public static bool Disabled = false; public static readonly List<string> TileNames = new List<string> { "Tile", "MeshTile", "InsulationTile", "GasPermeableMembrane" }; } }
mit
C#
edb97837fd8908405307e60b9d37b748693a217f
Remove connection warmup
samcook/RedLock.net
RedLock/RedisLockFactory.cs
RedLock/RedisLockFactory.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using RedLock.Logging; using StackExchange.Redis; namespace RedLock { public class RedisLockFactory : IDisposable { private readonly IList<ConnectionMultiplexer> redisCaches; private readonly IRedLockLogger logger; public RedisLockFactory(params EndPoint[] redisEndPoints) : this(redisEndPoints, null) { } public RedisLockFactory(IEnumerable<EndPoint> redisEndPoints) : this(redisEndPoints, null) { } public RedisLockFactory(IEnumerable<EndPoint> redisEndPoints, IRedLockLogger logger) { redisCaches = CreateRedisCaches(redisEndPoints.ToArray()); this.logger = logger ?? new NullLogger(); } private IList<ConnectionMultiplexer> CreateRedisCaches(ICollection<EndPoint> redisEndPoints) { var caches = new List<ConnectionMultiplexer>(redisEndPoints.Count); foreach (var endPoint in redisEndPoints) { var configuration = new ConfigurationOptions { AbortOnConnectFail = false, ConnectTimeout = 100 }; configuration.EndPoints.Add(endPoint); caches.Add(ConnectionMultiplexer.Connect(configuration)); } return caches; } public RedisLock Create(string resource, TimeSpan expiryTime) { return new RedisLock(redisCaches, resource, expiryTime, null, logger); } public void Dispose() { foreach (var cache in redisCaches) { cache.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using RedLock.Logging; using StackExchange.Redis; namespace RedLock { public class RedisLockFactory : IDisposable { private readonly IList<ConnectionMultiplexer> redisCaches; private readonly IRedLockLogger logger; public RedisLockFactory(params EndPoint[] redisEndPoints) : this(redisEndPoints, null) { } public RedisLockFactory(IEnumerable<EndPoint> redisEndPoints) : this(redisEndPoints, null) { } public RedisLockFactory(IEnumerable<EndPoint> redisEndPoints, IRedLockLogger logger) { redisCaches = CreateRedisCaches(redisEndPoints.ToArray()); this.logger = logger ?? new NullLogger(); } private IList<ConnectionMultiplexer> CreateRedisCaches(ICollection<EndPoint> redisEndPoints, bool tryToWarmUpConnections = true) { var caches = new List<ConnectionMultiplexer>(redisEndPoints.Count); foreach (var endPoint in redisEndPoints) { var configuration = new ConfigurationOptions { AbortOnConnectFail = false, ConnectTimeout = 100 }; configuration.EndPoints.Add(endPoint); var cache = ConnectionMultiplexer.Connect(configuration); if (tryToWarmUpConnections) { try { var ping = cache.GetDatabase().Ping(); logger.DebugWrite("{0} Ping 1 took {1}ms", RedisLock.GetHost(cache), ping.TotalMilliseconds); ping = cache.GetDatabase().Ping(); logger.DebugWrite("{0} Ping 2 took {1}ms", RedisLock.GetHost(cache), ping.TotalMilliseconds); } // ReSharper disable once EmptyGeneralCatchClause catch (Exception) { // ignore this } } caches.Add(cache); } return caches; } public RedisLock Create(string resource, TimeSpan expiryTime) { return new RedisLock(redisCaches, resource, expiryTime, null, logger); } public void Dispose() { foreach (var cache in redisCaches) { cache.Dispose(); } } } }
mit
C#
874a2ec7688979fadfe95662b8953610b3831399
update to event role dto
Paymentsense/Dapper.SimpleSave
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/EventRoleLnkDto.cs
PS.Mothership.Core/PS.Mothership.Core.Common/Dto/Event/EventRoleLnkDto.cs
using System; using System.Runtime.Serialization; using PS.Mothership.Core.Common.Dto.Roles; namespace PS.Mothership.Core.Common.Dto.Event { [DataContract] public class EventRoleLnkDto { [DataMember] public Guid EventRoleGuid { get; set; } [DataMember] public Guid RoleGuid { get; set; } [DataMember] public Guid EventGuid { get; set; } [DataMember] public DateTimeOffset UpdateDate { get; set; } [DataMember] public Guid UpdateSessionGuid { get; set; } [DataMember] public EventTransactionDto Event { get; set; } [DataMember] public RoleDto Role { get; set; } } }
using System; using System.Runtime.Serialization; using PS.Mothership.Core.Common.Dto.Roles; namespace PS.Mothership.Core.Common.Dto.Event { [DataContract] public class EventRoleLnkDto { [DataMember] public Guid EventRoleGuid { get; set; } [DataMember] public Guid RoleGuid { get; set; } [DataMember] public Guid EventGuid { get; set; } [DataMember] public EventTransactionDto Event { get; set; } [DataMember] public RoleDto Role { get; set; } } }
mit
C#
826db370458641e08f66de445f12a2eabfbbd1ca
Fix hair rendering offset for ranged weapons
ethanmoffat/EndlessClient
EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs
EndlessClient/Rendering/CharacterProperties/HairRenderLocationCalculator.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; namespace EndlessClient.Rendering.CharacterProperties { public class HairRenderLocationCalculator { private readonly ICharacterRenderProperties _renderProperties; public HairRenderLocationCalculator(ICharacterRenderProperties renderProperties) { _renderProperties = renderProperties; } public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea) { var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; var isFlipped = _renderProperties.IsFacing(EODirection.Up, EODirection.Right); if (_renderProperties.IsRangedWeapon && _renderProperties.AttackFrame == 1) { var rangedXOff = _renderProperties.Gender == 0 ? 1 : 3; resX += rangedXOff * (isFlipped ? 1 : -1); resY += _renderProperties.IsFacing(EODirection.Down, EODirection.Right) ? 1 : 0; } else if (_renderProperties.AttackFrame == 2) { resX += isFlipped ? 4 : -4; resX += _renderProperties.IsFacing(EODirection.Up) ? _renderProperties.Gender * -2 : _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender * 2 : 0; resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; } var flippedOffset = isFlipped ? 2 : 0; return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EOLib; using EOLib.Domain.Character; using EOLib.Domain.Extensions; using Microsoft.Xna.Framework; namespace EndlessClient.Rendering.CharacterProperties { public class HairRenderLocationCalculator { private readonly ICharacterRenderProperties _renderProperties; public HairRenderLocationCalculator(ICharacterRenderProperties renderProperties) { _renderProperties = renderProperties; } public Vector2 CalculateDrawLocationOfCharacterHair(Rectangle hairRectangle, Rectangle parentCharacterDrawArea) { var resX = -(float)Math.Floor(Math.Abs((float)hairRectangle.Width - parentCharacterDrawArea.Width) / 2) - 1; var resY = -(float)Math.Floor(Math.Abs(hairRectangle.Height - (parentCharacterDrawArea.Height / 2f)) / 2) - _renderProperties.Gender; if (_renderProperties.AttackFrame == 2) { resX += _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 4 : -4; resX += _renderProperties.IsFacing(EODirection.Up) ? _renderProperties.Gender * -2 : _renderProperties.IsFacing(EODirection.Left) ? _renderProperties.Gender * 2 : 0; resY += _renderProperties.IsFacing(EODirection.Up, EODirection.Left) ? 1 : 5; resY -= _renderProperties.IsFacing(EODirection.Right, EODirection.Down) ? _renderProperties.Gender : 0; } var flippedOffset = _renderProperties.IsFacing(EODirection.Up, EODirection.Right) ? 2 : 0; return parentCharacterDrawArea.Location.ToVector2() + new Vector2(resX + flippedOffset, resY); } } }
mit
C#
78f4bff84f15b3bedb707e61398026626ae1720d
work on DateTimeTests
Teodor92/MoreDotNet,vladislav-karamfilov/MoreDotNet
Source/MoreDotNet.Test/Extensions/Common/RandomExtensions/NextDateTime.cs
Source/MoreDotNet.Test/Extensions/Common/RandomExtensions/NextDateTime.cs
namespace MoreDotNet.Tests.Extensions.Common.RandomExtensions { using System; using System.Linq; using MoreDotNet.Extensions.Common; using Xunit; public class NextDateTime { private const int Counter = 1000; [Fact] public void NextDateTime_ShouldThrow_ArgumentNullException() { Random random = null; Assert.Throws<ArgumentNullException>(() => random.NextDateTime()); } // TODO: minValue => null / maxValue => null ; [Fact] public void NextDateTime_ShouldReturnDateTime() { var random = new Random(); var result = random.NextDateTime(); Assert.IsType<DateTime>(result); } [Fact] public void NextDateTime_ShouldReturnDateTime_OneHundredDistinctValues() { // TODO: Fix test var random = new Random(); var dates = new DateTime[Counter]; for (int i = 0; i < Counter; i++) { dates[i] = random.NextDateTime(); } Assert.Equal(Counter, dates.Distinct().Count()); } [Fact] public void NextDateTime_ShouldReturnDateTime_BetweenMinAndMaxValue() { var random = new Random(); var mivValue = new DateTime(2016, 1, 1, 0, 0, 0); var maxValue = new DateTime(2018, 1, 1, 0, 0, 0); for (int i = 0; i < Counter; i++) { var result = random.NextDateTime(mivValue, maxValue); Assert.True(result >= mivValue && result < maxValue); } } } }
namespace MoreDotNet.Tests.Extensions.Common.RandomExtensions { using System; using System.Linq; using MoreDotNet.Extensions.Common; using Xunit; public class NextDateTime { [Fact] public void NextDateTime_ShouldReturnDateTime() { var random = new Random(); var result = random.NextDateTime(); Assert.IsType<DateTime>(result); } [Fact] public void NextDateTime_ShouldReturnDateTime_OneHundredDistinctValues() { // TODO: Fix test var random = new Random(); var counter = 100; var dates = new DateTime[counter]; for (int i = 0; i < counter; i++) { dates[i] = random.NextDateTime(); } Assert.Equal(counter, dates.Distinct().Count()); } [Fact] public void NextDateTime_ShouldReturnDateTime_BetweenMinAndMaxValue() { var random = new Random(); var mivValue = new DateTime(2016, 1, 1, 0, 0, 0); var maxValue = new DateTime(2018, 1, 1, 0, 0, 0); var result = random.NextDateTime(mivValue, maxValue); Assert.True(result >= mivValue && result < maxValue); } } }
mit
C#
4555695080831288193aecdb8330625152e5a8a1
fix a build warning
MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps,MattFarm/BusinessPlatformApps
Source/Actions/Microsoft.Deployment.Actions.Custom/Facebook/ValidateFacebookPage.cs
Source/Actions/Microsoft.Deployment.Actions.Custom/Facebook/ValidateFacebookPage.cs
using System.ComponentModel.Composition; using System.Net.Http; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Microsoft.Deployment.Common.ActionModel; using Microsoft.Deployment.Common.Actions; namespace Microsoft.Deployment.Actions.Custom.Facebook { [Export(typeof(IAction))] public class ValidateFacebookPage : BaseAction { public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request) { string clientId = request.DataStore.GetValue("FacebookClientId"); string clientSecret = request.DataStore.GetValue("FacebookClientSecret"); string pages = request.DataStore.GetValue("FacebookPages"); foreach (var pageToSearch in pages.Split(',')) { string page = pageToSearch.Replace(" ", ""); string requestUri = $"https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}"; HttpClient client = new HttpClient(); var response = await client.GetAsync(requestUri); string responseObj = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return new ActionResponse(ActionStatus.FailureExpected, responseObj); } string accessToken = JObject.Parse(responseObj)["access_token"].ToString(); string pageRequestUri = $"https://graph.facebook.com/{page}?access_token={accessToken}"; response = await client.GetAsync(pageRequestUri); responseObj = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return new ActionResponse(ActionStatus.FailureExpected, responseObj, $"Facebook Page not found: {page}"); } } return new ActionResponse(ActionStatus.Success); } } }
using System.ComponentModel.Composition; using System.Globalization; using System.Threading.Tasks; using Microsoft.Deployment.Common.ActionModel; using Microsoft.Deployment.Common.Actions; using Microsoft.Deployment.Common.Helpers; using System.Net.Http; using Newtonsoft.Json.Linq; using System.Collections.Generic; namespace Microsoft.Deployment.Actions.Custom.Facebook { [Export(typeof(IAction))] public class ValidateFacebookPage : BaseAction { public override async Task<ActionResponse> ExecuteActionAsync(ActionRequest request) { string clientId = request.DataStore.GetValue("FacebookClientId"); string clientSecret = request.DataStore.GetValue("FacebookClientSecret"); string pages = request.DataStore.GetValue("FacebookPages"); string pageIds = ""; foreach (var pageToSearch in pages.Split(',')) { string page = pageToSearch.Replace(" ", ""); string requestUri = $"https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={clientId}&client_secret={clientSecret}"; HttpClient client = new HttpClient(); var response = await client.GetAsync(requestUri); string responseObj = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return new ActionResponse(ActionStatus.FailureExpected, responseObj); } string accessToken = JObject.Parse(responseObj)["access_token"].ToString(); string pageRequestUri = $"https://graph.facebook.com/{page}?access_token={accessToken}"; response = await client.GetAsync(pageRequestUri); responseObj = await response.Content.ReadAsStringAsync(); if (!response.IsSuccessStatusCode) { return new ActionResponse(ActionStatus.FailureExpected, responseObj, $"Facebook Page not found: {page}"); } } return new ActionResponse(ActionStatus.Success); } } }
mit
C#
0510d9267f00a87ab091c8a6286516ad94c5afe9
add imageEmployee
MIS-Department/HR-Department,MIS-Department/HR-Department,MIS-Department/HR-Department
HR-Department.Models/Tables/Employee.cs
HR-Department.Models/Tables/Employee.cs
using System.ComponentModel.DataAnnotations; using HR_Department.Models.Tables.Interfaces; namespace HR_Department.Models.Tables { public class Employee : IEmployee { public int EmployeeId { get; set; } [Required] public string EmployeeNumber { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstName { get; set; } [Required] public string MiddleName { get; set; } //public string Address { get; set; } //public string Gender { get; set; } //public string ContactNumber { get; set; } //public DateTime Birthdate { get; set; } //public string SssNumber { get; set; } //public string TinNumber { get; set; } //public int CivilStatusId { get; set; } //public int TaxId { get; set; } //public int DepartmentId { get; set; } //public int SectionId { get; set; } //public int PositionId { get; set; } //public DateTime DateHired { get; set; } //public DateTime DateRegularization { get; set; } //public int EmploymentStatusId { get; set; } //public string PhilHealthNumber { get; set; } //public string HdmfNumber { get; set; } //public string HdmfRtn { get; set; } //public string SalaryRate { get; set; } //public string SalaryStructure { get; set; } //public int SalaryTypeId { get; set; } //public int IsResign { get; set; } //public int IsActive { get; set; } //public DateTime DateResign { get; set; } //public int WorkersId { get; set; } //public string InCaseOfEmergencyName { get; set; } //public string InCaseOfEmergencyContactNo { get; set; } //[Required] public byte[] ImageEmployee { get; set; } //public int IsSelected { get; set; } } }
using System.ComponentModel.DataAnnotations; using HR_Department.Models.Tables.Interfaces; namespace HR_Department.Models.Tables { public class Employee : IEmployee { public int EmployeeId { get; set; } [Required] public string EmployeeNumber { get; set; } [Required] public string LastName { get; set; } [Required] public string FirstName { get; set; } [Required] public string MiddleName { get; set; } //public string Address { get; set; } //public string Gender { get; set; } //public string ContactNumber { get; set; } //public DateTime Birthdate { get; set; } //public string SssNumber { get; set; } //public string TinNumber { get; set; } //public int CivilStatusId { get; set; } //public int TaxId { get; set; } //public int DepartmentId { get; set; } //public int SectionId { get; set; } //public int PositionId { get; set; } //public DateTime DateHired { get; set; } //public DateTime DateRegularization { get; set; } //public int EmploymentStatusId { get; set; } //public string PhilHealthNumber { get; set; } //public string HdmfNumber { get; set; } //public string HdmfRtn { get; set; } //public string SalaryRate { get; set; } //public string SalaryStructure { get; set; } //public int SalaryTypeId { get; set; } //public int IsResign { get; set; } //public int IsActive { get; set; } //public DateTime DateResign { get; set; } //public int WorkersId { get; set; } //public string InCaseOfEmergencyName { get; set; } //public string InCaseOfEmergencyContactNo { get; set; } [Required] public byte[] ImageEmployee { get; set; } //public int IsSelected { get; set; } } }
mit
C#
5c7c42bae33f9f922bb3ed248450621dbe815154
store inner image as weak reference to object
LayoutFarm/PixelFarm
a_mini/projects/PixelFarm/PixelFarm.DrawingCore/2_Abstract_DrawingElements/Image.cs
a_mini/projects/PixelFarm/PixelFarm.DrawingCore/2_Abstract_DrawingElements/Image.cs
//MIT, 2014-2017, WinterDev using System; namespace PixelFarm.Drawing { public abstract class Image : System.IDisposable { public abstract void Dispose(); public abstract int Width { get; } public abstract int Height { get; } public Size Size { get { return new Size(this.Width, this.Height); } } public abstract bool IsReferenceImage { get; } public abstract int ReferenceX { get; } public abstract int ReferenceY { get; } public abstract byte[] CopyInternalBitmapBuffer(); //-------- WeakReference innerImage; public static object GetCacheInnerImage(Image img) { if (img.innerImage != null && img.innerImage.IsAlive) { return img.innerImage.Target; } return null; } public static void ClearCache(Image img) { if (img != null) { img.innerImage = null; } } public static void SetCacheInnerImage(Image img, object o) { img.innerImage = new WeakReference(o); } } }
//MIT, 2014-2017, WinterDev namespace PixelFarm.Drawing { public abstract class Image : System.IDisposable { public abstract void Dispose(); public abstract int Width { get; } public abstract int Height { get; } public Size Size { get { return new Size(this.Width, this.Height); } } public abstract bool IsReferenceImage { get; } public abstract int ReferenceX { get; } public abstract int ReferenceY { get; } public abstract byte[] CopyInternalBitmapBuffer(); //-------- System.IDisposable innerImage; public static System.IDisposable GetCacheInnerImage(Image img) { return img.innerImage; } public static void SetCacheInnerImage(Image img, System.IDisposable innerImage) { img.innerImage = innerImage; } } }
bsd-2-clause
C#
a3c71ee1d0d1d75e06643fff5dcedd531ea75f17
优化 CSS 样式支持
zpzgone/Jumony,wukaixian/Jumony,zpzgone/Jumony,yonglehou/Jumony,yonglehou/Jumony,wukaixian/Jumony
Ivony.Html/Css/CssStyleSpecificationBase.cs
Ivony.Html/Css/CssStyleSpecificationBase.cs
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace Ivony.Html.Css { public abstract class CssStyleSpecificationBase { protected CssStyleSpecificationBase() { StyleShorthandRules = new CssStyleShorthandRuleCollection(); SyncRoot = new object(); } protected CssStyleShorthandRuleCollection StyleShorthandRules { get; private set; } public CssStyleProperty[] TransformProperties( CssStyleProperty[] properties ) { var result = properties.SelectMany( p => ExtractShorthand( p ) ); return result.Where( p => ValidateProperty( p ) ).ToArray(); } public object SyncRoot { get; private set; } protected abstract bool ValidateProperty( CssStyleProperty property ); protected virtual IEnumerable<CssStyleProperty> ExtractShorthand( CssStyleProperty property ) { lock ( SyncRoot ) { if ( StyleShorthandRules.Contains( property.Name ) ) return StyleShorthandRules[property.Name].ExtractProperties( property.Value ); else return new[] { property }; } } } public class Css21StyleSpecification : CssStyleSpecificationBase { } public class CssStyleShorthandRuleCollection : KeyedCollection<string, ICssStyleShorthandRule> { protected override string GetKeyForItem( ICssStyleShorthandRule item ) { return item.Name; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; namespace Ivony.Html.Css { public abstract class CssStyleSpecificationBase { public CssStyleProperty[] TransformProperties( CssStyleProperty[] properties ) { } } public class Css21StyleSpecification : CssStyleSpecificationBase { } public class CssStyleShorthandRuleCollection : KeyedCollection<string, ICssStyleShorthandRule> { protected override string GetKeyForItem( ICssStyleShorthandRule item ) { return item.Name; } } }
apache-2.0
C#
e6b85fcaeafa47e2eca48ca28b946c634b5a301d
Add capturing.
joshuadeleon/typingclassifier,joshuadeleon/typingclassifier,joshuadeleon/typingclassifier
ML.TypingClassifier/Views/Home/Index.cshtml
ML.TypingClassifier/Views/Home/Index.cshtml
@{ ViewBag.Title = "Typing Classifier"; } @section scripts { <script type="text/javascript"> 'use strict' var now = getTimer(); $(function() { var start , trapper , events = [] , capturing = false; function resetTrapper() { if(trapper) { window.clearTimeout(trapper); } trapper = setTimeout(function() { capturing = false; console.log('stopped capturing'); }, 1005); } document.addEventListener('keydown', function(event) { resetTrapper(); if(!capturing) { console.log('capturing...'); capturing = true; start = now(); } var t = now(); events.push({ e: event, t: t }); console.log(event.key); }); }); function getTimer() { if(window.performance.now) { return function() { return window.performance.now(); }; } else if(window.performance.webkitNow) { return function() { return window.performance.webkitNow(); } } else { return function() { return new Date().getTime(); } } } </script> } <div class="jumbotron"> This will be our awesome typing classifier </div> <div class="row"> Typing classifier goes here. <textarea></textarea> @Html.ActionLink("Go to results", "Results", "Home"); </div>
@{ ViewBag.Title = "Typing Classifier"; } @section scripts { <script type="text/javascript"> 'use strict' var timer = getTimer(); $(function() { var capturing = false; document.addEventListener('keydown', function(event) { if(!capturing) { capturing = true; } }); }); function getTimer() { if(window.performance.now) { return function() { return window.performance.now(); }; } else if(window.performance.webkitNow) { return function() { return window.performance.webkitNot(); } } else { return function() { return new Date().getTime(); } } } </script> } <div class="jumbotron"> This will be our awesome typing classifier </div> <div class="row"> Typing classifier goes here. <textarea></textarea> @Html.ActionLink("Go to results", "Results", "Home"); </div>
mit
C#
e485728109869c1e3704056e1c2b9c98708c43d1
Add keywords to make finding audio offset adjustments easier in settings
smoogipooo/osu,smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu
osu.Game/Overlays/Settings/Sections/Audio/OffsetSettings.cs
osu.Game/Overlays/Settings/Sections/Audio/OffsetSettings.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 System.Linq; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Configuration; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections.Audio { public class OffsetSettings : SettingsSubsection { protected override LocalisableString Header => "Offset Adjustment"; public override IEnumerable<string> FilterTerms => base.FilterTerms.Concat(new[] { "universal", "uo", "timing" }); [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double, OffsetSlider> { LabelText = "Audio offset", Current = config.GetBindable<double>(OsuSetting.AudioOffset), KeyboardStep = 1f }, new SettingsButton { Text = "Offset wizard" } }; } private class OffsetSlider : OsuSliderBar<double> { public override LocalisableString TooltipText => Current.Value.ToString(@"0ms"); } } }
// 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.Allocation; using osu.Framework.Graphics; using osu.Framework.Localisation; using osu.Game.Configuration; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Settings.Sections.Audio { public class OffsetSettings : SettingsSubsection { protected override LocalisableString Header => "Offset Adjustment"; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { Children = new Drawable[] { new SettingsSlider<double, OffsetSlider> { LabelText = "Audio offset", Current = config.GetBindable<double>(OsuSetting.AudioOffset), KeyboardStep = 1f }, new SettingsButton { Text = "Offset wizard" } }; } private class OffsetSlider : OsuSliderBar<double> { public override LocalisableString TooltipText => Current.Value.ToString(@"0ms"); } } }
mit
C#
83e2b6c198b74ba0eab08903fe4e99f37b6f5577
Add more logic to the custom action.
jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes
ConsoleApps/FunWithSpikes/Wix.CustomActions/CustomAction.cs
ConsoleApps/FunWithSpikes/Wix.CustomActions/CustomAction.cs
using System; using Microsoft.Deployment.WindowsInstaller; namespace Wix.CustomActions { using System.IO; using System.Diagnostics; public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { Debugger.Launch(); const string fileFullPath = @"c:\KensCustomAction.txt"; if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } }
using System; using Microsoft.Deployment.WindowsInstaller; namespace Wix.CustomActions { using System.IO; public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { const string fileFullPath = @"c:\KensCustomAction.txt"; if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } }
mit
C#
7342a222d437356ef8dc8f170bc6fc2e0f2219cf
Write release notes to a file instead
red-gate/Library,red-gate/Library
tools/ReleaseNotesGenerator/ReleaseNotesGenerator.csx
tools/ReleaseNotesGenerator/ReleaseNotesGenerator.csx
var octokit = Require<OctokitPack>(); var client = octokit.Create("Octopus.Library.ReleaseNotesGenerator"); var owner = Env.ScriptArgs[0]; var repo = Env.ScriptArgs[1]; var milestone = Env.ScriptArgs[2]; var state = Env.ScriptArgs[3] != null ? (ItemStateFilter)Enum.Parse(typeof(ItemStateFilter), Env.ScriptArgs[3]) : ItemStateFilter.Open; bool isTeamCity; if(!bool.TryParse(Env.ScriptArgs[4], out isTeamCity)) { isTeamCity = false; } async Task<string> BuildGitHubReleaseNotes() { var releaseNotesBuilder = new StringBuilder(); var milestones = await client.Issue.Milestone.GetAllForRepository(owner, repo); var milestoneNumber = milestones.First(m => m.Title == milestone).Number; var milestoneIssues = await client.Issue.GetAllForRepository(owner, repo, new Octokit.RepositoryIssueRequest { Milestone = milestoneNumber.ToString(), State = state }); if (milestoneIssues.Any()) { Console.WriteLine($"Found {milestoneIssues.Count()} closed PRs in milestone {milestone}"); foreach (var issue in milestoneIssues) { var files = (await client.PullRequest.Files(owner, repo, issue.Number)).Where(f => f.FileName.EndsWith(".json")).ToList(); var status = ""; var fileNameFormat = "{0}"; if (files.Count() > 1) { fileNameFormat = $"[{fileNameFormat}]"; } var fileNameList = string.Format(fileNameFormat, string.Join(", ", files.Select(f => $"`{f.FileName.Replace("step-templates/", "")}`").ToList())); status = files.All(f => f.Deletions == 0) ? "New: " : "Improved: "; releaseNotesBuilder.AppendLine($"- {status}[#{issue.Number}]({issue.HtmlUrl}) - {fileNameList} - {issue.Title} - via @{issue.User.Login}"); } } else { Console.WriteLine($"Well played sir! There are no closed PRs in milestone {milestone}. Woohoo!"); } return releaseNotesBuilder.ToString(); } Console.WriteLine($"Getting all {state} issues in milestone {milestone} of repository {owner}\\{repo}"); var releaseNotes = BuildGitHubReleaseNotes().Result; if(!isTeamCity) { Console.WriteLine(releaseNotes); } else { var cwd = Directory.GetCurrentDirectory(); var releaseNotesFile = $"{cwd}\\Library_ReleaseNotes.txt"; File.WriteAllText(releaseNotesFile, releaseNotes); Console.WriteLine($"##teamcity[setParameter name='Library.ReleaseNotesFile' value='{releaseNotesFile}'"); }
var octokit = Require<OctokitPack>(); var client = octokit.Create("Octopus.Library.ReleaseNotesGenerator"); var owner = Env.ScriptArgs[0]; var repo = Env.ScriptArgs[1]; var milestone = Env.ScriptArgs[2]; var state = Env.ScriptArgs[3] != null ? (ItemStateFilter)Enum.Parse(typeof(ItemStateFilter), Env.ScriptArgs[3]) : ItemStateFilter.Open; bool isTeamCity; if(!bool.TryParse(Env.ScriptArgs[4], out isTeamCity)) { isTeamCity = false; } async Task<string> BuildGitHubReleaseNotes() { var releaseNotesBuilder = new StringBuilder(); var milestones = await client.Issue.Milestone.GetAllForRepository(owner, repo); var milestoneNumber = milestones.First(m => m.Title == milestone).Number; var milestoneIssues = await client.Issue.GetAllForRepository(owner, repo, new Octokit.RepositoryIssueRequest { Milestone = milestoneNumber.ToString(), State = state }); if (milestoneIssues.Any()) { Console.WriteLine($"Found {milestoneIssues.Count()} closed PRs in milestone {milestone}"); foreach (var issue in milestoneIssues) { var files = (await client.PullRequest.Files(owner, repo, issue.Number)).Where(f => f.FileName.EndsWith(".json")).ToList(); var status = ""; var fileNameFormat = "{0}"; if (files.Count() > 1) { fileNameFormat = $"[{fileNameFormat}]"; } var fileNameList = string.Format(fileNameFormat, string.Join(", ", files.Select(f => $"`{f.FileName.Replace("step-templates/", "")}`").ToList())); status = files.All(f => f.Deletions == 0) ? "New: " : "Improved: "; releaseNotesBuilder.AppendLine($"- {status}[#{issue.Number}]({issue.HtmlUrl}) - {fileNameList} - {issue.Title} - via @{issue.User.Login}"); } } else { Console.WriteLine($"Well played sir! There are no closed PRs in milestone {milestone}. Woohoo!"); } return releaseNotesBuilder.ToString(); } Console.WriteLine($"Getting all {state} issues in milestone {milestone} of repository {owner}\\{repo}"); var releaseNotes = BuildGitHubReleaseNotes().Result; if(!isTeamCity) { Console.WriteLine(releaseNotes); } else { Console.WriteLine($"##teamcity[setParameter name='Library.ReleaseNotes' value='{releaseNotes.Replace("[", "|[").Replace("]", "|]").Replace(Environment.NewLine, "|n")}']"); }
apache-2.0
C#
97c9254b7456b6034c9d2b3dadcf156fb3c62685
Change logging output format
Marc3842h/Titan,Marc3842h/Titan,Marc3842h/Titan
Titan/Logging/LogCreator.cs
Titan/Logging/LogCreator.cs
using System; using System.Diagnostics; using System.IO; using Serilog; using Serilog.Core; namespace Titan.Logging { public class LogCreator { public static DirectoryInfo LogDirectory = new DirectoryInfo(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "logs"); public static Logger Create(string name) { return new LoggerConfiguration() .WriteTo.LiterateConsole(outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {Message}{NewLine}{Exception}") .WriteTo.RollingFile(Path.Combine(LogDirectory.ToString(), name + "-{Date}.log"), outputTemplate: "[{Timestamp:HH:mm:ss} {Level}] {Message}{NewLine}{Exception}") .MinimumLevel.Debug() // TODO: Change this to "INFO" on release. .CreateLogger(); } public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)"); } } }
using System; using System.Diagnostics; using System.IO; using Serilog; using Serilog.Core; namespace Titan.Logging { public class LogCreator { public static DirectoryInfo LogDirectory = new DirectoryInfo(Environment.CurrentDirectory + Path.DirectorySeparatorChar + "logs"); public static Logger Create(string name) { return new LoggerConfiguration() .WriteTo.LiterateConsole() .WriteTo.RollingFile(Path.Combine(LogDirectory.ToString(), name + "-{Date}.log")) .MinimumLevel.Debug() // TODO: Change this to "INFO" on release. .CreateLogger(); } public static Logger Create() { var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType; return Create(reflectedType != null ? reflectedType.Name : "Titan (unknown Parent)"); } } }
mit
C#
189e3d52e2eb7c79e05ddff59f8a3c66a8709114
Fix executable path on .NET Core
kohsuke/winsw
src/Core/WinSWCore/Configuration/DefaultSettings.cs
src/Core/WinSWCore/Configuration/DefaultSettings.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using WMI; namespace winsw.Configuration { /// <summary> /// Default WinSW settings /// </summary> public sealed class DefaultWinSWSettings : IWinSWConfiguration { public string Id => throw new InvalidOperationException(nameof(Id) + " must be specified."); public string Caption => throw new InvalidOperationException(nameof(Caption) + " must be specified."); public string Description => throw new InvalidOperationException(nameof(Description) + " must be specified."); public string Executable => throw new InvalidOperationException(nameof(Executable) + " must be specified."); public bool HideWindow => false; public string ExecutablePath => Process.GetCurrentProcess().MainModule.FileName; // Installation public bool AllowServiceAcountLogonRight => false; public string? ServiceAccountPassword => null; public string ServiceAccountUser => "NULL\\NULL"; public List<Native.SC_ACTION> FailureActions => new List<Native.SC_ACTION>(0); public TimeSpan ResetFailureAfter => TimeSpan.FromDays(1); // Executable management public string Arguments => string.Empty; public string? Startarguments => null; public string? StopExecutable => null; public string? Stoparguments => null; public string WorkingDirectory => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; public ProcessPriorityClass Priority => ProcessPriorityClass.Normal; public TimeSpan StopTimeout => TimeSpan.FromSeconds(15); public bool StopParentProcessFirst => false; // Service management public StartMode StartMode => StartMode.Automatic; public bool DelayedAutoStart => false; public string[] ServiceDependencies => new string[0]; public TimeSpan WaitHint => TimeSpan.FromSeconds(15); public TimeSpan SleepTime => TimeSpan.FromSeconds(1); public bool Interactive => false; // Logging public string LogDirectory => Path.GetDirectoryName(ExecutablePath)!; public string LogMode => "append"; public bool OutFileDisabled => false; public bool ErrFileDisabled => false; public string OutFilePattern => ".out.log"; public string ErrFilePattern => ".err.log"; // Environment public List<Download> Downloads => new List<Download>(0); public Dictionary<string, string> EnvironmentVariables => new Dictionary<string, string>(0); // Misc public bool BeepOnShutdown => false; // Extensions public XmlNode? ExtensionsConfiguration => null; } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using WMI; namespace winsw.Configuration { /// <summary> /// Default WinSW settings /// </summary> public sealed class DefaultWinSWSettings : IWinSWConfiguration { public string Id => throw new InvalidOperationException(nameof(Id) + " must be specified."); public string Caption => throw new InvalidOperationException(nameof(Caption) + " must be specified."); public string Description => throw new InvalidOperationException(nameof(Description) + " must be specified."); public string Executable => throw new InvalidOperationException(nameof(Executable) + " must be specified."); public bool HideWindow => false; // this returns the executable name as given by the calling process, so // it needs to be absolutized. public string ExecutablePath => Path.GetFullPath(Environment.GetCommandLineArgs()[0]); // Installation public bool AllowServiceAcountLogonRight => false; public string? ServiceAccountPassword => null; public string ServiceAccountUser => "NULL\\NULL"; public List<Native.SC_ACTION> FailureActions => new List<Native.SC_ACTION>(0); public TimeSpan ResetFailureAfter => TimeSpan.FromDays(1); // Executable management public string Arguments => string.Empty; public string? Startarguments => null; public string? StopExecutable => null; public string? Stoparguments => null; public string WorkingDirectory => Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!; public ProcessPriorityClass Priority => ProcessPriorityClass.Normal; public TimeSpan StopTimeout => TimeSpan.FromSeconds(15); public bool StopParentProcessFirst => false; // Service management public StartMode StartMode => StartMode.Automatic; public bool DelayedAutoStart => false; public string[] ServiceDependencies => new string[0]; public TimeSpan WaitHint => TimeSpan.FromSeconds(15); public TimeSpan SleepTime => TimeSpan.FromSeconds(1); public bool Interactive => false; // Logging public string LogDirectory => Path.GetDirectoryName(ExecutablePath)!; public string LogMode => "append"; public bool OutFileDisabled => false; public bool ErrFileDisabled => false; public string OutFilePattern => ".out.log"; public string ErrFilePattern => ".err.log"; // Environment public List<Download> Downloads => new List<Download>(0); public Dictionary<string, string> EnvironmentVariables => new Dictionary<string, string>(0); // Misc public bool BeepOnShutdown => false; // Extensions public XmlNode? ExtensionsConfiguration => null; } }
mit
C#
f5ceb1bbe8cd105366670bb7df83fadc71c0e947
Update _Error403.cshtml
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml
src/SFA.DAS.ProviderApprenticeshipsService.Web/Views/Error/_Error403.cshtml
@{ ViewBag.Title = "You do not have permission to access this page"; ViewBag.PageId = "error-403"; ViewBag.HideNavBar = true; } <main id="content" role="main" class="error-403"> <div class="grid-row"> <div class="column-two-thirds"> <div class="hgroup"> <h1 class="heading-xlarge"> You do not have permission to access this page </h1> </div> <div class="inner"> <p> If you think you should have permission to access this page or want to confirm what permissions you have, contact an account owner. </p> <p> <a href="@Url.Action("Index", "Account")"> Go back to home page </a> </p> </div> </div> </div> </main>
@{ ViewBag.Title = "Access denied - Error 403"; ViewBag.PageId = "error-403"; ViewBag.HideNavBar = true; } <main id="content" role="main" class="error-403"> <div class="grid-row"> <div class="column-two-thirds"> <div class="hgroup"> <h1 class="heading-xlarge"> You do not have permission to access this page </h1> </div> <div class="inner"> <p> If you think you should have permission to access this page or want to confirm what permissions you have, contact an account owner. </p> <p> <a href="@Url.Action("Index", "Account")"> Go back to home page </a> </p> </div> </div> </div> </main>
mit
C#
4dbb6236ead4437d88544e74697815a076bf266c
Update morphology_han-readings.cs
rosette-api/java,rosette-api/java,rosette-api/java
csharp/rosette_apiExamples/morphology_han-readings.cs
csharp/rosette_apiExamples/morphology_han-readings.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using rosette_api; namespace rosette_apiExamples { class morphology_han_readings { /// <summary> /// Example code to call Rosette API to get Chinese readings for words in a piece of text. /// Requires Nuget Package: /// rosette_api /// </summary> static void Main() { //To use the C# API, you must provide an API key CAPI MorphologyCAPI = new CAPI("your API key"); try { //The results of the API call will come back in the form of a Dictionary Dictionary<string, Object> MorphologyResult = MorphologyCAPI.Morphology("北京大学生物系主任办公室内部会议", null, null, null, null, "han-readings"); Console.WriteLine(new JavaScriptSerializer().Serialize(MorphologyResult)); } catch (RosetteException e) { Console.WriteLine("Error Code " + e.Code.ToString() + ":" + e.Message); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.Script.Serialization; using rosette_api; namespace rosette_apiExamples { class morphology_han_readings { /// <summary> /// Example code to call Rosette API to get Chinese readings for words in a piece of text. /// Requires Nuget Package: /// rosette_api /// </summary> static void Main() { //To use the C# API, you must provide an API key CAPI MorphologyCAPI = new CAPI("your API key"); try { //The results of the API call will come back in the form of a Dictionary Dictionary<string, Object> MorphologyResult = MorphologyCAPI.Morphology("$北京大学生物系主任办公室内部会议", null, null, null, null, "han-readings"); Console.WriteLine(new JavaScriptSerializer().Serialize(MorphologyResult)); } catch (RosetteException e) { Console.WriteLine("Error Code " + e.Code.ToString() + ":" + e.Message); } } } }
apache-2.0
C#
273e346b4f78bb680f00729dd6e10b3609518b60
Add CommandDispatcher#Dispatch
appharbor/appharbor-cli
src/AppHarbor/CommandDispatcher.cs
src/AppHarbor/CommandDispatcher.cs
using System; using System.Collections.Generic; namespace AppHarbor { public class CommandDispatcher { private readonly IEnumerable<ICommand> _commands; public CommandDispatcher(IEnumerable<ICommand> commands) { _commands = commands; } public void Dispatch(string[] args) { throw new NotImplementedException(); } } }
using System.Collections.Generic; namespace AppHarbor { public class CommandDispatcher { private readonly IEnumerable<ICommand> _commands; public CommandDispatcher(IEnumerable<ICommand> commands) { _commands = commands; } } }
mit
C#
503330a6267d144cef09ff0624fe6ff1256fb9ef
Fix header behavior for the fixed length types
forcewake/FlatFile
src/FlatFile.FixedLength.Attributes/Infrastructure/FixedLayoutDescriptorProvider.cs
src/FlatFile.FixedLength.Attributes/Infrastructure/FixedLayoutDescriptorProvider.cs
namespace FlatFile.FixedLength.Attributes.Infrastructure { using System; using System.Linq; using FlatFile.Core; using FlatFile.Core.Attributes.Extensions; using FlatFile.Core.Attributes.Infrastructure; using FlatFile.Core.Base; public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>> { public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>() { var container = new FieldsContainer<FixedFieldSettings>(); var fileMappingType = typeof(T); var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>(); if (fileAttribute == null) { throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute", fileMappingType.Name, typeof(FixedLengthFileAttribute).Name)); } var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>(); foreach (var p in properties) { var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute; if (attribute != null) { var fieldSettings = attribute.GetFieldSettings(p.Property); container.AddOrUpdate(fieldSettings, false); } } var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container) { HasHeader = false }; return descriptor; } } }
namespace FlatFile.FixedLength.Attributes.Infrastructure { using System; using System.Linq; using FlatFile.Core; using FlatFile.Core.Attributes.Extensions; using FlatFile.Core.Attributes.Infrastructure; using FlatFile.Core.Base; public class FixedLayoutDescriptorProvider : ILayoutDescriptorProvider<FixedFieldSettings, ILayoutDescriptor<FixedFieldSettings>> { public ILayoutDescriptor<FixedFieldSettings> GetDescriptor<T>() { var container = new FieldsContainer<FixedFieldSettings>(); var fileMappingType = typeof(T); var fileAttribute = fileMappingType.GetAttribute<FixedLengthFileAttribute>(); if (fileAttribute == null) { throw new NotSupportedException(string.Format("Mapping type {0} should be marked with {1} attribute", fileMappingType.Name, typeof(FixedLengthFileAttribute).Name)); } var properties = fileMappingType.GetTypeDescription<FixedLengthFieldAttribute>(); foreach (var p in properties) { var attribute = p.Attributes.FirstOrDefault() as FixedLengthFieldAttribute; if (attribute != null) { var fieldSettings = attribute.GetFieldSettings(p.Property); container.AddOrUpdate(fieldSettings, false); } } var descriptor = new LayoutDescriptorBase<FixedFieldSettings>(container); return descriptor; } } }
mit
C#
50f6278372c5ad2589c0efb099eb59026e79fc18
Update PageView.axaml.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/Views/PageView.axaml.cs
src/Core2D/Views/PageView.axaml.cs
using Avalonia.Controls; using Avalonia.Markup.Xaml; namespace Core2D.Views { public class PageView : UserControl { public PageView() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
using Avalonia.Controls; using Avalonia.Controls.PanAndZoom; using Avalonia.Markup.Xaml; namespace Core2D.Views { public class PageView : UserControl { private ScrollViewer _scrollViewer; private ZoomBorder _zoomBorder; private PresenterView _presenterViewData; private PresenterView _presenterViewTemplate; private PresenterView _presenterViewEditor; private TextBox _textEditor; public PageView() { InitializeComponent(); _scrollViewer = this.FindControl<ScrollViewer>("PageScrollViewer"); _zoomBorder = this.FindControl<ZoomBorder>("PageZoomBorder"); _presenterViewData = this.FindControl<PresenterView>("PresenterViewData"); _presenterViewTemplate = this.FindControl<PresenterView>("PresenterViewTemplate"); _presenterViewEditor = this.FindControl<PresenterView>("PresenterViewEditor"); _textEditor = this.FindControl<TextBox>("EditorTextBox"); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
b9da37aa64eaa92e884f449aa4a88d51ed9aa598
revert thumbprint name change on needless file
takenet/lime-csharp
src/Lime.Transport.WebSocket/X509CertificateInfo.cs
src/Lime.Transport.WebSocket/X509CertificateInfo.cs
using System; using System.Security.Cryptography.X509Certificates; namespace Lime.Transport.WebSocket { /// <summary> /// Provides information about a stored certificate. /// </summary> public sealed class X509CertificateInfo { /// <summary> /// Initializes a new instance of the <see cref="X509CertificateInfo"/> class. /// </summary> /// <param name="thumbprint">The thumbprint.</param> /// <param name="store">The store.</param> /// <exception cref="ArgumentNullException"></exception> public X509CertificateInfo(string thumbprint, StoreName store = StoreName.My) { if (thumbprint == null) throw new ArgumentNullException(nameof(thumbprint)); Thumbprint = thumbprint; Store = store; } /// <summary> /// Gets the certificate thumbprint. /// </summary> /// <value> /// The thumbprint. /// </value> public string Thumbprint { get; } /// <summary> /// Gets the certificate store. /// </summary> /// <value> /// The store. /// </value> public StoreName Store { get; } } }
using System; using System.Security.Cryptography.X509Certificates; namespace Lime.Transport.WebSocket { /// <summary> /// Provides information about a stored certificate. /// </summary> public sealed class X509CertificateInfo { /// <summary> /// Initializes a new instance of the <see cref="X509CertificateInfo"/> class. /// </summary> /// <param name="certificateThumbprint">The thumbprint.</param> /// <param name="store">The store.</param> /// <exception cref="ArgumentNullException"></exception> public X509CertificateInfo(string certificateThumbprint, StoreName store = StoreName.My) { if (certificateThumbprint == null) throw new ArgumentNullException(nameof(certificateThumbprint)); CertificateThumbprint = certificateThumbprint; Store = store; } /// <summary> /// Gets the certificate thumbprint. /// </summary> /// <value> /// The thumbprint. /// </value> public string CertificateThumbprint { get; } /// <summary> /// Gets the certificate store. /// </summary> /// <value> /// The store. /// </value> public StoreName Store { get; } } }
apache-2.0
C#
d6b45171cd13c7106b6e9a7ad6e1bde7995b69ad
Test Karen Demostration
camiloandresok/SubwayNFCT,camiloandresok/SubwayNFCT,camiloandresok/SubwayNFCT
SubWay/SubWay/Controllers/HomeController.cs
SubWay/SubWay/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SubWay.DAL; namespace SubWay.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { try { demosubwaydbEntities dbContext = new demosubwaydbEntities(); Customer newCustomer = new Customer(); newCustomer.Nombres = "Pepito Perez"; newCustomer.Telefono = "325206613"; newCustomer.Email = "pepitogay@hotmail.com"; newCustomer.TwilioCode = "XZWSCERT"; dbContext.Customers.Add(newCustomer); dbContext.SaveChanges(); ViewBag.Message = "Customer Salvado Ok gracias karen..."; } catch (Exception ex) { ViewBag.Message = ex.Message; } return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SubWay.DAL; namespace SubWay.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { try { demosubwaydbEntities dbContext = new demosubwaydbEntities(); Customer newCustomer = new Customer(); newCustomer.Nombres = "Andrea Reyes"; newCustomer.Telefono = "3112110445"; newCustomer.Email = "yurypecas@hotmail.com"; newCustomer.TwilioCode = "XZZXCERT"; dbContext.Customers.Add(newCustomer); dbContext.SaveChanges(); ViewBag.Message = "Salvado Ok ..."; } catch (Exception ex) { ViewBag.Message = ex.Message; } return View(); } } }
mit
C#
2e1edaa2338675918b88a03a3112700ec243306f
Update CompositeAssemblyStringLocalizerTests.cs
tiksn/TIKSN-Framework
TIKSN.UnitTests.Shared/Localization/CompositeAssemblyStringLocalizerTests.cs
TIKSN.UnitTests.Shared/Localization/CompositeAssemblyStringLocalizerTests.cs
using System; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using TIKSN.DependencyInjection.Tests; using Xunit; using Xunit.Abstractions; namespace TIKSN.Localization.Tests { public class CompositeAssemblyStringLocalizerTests { private readonly IServiceProvider _serviceProvider; public CompositeAssemblyStringLocalizerTests(ITestOutputHelper testOutputHelper) { var compositionRoot = new TestCompositionRootSetup(testOutputHelper); this._serviceProvider = compositionRoot.CreateServiceProvider(); } [Fact] public void KeyUniqueness() { var resourceNamesCache = new ResourceNamesCache(); var testStringLocalizer = new TestStringLocalizer(resourceNamesCache, this._serviceProvider.GetRequiredService<ILogger<TestStringLocalizer>>()); var duplicatesCount = testStringLocalizer.GetAllStrings().GroupBy(item => item.Name.ToLowerInvariant()).Count(item => item.Count() > 1); _ = duplicatesCount.Should().Be(0); } } }
using System; using System.Linq; using FluentAssertions; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using TIKSN.DependencyInjection.Tests; using Xunit; using Xunit.Abstractions; namespace TIKSN.Localization.Tests { public class CompositeAssemblyStringLocalizerTests { private readonly IServiceProvider _serviceProvider; public CompositeAssemblyStringLocalizerTests(ITestOutputHelper testOutputHelper) { var compositionRoot = new TestCompositionRootSetup(testOutputHelper); _serviceProvider = compositionRoot.CreateServiceProvider(); } [Fact] public void KeyUniqueness() { var resourceNamesCache = new ResourceNamesCache(); var testStringLocalizer = new TestStringLocalizer(resourceNamesCache, _serviceProvider.GetRequiredService<ILogger<TestStringLocalizer>>()); var duplicatesCount = testStringLocalizer.GetAllStrings().GroupBy(item => item.Name.ToLowerInvariant()).Count(item => item.Count() > 1); duplicatesCount.Should().Be(0); } } }
mit
C#
5f6d0d366eb243db6b567e0a21ec8ae36fd325a0
Use Task.FromResult
dbolkensteyn/Nancy,grumpydev/Nancy,davidallyoung/Nancy,charleypeng/Nancy,blairconrad/Nancy,danbarua/Nancy,jchannon/Nancy,thecodejunkie/Nancy,jchannon/Nancy,felipeleusin/Nancy,thecodejunkie/Nancy,dbolkensteyn/Nancy,danbarua/Nancy,sadiqhirani/Nancy,felipeleusin/Nancy,JoeStead/Nancy,ccellar/Nancy,davidallyoung/Nancy,dbolkensteyn/Nancy,jchannon/Nancy,grumpydev/Nancy,damianh/Nancy,xt0rted/Nancy,sloncho/Nancy,jeff-pang/Nancy,ccellar/Nancy,blairconrad/Nancy,sadiqhirani/Nancy,asbjornu/Nancy,NancyFx/Nancy,davidallyoung/Nancy,davidallyoung/Nancy,phillip-haydon/Nancy,sloncho/Nancy,JoeStead/Nancy,khellang/Nancy,ccellar/Nancy,xt0rted/Nancy,davidallyoung/Nancy,thecodejunkie/Nancy,sadiqhirani/Nancy,anton-gogolev/Nancy,sadiqhirani/Nancy,dbolkensteyn/Nancy,jchannon/Nancy,JoeStead/Nancy,xt0rted/Nancy,xt0rted/Nancy,grumpydev/Nancy,asbjornu/Nancy,VQComms/Nancy,damianh/Nancy,danbarua/Nancy,NancyFx/Nancy,ccellar/Nancy,anton-gogolev/Nancy,asbjornu/Nancy,thecodejunkie/Nancy,asbjornu/Nancy,danbarua/Nancy,phillip-haydon/Nancy,sloncho/Nancy,jeff-pang/Nancy,phillip-haydon/Nancy,asbjornu/Nancy,grumpydev/Nancy,phillip-haydon/Nancy,sloncho/Nancy,jeff-pang/Nancy,charleypeng/Nancy,jeff-pang/Nancy,khellang/Nancy,NancyFx/Nancy,JoeStead/Nancy,charleypeng/Nancy,jchannon/Nancy,blairconrad/Nancy,anton-gogolev/Nancy,charleypeng/Nancy,felipeleusin/Nancy,charleypeng/Nancy,VQComms/Nancy,felipeleusin/Nancy,khellang/Nancy,NancyFx/Nancy,VQComms/Nancy,khellang/Nancy,VQComms/Nancy,anton-gogolev/Nancy,blairconrad/Nancy,damianh/Nancy,VQComms/Nancy
src/Nancy.Tests/Fakes/FakeRoute.cs
src/Nancy.Tests/Fakes/FakeRoute.cs
namespace Nancy.Tests.Fakes { using System; using System.Threading; using System.Threading.Tasks; using Nancy.Routing; public class FakeRoute : Route { private static Func<dynamic, CancellationToken, Task<dynamic>>DefaultAction = (parameters, token) => null; public bool ActionWasInvoked; public DynamicDictionary ParametersUsedToInvokeAction; public FakeRoute() : this(new Response()) { } public FakeRoute(dynamic response) : base("GET", "/", null, (parametes, token) => null) { this.Action = Wrap(this, (parameters, token) => Task.FromResult<dynamic>(response)); } public FakeRoute(Func<dynamic, CancellationToken, Task<dynamic>> action) : base("GET", "/", null, (parametes, token) => null) { this.Action = Wrap(this, action); } private static Func<dynamic, CancellationToken, Task<dynamic>> Wrap( FakeRoute route, Func<dynamic, CancellationToken, Task<dynamic>> action) { return (parameters, token) => { route.ParametersUsedToInvokeAction = parameters; route.ActionWasInvoked = true; var tcs = new TaskCompletionSource<dynamic>(); try { var result = action.Invoke(parameters, token); tcs.SetResult(result.Result); } catch (Exception e) { tcs.SetException(e); } return tcs.Task; }; } } }
namespace Nancy.Tests.Fakes { using System; using System.Threading; using System.Threading.Tasks; using Nancy.Routing; public class FakeRoute : Route { private static Func<dynamic, CancellationToken, Task<dynamic>>DefaultAction = (parameters, token) => null; public bool ActionWasInvoked; public DynamicDictionary ParametersUsedToInvokeAction; public FakeRoute() : this(new Response()) { } public FakeRoute(dynamic response) : base("GET", "/", null, (parametes, token) => null) { this.Action = Wrap(this, (parameters, token) => Task.FromResult(response)); } public FakeRoute(Func<dynamic, CancellationToken, Task<dynamic>> action) : base("GET", "/", null, (parametes, token) => null) { this.Action = Wrap(this, action); } private static Func<dynamic, CancellationToken, Task<dynamic>> Wrap( FakeRoute route, Func<dynamic, CancellationToken, Task<dynamic>> action) { return (parameters, token) => { route.ParametersUsedToInvokeAction = parameters; route.ActionWasInvoked = true; var tcs = new TaskCompletionSource<dynamic>(); try { var result = action.Invoke(parameters, token); tcs.SetResult(result.Result); } catch (Exception e) { tcs.SetException(e); } return tcs.Task; }; } } }
mit
C#
240f5c07b9e729a415dbb5828b4ae8097f34b0de
fix doc
marihachi/CrystalResonanceForDesktop
src/Utility/SoundCloudExtractor.cs
src/Utility/SoundCloudExtractor.cs
using Codeplex.Data; using System; using System.Net.Http; using System.Threading.Tasks; namespace CrystalResonanceDesktop.Utility { public class SoundCloudOggExtractor : OggExtractor { public SoundCloudOggExtractor() : base() { } public SoundCloudOggExtractor(string ffmpegFilePath) : base(ffmpegFilePath) { } /// <summary> /// SoundCloudのトラックをogg形式の音声ファイルとして抽出します /// </summary> /// <param name="listenPageUrl">視聴ページのURL</param> /// <returns>一時フォルダ上のファイルパス</returns> public override async Task<string> Extract(Uri listenPageUrl) { if (listenPageUrl == null) throw new ArgumentNullException("listenPageUrl"); var clientId = "376f225bf427445fc4bfb6b99b72e0bf"; // var clientId2 = "06e3e204bdd61a0a41d8eaab895cb7df"; // var clientId3 = "02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea"; var resolveUrl = "http://api.soundcloud.com/resolve.json?url={0}&client_id={1}"; var trackStreamUrl = "http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}"; string downloadUrl; using (var client = new HttpClient()) { // get track id var res = await client.GetAsync(string.Format(resolveUrl, listenPageUrl, clientId)); var resolveJsonString = await res.Content.ReadAsStringAsync(); var resolveJson = DynamicJson.Parse(resolveJsonString); var trackId = (int)resolveJson.id; // get download url res = await client.GetAsync(string.Format(trackStreamUrl, trackId, clientId)); var trackStreamJsonString = await res.Content.ReadAsStringAsync(); var trackStreamJson = DynamicJson.Parse(trackStreamJsonString); downloadUrl = trackStreamJson.http_mp3_128_url; return await Convert(downloadUrl, 0, false); } } } }
using Codeplex.Data; using System; using System.Net.Http; using System.Threading.Tasks; namespace CrystalResonanceDesktop.Utility { public class SoundCloudOggExtractor : OggExtractor { public SoundCloudOggExtractor() : base() { } public SoundCloudOggExtractor(string ffmpegFilePath) : base(ffmpegFilePath) { } /// <summary> /// SoundCloudのトラックをogg形式の音声ファイルとして抽出します /// </summary> /// <param name="watchPageUrl">視聴ページのURL</param> /// <returns>一時フォルダ上のファイルパス</returns> public override async Task<string> Extract(Uri listenPageUrl) { if (listenPageUrl == null) throw new ArgumentNullException("listenPageUrl"); var clientId = "376f225bf427445fc4bfb6b99b72e0bf"; // var clientId2 = "06e3e204bdd61a0a41d8eaab895cb7df"; // var clientId3 = "02gUJC0hH2ct1EGOcYXQIzRFU91c72Ea"; var resolveUrl = "http://api.soundcloud.com/resolve.json?url={0}&client_id={1}"; var trackStreamUrl = "http://api.soundcloud.com/i1/tracks/{0}/streams?client_id={1}"; string downloadUrl; using (var client = new HttpClient()) { // get track id var res = await client.GetAsync(string.Format(resolveUrl, listenPageUrl, clientId)); var resolveJsonString = await res.Content.ReadAsStringAsync(); var resolveJson = DynamicJson.Parse(resolveJsonString); var trackId = (int)resolveJson.id; // get download url res = await client.GetAsync(string.Format(trackStreamUrl, trackId, clientId)); var trackStreamJsonString = await res.Content.ReadAsStringAsync(); var trackStreamJson = DynamicJson.Parse(trackStreamJsonString); downloadUrl = trackStreamJson.http_mp3_128_url; return await Convert(downloadUrl, 0, false); } } } }
mit
C#
873bd1ff264357c45c4f4c72564ed58d6afa4fe1
Update CurrencylayerDotComTests.cs
tiksn/TIKSN-Framework
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs
TIKSN.Framework.IntegrationTests/Finance/ForeignExchange/CurrencylayerDotComTests.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Cumulative; using TIKSN.Framework.IntegrationTests; using TIKSN.Globalization; using TIKSN.Time; using Xunit; namespace TIKSN.Finance.Tests.ForeignExchange { [Collection("ServiceProviderCollection")] public class CurrencylayerDotComTests { const string skip = "API changed, code needs to be adopted"; private readonly string accessKey = "<put your access key here>"; private readonly ICurrencyFactory currencyFactory; private readonly ITimeProvider timeProvider; private readonly ServiceProviderFixture serviceProviderFixture; public CurrencylayerDotComTests(ServiceProviderFixture serviceProviderFixture) { this.currencyFactory = serviceProviderFixture.Services.GetRequiredService<ICurrencyFactory>(); this.timeProvider = serviceProviderFixture.Services.GetRequiredService<ITimeProvider>(); this.serviceProviderFixture = serviceProviderFixture ?? throw new ArgumentNullException(nameof(serviceProviderFixture)); } [Fact(Skip = skip)] public async Task GetCurrencyPairs001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(pairs.Count() > 0); } [Fact(Skip = skip)] public async Task GetExchangeRateAsync001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH")); var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(rate > decimal.Zero); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using TIKSN.Finance.ForeignExchange.Cumulative; using TIKSN.Framework.IntegrationTests; using TIKSN.Globalization; using TIKSN.Time; using Xunit; namespace TIKSN.Finance.Tests.ForeignExchange { [Collection("ServiceProviderCollection")] public class CurrencylayerDotComTests { private readonly string accessKey = "<put your access key here>"; private readonly ICurrencyFactory currencyFactory; private readonly ITimeProvider timeProvider; private readonly ServiceProviderFixture serviceProviderFixture; public CurrencylayerDotComTests(ServiceProviderFixture serviceProviderFixture) { this.currencyFactory = serviceProviderFixture.Services.GetRequiredService<ICurrencyFactory>(); this.timeProvider = serviceProviderFixture.Services.GetRequiredService<ITimeProvider>(); this.serviceProviderFixture = serviceProviderFixture ?? throw new ArgumentNullException(nameof(serviceProviderFixture)); } //[Fact] public async Task GetCurrencyPairs001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pairs = await exchange.GetCurrencyPairsAsync(DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(pairs.Count() > 0); } //[Fact] public async Task GetExchangeRateAsync001Async() { var exchange = new CurrencylayerDotCom(this.currencyFactory, this.timeProvider, this.accessKey); var pair = new CurrencyPair(new CurrencyInfo("USD"), new CurrencyInfo("UAH")); var rate = await exchange.GetExchangeRateAsync(pair, DateTimeOffset.Now, default).ConfigureAwait(true); Assert.True(rate > decimal.Zero); } } }
mit
C#
14fba9cb346cc64a4119f1262374209692e8b1cf
Return {success = true} for Variant960Controller.StoreAnonymousIdentifier
Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training
src/ChessVariantsTraining/Controllers/Variant960Controller.cs
src/ChessVariantsTraining/Controllers/Variant960Controller.cs
using ChessVariantsTraining.DbRepositories; using ChessVariantsTraining.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; namespace ChessVariantsTraining.Controllers { public class Variant960Controller : CVTController { IRandomProvider randomProvider; public Variant960Controller(IUserRepository _userRepository, IPersistentLoginHandler _loginHandler, IRandomProvider _randomProvider) : base(_userRepository, _loginHandler) { randomProvider = _randomProvider; } [Route("/Variant960")] public IActionResult Lobby() { return View(); } [Route("/Variant960/Game/{id}")] public IActionResult Game() { return View(); } [Route("/Variant960/Lobby/StoreAnonymousIdentifier")] public IActionResult StoreAnonymousIdentifier() { if (loginHandler.LoggedInUserId(HttpContext).HasValue) { return Json(new { success = true }); } HttpContext.Session.SetString("anonymousIdentifier", randomProvider.RandomString(12)); return Json(new { success = true }); } } }
using ChessVariantsTraining.DbRepositories; using ChessVariantsTraining.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; namespace ChessVariantsTraining.Controllers { public class Variant960Controller : CVTController { IRandomProvider randomProvider; public Variant960Controller(IUserRepository _userRepository, IPersistentLoginHandler _loginHandler, IRandomProvider _randomProvider) : base(_userRepository, _loginHandler) { randomProvider = _randomProvider; } [Route("/Variant960")] public IActionResult Lobby() { return View(); } [Route("/Variant960/Game/{id}")] public IActionResult Game() { return View(); } [Route("/Variant960/Lobby/StoreAnonymousIdentifier")] public IActionResult StoreAnonymousIdentifier() { if (loginHandler.LoggedInUserId(HttpContext).HasValue) { return Json(new {}); } HttpContext.Session.SetString("anonymousIdentifier", randomProvider.RandomString(12)); return Json(new {}); } } }
agpl-3.0
C#
c32d381d3234d14cd84ef30300b5383ca4844361
Add DateTimeHelper.GetISO8601String() ()
eleven41/Eleven41.Helpers
Eleven41.Helpers/DateTimeHelper.cs
Eleven41.Helpers/DateTimeHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Eleven41.Helpers { public static class DateTimeHelper { // Our base is the same as the standard unix file base private static DateTime _base = new DateTime(1970, 1, 1); public static DateTime FromUnixTime(int dt) { return _base.AddSeconds(dt).ToLocalTime(); } public static int ToUnixTime(DateTime dt) { TimeSpan span = dt.ToUniversalTime() - _base; return Convert.ToInt32(span.TotalSeconds); } public static DateTime FromXferTime(long dt) { return _base.AddMilliseconds(dt).ToLocalTime(); } public static long ToXferTime(DateTime dt) { TimeSpan span = dt.ToUniversalTime() - _base; return Convert.ToInt64(span.TotalMilliseconds); } public static DateTime CombineDateWithTime(DateTime useTime, DateTime useDate) { return useDate.Date + useTime.TimeOfDay; //return new DateTime(useDate.Year, useDate.Month, useDate.Day, useTime.Hour, useTime.Minute, useTime.Second, useTime.Kind); } public static int WeekOfMonth(DateTime d) { int remainder; return Math.DivRem(d.Day - 1, 7, out remainder) + 1; } public static int InvWeekOfMonth(DateTime d) { // How many days in the month? int daysInMonth = DateTime.DaysInMonth(d.Year, d.Month); int invDay = (daysInMonth - d.Day); int remainder; return Math.DivRem(invDay, 7, out remainder) + 1; } public static string GetISO8601String(DateTime d) { return d.ToUniversalTime().ToString("yyyy-MM-dd\\THH:mm:ss.fff\\Z"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Eleven41.Helpers { public static class DateTimeHelper { // Our base is the same as the standard unix file base private static DateTime _base = new DateTime(1970, 1, 1); public static DateTime FromUnixTime(int dt) { return _base.AddSeconds(dt).ToLocalTime(); } public static int ToUnixTime(DateTime dt) { TimeSpan span = dt.ToUniversalTime() - _base; return Convert.ToInt32(span.TotalSeconds); } public static DateTime FromXferTime(long dt) { return _base.AddMilliseconds(dt).ToLocalTime(); } public static long ToXferTime(DateTime dt) { TimeSpan span = dt.ToUniversalTime() - _base; return Convert.ToInt64(span.TotalMilliseconds); } public static DateTime CombineDateWithTime(DateTime useTime, DateTime useDate) { return useDate.Date + useTime.TimeOfDay; //return new DateTime(useDate.Year, useDate.Month, useDate.Day, useTime.Hour, useTime.Minute, useTime.Second, useTime.Kind); } public static int WeekOfMonth(DateTime d) { int remainder; return Math.DivRem(d.Day - 1, 7, out remainder) + 1; } public static int InvWeekOfMonth(DateTime d) { // How many days in the month? int daysInMonth = DateTime.DaysInMonth(d.Year, d.Month); int invDay = (daysInMonth - d.Day); int remainder; return Math.DivRem(invDay, 7, out remainder) + 1; } } }
mit
C#
4ac8c43176a28851e0f494b35424696604c946a3
Initialize android test library on contructor
adjust/unity_sdk,adjust/unity_sdk,adjust/unity_sdk
Assets/Adjust/Test/TestFactoryAndroid.cs
Assets/Adjust/Test/TestFactoryAndroid.cs
using UnityEngine; namespace com.adjust.sdk.test { public class TestFactoryAndroid : ITestFactory { private string _baseUrl; private AndroidJavaObject ajoTestLibrary; private CommandListenerAndroid onCommandReceivedListener; public TestFactoryAndroid(string baseUrl) { _baseUrl = baseUrl; CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl); onCommandReceivedListener = new CommandListenerAndroid(commandExecutor); ajoTestLibrary = new AndroidJavaObject( "com.adjust.testlibrary.TestLibrary", _baseUrl, onCommandReceivedListener); } public void StartTestSession() { ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK); } public void AddInfoToSend(string key, string paramValue) { ajoTestLibrary.Call("addInfoToSend", key, paramValue); } public void SendInfoToServer(string basePath) { ajoTestLibrary.Call("sendInfoToServer", basePath); } public void AddTest(string testName) { ajoTestLibrary.Call("addTest", testName); } public void AddTestDirectory(string testDirectory) { ajoTestLibrary.Call("addTestDirectory", testDirectory); } } }
using UnityEngine; namespace com.adjust.sdk.test { public class TestFactoryAndroid : ITestFactory { private string _baseUrl; private AndroidJavaObject ajoTestLibrary; private CommandListenerAndroid onCommandReceivedListener; public TestFactoryAndroid(string baseUrl) { _baseUrl = baseUrl; CommandExecutor commandExecutor = new CommandExecutor(this, baseUrl); onCommandReceivedListener = new CommandListenerAndroid(commandExecutor); } public void StartTestSession() { TestApp.Log("TestFactory -> StartTestSession()"); if (ajoTestLibrary == null) { ajoTestLibrary = new AndroidJavaObject( "com.adjust.testlibrary.TestLibrary", _baseUrl, onCommandReceivedListener); } TestApp.Log("TestFactory -> calling testLib.startTestSession()"); ajoTestLibrary.Call("startTestSession", TestApp.CLIENT_SDK); } public void AddInfoToSend(string key, string paramValue) { if (ajoTestLibrary == null) { return; } ajoTestLibrary.Call("addInfoToSend", key, paramValue); } public void SendInfoToServer(string basePath) { if (ajoTestLibrary == null) { return; } ajoTestLibrary.Call("sendInfoToServer", basePath); } public void AddTest(string testName) { if (ajoTestLibrary == null) { return; } ajoTestLibrary.Call("addTest", testName); } public void AddTestDirectory(string testDirectory) { if (ajoTestLibrary == null) { return; } ajoTestLibrary.Call("addTestDirectory", testDirectory); } } }
mit
C#
af4d369f22a1fa4b7eea731f7e1d52d2966a7afd
Fix QuoteRepository expressions.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Services/Database/Repositories/Impl/QuoteRepository.cs
src/MitternachtBot/Services/Database/Repositories/Impl/QuoteRepository.cs
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Extensions; using Mitternacht.Services.Database.Models; using System.Linq.Expressions; namespace Mitternacht.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).AsEnumerable().Where(q => q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase)); public IEnumerable<Quote> GetAllForGuild(ulong guildId) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).ToList(); public Quote GetRandomQuoteByKeyword(ulong guildId, string keyword) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).AsEnumerable().Where(q => q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase)).Shuffle().FirstOrDefault(); public Quote SearchQuoteKeywordText(ulong guildId, string keyword, string text) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).AsEnumerable().Where(q => q.Text.ContainsNoCase(text, StringComparison.OrdinalIgnoreCase) && q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase)).Shuffle().FirstOrDefault(); public void RemoveAllByKeyword(ulong guildId, string keyword) => _set.RemoveRange(_set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).Where(q => q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase))); } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Mitternacht.Extensions; using Mitternacht.Services.Database.Models; using System.Linq.Expressions; namespace Mitternacht.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId && q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase))); public IEnumerable<Quote> GetAllForGuild(ulong guildId) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId)).ToList(); public Quote GetRandomQuoteByKeyword(ulong guildId, string keyword) => _set.Where((Expression<Func<Quote, bool>>)(q => q.GuildId == guildId && q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase))).AsEnumerable().Shuffle().FirstOrDefault(); public Quote SearchQuoteKeywordText(ulong guildId, string keyword, string text) => _set.Where((Expression<Func<Quote, bool>>)(q => q.Text.ContainsNoCase(text, StringComparison.OrdinalIgnoreCase) && q.GuildId == guildId && q.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase))).AsEnumerable().Shuffle().FirstOrDefault(); public void RemoveAllByKeyword(ulong guildId, string keyword) => _set.RemoveRange(_set.Where((Expression<Func<Quote, bool>>)(x => x.GuildId == guildId && x.Keyword.Equals(keyword, StringComparison.OrdinalIgnoreCase)))); } }
mit
C#
d8a696c968f03ad900d9c0068016dc26ef1b7e4d
Adjust output directory in script
PluginsForXamarin/vibrate
CI/build.cake
CI/build.cake
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Default").Does (() => { const string sln = "./../Vibrate.sln"; const string cfg = "Release"; NuGetRestore (sln); if (!IsRunningOnWindows ()) DotNetBuild (sln, c => c.Configuration = cfg); else MSBuild (sln, c => { c.Configuration = cfg; c.MSBuildPlatform = MSBuildPlatform.x86; }); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./../", BasePath = "./", }); }); RunTarget (TARGET);
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Default").Does (() => { const string sln = "./../Vibrate.sln"; const string cfg = "Release"; NuGetRestore (sln); if (!IsRunningOnWindows ()) DotNetBuild (sln, c => c.Configuration = cfg); else MSBuild (sln, c => { c.Configuration = cfg; c.MSBuildPlatform = MSBuildPlatform.x86; }); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./../Vibrate.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
mit
C#
e137066dd41368553be7f3e1a0b863fe93ade783
remove comment only
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob/Program.cs
src/SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob/Program.cs
using System; using SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob.DependencyResolution; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976 class Program { static void Main() { var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); var addEpaToApprenticeship = container.GetInstance<IAddEpaToApprenticeships>(); logger.Info("Starting AddEpaToApprenticeships.WebJob"); // we don't need to use JobHost - the other web jobs in the solution don't. here's why... // https://stackoverflow.com/questions/25811719/azure-webjobs-sdk-in-what-scenarios-is-creation-of-a-jobhost-object-required try { addEpaToApprenticeship.Update().Wait(); } catch (Exception ex) { logger.Error(ex, "Error running AddEpaToApprenticeship.WebJob"); } } } }
using System; using SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob.DependencyResolution; using SFA.DAS.NLog.Logger; namespace SFA.DAS.Commitments.AddEpaToApprenticeships.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see https://go.microsoft.com/fwlink/?LinkID=320976 class Program { static void Main() { //todo: db will need to be deployed var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); var addEpaToApprenticeship = container.GetInstance<IAddEpaToApprenticeships>(); logger.Info("Starting AddEpaToApprenticeships.WebJob"); // we don't need to use JobHost - the other web jobs in the solution don't. here's why... // https://stackoverflow.com/questions/25811719/azure-webjobs-sdk-in-what-scenarios-is-creation-of-a-jobhost-object-required try { addEpaToApprenticeship.Update().Wait(); } catch (Exception ex) { logger.Error(ex, "Error running AddEpaToApprenticeship.WebJob"); } } } }
mit
C#
5aaa7c35ab0b82122c21d01bd6afa8b9f87d87ee
Change version number.
ollyau/FSActiveFires
FSActiveFires/Properties/AssemblyInfo.cs
FSActiveFires/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("FSActiveFires")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FSActiveFires")] [assembly: AssemblyCopyright("Copyright © Orion Lyau 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
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("FSActiveFires")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("FSActiveFires")] [assembly: AssemblyCopyright("Copyright © Orion Lyau 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //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.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
cea5f4d9374fafc6bc30304d897b4188bd6db637
Add commission as Employee Pay Type
mattgwagner/CertiPay.Payroll.Common
CertiPay.Payroll.Common/EmployeePayType.cs
CertiPay.Payroll.Common/EmployeePayType.cs
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Describes how an employee pay is calculated /// </summary> public enum EmployeePayType : byte { /// <summary> /// Employee earns a set salary per period of time, i.e. $70,000 yearly /// </summary> Salary = 1, /// <summary> /// Employee earns a given amount per hour of work, i.e. $10 per hour /// </summary> Hourly = 2, /// <summary> /// Employee earns a flat rate based on sales or project completion /// </summary> Commission = 3 } public static class EmployeePayTypes { public static IEnumerable<EmployeePayType> Values() { yield return EmployeePayType.Salary; yield return EmployeePayType.Hourly; yield return EmployeePayType.Commission; } } }
using System.Collections.Generic; namespace CertiPay.Payroll.Common { /// <summary> /// Describes how an employee pay is calculated /// </summary> public enum EmployeePayType : byte { /// <summary> /// Employee earns a set salary per period of time, i.e. $70,000 yearly /// </summary> Salary = 1, /// <summary> /// Employee earns a given amount per hour of work, i.e. $10 per hour /// </summary> Hourly = 2 } public static class EmployeePayTypes { public static IEnumerable<EmployeePayType> Values() { yield return EmployeePayType.Salary; yield return EmployeePayType.Hourly; } } }
mit
C#
a99e814eff99b2d47433610831f60fdadc63b6eb
Remove Init SSO button
maestrano/demoapp-dotnet
MnoDemoApp/Views/Home/Index.cshtml
MnoDemoApp/Views/Home/Index.cshtml
@{ var session = System.Web.HttpContext.Current.Session; } <div class="row"> <div class="span8 offset2"> @if (session["loggedIn"] != null) { <h4> Hello @session["firstName"] @session["lastName"] </h4> <br /> <p> You logged in via group <b>@session["groupName"]</b> </p> } else { <h3>Discovered Marketplaces</h3> foreach (var item in Maestrano.MnoHelper.Presets()) { <div> <h4>@item.Key</h4> <span>@item.Value.Api.Host</span> </div> } } </div> </div>
@{ var session = System.Web.HttpContext.Current.Session; } <div class="row"> <div class="span8 offset2" style="text-align: center;"> @if (session["loggedIn"] != null) { <h4> Hello @session["firstName"] @session["lastName"] </h4> <br /> <p> You logged in via group <b>@session["groupName"]</b> </p> } else { foreach (var item in Maestrano.MnoHelper.Presets()) { <a class="btn btn-large" href="@item.Value.Sso.InitUrl()">Login To @item.Key</a> } } </div> </div>
mit
C#
df3a7c4df829e5bfdfa21c500998d232fef250df
add AcceptHeader for delete reactions method
TattsGroup/octokit.net,shiftkey-tester/octokit.net,ivandrofly/octokit.net,octokit/octokit.net,rlugojr/octokit.net,editor-tools/octokit.net,ivandrofly/octokit.net,Sarmad93/octokit.net,devkhan/octokit.net,shana/octokit.net,SmithAndr/octokit.net,devkhan/octokit.net,octokit/octokit.net,dampir/octokit.net,eriawan/octokit.net,thedillonb/octokit.net,dampir/octokit.net,adamralph/octokit.net,editor-tools/octokit.net,rlugojr/octokit.net,alfhenrik/octokit.net,M-Zuber/octokit.net,gdziadkiewicz/octokit.net,shana/octokit.net,eriawan/octokit.net,alfhenrik/octokit.net,M-Zuber/octokit.net,khellang/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,Sarmad93/octokit.net,shiftkey/octokit.net,thedillonb/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,SmithAndr/octokit.net,shiftkey-tester/octokit.net,TattsGroup/octokit.net,khellang/octokit.net,shiftkey/octokit.net
Octokit/Clients/ReactionsClient.cs
Octokit/Clients/ReactionsClient.cs
using System; using System.Threading.Tasks; namespace Octokit { public class ReactionsClient : ApiClient, IReactionsClient { /// <summary> /// Instantiates a new GitHub Reactions API client /// </summary> /// <param name="apiConnection">An API connection</param> public ReactionsClient(IApiConnection apiConnection) : base(apiConnection) { CommitComment = new CommitCommentReactionsClient(apiConnection); Issue = new IssueReactionsClient(apiConnection); IssueComment = new IssueCommentReactionsClient(apiConnection); PullRequestReviewComment = new PullRequestReviewCommentReactionsClient(apiConnection); } /// <summary> /// Access GitHub's Reactions API for Commit Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public ICommitCommentReactionsClient CommitComment { get; private set; } /// <summary> /// Access GitHub's Reactions API for Issues. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IIssueReactionsClient Issue { get; private set; } /// <summary> /// Access GitHub's Reactions API for Issue Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IIssueCommentReactionsClient IssueComment { get; private set; } /// <summary> /// Access GitHub's Reactions API for Pull Request Review Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IPullRequestReviewCommentReactionsClient PullRequestReviewComment { get; private set; } /// <summary> /// Delete a reaction. /// </summary> /// <remarks>https://developer.github.com/v3/reactions/#delete-a-reaction</remarks> /// <param name="number">The reaction id</param> /// <returns></returns> public Task Delete(int number) { return ApiConnection.Delete(ApiUrls.Reactions(number),null, AcceptHeaders.ReactionsPreview); } } }
using System; using System.Threading.Tasks; namespace Octokit { public class ReactionsClient : ApiClient, IReactionsClient { /// <summary> /// Instantiates a new GitHub Reactions API client /// </summary> /// <param name="apiConnection">An API connection</param> public ReactionsClient(IApiConnection apiConnection) : base(apiConnection) { CommitComment = new CommitCommentReactionsClient(apiConnection); Issue = new IssueReactionsClient(apiConnection); IssueComment = new IssueCommentReactionsClient(apiConnection); PullRequestReviewComment = new PullRequestReviewCommentReactionsClient(apiConnection); } /// <summary> /// Access GitHub's Reactions API for Commit Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public ICommitCommentReactionsClient CommitComment { get; private set; } /// <summary> /// Access GitHub's Reactions API for Issues. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IIssueReactionsClient Issue { get; private set; } /// <summary> /// Access GitHub's Reactions API for Issue Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IIssueCommentReactionsClient IssueComment { get; private set; } /// <summary> /// Access GitHub's Reactions API for Pull Request Review Comments. /// </summary> /// <remarks> /// Refer to the API documentation for more information: https://developer.github.com/v3/reactions/ /// </remarks> public IPullRequestReviewCommentReactionsClient PullRequestReviewComment { get; private set; } /// <summary> /// Delete a reaction. /// </summary> /// <remarks>https://developer.github.com/v3/reactions/#delete-a-reaction</remarks> /// <param name="number">The reaction id</param> /// <returns></returns> public Task Delete(int number) { return ApiConnection.Delete(ApiUrls.Reactions(number)); } } }
mit
C#
74bf8aae0a9094559fadf47cc3f15c294eb8f038
Fix typo
celeron533/marukotoolbox
mp4box/Properties/AssemblyInfo.cs
mp4box/Properties/AssemblyInfo.cs
// ------------------------------------------------------------------ // Copyright (C) 2011-2017 Maruko Toolbox Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. // See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------- // using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Maruko Toolbox")] [assembly: AssemblyDescription("A Video-processing GUI")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://maruko.appinn.me/")] [assembly: AssemblyProduct("Maruko Toolbox")] [assembly: AssemblyCopyright("Copyright © 2011-2017")] [assembly: AssemblyTrademark("Maruko")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d8671a06-a28b-4e6a-a2cb-5649d5fbf2ab")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("242")]
// ------------------------------------------------------------------ // Copyright (C) 2011-2017 Maruko Toolbox Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. // See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------- // using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Maruko Toolbox")] [assembly: AssemblyDescription("A Video-prosessing GUI")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("http://maruko.appinn.me/")] [assembly: AssemblyProduct("Maruko Toolbox")] [assembly: AssemblyCopyright("Copyright © 2011-2016")] [assembly: AssemblyTrademark("Maruko")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("d8671a06-a28b-4e6a-a2cb-5649d5fbf2ab")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("242")]
apache-2.0
C#
d04d580bc8fdecabbd9cf97613eb720fabffcde7
change meggages in homecontroller
Hopur42/verkApp,Hopur42/verkApp
verkApp/Controllers/HomeController.cs
verkApp/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace verkApp.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "hello world!"; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace verkApp.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
mit
C#
ff65c67f77b4e7ac2a63a292193a60d3beac371a
Remove code line commented
lucasdavid/Gamedalf,lucasdavid/Gamedalf
Gamedalf.Core/Data/ApplicationDbContext.cs
Gamedalf.Core/Data/ApplicationDbContext.cs
using Gamedalf.Core.Infrastructure; using Gamedalf.Core.Models; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Gamedalf.Core.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDateTracker { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public void TrackDate() { foreach (var entity in ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Modified)) { if (entity.State == EntityState.Added && entity.Entity is IDateCreatedTrackable) { ((IDateCreatedTrackable)entity.Entity).DateCreated = DateTime.Now; } if (entity.State == EntityState.Modified && entity.Entity is IDateUpdatedTrackable) { ((IDateUpdatedTrackable)entity.Entity).DateUpdated = DateTime.Now; } } } public override int SaveChanges() { TrackDate(); return base.SaveChanges(); } public override Task<int> SaveChangesAsync() { TrackDate(); return base.SaveChangesAsync(); } public virtual DbSet<Employee> Employees { get; set; } public virtual DbSet<Player> Players { get; set; } public virtual DbSet<Game> Games { get; set; } public virtual DbSet<Playing> Playings { get; set; } public virtual DbSet<Terms> Terms { get; set; } public virtual DbSet<Payment> Payments { get; set; } public virtual DbSet<Subscription> Subscriptions { get; set; } } }
using Gamedalf.Core.Infrastructure; using Gamedalf.Core.Models; using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Data.Entity; using System.Linq; using System.Threading.Tasks; namespace Gamedalf.Core.Data { public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IDateTracker { public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { return new ApplicationDbContext(); } public void TrackDate() { foreach (var entity in ChangeTracker.Entries().Where(p => p.State == EntityState.Added || p.State == EntityState.Modified)) { if (entity.State == EntityState.Added && entity.Entity is IDateCreatedTrackable) { ((IDateCreatedTrackable)entity.Entity).DateCreated = DateTime.Now; } if (entity.State == EntityState.Modified && entity.Entity is IDateUpdatedTrackable) { ((IDateUpdatedTrackable)entity.Entity).DateUpdated = DateTime.Now; } } } public override int SaveChanges() { TrackDate(); return base.SaveChanges(); } public override Task<int> SaveChangesAsync() { TrackDate(); return base.SaveChangesAsync(); } public virtual DbSet<Employee> Employees { get; set; } public virtual DbSet<Player> Players { get; set; } public virtual DbSet<Game> Games { get; set; } public virtual DbSet<Playing> Playings { get; set; } public virtual DbSet<Terms> Terms { get; set; } public virtual DbSet<Payment> Payments { get; set; } public virtual DbSet<Subscription> Subscriptions { get; set; } //public System.Data.Entity.DbSet<Gamedalf.Core.Models.Payment> Payments { get; set; } } }
mit
C#
cac2009341dda0a395518da0d110ba3aaac86586
Update Program.cs
fredatgithub/uptime
Uptime/Program.cs
Uptime/Program.cs
using System; using System.Globalization; namespace Uptime { class Program { static void Main() { Action<string> display = Console.WriteLine; display("UpTime.exe is a Freeware written by Freddy Juhel in 2013\n"); var ts = TimeSpan.FromMilliseconds(Environment.TickCount); int nombreDeTicks = Environment.TickCount; // &Int32.MaxValue; Console.WriteLine("System is up since {0:HH:mm:ss} milliseconds\n", Environment.TickCount.ToString(CultureInfo.CurrentCulture)); Console.WriteLine("which is {0} day{1} {2} hour{3} {4} minute{5} {6} second{7} {8} millisecond{9}\n", ts.Days, Plural(ts.Days), ts.Hours, Plural(ts.Hours), ts.Minutes, Plural(ts.Minutes), ts.Seconds, Plural(ts.Seconds), ts.Milliseconds, Plural(ts.Milliseconds)); display("Press a key to exit:"); Console.ReadKey(); } private static string Plural(Int32 number) { return number > 1 ? "s" : string.Empty; } } }
/* The MIT License(MIT) Copyright(c) 2015 Freddy Juhel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Globalization; namespace Uptime { class Program { static void Main() { Action<string> display = Console.WriteLine; display("UpTime.exe is a Freeware written by Freddy Juhel in 2013\n"); var ts = TimeSpan.FromMilliseconds(Environment.TickCount); int nombreDeTicks = Environment.TickCount; // &Int32.MaxValue; Console.WriteLine("System is up since {0:HH:mm:ss} milliseconds\n", Environment.TickCount.ToString(CultureInfo.CurrentCulture)); Console.WriteLine("which is {0} day{1} {2} hour{3} {4} minute{5} {6} second{7} {8} millisecond{9}\n", ts.Days, Plural(ts.Days), ts.Hours, Plural(ts.Hours), ts.Minutes, Plural(ts.Minutes), ts.Seconds, Plural(ts.Seconds), ts.Milliseconds, Plural(ts.Milliseconds)); display("Press a key to exit:"); Console.ReadKey(); } private static string Plural(Int32 number) { return number > 1 ? "s" : string.Empty; } } }
apache-2.0
C#
6dca035a28187ab34bd4fea09a29222c33b786a1
Use correct enumeration value
sevoku/xwt,mminns/xwt,steffenWi/xwt,residuum/xwt,iainx/xwt,hwthomas/xwt,directhex/xwt,TheBrainTech/xwt,akrisiun/xwt,lytico/xwt,mono/xwt,hamekoz/xwt,antmicro/xwt,mminns/xwt,cra0zy/xwt
Xwt/Xwt/Slider.cs
Xwt/Xwt/Slider.cs
// // Slider.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2013 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; namespace Xwt { [BackendType (typeof(ISliderBackend))] public class Slider : Widget { public Slider () { } protected new class WidgetBackendHost: Widget.WidgetBackendHost, ISpinButtonEventSink { public void ValueChanged () { ((Slider)Parent).OnValueChanged (EventArgs.Empty); } } ISliderBackend Backend { get { return (ISliderBackend) BackendHost.Backend; } } protected override BackendHost CreateBackendHost () { return new WidgetBackendHost (); } public double Value { get { return Backend.Value; } set { Backend.Value = value; } } public double MinimumValue { get { return Backend.MinimumValue; } set { Backend.MinimumValue = value; } } public double MaximumValue { get { return Backend.MaximumValue; } set { Backend.MaximumValue = value; } } protected virtual void OnValueChanged (EventArgs e) { if (valueChanged != null) valueChanged (this, e); } EventHandler valueChanged; public event EventHandler ValueChanged { add { BackendHost.OnBeforeEventAdd (SliderEvent.ValueChanged, valueChanged); valueChanged += value; } remove { valueChanged -= value; BackendHost.OnAfterEventRemove (SliderEvent.ValueChanged, valueChanged); } } } }
// // Slider.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2013 Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; namespace Xwt { [BackendType (typeof(ISliderBackend))] public class Slider : Widget { public Slider () { } protected new class WidgetBackendHost: Widget.WidgetBackendHost, ISpinButtonEventSink { public void ValueChanged () { ((Slider)Parent).OnValueChanged (EventArgs.Empty); } } ISliderBackend Backend { get { return (ISliderBackend) BackendHost.Backend; } } protected override BackendHost CreateBackendHost () { return new WidgetBackendHost (); } public double Value { get { return Backend.Value; } set { Backend.Value = value; } } public double MinimumValue { get { return Backend.MinimumValue; } set { Backend.MinimumValue = value; } } public double MaximumValue { get { return Backend.MaximumValue; } set { Backend.MaximumValue = value; } } protected virtual void OnValueChanged (EventArgs e) { if (valueChanged != null) valueChanged (this, e); } EventHandler valueChanged; public event EventHandler ValueChanged { add { BackendHost.OnBeforeEventAdd (SpinButtonEvent.ValueChanged, valueChanged); valueChanged += value; } remove { valueChanged -= value; BackendHost.OnAfterEventRemove (SpinButtonEvent.ValueChanged, valueChanged); } } } }
mit
C#
d4af9dc9f2563ab439bfbf88c797eddc562b8ed6
increase version number to 0.2.1.1
ChrisDeadman/KSPPartRemover
KSPPartRemover/Properties/AssemblyInfo.cs
KSPPartRemover/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KSPPartRemover")] [assembly: AssemblyDescription("Removes parts from KSP save files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Deadman")] [assembly: AssemblyProduct("KSPPartRemover")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7e074eb8-495e-4401-afc9-9608b11403c3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.1.1")] [assembly: AssemblyFileVersion("0.2.1.1")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("KSPPartRemover")] [assembly: AssemblyDescription("Removes parts from KSP save files")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Deadman")] [assembly: AssemblyProduct("KSPPartRemover")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7e074eb8-495e-4401-afc9-9608b11403c3")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.1.0")] [assembly: AssemblyFileVersion("0.2.1.0")]
mit
C#
e441261a512a218a1b37bac8f62649f8e47ec1c7
Update controller for request validation
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
guides/request-validation-csharp/example-2/example-2.4.x.cs
guides/request-validation-csharp/example-2/example-2.4.x.cs
using System.Web.Mvc; using Twilio.AspNet.Mvc; using Twilio.TwiML; using ValidateRequestExample.Filters; namespace ValidateRequestExample.Controllers { public class IncomingController : TwilioController { [ValidateTwilioRequest] public ActionResult Voice(string from) { var message = "Thanks for calling! " + $"Your phone number is {from}. " + "I got your call because of Twilio's webhook. " + "Goodbye!"; var response = new VoiceResponse(); response.Say(string.Format(message, from)); response.Hangup(); return TwiML(response); } [ValidateTwilioRequest] public ActionResult Message(string body) { var message = $"Your text to me was {body.Length} characters long. " + "Webhooks are neat :)"; var response = new MessagingResponse(); response.Message(new Message(message)); return TwiML(response); } } }
using System.Web.Mvc; using Twilio.TwiML; using Twilio.TwiML.Mvc; using ValidateRequestExample.Filters; namespace ValidateRequestExample.Controllers { public class IncomingController : TwilioController { [ValidateTwilioRequest] public ActionResult Voice(string from) { var response = new TwilioResponse(); const string message = "Thanks for calling! " + "Your phone number is {0}. I got your call because of Twilio's webhook. " + "Goodbye!"; response.Say(string.Format(message, from)); response.Hangup(); return TwiML(response); } [ValidateTwilioRequest] public ActionResult Message(string body) { var response = new TwilioResponse(); response.Say($"Your text to me was {body.Length} characters long. Webhooks are neat :)"); response.Hangup(); return TwiML(response); } } }
mit
C#
be0a38cbe797df83f556ee3bf88a2668c94739e7
Make Cancel consistent with Save appearance
tpkelly/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,Generic-Voting-Application/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,stevenhillcox/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,Generic-Voting-Application/voting-application
VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml
VotingApplication/VotingApplication.Web/Views/Routes/ManageInvitees.cshtml
<div ng-app="GVA.Creation" ng-controller="ManageInviteesController"> <div class="centered"> <h2>Poll Invitees</h2> <h4>Email to Invite</h4> <input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" /> <span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span> <h4>Pending</h4> <p ng-if="pendingUsers.length === 0">No pending users</p> <div class="pill-box"> <div class="invitee-pill" ng-repeat="pending in pendingUsers"> <span class="invitee-pill-text">{{pending.Email}}</span> <span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span> </div> </div> <div class="manage-section" ng-if="pendingUsers.length > 0"> <button class="manage-btn" ng-click="addInvitee(inviteString); sendInvitations();">Invite</button> </div> <h4>Invited</h4> <p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p> <div class="pill-box"> <div class="invitee-pill" ng-repeat="invitee in invitedUsers"> <span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span> <span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span> </div> </div> <div class="manage-section"> <button class="manage-btn" ng-click="updatePoll(); return()">Save</button> <button class="manage-btn" ng-click="return()">Cancel</button> </div> </div> </div>
<div ng-app="GVA.Creation" ng-controller="ManageInviteesController"> <div class="centered"> <h2>Poll Invitees</h2> <h4>Email to Invite</h4> <input id="new-invitee" name="new-invitee" ng-model="inviteString" ng-change="emailUpdated()" ng-trim="false" /> <span class="glyphicon glyphicon-plus" ng-click="addInvitee(inviteString);"></span> <h4>Pending</h4> <p ng-if="pendingUsers.length === 0">No pending users</p> <div class="pill-box"> <div class="invitee-pill" ng-repeat="pending in pendingUsers"> <span class="invitee-pill-text">{{pending.Email}}</span> <span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deletePendingVoter(pending)" aria-hidden="true"></span> </div> </div> <div class="manage-section" ng-if="pendingUsers.length > 0"> <button class="manage-btn" ng-click="addInvitee(inviteString); sendInvitations();">Invite</button> </div> <h4>Invited</h4> <p ng-if="invitedUsers.length === 0">You haven't invited anybody yet</p> <div class="pill-box"> <div class="invitee-pill" ng-repeat="invitee in invitedUsers"> <span class="invitee-pill-text">{{invitee.Name || invitee.Email}}</span> <span class="glyphicon glyphicon-remove invitee-pill-delete" ng-click="deleteInvitedVoter(invitee)" aria-hidden="true"></span> </div> </div> <div class="manage-section"> <button class="manage-btn" ng-click="updatePoll(); return()">Save</button> <button class="inactive-btn" ng-click="return()">Cancel</button> </div> </div> </div>
apache-2.0
C#
b4608c2e68fb1ea8704f164d281b92e9ed86b355
Fix test for NotNullOrEmpty passing check.
devtyr/gullap
DevTyr.Gullap.Tests/With_Guard/For_NotNullOrEmpty/When_argument_is_not_null.cs
DevTyr.Gullap.Tests/With_Guard/For_NotNullOrEmpty/When_argument_is_not_null.cs
using System; using NUnit.Framework; using DevTyr.Gullap; namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty { [TestFixture] public class When_argument_is_not_null_or_empty { [Test] public void Should_pass () { Guard.NotNullOrEmpty ("Test", null); Assert.Pass (); } } }
using System; using NUnit.Framework; using DevTyr.Gullap; namespace DevTyr.Gullap.Tests.With_Guard.For_NotNullOrEmpty { [TestFixture] public class When_argument_is_not_null { [Test] public void Should_pass () { Guard.NotNullOrEmpty ("", null); Assert.Pass (); } } }
mit
C#
ec4dec32ba3b17a6f5b5e5b633d8eff0a2af03bd
Update AssemblyInfo
MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net
Mindscape.Raygun4Net.Azure.WebJob/Properties/AssemblyInfo.cs
Mindscape.Raygun4Net.Azure.WebJob/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("Mindscape.Raygun4Net.Azure.WebJob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Raygun")] [assembly: AssemblyProduct("Raygun4Net")] [assembly: AssemblyCopyright("Copyright © Raygun 2014-2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca9d9a01-c33b-4f17-af07-0305e86764c8")]
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("Mindscape.Raygun4Net.Azure.WebJob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mindscape.Raygun4Net.Azure.WebJob")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ca9d9a01-c33b-4f17-af07-0305e86764c8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
528d959c9113bffff69caac713e873658d30d758
Remove EnableCors attribute from controller
mersocarlin/aspnet-core-docker-sample,mersocarlin/aspnet-core-docker-sample,mersocarlin/aspnet-core-docker-sample
BankService/BankService.Api/Controllers/AccountHolderController.cs
BankService/BankService.Api/Controllers/AccountHolderController.cs
using BankService.Domain.Contracts; using BankService.Domain.Models; using Microsoft.AspNet.Mvc; using System.Collections.Generic; namespace BankService.Api.Controllers { [Route("api/accountHolders")] public class AccountHolderController : Controller { private readonly IAccountHolderRepository accountHolderRepository; private readonly ICachedAccountHolderRepository cachedAccountHolderRepository; public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository) { this.accountHolderRepository = repository; this.cachedAccountHolderRepository = cachedRepository; } [HttpGet] public IEnumerable<AccountHolder> Get() { return this.accountHolderRepository.GetWithLimit(100); } [HttpGet("{id}")] public AccountHolder Get(string id) { var accountHolder = this.cachedAccountHolderRepository.Get(id); if (accountHolder != null) { return accountHolder; } accountHolder = this.accountHolderRepository.GetById(id); this.cachedAccountHolderRepository.Set(accountHolder); return accountHolder; } } }
using BankService.Domain.Contracts; using BankService.Domain.Models; using Microsoft.AspNet.Cors; using Microsoft.AspNet.Mvc; using System.Collections.Generic; namespace BankService.Api.Controllers { [EnableCors("MyPolicy")] [Route("api/accountHolders")] public class AccountHolderController : Controller { private readonly IAccountHolderRepository accountHolderRepository; private readonly ICachedAccountHolderRepository cachedAccountHolderRepository; public AccountHolderController(IAccountHolderRepository repository, ICachedAccountHolderRepository cachedRepository) { this.accountHolderRepository = repository; this.cachedAccountHolderRepository = cachedRepository; } [HttpGet] public IEnumerable<AccountHolder> Get() { return this.accountHolderRepository.GetWithLimit(100); } [HttpGet("{id}")] public AccountHolder Get(string id) { var accountHolder = this.cachedAccountHolderRepository.Get(id); if (accountHolder != null) { return accountHolder; } accountHolder = this.accountHolderRepository.GetById(id); this.cachedAccountHolderRepository.Set(accountHolder); return accountHolder; } } }
mit
C#
84fe00f872a9a8ac6a1511001c441a600fba9ac7
Fix it only theorectically working.
Pathoschild/StardewMods
ContentPatcher/Framework/Tokens/ValueProviders/ModValueProvider.cs
ContentPatcher/Framework/Tokens/ValueProviders/ModValueProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContentPatcher.Framework.Tokens.ValueProviders { internal class ModValueProvider : BaseValueProvider { /********* ** Fields *********/ /// <summary>The function providing values.</summary> private readonly Func<ITokenString, string[]> ValueFunction; /// <summary>The possible resulting values for this token.</summary> private HashSet<string> Values = new HashSet<string>(); /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="name"> The value provider name.</param> /// <param name="valueFunction">The function providing values.</param> public ModValueProvider(string name, Func<ITokenString, string[]> valueFunction) : base(name, true) { this.ValueFunction = valueFunction; this.EnableInputArguments(true, true); } /// <summary>Get the current values.</summary> /// <param name="input">The input argument, if applicable.</param> /// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception> public override IEnumerable<string> GetValues(IManagedTokenString input) { this.AssertInputArgument(input); foreach (string value in this.ValueFunction(input)) yield return value; } /// <summary>Update the instance when the context changes.</summary> /// <param name="context">Provides access to contextual tokens.</param> /// <returns>Returns whether the instance changed.</returns> public override bool UpdateContext(IContext context) { return this.IsChanged(this.Values, () => { this.Values = new HashSet<string>(this.ValueFunction(null)); this.IsReady = this.Values.Count > 0; }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ContentPatcher.Framework.Tokens.ValueProviders { internal class ModValueProvider : BaseValueProvider { /********* ** Fields *********/ /// <summary>The function providing values.</summary> private readonly Func<ITokenString, string[]> ValueFunction; /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="name"> The value provider name.</param> /// <param name="valueFunction">The function providing values.</param> public ModValueProvider(string name, Func<ITokenString, string[]> valueFunction) : base(name, true) { this.ValueFunction = valueFunction; } /// <summary>Get the current values.</summary> /// <param name="input">The input argument, if applicable.</param> /// <exception cref="InvalidOperationException">The input argument doesn't match this value provider, or does not respect <see cref="IValueProvider.AllowsInput"/> or <see cref="IValueProvider.RequiresInput"/>.</exception> public override IEnumerable<string> GetValues(IManagedTokenString input) { this.AssertInputArgument(input); foreach (string value in this.ValueFunction(input)) yield return value; } } }
mit
C#
bb4a0049525c979c44af2a71e343212515aca3d8
Hide UserId by Editing in KendoGrid PopUp
KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem
VotingSystem.Web/Areas/User/ViewModels/UserPollsViewModel.cs
VotingSystem.Web/Areas/User/ViewModels/UserPollsViewModel.cs
namespace VotingSystem.Web.Areas.User.ViewModels { using System; using System.Collections.Generic; using System.Web.Mvc; using VotingSystem.Models; using VotingSystem.Web.Infrastructure.Mapping; using AutoMapper; public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings { [HiddenInput(DisplayValue = false)] public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } [HiddenInput(DisplayValue = false)] public string Author { get; set; } public bool IsPublic { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } [HiddenInput(DisplayValue = false)] public string UserId { get; set; } public void CreateMappings(AutoMapper.IConfiguration configuration) { configuration.CreateMap<Poll, UserPollsViewModel>() .ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName)); } } }
namespace VotingSystem.Web.Areas.User.ViewModels { using System; using System.Collections.Generic; using System.Web.Mvc; using VotingSystem.Models; using VotingSystem.Web.Infrastructure.Mapping; using AutoMapper; public class UserPollsViewModel : IMapFrom<Poll>, IHaveCustomMappings { [HiddenInput(DisplayValue = false)] public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } [HiddenInput(DisplayValue = false)] public string Author { get; set; } public bool IsPublic { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public string UserId { get; set; } public void CreateMappings(AutoMapper.IConfiguration configuration) { configuration.CreateMap<Poll, UserPollsViewModel>() .ForMember(m => m.Author, opt => opt.MapFrom(a => a.User.UserName)); } } }
mit
C#
f8c8004c138462d22ebae5b5d8aa8255ca7467c8
Remove confusing comment
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
WalletWasabi/Crypto/ZeroKnowledge/LinearRelation/Equation.cs
using NBitcoin.Secp256k1; using System.Linq; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { // Each proof of a linear relation consists of multiple knowledge of // representation equations, all sharing a single witness comprised of several // secrets. // // Note that some of the generators can be the point at infinity, when a term // in the witness does not play a part in the representation of a specific // point. public class Equation { public Equation(GroupElement publicPoint, GroupElementVector generators) { Guard.NotNullOrEmpty(nameof(generators), generators); PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint); Generators = generators; } // Knowledge of representation asserts // P = x_1*G_1 + x_2*G_2 + ... // so we need a single public input and several generators public GroupElement PublicPoint { get; } public GroupElementVector Generators { get; } // Evaluate the verification equation corresponding to the one in the statement internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses) { // the verification equation (for 1 generator case) is: // sG =? R + eP // where: // - R = kG is the public nonce, k is the secret nonce // - P = xG is the public input, x is the secret // - e is the challenge // - s is the response return responses * Generators == (publicNonce + challenge * PublicPoint); } // Simulate a public nonce given a challenge and arbitrary responses (should be random) internal GroupElement Simulate(Scalar challenge, ScalarVector givenResponses) { // The verification equation above can be rearranged as a formula for R // given e, P and s by subtracting eP from both sides: // R = sG - eP return givenResponses * Generators - challenge * PublicPoint; } // Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness internal ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge) { // By canceling G on both sides of the verification equation above we can // obtain a formula for the response s given k, e and x: // s = k + ex return secretNonces + challenge * witness; } } }
using NBitcoin.Secp256k1; using System.Linq; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge.LinearRelation { // Each proof of a linear relation consists of multiple knowledge of // representation equations, all sharing a single witness comprised of several // secrets. // // Note that some of the generators can be the point at infinity, when a term // in the witness does not play a part in the representation of a specific // point. public class Equation { public Equation(GroupElement publicPoint, GroupElementVector generators) { Guard.NotNullOrEmpty(nameof(generators), generators); // generators can be null PublicPoint = Guard.NotNull(nameof(publicPoint), publicPoint); Generators = generators; } // Knowledge of representation asserts // P = x_1*G_1 + x_2*G_2 + ... // so we need a single public input and several generators public GroupElement PublicPoint { get; } public GroupElementVector Generators { get; } // Evaluate the verification equation corresponding to the one in the statement internal bool Verify(GroupElement publicNonce, Scalar challenge, ScalarVector responses) { // the verification equation (for 1 generator case) is: // sG =? R + eP // where: // - R = kG is the public nonce, k is the secret nonce // - P = xG is the public input, x is the secret // - e is the challenge // - s is the response return responses * Generators == (publicNonce + challenge * PublicPoint); } // Simulate a public nonce given a challenge and arbitrary responses (should be random) internal GroupElement Simulate(Scalar challenge, ScalarVector givenResponses) { // The verification equation above can be rearranged as a formula for R // given e, P and s by subtracting eP from both sides: // R = sG - eP return givenResponses * Generators - challenge * PublicPoint; } // Given a witness and secret nonces, respond to a challenge proving the equation holds w.r.t the witness internal ScalarVector Respond(ScalarVector witness, ScalarVector secretNonces, Scalar challenge) { // By canceling G on both sides of the verification equation above we can // obtain a formula for the response s given k, e and x: // s = k + ex return secretNonces + challenge * witness; } } }
mit
C#
a451c5d5896156fa11a526798b1648b07bf790d6
Update GameController.cs
MoonMaster/FunnyGame
FunnyGame/src/GameController.cs
FunnyGame/src/GameController.cs
using System; using System.Linq; namespace FunnyGame { public class GameController : IGameController { public void Run() { ViewGame viewerGame = new ViewGame(); PersonController personController = new PersonController(); string gamerName; string choiceGamer; viewerGame.GetWelcomePage(); do { gamerName = viewerGame.GetGamerName(); if (!personController.CheckCorrectGameName(gamerName)) { Console.WriteLine("The Gamer Name is not correct"); } else { break; } } while (true); do { choiceGamer = viewerGame.GetChoiceModeGamer(); if (!personController.CheckCorrectChoiceGamer(choiceGamer)) { Console.WriteLine("The Mode Game is not correct"); } else { break; } } while (true); Person gamer = new Person(gamerName, choiceGamer == "o" ? new int[]{1,2,3} : new []{4,5,6,7,8,9}); do { try { int gamerNumber = viewerGame.GetNumberGame(gamer); if (!personController.CheckGenerateNumberGamer(gamerNumber)) { Console.WriteLine("Not correct number"); } else { int compNumer = viewerGame.GetNumberOpponent(); int resultMultiply = gamerNumber*compNumer; viewerGame.OutputResultMultiply(resultMultiply); int firstDigits = CheckFirstDigital(resultMultiply); if (firstDigits == 0) { Console.WriteLine("Continuo game. DRAW"); } else if (gamer.ModeGame.Contains(firstDigits)) { Console.WriteLine("The Gamer " + gamer.PersonName + " is WIN"); } else { Console.WriteLine("The Computer is Win"); } Console.WriteLine("Press any key to continue. Press Esc to exit"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) break; } } catch (InvalidCastException ex) { Console.WriteLine(ex.ToString()); } } while (true); Console.WriteLine("Exit programm"); Console.ReadLine(); } private int CheckFirstDigital(int numbr) { int result = Math.Abs(numbr); while (result >= 10) { result /= 10; } return result; } } }
using System; using System.Linq; namespace FunnyGame { public class GameController : IGameController { public void Run() { ViewGame viewerGame = new ViewGame(); PersonController personController = new PersonController(); string gamerName; string choiceGamer; viewerGame.GetWelcomePage(); do { gamerName = viewerGame.GetGamerName(); if (!personController.CheckCorrectGameName(gamerName)) { Console.WriteLine("The Gamer Name is not correct"); } else { break; } } while (true); do { choiceGamer = viewerGame.GetChoiceModeGamer(); if (!personController.CheckCorrectChoiceGamer(choiceGamer)) { Console.WriteLine("The Mode Game is not correct"); } else { break; } } while (true); Person gamer = new Person(gamerName, choiceGamer == "o" ? new int[]{1,2,3} : new []{4,5,6,7,8,9}); do { try { int gamerNumber = viewerGame.GetNumberGame(gamer); if (!personController.CheckGenerateNumberGamer(gamerNumber)) { Console.WriteLine("Not correct number"); } else { int compNumer = viewerGame.GetNumberOpponent(); int resultMultiply = gamerNumber*compNumer; viewerGame.OutputResultMultiply(resultMultiply); int firstDigits = CheckFirstDigital(resultMultiply); if (firstDigits == 0) { Console.WriteLine("Continuo game. DRAW"); } else if (gamer.ModeGame.Contains(firstDigits)) { Console.WriteLine("The Gamer " + gamer.PersonName + " is WIN"); } else { Console.WriteLine("The Computer is Win"); } Console.WriteLine("For exit input esc. To Continue input various button"); if (Console.ReadKey(true).Key == ConsoleKey.Escape) break; } } catch (InvalidCastException ex) { Console.WriteLine(ex.ToString()); } } while (true); Console.WriteLine("Exit programm"); Console.ReadLine(); } private int CheckFirstDigital(int numbr) { int result = Math.Abs(numbr); while (result >= 10) { result /= 10; } return result; } } }
mit
C#
25dae71f944ae10fae6b853becd37e49fe560471
Define Organization struct
SICU-Stress-Measurement-System/frontend-cs
StressMeasurementSystem/Models/Patient.cs
StressMeasurementSystem/Models/Patient.cs
namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } struct Organization { public string Company { get; set; } public string JobTitle { get; set; } } struct PhoneNumber { internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private int _age; #endregion } }
namespace StressMeasurementSystem.Models { public class Patient { #region Structs struct Name { public string Prefix { get; set; } public string First { get; set; } public string Middle { get; set; } public string Last { get; set; } public string Suffix { get; set; } } struct PhoneNumber { internal enum Type {Mobile, Home, Work, Main, WorkFax, HomeFax, Pager, Other} public string Number { get; set; } public Type T { get; set; } } #endregion #region Fields private Name _name; private int _age; #endregion } }
apache-2.0
C#
4b621602d88ddc90700ed9c0b7a7ae11501f9a12
Update IHttpClientFactory.cs
tiksn/TIKSN-Framework
TIKSN.Core/Web/Rest/IHttpClientFactory.cs
TIKSN.Core/Web/Rest/IHttpClientFactory.cs
using System; using System.Net.Http; using System.Threading.Tasks; namespace TIKSN.Web.Rest { public interface IHttpClientFactory { Task<HttpClient> Create(Guid apiKey); } }
using System; using System.Net.Http; using System.Threading.Tasks; namespace TIKSN.Web.Rest { public interface IHttpClientFactory { Task<HttpClient> Create(Guid apiKey); } }
mit
C#
4f78566f52e6f3b5ab93bba5107be73c7493ca33
clear cache when refreshing stats
ghuntley/stack-exchange-data-explorer,SamSaffron/DataExplorerPG,SamSaffron/DataExplorerPG,ghuntley/stack-exchange-data-explorer,ghuntley/stack-exchange-data-explorer
App/StackExchange.DataExplorer/Controllers/AdminController.cs
App/StackExchange.DataExplorer/Controllers/AdminController.cs
using System.Web.Mvc; using StackExchange.DataExplorer.Helpers; using StackExchange.DataExplorer.Models; namespace StackExchange.DataExplorer.Controllers { public class AdminController : StackOverflowController { [Route("admin")] public ActionResult Index() { if (!Allowed()) { return TextPlainNotFound(); } return View(); } [Route("admin/refresh_stats", HttpVerbs.Post)] public ActionResult RefreshStats() { if (!Allowed()) { return TextPlainNotFound(); } foreach (Site site in Current.DB.Sites) { site.UpdateStats(); } Current.DB.ExecuteCommand("DELETE FROM CachedResults"); return Content("sucess"); } public bool Allowed() { return CurrentUser.IsAdmin; } } }
using System.Web.Mvc; using StackExchange.DataExplorer.Helpers; using StackExchange.DataExplorer.Models; namespace StackExchange.DataExplorer.Controllers { public class AdminController : StackOverflowController { [Route("admin")] public ActionResult Index() { if (!Allowed()) { return TextPlainNotFound(); } return View(); } [Route("admin/refresh_stats", HttpVerbs.Post)] public ActionResult RefreshStats() { if (!Allowed()) { return TextPlainNotFound(); } foreach (Site site in Current.DB.Sites) { site.UpdateStats(); } return Content("sucess"); } public bool Allowed() { return CurrentUser.IsAdmin; } } }
mit
C#
6e39661223431c78d83d2d7cd274fd6ab3855cab
Fix error in sampler state pin connection
id144/dx11-vvvv,id144/dx11-vvvv,id144/dx11-vvvv
Core/VVVV.DX11.Lib/Effects/Pins/Resources/SamplerShaderPin.cs
Core/VVVV.DX11.Lib/Effects/Pins/Resources/SamplerShaderPin.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VVVV.DX11.Internals.Effects.Pins; using VVVV.PluginInterfaces.V2; using SlimDX.Direct3D11; using VVVV.PluginInterfaces.V1; using VVVV.Hosting.Pins; using VVVV.DX11.Lib.Effects.Pins; using FeralTic.DX11; namespace VVVV.DX11.Internals.Effects.Pins { public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription> { private SamplerState state; protected override void ProcessAttribute(InputAttribute attr, EffectVariable var) { attr.IsSingle = true; attr.CheckIfChanged = true; } protected override bool RecreatePin(EffectVariable var) { return false; } public override void SetVariable(DX11ShaderInstance shaderinstance, int slice) { if (this.pin.PluginIO.IsConnected) { using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice])) { shaderinstance.SetByName(this.Name, state); } } else { shaderinstance.Effect.GetVariableByName(this.Name).AsSampler().UndoSetSamplerState(0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using VVVV.DX11.Internals.Effects.Pins; using VVVV.PluginInterfaces.V2; using SlimDX.Direct3D11; using VVVV.PluginInterfaces.V1; using VVVV.Hosting.Pins; using VVVV.DX11.Lib.Effects.Pins; using FeralTic.DX11; namespace VVVV.DX11.Internals.Effects.Pins { public class SamplerShaderPin : AbstractShaderV2Pin<SamplerDescription> { private SamplerState state; protected override void ProcessAttribute(InputAttribute attr, EffectVariable var) { attr.IsSingle = true; attr.CheckIfChanged = true; } protected override bool RecreatePin(EffectVariable var) { return false; } public override void SetVariable(DX11ShaderInstance shaderinstance, int slice) { if (this.pin.PluginIO.IsConnected) { using (var state = SamplerState.FromDescription(shaderinstance.RenderContext.Device, this.pin[slice])) { shaderinstance.SetByName(this.Name, state); } } else { shaderinstance.Effect.GetVariableByName(this.Name).AsConstantBuffer().UndoSetConstantBuffer(); } } } }
bsd-3-clause
C#
b5d1ee405511716db55d61ef944d59722878a6d2
Update MainActivity.cs
jamesmontemagno/MyWeather.Forms
MyWeather.Droid/MainActivity.cs
MyWeather.Droid/MainActivity.cs
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Plugin.Permissions; using Android.Content.PM; namespace MyWeather.Droid { [Activity (Label = "My Weather", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : FormsAppCompatActivity { protected override void OnCreate (Bundle bundle) { ToolbarResource = Resource.Layout.toolbar; TabLayoutResource = Resource.Layout.tabs; base.OnCreate (bundle); Forms.Init(this, bundle); Xamarin.Insights.Initialize(Xamarin.Insights.DebugModeKey, this); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults) { PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; namespace MyWeather.Droid { [Activity (Label = "My Weather", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : FormsAppCompatActivity { protected override void OnCreate (Bundle bundle) { ToolbarResource = Resource.Layout.toolbar; TabLayoutResource = Resource.Layout.tabs; base.OnCreate (bundle); Forms.Init(this, bundle); Xamarin.Insights.Initialize(Xamarin.Insights.DebugModeKey, this); LoadApplication(new App()); } } }
mit
C#
1ee5df22dcf4fb0035e4a6bed22b4e60d98851de
Remove null handling from RsaEncryptor (handled elsewhere)
NFig/NFig
NFig/Encryption/RsaEncryptor.cs
NFig/Encryption/RsaEncryptor.cs
using System; using System.Security.Cryptography; using System.Text; namespace NFig.Encryption { public class RsaEncryptor : ISettingEncryptor { private readonly RSACryptoServiceProvider _rsa; /// <summary> /// Uses a pre-initialized RSACryptoServiceProvider object to provide encryption and decryption. /// </summary> public RsaEncryptor(RSACryptoServiceProvider rsa) { _rsa = rsa; } /// <summary> /// Initializes a RSACryptoServiceProvider with the provided XML key. /// </summary> /// <param name="key">XML-encoded key. If using a public key, calls to Decrypt will fail. You must provide the private key for use in an NFigStore.</param> public RsaEncryptor(string key) { _rsa = new RSACryptoServiceProvider(); _rsa.FromXmlString(key); } public string Encrypt(string value) { var data = Encoding.UTF8.GetBytes(value); var encrypted = _rsa.Encrypt(data, true); return Convert.ToBase64String(encrypted); } public string Decrypt(string encryptedValue) { var encrypted = Convert.FromBase64String(encryptedValue); var decrypted = _rsa.Decrypt(encrypted, true); return Encoding.UTF8.GetString(decrypted); } /// <summary> /// Helper method to generate an RSA public/private key pair. /// </summary> /// <param name="keySize">Size of the key in bits.</param> /// <param name="privateKey">XML-encoded private key which can be used for both encryption and decryption.</param> /// <param name="publicKey">XML-encoded public key which can only be used for encryption.</param> public static void CreateKeyPair(int keySize, out string privateKey, out string publicKey) { using (var rsa = new RSACryptoServiceProvider(keySize)) { privateKey = rsa.ToXmlString(true); publicKey = rsa.ToXmlString(false); } } } }
using System; using System.Security.Cryptography; using System.Text; namespace NFig.Encryption { public class RsaEncryptor : ISettingEncryptor { private readonly RSACryptoServiceProvider _rsa; /// <summary> /// Uses a pre-initialized RSACryptoServiceProvider object to provide encryption and decryption. /// </summary> public RsaEncryptor(RSACryptoServiceProvider rsa) { _rsa = rsa; } /// <summary> /// Initializes a RSACryptoServiceProvider with the provided XML key. /// </summary> /// <param name="key">XML-encoded key. If using a public key, calls to Decrypt will fail. You must provide the private key for use in an NFigStore.</param> public RsaEncryptor(string key) { _rsa = new RSACryptoServiceProvider(); _rsa.FromXmlString(key); } public string Encrypt(string value) { if (value == null) return null; var data = Encoding.UTF8.GetBytes(value); var encrypted = _rsa.Encrypt(data, true); return Convert.ToBase64String(encrypted); } public string Decrypt(string encryptedValue) { if (encryptedValue == null) return null; var encrypted = Convert.FromBase64String(encryptedValue); var decrypted = _rsa.Decrypt(encrypted, true); return Encoding.UTF8.GetString(decrypted); } /// <summary> /// Helper method to generate an RSA public/private key pair. /// </summary> /// <param name="keySize">Size of the key in bits.</param> /// <param name="privateKey">XML-encoded private key which can be used for both encryption and decryption.</param> /// <param name="publicKey">XML-encoded public key which can only be used for encryption.</param> public static void CreateKeyPair(int keySize, out string privateKey, out string publicKey) { using (var rsa = new RSACryptoServiceProvider(keySize)) { privateKey = rsa.ToXmlString(true); publicKey = rsa.ToXmlString(false); } } } }
mit
C#
1f871b176f7b966b119e2f7ee9a3d192596bb5b7
add config
Xarlot/NGitLab
NGitLab/NGitLab.Tests/Config.cs
NGitLab/NGitLab.Tests/Config.cs
namespace NGitLab.Tests { public static class Config { public const string ServiceUrl = "http://gitserver/"; public const string Secret = "kpdcucE1Y4wykmqBGD4x"; public static GitLabClient Connect() { return GitLabClient.Connect(ServiceUrl, Secret); } } }
namespace NGitLab.Tests { public static class Config { public const string ServiceUrl = "https://gitlab.com/api/v3"; public const string Secret = "TOKEN"; public static GitLabClient Connect() { return GitLabClient.Connect(ServiceUrl, Secret); } } }
mit
C#
f93f865b97eb79aadab6fd1338c61b647f72696a
fix interface inheritance bug
AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework,AspectCore/Lite
src/AspectCore.Abstractions/Internal/ProxyGenerator.cs
src/AspectCore.Abstractions/Internal/ProxyGenerator.cs
using System; using System.Reflection; using AspectCore.Abstractions.Internal.Generator; namespace AspectCore.Abstractions.Internal { public sealed class ProxyGenerator : IProxyGenerator { private readonly IAspectValidator aspectValidator; public ProxyGenerator(IAspectValidator aspectValidator) { if (aspectValidator == null) { throw new ArgumentNullException(nameof(aspectValidator)); } this.aspectValidator = aspectValidator; } public Type CreateClassProxyType(Type serviceType, Type implementationType, params Type[] interfaces) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } if (!serviceType.GetTypeInfo().IsClass) { throw new ArgumentException($"Type '{serviceType}' should be class.", nameof(serviceType)); } return new ClassProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator).CreateTypeInfo().AsType(); } public Type CreateInterfaceProxyType(Type serviceType, Type implementationType, params Type[] interfaces) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } return GetInterfaceProxyTypeGenerator(serviceType, implementationType, interfaces).CreateTypeInfo().AsType(); } private ProxyTypeGenerator GetInterfaceProxyTypeGenerator(Type serviceType, Type implementationType, params Type[] interfaces) { //var proxyStructureAttribute = serviceType.GetTypeInfo().GetCustomAttribute<ProxyStructureAttribute>(); //if (proxyStructureAttribute != null && proxyStructureAttribute.ProxyMode == ProxyMode.Inheritance) //{ // return new InheritanceInterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator); //} return new InterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator); } } }
using System; using System.Reflection; using AspectCore.Abstractions.Internal.Generator; namespace AspectCore.Abstractions.Internal { public sealed class ProxyGenerator : IProxyGenerator { private readonly IAspectValidator aspectValidator; public ProxyGenerator(IAspectValidator aspectValidator) { if (aspectValidator == null) { throw new ArgumentNullException(nameof(aspectValidator)); } this.aspectValidator = aspectValidator; } public Type CreateClassProxyType(Type serviceType, Type implementationType, params Type[] interfaces) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } if (!serviceType.GetTypeInfo().IsClass) { throw new ArgumentException($"Type '{serviceType}' should be class.", nameof(serviceType)); } return new ClassProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator).CreateTypeInfo().AsType(); } public Type CreateInterfaceProxyType(Type serviceType, Type implementationType, params Type[] interfaces) { if (serviceType == null) { throw new ArgumentNullException(nameof(serviceType)); } return GetInterfaceProxyTypeGenerator(serviceType, implementationType).CreateTypeInfo().AsType(); } private ProxyTypeGenerator GetInterfaceProxyTypeGenerator(Type serviceType, Type implementationType, params Type[] interfaces) { //var proxyStructureAttribute = serviceType.GetTypeInfo().GetCustomAttribute<ProxyStructureAttribute>(); //if (proxyStructureAttribute != null && proxyStructureAttribute.ProxyMode == ProxyMode.Inheritance) //{ // return new InheritanceInterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator); //} return new InterfaceProxyTypeGenerator(serviceType, implementationType, interfaces, aspectValidator); } } }
mit
C#
978059dd8c6cc448026e60eaf1b9c70235d244d2
Add component status UnderMaintenance
litmus/statuspageio-dotnet
StatusPageIo/StatusPageIo.Api/Models/Components/ComponentStatus.cs
StatusPageIo/StatusPageIo.Api/Models/Components/ComponentStatus.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StatusPageIo.Api.Models.Components { public enum ComponentStatus { Operational, DegradedPerformance, PartialOutage, MajorOutage, UnderMaintenance } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StatusPageIo.Api.Models.Components { public enum ComponentStatus { Operational, DegradedPerformance, PartialOutage, MajorOutage } }
mit
C#
2713095a4adc8a244d091b37de92245a255f7f8a
Fix Monitor.TryEnter/Monitor.Exit Mismatch in System.Threading.Tests (#22815)
jlin177/corefx,tijoytom/corefx,tijoytom/corefx,MaggieTsang/corefx,krk/corefx,nchikanov/corefx,the-dwyer/corefx,ravimeda/corefx,richlander/corefx,the-dwyer/corefx,wtgodbe/corefx,mazong1123/corefx,ravimeda/corefx,jlin177/corefx,Ermiar/corefx,seanshpark/corefx,parjong/corefx,krk/corefx,zhenlan/corefx,the-dwyer/corefx,MaggieTsang/corefx,Ermiar/corefx,ravimeda/corefx,wtgodbe/corefx,ptoonen/corefx,ravimeda/corefx,the-dwyer/corefx,richlander/corefx,jlin177/corefx,krk/corefx,krk/corefx,tijoytom/corefx,rubo/corefx,nchikanov/corefx,wtgodbe/corefx,mazong1123/corefx,wtgodbe/corefx,shimingsg/corefx,fgreinacher/corefx,zhenlan/corefx,shimingsg/corefx,BrennanConroy/corefx,seanshpark/corefx,axelheer/corefx,tijoytom/corefx,zhenlan/corefx,ravimeda/corefx,mazong1123/corefx,mazong1123/corefx,tijoytom/corefx,twsouthwick/corefx,fgreinacher/corefx,shimingsg/corefx,mmitche/corefx,krk/corefx,MaggieTsang/corefx,MaggieTsang/corefx,ericstj/corefx,parjong/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,jlin177/corefx,ravimeda/corefx,MaggieTsang/corefx,mmitche/corefx,parjong/corefx,rubo/corefx,fgreinacher/corefx,wtgodbe/corefx,twsouthwick/corefx,nchikanov/corefx,ptoonen/corefx,richlander/corefx,Ermiar/corefx,seanshpark/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,Jiayili1/corefx,mazong1123/corefx,krk/corefx,richlander/corefx,jlin177/corefx,mmitche/corefx,wtgodbe/corefx,ViktorHofer/corefx,the-dwyer/corefx,axelheer/corefx,nchikanov/corefx,BrennanConroy/corefx,tijoytom/corefx,mazong1123/corefx,Ermiar/corefx,axelheer/corefx,twsouthwick/corefx,mmitche/corefx,zhenlan/corefx,Ermiar/corefx,richlander/corefx,shimingsg/corefx,rubo/corefx,mmitche/corefx,zhenlan/corefx,Jiayili1/corefx,ViktorHofer/corefx,twsouthwick/corefx,JosephTremoulet/corefx,the-dwyer/corefx,ericstj/corefx,JosephTremoulet/corefx,mazong1123/corefx,Ermiar/corefx,richlander/corefx,ViktorHofer/corefx,ericstj/corefx,zhenlan/corefx,shimingsg/corefx,mmitche/corefx,jlin177/corefx,JosephTremoulet/corefx,nchikanov/corefx,zhenlan/corefx,Jiayili1/corefx,twsouthwick/corefx,tijoytom/corefx,richlander/corefx,ericstj/corefx,parjong/corefx,BrennanConroy/corefx,axelheer/corefx,mmitche/corefx,seanshpark/corefx,Jiayili1/corefx,ericstj/corefx,shimingsg/corefx,Ermiar/corefx,ravimeda/corefx,jlin177/corefx,parjong/corefx,krk/corefx,twsouthwick/corefx,parjong/corefx,ptoonen/corefx,nchikanov/corefx,twsouthwick/corefx,ViktorHofer/corefx,Jiayili1/corefx,seanshpark/corefx,Jiayili1/corefx,MaggieTsang/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,shimingsg/corefx,fgreinacher/corefx,axelheer/corefx,the-dwyer/corefx,ViktorHofer/corefx,rubo/corefx,ericstj/corefx,ptoonen/corefx,ptoonen/corefx,nchikanov/corefx,ptoonen/corefx,wtgodbe/corefx,axelheer/corefx,rubo/corefx,seanshpark/corefx,parjong/corefx,seanshpark/corefx,Jiayili1/corefx,JosephTremoulet/corefx,ptoonen/corefx
src/System.Threading/tests/Performance/Perf.Monitor.cs
src/System.Threading/tests/Performance/Perf.Monitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; namespace System.Threading.Tests { public class Perf_Monitor { [Benchmark(InnerIterationCount = 250)] public static void EnterExit() { object sync = new object(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Monitor.Enter(sync); Monitor.Exit(sync); } } } } [Benchmark(InnerIterationCount = 100)] public static void TryEnterExit() { object sync = new object(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Monitor.TryEnter(sync, 0); Monitor.Exit(sync); } } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; namespace System.Threading.Tests { public class Perf_Monitor { [Benchmark(InnerIterationCount = 250)] public static void EnterExit() { object sync = new object(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Monitor.Enter(sync); Monitor.Exit(sync); } } } } [Benchmark(InnerIterationCount = 100)] public static void TryEnterExit() { object sync = new object(); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < Benchmark.InnerIterationCount; i++) { Monitor.TryEnter(sync, 0); Monitor.TryEnter(sync, 0); Monitor.Exit(sync); } } } } } }
mit
C#
d17bd100346011cab4e0d92127247e0c46f0f086
Fix test to work in any timezone
ithielnor/harvest.net
Harvest.Net.Tests/ResourceFacts/TimeTrackingFacts.cs
Harvest.Net.Tests/ResourceFacts/TimeTrackingFacts.cs
using Harvest.Net.Models; using System; using System.Linq; using Xunit; namespace Harvest.Net.Tests { public class TimeTrackingFacts : FactBase, IDisposable { DayEntry _todelete = null; [Fact] public void Daily_ReturnsResult() { var result = Api.Daily(); Assert.NotNull(result); Assert.NotNull(result.DayEntries); Assert.NotNull(result.Projects); // The test harvest account is in EST, but Travis CI runs in different timezones Assert.Equal(TimeZoneInfo.ConvertTime(DateTime.UtcNow, TimeZoneInfo.Utc, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")).Date, result.ForDay); } [Fact] public void Daily_ReturnsCorrectResult() { var result = Api.Daily(286857409); Assert.NotNull(result); Assert.Equal(1m, result.DayEntry.Hours); Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt); } [Fact] public void CreateDaily_CreatesAnEntry() { var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2); _todelete = result.DayEntry; Assert.Equal(2m, result.DayEntry.Hours); Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId); Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId); } public void Dispose() { if (_todelete != null) Api.DeleteDaily(_todelete.Id); } } }
using Harvest.Net.Models; using System; using System.Linq; using Xunit; namespace Harvest.Net.Tests { public class TimeTrackingFacts : FactBase, IDisposable { DayEntry _todelete = null; [Fact] public void Daily_ReturnsResult() { var result = Api.Daily(); Assert.NotNull(result); Assert.NotNull(result.DayEntries); Assert.NotNull(result.Projects); Assert.Equal(DateTime.Now.Date, result.ForDay); } [Fact] public void Daily_ReturnsCorrectResult() { var result = Api.Daily(286857409); Assert.NotNull(result); Assert.Equal(1m, result.DayEntry.Hours); Assert.Equal(new DateTime(2014, 12, 19), result.DayEntry.SpentAt); } [Fact] public void CreateDaily_CreatesAnEntry() { var result = Api.CreateDaily(DateTime.Now.Date, GetTestId(TestId.ProjectId), GetTestId(TestId.TaskId), 2); _todelete = result.DayEntry; Assert.Equal(2m, result.DayEntry.Hours); Assert.Equal(GetTestId(TestId.ProjectId), result.DayEntry.ProjectId); Assert.Equal(GetTestId(TestId.TaskId), result.DayEntry.TaskId); } public void Dispose() { if (_todelete != null) Api.DeleteDaily(_todelete.Id); } } }
mit
C#
57b9f79801e0649a8e7bda74a75ff3b3ce183587
Add encoding header to protobuf content
Hypnobrew/StockMonitor
Infrastructure/Formatters/ProtobufOutputFormatter.cs
Infrastructure/Formatters/ProtobufOutputFormatter.cs
using System; using Microsoft.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Formatters; using ProtoBuf.Meta; namespace Infrastructure { public class ProtobufOutputFormatter : OutputFormatter { private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel); public string ContentType { get; private set; } public static RuntimeTypeModel Model { get { return model.Value; } } public ProtobufOutputFormatter() { ContentType = "application/x-protobuf"; var mediaTypeHeader = MediaTypeHeaderValue.Parse(ContentType); mediaTypeHeader.Encoding = System.Text.Encoding.UTF8; SupportedMediaTypes.Add(mediaTypeHeader); } private static RuntimeTypeModel CreateTypeModel() { var typeModel = TypeModel.Create(); typeModel.UseImplicitZeroDefaults = false; return typeModel; } public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { var response = context.HttpContext.Response; Model.Serialize(response.Body, context.Object); return Task.FromResult(response); } } }
using System; using Microsoft.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Formatters; using ProtoBuf.Meta; namespace Infrastructure { public class ProtobufOutputFormatter : OutputFormatter { private static Lazy<RuntimeTypeModel> model = new Lazy<RuntimeTypeModel>(CreateTypeModel); public string ContentType { get; private set; } public static RuntimeTypeModel Model { get { return model.Value; } } public ProtobufOutputFormatter() { ContentType = "application/x-protobuf"; SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/x-protobuf")); //SupportedEncodings.Add(Encoding.GetEncoding("utf-8")); } private static RuntimeTypeModel CreateTypeModel() { var typeModel = TypeModel.Create(); typeModel.UseImplicitZeroDefaults = false; return typeModel; } public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) { var response = context.HttpContext.Response; Model.Serialize(response.Body, context.Object); return Task.FromResult(response); } } }
mit
C#
95cb0f83bd09c4b4d93212d8684829ccd9745916
fix exception MPLY-6674 Buddy: Vimmy
wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app
windows/ExampleApp/ExampleAppWPF/Views/SearchResultPoi/GeonamesSearchResultsPoiView.cs
windows/ExampleApp/ExampleAppWPF/Views/SearchResultPoi/GeonamesSearchResultsPoiView.cs
using System; using System.Windows; using System.Windows.Controls; namespace ExampleAppWPF { public class GeoNamesSearchResultsPoiView : SearchResultPoiViewBase { private ExampleApp.SearchResultModelCLI m_model; private Image m_categoryIcon; public string Title { get; set; } public string Country { get; set; } static GeoNamesSearchResultsPoiView() { DefaultStyleKeyProperty.OverrideMetadata(typeof(GeoNamesSearchResultsPoiView), new FrameworkPropertyMetadata(typeof(GeoNamesSearchResultsPoiView))); } public GeoNamesSearchResultsPoiView(IntPtr nativeCallerPointer) : base(nativeCallerPointer) { } public override void OnApplyTemplate() { base.OnApplyTemplate(); m_categoryIcon = (Image)GetTemplateChild("CategoryIcon"); m_mainContainer = (FrameworkElement)GetTemplateChild("GeoNamesResultView"); } public override void DisplayPoiInfo(Object modelObject, bool isPinned) { m_model = modelObject as ExampleApp.SearchResultModelCLI; m_categoryIcon.Source = StartupResourceLoader.GetBitmap(SearchResultCategoryMapper.GetIconImageName(m_model.Category)); m_closing = false; Title = m_model.Title; Country = m_model.Subtitle; m_isPinned = isPinned; ShowAll(); } public override void UpdateImageData(string url, bool hasImage, byte[] imgData) { // No image for this view type } } }
using System; using System.Windows; using System.Windows.Controls; namespace ExampleAppWPF { public class GeoNamesSearchResultsPoiView : SearchResultPoiViewBase { private ExampleApp.SearchResultModelCLI m_model; public string Title { get; set; } public string Country { get; set; } static GeoNamesSearchResultsPoiView() { DefaultStyleKeyProperty.OverrideMetadata(typeof(GeoNamesSearchResultsPoiView), new FrameworkPropertyMetadata(typeof(GeoNamesSearchResultsPoiView))); } public GeoNamesSearchResultsPoiView(IntPtr nativeCallerPointer) : base(nativeCallerPointer) { } public override void OnApplyTemplate() { base.OnApplyTemplate(); Image categoryIcon = (Image)GetTemplateChild("CategoryIcon"); categoryIcon.Source = StartupResourceLoader.GetBitmap(SearchResultCategoryMapper.GetIconImageName(m_model.Category)); m_mainContainer = (FrameworkElement)GetTemplateChild("GeoNamesResultView"); } public override void DisplayPoiInfo(Object modelObject, bool isPinned) { m_model = modelObject as ExampleApp.SearchResultModelCLI; m_closing = false; Title = m_model.Title; Country = m_model.Subtitle; m_isPinned = isPinned; ShowAll(); } public override void UpdateImageData(string url, bool hasImage, byte[] imgData) { // No image for this view type } } }
bsd-2-clause
C#
8487fe67fb89de56be657d3700174d0c3d3d92b9
mark [Preserve]
dlech/monomac,PlayScriptRedux/monomac
src/Foundation/MonoMacException.cs
src/Foundation/MonoMacException.cs
// // Copyright 2013, Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace MonoMac.Foundation { public class MonoMacException : Exception { NSException native_exc; public MonoMacException () : base () { native_exc = new NSException ("default", String.Empty, null); } public MonoMacException (NSException exc) : base () { native_exc = exc; } [Preserve] internal static void Throw (IntPtr handle) { throw new MonoMacException (new NSException (handle)); } public NSException NSException { get { return native_exc; } } public string Reason { get { return native_exc.Reason; } } public string Name { get { return native_exc.Name; } } public override string Message { get { return string.Format ("Objective-C exception thrown. Name: {0} Reason: {1}", Name, Reason); } } } }
// // Copyright 2013, Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace MonoMac.Foundation { public class MonoMacException : Exception { NSException native_exc; public MonoMacException () : base () { native_exc = new NSException ("default", String.Empty, null); } public MonoMacException (NSException exc) : base () { native_exc = exc; } internal static void Throw (IntPtr handle) { throw new MonoMacException (new NSException (handle)); } public NSException NSException { get { return native_exc; } } public string Reason { get { return native_exc.Reason; } } public string Name { get { return native_exc.Name; } } public override string Message { get { return string.Format ("Objective-C exception thrown. Name: {0} Reason: {1}", Name, Reason); } } } }
apache-2.0
C#
7de22a14d1e2522ea813ee057ac6533c40851149
use new attr on relationship
Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore,Research-Institute/json-api-dotnet-core
src/JsonApiDotNetCore/Internal/Generics/GenericProcessor.cs
src/JsonApiDotNetCore/Internal/Generics/GenericProcessor.cs
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Models; using Microsoft.EntityFrameworkCore; namespace JsonApiDotNetCore.Internal { public class GenericProcessor<T> : IGenericProcessor where T : class, IIdentifiable { private readonly DbContext _context; public GenericProcessor(DbContext context) { _context = context; } public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute relationship, IEnumerable<string> relationshipIds) { var relationshipType = relationship.Type; if(relationship.IsHasMany) { var entities = _context.GetDbSet<T>().Where(x => relationshipIds.Contains(x.Id.ToString())).ToList(); relationship.SetValue(parent, entities); } else { var entity = _context.GetDbSet<T>().SingleOrDefault(x => relationshipIds.First() == x.Id.ToString()); relationship.SetValue(parent, entity); } await _context.SaveChangesAsync(); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using JsonApiDotNetCore.Extensions; using JsonApiDotNetCore.Models; using Microsoft.EntityFrameworkCore; namespace JsonApiDotNetCore.Internal { public class GenericProcessor<T> : IGenericProcessor where T : class, IIdentifiable { private readonly DbContext _context; public GenericProcessor(DbContext context) { _context = context; } public async Task UpdateRelationshipsAsync(object parent, RelationshipAttribute relationship, IEnumerable<string> relationshipIds) { var relationshipType = relationship.Type; // TODO: replace with relationship.IsMany if(relationship.Type.GetInterfaces().Contains(typeof(IEnumerable))) { var entities = _context.GetDbSet<T>().Where(x => relationshipIds.Contains(x.Id.ToString())).ToList(); relationship.SetValue(parent, entities); } else { var entity = _context.GetDbSet<T>().SingleOrDefault(x => relationshipIds.First() == x.Id.ToString()); relationship.SetValue(parent, entity); } await _context.SaveChangesAsync(); } } }
mit
C#
dc5fb54353e715b5f804cc239eaba6376eda4e0f
Update DiagnosticsDialogPage.cs
YOTOV-LIMITED/poshtools,adamdriscoll/poshtools,daviwil/poshtools,SpotLabsNET/poshtools,Microsoft/poshtools,KevinHorvatin/poshtools,mgreenegit/poshtools,erwindevreugd/poshtools,zbrad/poshtools
PowerShellTools/Diagnostics/DiagnosticsDialogPage.cs
PowerShellTools/Diagnostics/DiagnosticsDialogPage.cs
using System; using System.ComponentModel; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; namespace PowerShellTools.Diagnostics { /// <summary> /// This class contains the DialogPage for all diagnostic related items. /// Currently only has one item, the DiagnosticLoggingSetting /// </summary> internal class DiagnosticsDialogPage : DialogPage { public DiagnosticsDialogPage() { InitializeSettings(); } private event EventHandler<bool> DiagnosticLoggingSettingChanged; [DisplayName(@"Enable Diagnostic Logging")] [Description("Diagnostic logging messages will be written to the output pane.")] public bool EnableDiagnosticLogging { get; set; } private void InitializeSettings() { EnableDiagnosticLogging = false; DiagnosticLoggingSettingChanged += PowerShellToolsPackage.Instance.DiagnosticLoggingSettingChanged; } protected override void OnApply(DialogPage.PageApplyEventArgs e) { base.OnApply(e); if (DiagnosticLoggingSettingChanged != null) { DiagnosticLoggingSettingChanged(this, EnableDiagnosticLogging); } } } }
using System; using System.ComponentModel; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Shell; namespace PowerShellTools.Diagnostics { /// <summary> /// This class contains the DialogPage for all dianostic related items. /// Currently only has one item, the DiagnosticLoggingSetting /// </summary> internal class DiagnosticsDialogPage : DialogPage { public DiagnosticsDialogPage() { InitializeSettings(); } private event EventHandler<bool> DiagnosticLoggingSettingChanged; [DisplayName(@"Enable Diagnostic Logging")] [Description("Diagnostic logging messages will be written to the output pane.")] public bool EnableDiagnosticLogging { get; set; } private void InitializeSettings() { EnableDiagnosticLogging = false; DiagnosticLoggingSettingChanged += PowerShellToolsPackage.Instance.DiagnosticLoggingSettingChanged; } protected override void OnApply(DialogPage.PageApplyEventArgs e) { base.OnApply(e); if (DiagnosticLoggingSettingChanged != null) { DiagnosticLoggingSettingChanged(this, EnableDiagnosticLogging); } } } }
apache-2.0
C#
585e99cd32a798cfc318b1b907c021368b664c10
Use StackFrame constructor overload that doesn't take a file name, when we don't have a valid file name, to avoid ArgumentException in test adapter.
zooba/PTVS,zooba/PTVS,Microsoft/PTVS,zooba/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,zooba/PTVS,int19h/PTVS,huguesv/PTVS,huguesv/PTVS,Microsoft/PTVS,int19h/PTVS,int19h/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,Microsoft/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,huguesv/PTVS
Python/Product/TestAdapter/PythonStackTraceParser.cs
Python/Product/TestAdapter/PythonStackTraceParser.cs
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestWindow.Extensibility; namespace Microsoft.PythonTools.TestAdapter { [Export(typeof(IStackTraceParser))] sealed class PythonStackTraceParser : IStackTraceParser { public Uri ExecutorUri { get { return TestContainerDiscoverer._ExecutorUri; } } public IEnumerable<StackFrame> GetStackFrames(string errorStackTrace) { var regex = new Regex(@"File ""(.+)"", line (\d+), in (\w+)"); foreach (Match match in regex.Matches(errorStackTrace)) { int lineno; if (int.TryParse(match.Groups[2].Value, out lineno)) { // In some cases (django), we may get a file name that isn't really a file // Ex: File "<frozen importlib._bootstrap>", line 978, in _gcd_import var file = match.Groups[1].Value; if (File.Exists(file)) { yield return new StackFrame( match.Groups[3].Value, file, lineno ); } else { yield return new StackFrame(match.Groups[3].Value); } } } } } }
// Visual Studio Shared Project // Copyright(c) Microsoft Corporation // All rights reserved. // // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Text.RegularExpressions; using Microsoft.VisualStudio.TestWindow.Extensibility; namespace Microsoft.PythonTools.TestAdapter { [Export(typeof(IStackTraceParser))] sealed class PythonStackTraceParser : IStackTraceParser { public Uri ExecutorUri { get { return TestContainerDiscoverer._ExecutorUri; } } public IEnumerable<StackFrame> GetStackFrames(string errorStackTrace) { var regex = new Regex(@"File ""(.+)"", line (\d+), in (\w+)"); foreach (Match match in regex.Matches(errorStackTrace)) { int lineno; if (int.TryParse(match.Groups[2].Value, out lineno)) { yield return new StackFrame( match.Groups[3].Value, match.Groups[1].Value, lineno ); } } } } }
apache-2.0
C#
45f935d81d2b4e36e71342e9281f091620beb7a1
Remove check for .meta file
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-yaml/src/Psi/Search/YamlReferenceSearcher.cs
resharper/resharper-yaml/src/Psi/Search/YamlReferenceSearcher.cs
using System.Collections.Generic; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Search; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Search { public class YamlReferenceSearcher : IDomainSpecificSearcher { private readonly IDeclaredElementsSet myElements; private readonly bool myFindCandidates; private readonly List<string> myElementNames; public YamlReferenceSearcher(IDomainSpecificSearcherFactory searchWordsProvider, IDeclaredElementsSet elements, bool findCandidates) { myElements = elements; myFindCandidates = findCandidates; myElementNames = new List<string>(elements.Count); foreach (var element in elements) { foreach (var name in searchWordsProvider.GetAllPossibleWordsInFile(element)) myElementNames.Add(name); } } // Note that some searchers (such as ReferenceSearchProcessorBase) will filter by word index before calling this. // Words come from IDomainSpecificSearcherFactory.GetAllPossibleWordsInFile public bool ProcessProjectItem<TResult>(IPsiSourceFile sourceFile, IFindResultConsumer<TResult> consumer) { if (sourceFile.GetPrimaryPsiFile() is IYamlFile yamlFile) return ProcessElement(yamlFile, consumer); return false; } public bool ProcessElement<TResult>(ITreeNode element, IFindResultConsumer<TResult> consumer) { Assertion.AssertNotNull(element, "element != null"); // wordsInText is used to create string searchers, which are used to see if chameleon subtree should be opened. // If this is null or empty, then all references are processed, without skipping chameleons. References are cached // in both cases. // referenceNames is used to create a reference name container which is used to optimise things. It's passed to // the reference provider's HasReferences to get a false or "maybe" based on name. It's then used (along with // PreFilterReference) to filter references before they're resolved, based on GetName/GetAllNames. // Normally, wordsInText will match referenceNames, as the reference's GetName will return a string that is also // in the text. One example of a reference with a different name is a constructor initialiser, where the name is // .ctor, but would appear in text as this or base var wordsInText = myElementNames; var referenceNames = myElementNames; var result = new ReferenceSearchSourceFileProcessorWorkaround<TResult>(element, myFindCandidates, consumer, myElements, wordsInText, referenceNames).Run(); return result == FindExecution.Stop; } } }
using System.Collections.Generic; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.ExtensionsAPI; using JetBrains.ReSharper.Psi.Files; using JetBrains.ReSharper.Psi.Search; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Yaml.Psi.Search { public class YamlReferenceSearcher : IDomainSpecificSearcher { private readonly IDeclaredElementsSet myElements; private readonly bool myFindCandidates; private readonly List<string> myElementNames; public YamlReferenceSearcher(IDomainSpecificSearcherFactory searchWordsProvider, IDeclaredElementsSet elements, bool findCandidates) { myElements = elements; myFindCandidates = findCandidates; myElementNames = new List<string>(elements.Count); foreach (var element in elements) { foreach (var name in searchWordsProvider.GetAllPossibleWordsInFile(element)) myElementNames.Add(name); } } // Note that some searchers (such as ReferenceSearchProcessorBase) will filter by word index before calling this. // Words come from IDomainSpecificSearcherFactory.GetAllPossibleWordsInFile public bool ProcessProjectItem<TResult>(IPsiSourceFile sourceFile, IFindResultConsumer<TResult> consumer) { // TODO: The YAML assembly shouldn't know anything about .meta files if (sourceFile.GetPrimaryPsiFile() is IYamlFile yamlFile && sourceFile.GetLocation().ExtensionNoDot != "meta") return ProcessElement(yamlFile, consumer); return false; } public bool ProcessElement<TResult>(ITreeNode element, IFindResultConsumer<TResult> consumer) { Assertion.AssertNotNull(element, "element != null"); // wordsInText is used to create string searchers, which are used to see if chameleon subtree should be opened. // If this is null or empty, then all references are processed, without skipping chameleons. References are cached // in both cases. // referenceNames is used to create a reference name container which is used to optimise things. It's passed to // the reference provider's HasReferences to get a false or "maybe" based on name. It's then used (along with // PreFilterReference) to filter references before they're resolved, based on GetName/GetAllNames. // Normally, wordsInText will match referenceNames, as the reference's GetName will return a string that is also // in the text. One example of a reference with a different name is a constructor initialiser, where the name is // .ctor, but would appear in text as this or base var wordsInText = myElementNames; var referenceNames = myElementNames; var result = new ReferenceSearchSourceFileProcessorWorkaround<TResult>(element, myFindCandidates, consumer, myElements, wordsInText, referenceNames).Run(); return result == FindExecution.Stop; } } }
apache-2.0
C#
da92bdc711b009ed4ec3e74e3398a0517764a027
Update Task
zindlsn/RosaroterTiger
RosaroterPanterWPF/RosaroterPanterWPF/DataService.cs
RosaroterPanterWPF/RosaroterPanterWPF/DataService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RosaroterPanterWPF { public class Color { public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public Color() { R = 0; G = 0; B = 0; } public Color(byte r, byte g, byte b) { R = r; G = g; B = b; } public static readonly Color White = new Color(255, 255, 255); } public class Task { public Color Color { get; set; } public string Description { get; set; } public bool Finished { get; private set; } public string Name { get; set; } public double TotalTime { get; private set; } public Task(string name, string description, Color color) { Name = name; Description = description; Color = color; } public Task(string name, string description) : this(name, description, Color.White) { } public Task(string name) : this(name, string.Empty, Color.White) { } public Task() : this(string.Empty, string.Empty, Color.White) { } void Completed(double time) { Finished = true; TotalTime = time; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RosaroterPanterWPF { public class Color { public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public Color() { R = 0; G = 0; B = 0; } public Color(byte r, byte g, byte b) { R = r; G = g; B = b; } } public class Task { public Color Color { get; set; } public string Name { get; set; } public string Description { get; set; } public double TotalTime { get; set; } public bool Finished { get; set; } } }
mit
C#
f73428faa975c5603960ed7a46e782ce0abd32ee
Update ConversationRequest.cs
kooboo-binbin/HelpScoutNet
src/Request/ConversationRequest.cs
src/Request/ConversationRequest.cs
using System; using System.Collections.Specialized; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace HelpScoutNet.Request { public class ConversationRequest : PageRequest { public string Status { get; set; } public DateTime? ModifiedSince { get; set; } public string Tag { get; set; } public override NameValueCollection ToNameValueCollection() { base.ToNameValueCollection(); if (!string.IsNullOrEmpty(Status)) Nv.Add("status", Status); if (ModifiedSince.HasValue) Nv.Add("modifiedSince", ModifiedSince.Value.ToIso8601()); return Nv; } } }
using System; using System.Collections.Specialized; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace HelpScoutNet.Request { public class ConversationRequest : PageRequest { public string Status { get; set; } public DateTime? ModifiedSince { get; set; } public string Tag { get; set; } public override NameValueCollection ToNameValueCollection() { base.ToNameValueCollection(); if (!string.IsNullOrEmpty(Status)) Nv.Add("status", Status); if (!ModifiedSince.HasValue) Nv.Add("modifiedSince", ModifiedSince.Value.ToIso8601()); return Nv; } } }
mit
C#
e4a49636503c94d470393ba2ec43454ba11d73cc
fix constraints
aloneguid/storage
src/Storage.Net/ConnectionString/ConnectionStringFactory.cs
src/Storage.Net/ConnectionString/ConnectionStringFactory.cs
using System; using System.Collections.Generic; using Storage.Net.Blobs; using System.Linq; using Storage.Net.KeyValue; using Storage.Net.Messaging; namespace Storage.Net.ConnectionString { static class ConnectionStringFactory { private const string TypeSeparator = "://"; private static readonly List<IConnectionFactory> Factories = new List<IConnectionFactory>(); static ConnectionStringFactory() { Register(new BuiltInConnectionFactory()); } public static void Register(IConnectionFactory factory) { if (factory == null) throw new ArgumentNullException(nameof(factory)); Factories.Add(factory); } public static IBlobStorage CreateBlobStorage(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateBlobStorage(cs)); } public static IKeyValueStorage CreateKeyValueStorage(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateKeyValueStorage(cs)); } public static IMessagePublisher CreateMessagePublisher(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateMessagePublisher(cs)); } public static IMessageReceiver CreateMessageReceiver(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateMessageReceiver(cs)); } private static TInstance Create<TInstance>(string connectionString, Func<IConnectionFactory, StorageConnectionString, TInstance> createAction) where TInstance: class { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } var pcs = new StorageConnectionString(connectionString); TInstance instance = Factories .Select(f => createAction(f, pcs)) .FirstOrDefault(b => b != null); if (instance == null) { throw new ArgumentException( $"could not create any implementation based on the passed connection string (prefix: {pcs.Prefix}), did you register required external module?", nameof(connectionString)); } return instance; } } }
using System; using System.Collections.Generic; using Storage.Net.Blobs; using System.Linq; using Storage.Net.KeyValue; using Storage.Net.Messaging; namespace Storage.Net.ConnectionString { static class ConnectionStringFactory { private const string TypeSeparator = "://"; private static readonly List<IConnectionFactory> Factories = new List<IConnectionFactory>(); static ConnectionStringFactory() { Register(new BuiltInConnectionFactory()); } public static void Register(IConnectionFactory factory) { if (factory == null) throw new ArgumentNullException(nameof(factory)); Factories.Add(factory); } public static IBlobStorage CreateBlobStorage(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateBlobStorage(cs)); } public static IKeyValueStorage CreateKeyValueStorage(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateKeyValueStorage(cs)); } public static IMessagePublisher CreateMessagePublisher(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateMessagePublisher(cs)); } public static IMessageReceiver CreateMessageReceiver(string connectionString) { return Create(connectionString, (factory, cs) => factory.CreateMessageReceiver(cs)); } private static TInstance Create<TInstance>(string connectionString, Func<IConnectionFactory, StorageConnectionString, TInstance> createAction) { if (connectionString == null) { throw new ArgumentNullException(nameof(connectionString)); } var pcs = new StorageConnectionString(connectionString); TInstance instance = Factories .Select(f => createAction(f, pcs)) .FirstOrDefault(b => b != null); if (instance == null) { throw new ArgumentException( $"could not create any implementation based on the passed connection string (prefix: {pcs.Prefix}), did you register required external module?", nameof(connectionString)); } return instance; } } }
mit
C#
e468b64a24ac471802ea0af0a41ee277a9bd3e01
update copyright
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/MultiPicklistObjectValue.cs
main/Smartsheet/Api/Models/MultiPicklistObjectValue.cs
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2019 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public class MultiPicklistObjectValue : ObjectValue { public MultiPicklistObjectValue(IList<string> values) { this.values = values; } /// <summary> /// the list of selected options /// </summary> private IList<string> values; public ObjectValueType ObjectType { get { return ObjectValueType.MULTI_PICKLIST; } } /// <summary> /// Gets the array of Contact objects /// </summary> public IList<string> Values { get { return values; } set { values = value; } } } }
// #[license] // SmartsheetClient SDK for C# // %% // Copyright (C) 2018 SmartsheetClient // %% // 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. // %[license] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public class MultiPicklistObjectValue : ObjectValue { public MultiPicklistObjectValue(IList<string> values) { this.values = values; } /// <summary> /// the list of selected options /// </summary> private IList<string> values; public ObjectValueType ObjectType { get { return ObjectValueType.MULTI_PICKLIST; } } /// <summary> /// Gets the array of Contact objects /// </summary> public IList<string> Values { get { return values; } set { values = value; } } } }
apache-2.0
C#
6115fc9f2a88da24d815a7f3b8878478be02f523
Fix unit tests failing after a bit too much linq hijinks
paladique/nodejstools,mousetraps/nodejstools,kant2002/nodejstools,AustinHull/nodejstools,avitalb/nodejstools,avitalb/nodejstools,munyirik/nodejstools,paulvanbrenk/nodejstools,Microsoft/nodejstools,mjbvz/nodejstools,paulvanbrenk/nodejstools,mjbvz/nodejstools,mjbvz/nodejstools,lukedgr/nodejstools,avitalb/nodejstools,mousetraps/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,Microsoft/nodejstools,munyirik/nodejstools,mjbvz/nodejstools,paulvanbrenk/nodejstools,lukedgr/nodejstools,mjbvz/nodejstools,Microsoft/nodejstools,paulvanbrenk/nodejstools,avitalb/nodejstools,paulvanbrenk/nodejstools,AustinHull/nodejstools,lukedgr/nodejstools,munyirik/nodejstools,Microsoft/nodejstools,paladique/nodejstools,kant2002/nodejstools,munyirik/nodejstools,paladique/nodejstools,avitalb/nodejstools,kant2002/nodejstools,paladique/nodejstools,kant2002/nodejstools,AustinHull/nodejstools,Microsoft/nodejstools,kant2002/nodejstools,mousetraps/nodejstools,mousetraps/nodejstools,mousetraps/nodejstools,lukedgr/nodejstools,AustinHull/nodejstools,paladique/nodejstools,AustinHull/nodejstools
Nodejs/Product/Npm/SPI/Dependencies.cs
Nodejs/Product/Npm/SPI/Dependencies.cs
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Collections; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Microsoft.NodejsTools.Npm.SPI { internal class Dependencies : IDependencies { private IList<Dependency> _dependencyProperties; public Dependencies(JObject package, params string[] dependencyPropertyNames) { _dependencyProperties = new List<Dependency>(); foreach (var propertyName in dependencyPropertyNames) { var dependencies = package[propertyName] as JObject; if (dependencies != null) { foreach (var property in dependencies.Properties()) { _dependencyProperties.Add(new Dependency(property.Name, property.Value.Value<string>())); } } } } public IEnumerator<IDependency> GetEnumerator() { return _dependencyProperties.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return this.Count(); } } public IDependency this[string name] { get { foreach (var dependeny in _dependencyProperties) { if (dependeny.Name == name) { return dependeny; } } return null; } } public bool Contains(string name) { return this[name] != null; } } }
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 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.Collections; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; namespace Microsoft.NodejsTools.Npm.SPI { internal class Dependencies : IDependencies { private IList<Dependency> _dependencyProperties; public Dependencies(JObject package, params string[] dependencyPropertyNames) { _dependencyProperties = dependencyPropertyNames .Select(propertyName => package[propertyName] as JObject) .Where(x => x != null) .SelectMany(x => x.Properties().Select(property => new Dependency(property.Name, property.Value.Value<string>()))) .ToList(); } public IEnumerator<IDependency> GetEnumerator() { return _dependencyProperties.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count { get { return this.Count(); } } public IDependency this[string name] { get { foreach (var dependeny in _dependencyProperties) { if (dependeny.Name == name) { return dependeny; } } return null; } } public bool Contains(string name) { return this[name] != null; } } }
apache-2.0
C#
bfa2b0a3a337958fce8841423e357ddbbd3301d7
fix AddScoped<IAspectCoreServiceProvider, AspectCoreServiceProvider>()
AspectCore/Lite,AspectCore/Abstractions,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework
src/DependencyInjection/src/AspectCore.Extensions.DependencyInjection/Extensions/AspectCoreOptionsExtensions.cs
src/DependencyInjection/src/AspectCore.Extensions.DependencyInjection/Extensions/AspectCoreOptionsExtensions.cs
using System; using AspectCore.Extensions.Configuration; using AspectCore.Extensions.DependencyInjection.Internals; using Microsoft.Extensions.DependencyInjection; namespace AspectCore.Extensions.DependencyInjection { public static class AspectCoreOptionsExtensions { public static AspectCoreOptions AddScopedServiceAccessor(this AspectCoreOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.InternalServices.AddTransient<IServiceScopeFactory, AspectCoreServiceScopeFactory>(); options.InternalServices.AddScoped<IAspectCoreServiceProvider, AspectCoreServiceProvider>(); options.InternalServices.AddSingleton(typeof(ITransientServiceAccessor<>), typeof(TransientServiceAccessor<>)); options.InternalServices.AddSingleton(typeof(IScopedServiceAccessor<>), typeof(ScopedServiceAccessor<>)); options.InternalServices.AddSingleton<IServiceScopeAccessor, ServiceScopeAccessor>(); return options; } } }
using System; using AspectCore.Extensions.Configuration; using AspectCore.Extensions.DependencyInjection.Internals; using Microsoft.Extensions.DependencyInjection; namespace AspectCore.Extensions.DependencyInjection { public static class AspectCoreOptionsExtensions { public static AspectCoreOptions AddScopedServiceAccessor(this AspectCoreOptions options) { if (options == null) { throw new ArgumentNullException(nameof(options)); } options.InternalServices.AddTransient<IServiceScopeFactory, AspectCoreServiceScopeFactory>(); options.InternalServices.AddScoped<AspectCoreServiceProvider, AspectCoreServiceProvider>(); options.InternalServices.AddSingleton(typeof(ITransientServiceAccessor<>), typeof(TransientServiceAccessor<>)); options.InternalServices.AddSingleton(typeof(IScopedServiceAccessor<>), typeof(ScopedServiceAccessor<>)); options.InternalServices.AddSingleton<IServiceScopeAccessor, ServiceScopeAccessor>(); return options; } } }
mit
C#
f17d6d4b657b926102c67f1816f993c9901030d2
Use localized string instead of hard-coded string for error text
AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,AzureAutomationTeam/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell,ClogenyTechnologies/azure-powershell
src/ResourceManager/Network/Commands.Network/VirtualNetwork/Subnet/GetAzureVirtualNetworkSubnetConfigCommand.cs
src/ResourceManager/Network/Commands.Network/VirtualNetwork/Subnet/GetAzureVirtualNetworkSubnetConfigCommand.cs
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Network.Models; using System; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.Get, "AzureRmVirtualNetworkSubnetConfig"), OutputType(typeof(PSSubnet))] public class GetAzureVirtualNetworkSubnetConfigCommand : NetworkBaseCmdlet { [Parameter( Mandatory = false, HelpMessage = "The name of the subnet")] public string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipeline = true, HelpMessage = "The virtualNetwork")] public PSVirtualNetwork VirtualNetwork { get; set; } public override void Execute() { base.Execute(); if (!string.IsNullOrEmpty(this.Name)) { var subnet = this.VirtualNetwork.Subnets.FirstOrDefault( resource => string.Equals(resource.Name, this.Name, StringComparison.CurrentCultureIgnoreCase)); if (subnet == null) { throw new ArgumentException(string.Format(Properties.Resources.ResourceNotFound, this.Name)); } WriteObject(subnet); } else { var subnets = this.VirtualNetwork.Subnets; WriteObject(subnets, true); } } } }
// ---------------------------------------------------------------------------------- // // Copyright 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. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Network.Models; using System; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.Get, "AzureRmVirtualNetworkSubnetConfig"), OutputType(typeof(PSSubnet))] public class GetAzureVirtualNetworkSubnetConfigCommand : NetworkBaseCmdlet { [Parameter( Mandatory = false, HelpMessage = "The name of the subnet")] public string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipeline = true, HelpMessage = "The virtualNetwork")] public PSVirtualNetwork VirtualNetwork { get; set; } public override void Execute() { base.Execute(); if (!string.IsNullOrEmpty(this.Name)) { var subnet = this.VirtualNetwork.Subnets.FirstOrDefault( resource => string.Equals(resource.Name, this.Name, StringComparison.CurrentCultureIgnoreCase)); if (subnet == null) { throw new ArgumentException("Subnet with the specified name does not exist"); } WriteObject(subnet); } else { var subnets = this.VirtualNetwork.Subnets; WriteObject(subnets, true); } } } }
apache-2.0
C#
5b4f9e2bdac71bd78b7a9aa457902f0e5d63efa3
Use the aspnet core built-in GetDisplayUrl method.
verdentk/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,ilyhacker/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,carldai0106/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate
src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs
src/Abp.AspNetCore/AspNetCore/EntityHistory/HttpRequestEntityChangeSetReasonProvider.cs
using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using Microsoft.AspNetCore.Http; using System.Text; using Microsoft.AspNetCore.Http.Extensions; namespace Abp.AspNetCore.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason => OverridedValue != null ? OverridedValue.Reason : HttpContextAccessor.HttpContext?.Request.GetDisplayUrl(); protected IHttpContextAccessor HttpContextAccessor { get; } private const string SchemeDelimiter = "://"; public HttpRequestEntityChangeSetReasonProvider( IHttpContextAccessor httpContextAccessor, IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { HttpContextAccessor = httpContextAccessor; } } }
using Abp.Dependency; using Abp.EntityHistory; using Abp.Runtime; using JetBrains.Annotations; using Microsoft.AspNetCore.Http; using System.Text; namespace Abp.AspNetCore.EntityHistory { /// <summary> /// Implements <see cref="IEntityChangeSetReasonProvider"/> to get reason from HTTP request. /// </summary> public class HttpRequestEntityChangeSetReasonProvider : EntityChangeSetReasonProviderBase, ISingletonDependency { [CanBeNull] public override string Reason { get { if (OverridedValue != null) { return OverridedValue.Reason; } // TODO: Use back HttpContextAccessor.HttpContext?.Request.GetDisplayUrl() // after moved to net core 3.0 // see https://github.com/aspnet/AspNetCore/issues/2718#issuecomment-482347489 return GetDisplayUrl(HttpContextAccessor.HttpContext?.Request); } } protected IHttpContextAccessor HttpContextAccessor { get; } private const string SchemeDelimiter = "://"; public HttpRequestEntityChangeSetReasonProvider( IHttpContextAccessor httpContextAccessor, IAmbientScopeProvider<ReasonOverride> reasonOverrideScopeProvider ) : base(reasonOverrideScopeProvider) { HttpContextAccessor = httpContextAccessor; } private string GetDisplayUrl(HttpRequest request) { if (request == null) { Logger.Debug("Unable to get URL from HttpRequest, fallback to null"); return null; } var scheme = request.Scheme ?? string.Empty; var host = request.Host.Value ?? string.Empty; var pathBase = request.PathBase.Value ?? string.Empty; var path = request.Path.Value ?? string.Empty; var queryString = request.QueryString.Value ?? string.Empty; // PERF: Calculate string length to allocate correct buffer size for StringBuilder. var length = scheme.Length + SchemeDelimiter.Length + host.Length + pathBase.Length + path.Length + queryString.Length; return new StringBuilder(length) .Append(scheme) .Append(SchemeDelimiter) .Append(host) .Append(pathBase) .Append(path) .Append(queryString) .ToString(); } } }
mit
C#
0c13b3a2a6b1126d09154b0405cf51b733f28bec
Fix unit of work ctor param
Branimir123/PhotoLife,Branimir123/PhotoLife,Branimir123/PhotoLife
PhotoLife/PhotoLife.Data/UnitOfWork.cs
PhotoLife/PhotoLife.Data/UnitOfWork.cs
using System; using PhotoLife.Data.Contracts; namespace PhotoLife.Data { public class UnitOfWork : IUnitOfWork { private readonly IPhotoLifeEntities dbContext; public UnitOfWork(IPhotoLifeEntities context) { if (context == null) { throw new ArgumentNullException("Context cannot be null"); } this.dbContext = context; } public void Dispose() { } public void Commit() { this.dbContext.SaveChanges(); } } }
using System; using System.Data.Entity; using PhotoLife.Data.Contracts; namespace PhotoLife.Data { public class UnitOfWork : IUnitOfWork { private readonly DbContext dbContext; public UnitOfWork(DbContext context) { if (context == null) { throw new ArgumentNullException("Context cannot be null"); } this.dbContext = context; } public void Dispose() { } public void Commit() { this.dbContext.SaveChanges(); } } }
mit
C#
7e6f2f0e22e18ceb00a7c929d7a8a4448a83d0c5
Add close link to admin stale page (#1495)
joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
src/JoinRpg.Portal/Areas/Admin/Views/AdminHome/StaleGames.cshtml
src/JoinRpg.Portal/Areas/Admin/Views/AdminHome/StaleGames.cshtml
@model System.Collections.Generic.IReadOnlyCollection<JoinRpg.Data.Interfaces.ProjectWithUpdateDateDto> @{ ViewBag.Title = "Список проблемных проектов"; } <h2>Список проблемных проектов</h2> <table> <tr><th>Проект</th><th>Последний раз обновлен</th><th>Другие проблемы</th></tr> @foreach (var project in Model) { <tr> <td>@Html.ActionLink(project.ProjectName, "Details", "Game", new {project.ProjectId, area =""}, null)</td> <td>@project.LastUpdated</td> <td>@if (project.LegacyMode) { <span class="label label-danger">Legacy режим</span>} </td> <td><a asp-controller="Game" asp-action="Close" asp-area="" asp-route-projectId="@project.ProjectId">закрыть</a></td> </tr> } </table>
@model System.Collections.Generic.IReadOnlyCollection<JoinRpg.Data.Interfaces.ProjectWithUpdateDateDto> @{ ViewBag.Title = "Список проблемных проектов"; } <h2>Список проблемных проектов</h2> <table> <tr><th>Проект</th><th>Последний раз обновлен</th><th>Другие проблемы</th></tr> @foreach (var project in Model) { <tr> <td>@Html.ActionLink(project.ProjectName, "Details", "Game", new {project.ProjectId, area =""}, null)</td> <td>@project.LastUpdated</td> <td>@if (project.LegacyMode) { <span class="label label-danger">Legacy режим</span>} </td> </tr> } </table>
mit
C#
621b278807db7e52bb1054dfffbd142a1529ee75
Scale up and down in demo
jefking/King.Service
Worker/Scalable/ScalableTask.cs
Worker/Scalable/ScalableTask.cs
namespace Worker.Scalable { using King.Service; using System; using System.Diagnostics; using System.Threading.Tasks; public class ScalableTask : IDynamicRuns { public int MaximumPeriodInSeconds { get { return 30; } } public int MinimumPeriodInSeconds { get { return 20; } } public Task<bool> Run() { var random = new Random(); var workWasDone = (random.Next() % 2) == 0; Trace.TraceInformation("Work was done: {0}", workWasDone); return Task.FromResult(workWasDone); } } }
namespace Worker.Scalable { using King.Service; using System.Diagnostics; using System.Threading.Tasks; public class ScalableTask : IDynamicRuns { public int MaximumPeriodInSeconds { get { return 30; } } public int MinimumPeriodInSeconds { get { return 20; } } public Task<bool> Run() { Trace.TraceInformation("Scalable Task Running."); return Task.FromResult(true); } } }
mit
C#
a756358200cb0d7ebe9f396ae5f4db567186bd40
Add filter property to trending shows request.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Shows/Common/TraktShowsTrendingRequest.cs
Source/Lib/TraktApiSharp/Requests/WithoutOAuth/Shows/Common/TraktShowsTrendingRequest.cs
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base; using Base.Get; using Objects.Basic; using Objects.Get.Shows.Common; internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow> { internal TraktShowsTrendingRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "shows/trending{?extended,page,limit,query,years,genres,languages,countries,runtimes,ratings,certifications,networks,status}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; internal TraktShowFilter Filter { get; set; } protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
namespace TraktApiSharp.Requests.WithoutOAuth.Shows.Common { using Base.Get; using Objects.Basic; using Objects.Get.Shows.Common; internal class TraktShowsTrendingRequest : TraktGetRequest<TraktPaginationListResult<TraktTrendingShow>, TraktTrendingShow> { internal TraktShowsTrendingRequest(TraktClient client) : base(client) { } protected override string UriTemplate => "shows/trending{?extended,page,limit}"; protected override TraktAuthorizationRequirement AuthorizationRequirement => TraktAuthorizationRequirement.NotRequired; protected override bool SupportsPagination => true; protected override bool IsListResult => true; } }
mit
C#
977c46804d75312f3e21e9050c92a8e51fffd50e
Access dos not support such join syntax.
MaceWindu/linq2db,linq2db/linq2db,LinqToDB4iSeries/linq2db,linq2db/linq2db,MaceWindu/linq2db,LinqToDB4iSeries/linq2db
Tests/Linq/UserTests/Issue1556Tests.cs
Tests/Linq/UserTests/Issue1556Tests.cs
using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { [TestFixture] public class Issue1556Tests : TestBase { [Test] public void Issue1556Test( [DataSources(ProviderName.Sybase, ProviderName.OracleNative, ProviderName.Access)] string context) { using (var db = GetDataContext(context)) { AreEqual( from p in db.Parent from c in db.Child where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID) select new { p, c } , db.Parent .InnerJoin(db.Child, (p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID), (p,c) => new { p, c })); } } } }
using System; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.UserTests { [TestFixture] public class Issue1556Tests : TestBase { [Test] public void Issue1556Test([DataSources(ProviderName.Sybase, ProviderName.OracleNative)] string context) { using (var db = GetDataContext(context)) { AreEqual( from p in db.Parent from c in db.Child where p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID) select new { p, c } , db.Parent .InnerJoin(db.Child, (p,c) => p.ParentID == c.ParentID || c.GrandChildren.Any(y => y.ParentID == p.ParentID), (p,c) => new { p, c })); } } } }
mit
C#
66fb81b722942828530a035617c881d1e3fc386d
Change to struct.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Models/ShieldState.cs
WalletWasabi.Gui/Models/ShieldState.cs
namespace WalletWasabi.Gui.Models { public struct ShieldState { public bool IsPrivacyCriticalVisible { get; } public bool IsPrivacySomeVisible { get; } public bool IsPrivacyFineVisible { get; } public bool IsPrivacyStrongVisible { get; } public bool IsPrivacySaiyanVisible { get; } public ShieldState(bool isPrivacyCriticalVisible, bool isPrivacySomeVisible, bool isPrivacyFineVisible, bool isPrivacyStrongVisible, bool isPrivacySaiyanVisible = false) { IsPrivacyCriticalVisible = isPrivacyCriticalVisible; IsPrivacySomeVisible = isPrivacySomeVisible; IsPrivacyFineVisible = isPrivacyFineVisible; IsPrivacyStrongVisible = isPrivacyStrongVisible; IsPrivacySaiyanVisible = isPrivacySaiyanVisible; } public override bool Equals(object obj) { if (obj is ShieldState state) { if (state.GetHashCode() == GetHashCode()) { return true; } } return false; } public override int GetHashCode() { var items = new[] { IsPrivacyCriticalVisible, IsPrivacySomeVisible, IsPrivacyFineVisible, IsPrivacyStrongVisible, IsPrivacySaiyanVisible, }; uint result = 0; for (int i = 0; i < items.Length; i++) { result |= (uint)(items[i] ? 1 : 0) << i; } return result.GetHashCode(); } public static bool operator ==(ShieldState left, ShieldState right) { return left.Equals(right); } public static bool operator !=(ShieldState left, ShieldState right) { return !(left == right); } } }
namespace WalletWasabi.Gui.Models { public class ShieldState { public bool IsPrivacyCriticalVisible { get; } public bool IsPrivacySomeVisible { get; } public bool IsPrivacyFineVisible { get; } public bool IsPrivacyStrongVisible { get; } public bool IsPrivacySaiyanVisible { get; } public ShieldState(bool isPrivacyCriticalVisible, bool isPrivacySomeVisible, bool isPrivacyFineVisible, bool isPrivacyStrongVisible, bool isPrivacySaiyanVisible = false) { IsPrivacyCriticalVisible = isPrivacyCriticalVisible; IsPrivacySomeVisible = isPrivacySomeVisible; IsPrivacyFineVisible = isPrivacyFineVisible; IsPrivacyStrongVisible = isPrivacyStrongVisible; IsPrivacySaiyanVisible = isPrivacySaiyanVisible; } } }
mit
C#
c07879fb3dcc27d77ee6e7624df3f9d7b5c32d39
Change default sorting
sboulema/Hops,sboulema/Hops,sboulema/Hops
src/Hops/Repositories/HopRepository.cs
src/Hops/Repositories/HopRepository.cs
using Hops.Models; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Linq; namespace Hops.Repositories { public class HopRepository : IHopRepository { private readonly HopContext context; private readonly IUrlHelper urlHelper; public HopRepository(HopContext context, IHttpContextAccessor contextAccessor) { this.context = context; urlHelper = contextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>(); } public ListModel GetPage(int page) { var hops = context.Hops; var results = new ListModel(); results.List = hops.OrderBy(h => h.Name).Skip((page - 1) * 15).Take(15).ToList(); results.NumberOfPages = (hops.Count() / 15) + 1; results.CurrentPageIndex = page; return results; } public Hop Get(long id) { var hop = context.Hops.First(t => t.Id == id); return hop; } public List<Hop> GetSubstitutions(long id) { var substitutions = context.Substitutions.Where(s => s.HopId == id).ToList(); var hops = new List<Hop>(); foreach (var substitute in substitutions) { hops.Add(Get(substitute.SubId)); } return hops; } public List<string> GetAliases(long id) { var aliases = context.Alias.Where(a => a.HopId == id).Select(a => a.Name).ToList(); return aliases; } } }
using Hops.Models; using Microsoft.AspNet.Http; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.DependencyInjection; using System.Collections.Generic; using System.Linq; namespace Hops.Repositories { public class HopRepository : IHopRepository { private readonly HopContext context; private readonly IUrlHelper urlHelper; public HopRepository(HopContext context, IHttpContextAccessor contextAccessor) { this.context = context; urlHelper = contextAccessor.HttpContext.RequestServices.GetRequiredService<IUrlHelper>(); } public ListModel GetPage(int page) { var hops = context.Hops; var results = new ListModel(); results.List = hops.OrderBy(h => h.Id).Skip((page - 1) * 15).Take(15).ToList(); results.NumberOfPages = (hops.Count() / 15) + 1; results.CurrentPageIndex = page; return results; } public Hop Get(long id) { var hop = context.Hops.First(t => t.Id == id); return hop; } public List<Hop> GetSubstitutions(long id) { var substitutions = context.Substitutions.Where(s => s.HopId == id).ToList(); var hops = new List<Hop>(); foreach (var substitute in substitutions) { hops.Add(Get(substitute.SubId)); } return hops; } public List<string> GetAliases(long id) { var aliases = context.Alias.Where(a => a.HopId == id).Select(a => a.Name).ToList(); return aliases; } } }
mit
C#
eb66f807b1e9a4dde726123352753c289b3293fe
Update Message.cs
hprose/hprose-dotnet
src/Hprose.RPC/Plugins/Push/Message.cs
src/Hprose.RPC/Plugins/Push/Message.cs
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | Message.cs | | | | Message class for C#. | | | | LastModified: Feb 2, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using Hprose.IO; namespace Hprose.RPC.Plugins.Push { public struct Message { public object Data; public string From; } }
/*--------------------------------------------------------*\ | | | hprose | | | | Official WebSite: https://hprose.com | | | | Message.cs | | | | Message class for C#. | | | | LastModified: Feb 2, 2019 | | Author: Ma Bingyao <andot@hprose.com> | | | \*________________________________________________________*/ using Hprose.IO; namespace Hprose.RPC.Plugins.Push { public struct Message { public string From; public object Data; } }
mit
C#
37364f46da00e2f84e0179cd0ce44ca686c09d1e
Fix integration tests for tracing
alexanderkozlenko/oads,alexanderkozlenko/oads
src/Anemonis.MicrosoftOffice.AddinHost.IntegrationTests/RequestTracingMiddlewareTests.cs
src/Anemonis.MicrosoftOffice.AddinHost.IntegrationTests/RequestTracingMiddlewareTests.cs
using System.Net.Http; using System.Threading.Tasks; using Anemonis.MicrosoftOffice.AddinHost.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests { [TestClass] public sealed class RequestTracingMiddlewareTests { [TestMethod] public async Task Trace() { var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict); loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>())); var builder = new WebHostBuilder() .ConfigureServices(sc => sc .AddSingleton(loggerMock.Object) .AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>()) .Configure(ab => ab .UseMiddleware<RequestTracingMiddleware>()); using (var server = new TestServer(builder)) { using (var client = server.CreateClient()) { var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress); var response = await client.SendAsync(request); } } loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<string>()), Times.Exactly(1)); } } }
using System.Net.Http; using System.Threading.Tasks; using Anemonis.MicrosoftOffice.AddinHost.Middleware; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Anemonis.MicrosoftOffice.AddinHost.IntegrationTests { [TestClass] public sealed class RequestTracingMiddlewareTests { [TestMethod] public async Task Trace() { var loggerMock = new Mock<Serilog.ILogger>(MockBehavior.Strict); loggerMock.Setup(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>())); var builder = new WebHostBuilder() .ConfigureServices(sc => sc .AddSingleton(loggerMock.Object) .AddSingleton<RequestTracingMiddleware, RequestTracingMiddleware>()) .Configure(ab => ab .UseMiddleware<RequestTracingMiddleware>()); using (var server = new TestServer(builder)) { using (var client = server.CreateClient()) { var request = new HttpRequestMessage(HttpMethod.Get, server.BaseAddress); var response = await client.SendAsync(request); } } loggerMock.Verify(o => o.Write(It.IsAny<Serilog.Events.LogEventLevel>(), It.IsAny<string>(), It.IsAny<object[]>()), Times.Exactly(1)); } } }
mit
C#
167b66615ea76e6097af8f4fe042b67218b3c9d9
Fix another typo.
natgla/roslyn,budcribar/roslyn,a-ctor/roslyn,krishnarajbb/roslyn,jbhensley/roslyn,KevinRansom/roslyn,ilyes14/roslyn,sharadagrawal/TestProject2,balajikris/roslyn,jamesqo/roslyn,antonssonj/roslyn,TyOverby/roslyn,lisong521/roslyn,Hosch250/roslyn,khyperia/roslyn,a-ctor/roslyn,eriawan/roslyn,jeffanders/roslyn,basoundr/roslyn,AmadeusW/roslyn,paulvanbrenk/roslyn,swaroop-sridhar/roslyn,ilyes14/roslyn,antonssonj/roslyn,khellang/roslyn,BugraC/roslyn,mattwar/roslyn,VShangxiao/roslyn,Inverness/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,srivatsn/roslyn,budcribar/roslyn,bbarry/roslyn,bbarry/roslyn,kelltrick/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,jhendrixMSFT/roslyn,rgani/roslyn,doconnell565/roslyn,jroggeman/roslyn,stephentoub/roslyn,CyrusNajmabadi/roslyn,KiloBravoLima/roslyn,natidea/roslyn,natidea/roslyn,DanielRosenwasser/roslyn,aanshibudhiraja/Roslyn,a-ctor/roslyn,xasx/roslyn,marksantos/roslyn,OmniSharp/roslyn,KevinH-MS/roslyn,paladique/roslyn,dotnet/roslyn,chenxizhang/roslyn,FICTURE7/roslyn,danielcweber/roslyn,MatthieuMEZIL/roslyn,srivatsn/roslyn,hanu412/roslyn,taylorjonl/roslyn,AArnott/roslyn,leppie/roslyn,magicbing/roslyn,physhi/roslyn,bkoelman/roslyn,grianggrai/roslyn,mattwar/roslyn,physhi/roslyn,Giten2004/roslyn,AlekseyTs/roslyn,yjfxfjch/roslyn,ljw1004/roslyn,grianggrai/roslyn,shyamnamboodiripad/roslyn,RipCurrent/roslyn,jonatassaraiva/roslyn,dpen2000/roslyn,Giftednewt/roslyn,jramsay/roslyn,KashishArora/Roslyn,ManishJayaswal/roslyn,aanshibudhiraja/Roslyn,ErikSchierboom/roslyn,drognanar/roslyn,Pvlerick/roslyn,bartdesmet/roslyn,REALTOBIZ/roslyn,v-codeel/roslyn,pjmagee/roslyn,xoofx/roslyn,sharwell/roslyn,hanu412/roslyn,swaroop-sridhar/roslyn,VSadov/roslyn,cybernet14/roslyn,mono/roslyn,GuilhermeSa/roslyn,VitalyTVA/roslyn,AlexisArce/roslyn,wschae/roslyn,AnthonyDGreen/roslyn,aanshibudhiraja/Roslyn,rgani/roslyn,vslsnap/roslyn,oberxon/roslyn,oocx/roslyn,ljw1004/roslyn,SeriaWei/roslyn,aelij/roslyn,ericfe-ms/roslyn,jrharmon/roslyn,taylorjonl/roslyn,EricArndt/roslyn,AnthonyDGreen/roslyn,budcribar/roslyn,evilc0des/roslyn,doconnell565/roslyn,davkean/roslyn,1234-/roslyn,mattscheffer/roslyn,KevinH-MS/roslyn,mmitche/roslyn,agocke/roslyn,krishnarajbb/roslyn,KevinRansom/roslyn,kienct89/roslyn,huoxudong125/roslyn,YOTOV-LIMITED/roslyn,stjeong/roslyn,khellang/roslyn,Shiney/roslyn,mavasani/roslyn,Pvlerick/roslyn,JakeGinnivan/roslyn,weltkante/roslyn,v-codeel/roslyn,nguerrera/roslyn,mattscheffer/roslyn,marksantos/roslyn,AlexisArce/roslyn,MichalStrehovsky/roslyn,OmarTawfik/roslyn,magicbing/roslyn,cybernet14/roslyn,cston/roslyn,sharwell/roslyn,evilc0des/roslyn,jramsay/roslyn,JakeGinnivan/roslyn,poizan42/roslyn,genlu/roslyn,EricArndt/roslyn,DanielRosenwasser/roslyn,VPashkov/roslyn,FICTURE7/roslyn,RipCurrent/roslyn,agocke/roslyn,aelij/roslyn,Giftednewt/roslyn,ValentinRueda/roslyn,jrharmon/roslyn,tannergooding/roslyn,paulvanbrenk/roslyn,zooba/roslyn,diryboy/roslyn,CaptainHayashi/roslyn,zmaruo/roslyn,zmaruo/roslyn,tang7526/roslyn,mono/roslyn,supriyantomaftuh/roslyn,YOTOV-LIMITED/roslyn,AnthonyDGreen/roslyn,Inverness/roslyn,poizan42/roslyn,cybernet14/roslyn,jgglg/roslyn,VPashkov/roslyn,leppie/roslyn,zooba/roslyn,KiloBravoLima/roslyn,bartdesmet/roslyn,AlexisArce/roslyn,Shiney/roslyn,orthoxerox/roslyn,heejaechang/roslyn,huoxudong125/roslyn,DanielRosenwasser/roslyn,jmarolf/roslyn,nemec/roslyn,ericfe-ms/roslyn,ahmedshuhel/roslyn,droyad/roslyn,TyOverby/roslyn,garryforreg/roslyn,mseamari/Stuff,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,bkoelman/roslyn,moozzyk/roslyn,hanu412/roslyn,jcouv/roslyn,oberxon/roslyn,dpoeschl/roslyn,BugraC/roslyn,doconnell565/roslyn,danielcweber/roslyn,paladique/roslyn,tsdl2013/roslyn,MatthieuMEZIL/roslyn,physhi/roslyn,heejaechang/roslyn,nagyistoce/roslyn,khellang/roslyn,CaptainHayashi/roslyn,eriawan/roslyn,khyperia/roslyn,jamesqo/roslyn,mseamari/Stuff,ManishJayaswal/roslyn,jhendrixMSFT/roslyn,genlu/roslyn,eriawan/roslyn,oberxon/roslyn,OmarTawfik/roslyn,khyperia/roslyn,oocx/roslyn,DinoV/roslyn,AArnott/roslyn,jonatassaraiva/roslyn,jasonmalinowski/roslyn,GuilhermeSa/roslyn,stephentoub/roslyn,dotnet/roslyn,reaction1989/roslyn,nguerrera/roslyn,wschae/roslyn,gafter/roslyn,Inverness/roslyn,taylorjonl/roslyn,OmniSharp/roslyn,xoofx/roslyn,dotnet/roslyn,mirhagk/roslyn,aelij/roslyn,DustinCampbell/roslyn,agocke/roslyn,davkean/roslyn,garryforreg/roslyn,akoeplinger/roslyn,devharis/roslyn,orthoxerox/roslyn,furesoft/roslyn,robinsedlaczek/roslyn,jramsay/roslyn,KirillOsenkov/roslyn,REALTOBIZ/roslyn,tmat/roslyn,MattWindsor91/roslyn,AlekseyTs/roslyn,yjfxfjch/roslyn,MihaMarkic/roslyn-prank,stjeong/roslyn,MattWindsor91/roslyn,poizan42/roslyn,jgglg/roslyn,huoxudong125/roslyn,amcasey/roslyn,3F/roslyn,michalhosala/roslyn,danielcweber/roslyn,vslsnap/roslyn,sharadagrawal/Roslyn,jaredpar/roslyn,tmat/roslyn,MavenRain/roslyn,vslsnap/roslyn,EricArndt/roslyn,rchande/roslyn,kuhlenh/roslyn,antiufo/roslyn,moozzyk/roslyn,oocx/roslyn,supriyantomaftuh/roslyn,stebet/roslyn,sharwell/roslyn,michalhosala/roslyn,brettfo/roslyn,KashishArora/Roslyn,ahmedshuhel/roslyn,ericfe-ms/roslyn,v-codeel/roslyn,jcouv/roslyn,gafter/roslyn,tang7526/roslyn,tannergooding/roslyn,chenxizhang/roslyn,jbhensley/roslyn,managed-commons/roslyn,stephentoub/roslyn,mmitche/roslyn,dpoeschl/roslyn,sharadagrawal/TestProject2,weltkante/roslyn,kienct89/roslyn,balajikris/roslyn,enginekit/roslyn,nguerrera/roslyn,stjeong/roslyn,russpowers/roslyn,bkoelman/roslyn,michalhosala/roslyn,jrharmon/roslyn,moozzyk/roslyn,nemec/roslyn,mmitche/roslyn,chenxizhang/roslyn,jhendrixMSFT/roslyn,ValentinRueda/roslyn,VSadov/roslyn,kuhlenh/roslyn,wvdd007/roslyn,pdelvo/roslyn,TyOverby/roslyn,jaredpar/roslyn,diryboy/roslyn,mono/roslyn,russpowers/roslyn,VitalyTVA/roslyn,cston/roslyn,antiufo/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,mirhagk/roslyn,OmniSharp/roslyn,Maxwe11/roslyn,1234-/roslyn,swaroop-sridhar/roslyn,brettfo/roslyn,Maxwe11/roslyn,KirillOsenkov/roslyn,dpen2000/roslyn,jroggeman/roslyn,DustinCampbell/roslyn,jeremymeng/roslyn,VPashkov/roslyn,MatthieuMEZIL/roslyn,cston/roslyn,abock/roslyn,tmeschter/roslyn,HellBrick/roslyn,MihaMarkic/roslyn-prank,HellBrick/roslyn,shyamnamboodiripad/roslyn,lorcanmooney/roslyn,dsplaisted/roslyn,mgoertz-msft/roslyn,mattwar/roslyn,Hosch250/roslyn,MavenRain/roslyn,FICTURE7/roslyn,VitalyTVA/roslyn,VSadov/roslyn,nagyistoce/roslyn,brettfo/roslyn,russpowers/roslyn,reaction1989/roslyn,dovzhikova/roslyn,sharadagrawal/Roslyn,jgglg/roslyn,managed-commons/roslyn,basoundr/roslyn,antonssonj/roslyn,dpoeschl/roslyn,3F/roslyn,BugraC/roslyn,jeremymeng/roslyn,MattWindsor91/roslyn,KashishArora/Roslyn,robinsedlaczek/roslyn,OmarTawfik/roslyn,dsplaisted/roslyn,jkotas/roslyn,ValentinRueda/roslyn,yeaicc/roslyn,ErikSchierboom/roslyn,MattWindsor91/roslyn,jcouv/roslyn,grianggrai/roslyn,jaredpar/roslyn,akrisiun/roslyn,dsplaisted/roslyn,rchande/roslyn,pjmagee/roslyn,tvand7093/roslyn,jkotas/roslyn,basoundr/roslyn,jroggeman/roslyn,sharadagrawal/TestProject2,yeaicc/roslyn,MichalStrehovsky/roslyn,pdelvo/roslyn,Giten2004/roslyn,reaction1989/roslyn,balajikris/roslyn,paladique/roslyn,tmeschter/roslyn,nagyistoce/roslyn,tmeschter/roslyn,vcsjones/roslyn,kienct89/roslyn,natgla/roslyn,marksantos/roslyn,Giten2004/roslyn,yeaicc/roslyn,davkean/roslyn,garryforreg/roslyn,Shiney/roslyn,jbhensley/roslyn,evilc0des/roslyn,REALTOBIZ/roslyn,amcasey/roslyn,KevinRansom/roslyn,SeriaWei/roslyn,rchande/roslyn,sharadagrawal/Roslyn,orthoxerox/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,diryboy/roslyn,VShangxiao/roslyn,Pvlerick/roslyn,genlu/roslyn,jeffanders/roslyn,nemec/roslyn,wvdd007/roslyn,jmarolf/roslyn,MichalStrehovsky/roslyn,DinoV/roslyn,abock/roslyn,zmaruo/roslyn,droyad/roslyn,akoeplinger/roslyn,heejaechang/roslyn,tmat/roslyn,xasx/roslyn,MihaMarkic/roslyn-prank,lorcanmooney/roslyn,HellBrick/roslyn,panopticoncentral/roslyn,bbarry/roslyn,lorcanmooney/roslyn,krishnarajbb/roslyn,mgoertz-msft/roslyn,pjmagee/roslyn,stebet/roslyn,Maxwe11/roslyn,mavasani/roslyn,mseamari/Stuff,devharis/roslyn,ManishJayaswal/roslyn,CyrusNajmabadi/roslyn,tsdl2013/roslyn,jkotas/roslyn,abock/roslyn,drognanar/roslyn,kuhlenh/roslyn,ManishJayaswal/roslyn,thomaslevesque/roslyn,DustinCampbell/roslyn,KamalRathnayake/roslyn,wschae/roslyn,bartdesmet/roslyn,mattscheffer/roslyn,akrisiun/roslyn,MavenRain/roslyn,rgani/roslyn,panopticoncentral/roslyn,managed-commons/roslyn,jeffanders/roslyn,dovzhikova/roslyn,wvdd007/roslyn,enginekit/roslyn,KamalRathnayake/roslyn,GuilhermeSa/roslyn,stebet/roslyn,lisong521/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,enginekit/roslyn,Giftednewt/roslyn,ljw1004/roslyn,mirhagk/roslyn,VShangxiao/roslyn,1234-/roslyn,devharis/roslyn,lisong521/roslyn,jasonmalinowski/roslyn,thomaslevesque/roslyn,KamalRathnayake/roslyn,vcsjones/roslyn,jmarolf/roslyn,dpen2000/roslyn,AArnott/roslyn,furesoft/roslyn,magicbing/roslyn,antiufo/roslyn,akrisiun/roslyn,vcsjones/roslyn,DinoV/roslyn,natgla/roslyn,ErikSchierboom/roslyn,pdelvo/roslyn,yjfxfjch/roslyn,AlekseyTs/roslyn,kelltrick/roslyn,xoofx/roslyn,kelltrick/roslyn,gafter/roslyn,KevinH-MS/roslyn,zooba/roslyn,tvand7093/roslyn,drognanar/roslyn,thomaslevesque/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,supriyantomaftuh/roslyn,KiloBravoLima/roslyn,akoeplinger/roslyn,YOTOV-LIMITED/roslyn,droyad/roslyn,ahmedshuhel/roslyn,AmadeusW/roslyn,tang7526/roslyn,tsdl2013/roslyn,CaptainHayashi/roslyn,srivatsn/roslyn,jeremymeng/roslyn,furesoft/roslyn,xasx/roslyn,Hosch250/roslyn,leppie/roslyn,SeriaWei/roslyn,paulvanbrenk/roslyn,dovzhikova/roslyn,jamesqo/roslyn,3F/roslyn,ilyes14/roslyn,RipCurrent/roslyn,jonatassaraiva/roslyn,amcasey/roslyn,mavasani/roslyn,natidea/roslyn,tvand7093/roslyn,shyamnamboodiripad/roslyn,JakeGinnivan/roslyn
src/EditorFeatures/Core/Shared/Tagging/TagProducers/AbstractSingleDocumentTagProducer.cs
src/EditorFeatures/Core/Shared/Tagging/TagProducers/AbstractSingleDocumentTagProducer.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// A specialization of <see cref="ITagProducer{TTag}" /> that only produces tags for single <see cref="Document" /> at a time. /// </summary> internal abstract class AbstractSingleDocumentTagProducer<TTag> : ITagProducer<TTag> where TTag : ITag { public virtual void Dispose() { } public virtual IEqualityComparer<TTag> TagComparer { get { return EqualityComparer<TTag>.Default; } } public Task<IEnumerable<ITagSpan<TTag>>> ProduceTagsAsync(IEnumerable<DocumentSnapshotSpan> snapshotSpans, SnapshotPoint? caretPosition, CancellationToken cancellationToken) { // This abstract class should only be used in places where the tagger will only ever be analyzing at most one // document and span. The .Single()s are appropriate here, and if you find yourself "fixing" a bug by replacing // them with .First() you don't understand this class in the first place. var snapshotSpan = snapshotSpans.Single().SnapshotSpan; var document = snapshotSpans.Single().Document; if (document == null) { return SpecializedTasks.EmptyEnumerable<ITagSpan<TTag>>(); } return ProduceTagsAsync(document, snapshotSpan, GetCaretPosition(caretPosition, snapshotSpan), cancellationToken); } public abstract Task<IEnumerable<ITagSpan<TTag>>> ProduceTagsAsync(Document document, SnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken); private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging { /// <summary> /// A specialization of <see cref="ITagProducer{TTag}" /> that only produces tags for single <see cref="Document" /> at a time. /// </summary> internal abstract class AbstractSingleDocumentTagProducer<TTag> : ITagProducer<TTag> where TTag : ITag { public virtual void Dispose() { } public virtual IEqualityComparer<TTag> TagComparer { get { return EqualityComparer<TTag>.Default; } } public Task<IEnumerable<ITagSpan<TTag>>> ProduceTagsAsync(IEnumerable<DocumentSnapshotSpan> snapshotSpans, SnapshotPoint? caretPosition, CancellationToken cancellationToken) { // This abstract class should only be used in places where the tagger will only ever be analyzing at most one // document and span. The .Single()s are appropriate here, and if you find yourself "fixing" a bug by replacing // them with .First() you don't understand this class in the first place. var snapshotSpan = snapshotSpans.Single().SnapshotSpan; var document = snapshotSpans.Single().Document; if (document == null) { SpecializedTasks.EmptyEnumerable<ITagSpan<TTag>>(); } return ProduceTagsAsync(document, snapshotSpan, GetCaretPosition(caretPosition, snapshotSpan), cancellationToken); } public abstract Task<IEnumerable<ITagSpan<TTag>>> ProduceTagsAsync(Document document, SnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken); private static int? GetCaretPosition(SnapshotPoint? caretPosition, SnapshotSpan snapshotSpan) { return caretPosition.HasValue && caretPosition.Value.Snapshot == snapshotSpan.Snapshot ? caretPosition.Value.Position : (int?)null; } } }
mit
C#
47dbe02482374ba169a206c6559e93e634a1eda9
Remove INameable interface implementation from IConceptualAnnotation.
LeonAkasaka/Levolution.TypeSchema
Levolution.TypeSchema.Pcl/ConceptualType/IConceptualAnnotation.cs
Levolution.TypeSchema.Pcl/ConceptualType/IConceptualAnnotation.cs
using Levolution.Data.Name; namespace Levolution.TypeSchema.ConceptualType { /// <summary> /// /// </summary> public interface IConceptualAnnotation { } }
using Levolution.Data.Name; namespace Levolution.TypeSchema.ConceptualType { /// <summary> /// /// </summary> public interface IConceptualAnnotation : INameable { } }
apache-2.0
C#
1f4bdffe016dcc5f9f164acb4d46a23d182bd789
Revert "Guard against empty translation keys"
n2cms/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,n2cms/n2cms,n2cms/n2cms,DejanMilicic/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,n2cms/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,SntsDev/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,DejanMilicic/n2cms,nimore/n2cms,VoidPointerAB/n2cms,DejanMilicic/n2cms,nimore/n2cms,EzyWebwerkstaden/n2cms
src/Framework/N2/Engine/Globalization/TranslationExtensions.cs
src/Framework/N2/Engine/Globalization/TranslationExtensions.cs
using N2.Collections; using N2.Details; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace N2.Engine.Globalization { public static class TranslationExtensions { public const string DefaultCollectionKey = "Translations"; public static string GetTranslation(this IContentList<DetailCollection> collections, string key, string collectionKey = DefaultCollectionKey) { return collections[collectionKey].Details.Where(cd => cd.Meta == key).Select(cd => cd.StringValue).FirstOrDefault(); } public static void SetTranslation(this IContentList<DetailCollection> collections, string key, string value, string collectionKey = DefaultCollectionKey) { var collection = collections[collectionKey]; var detail = collection.Details.Where(cd => cd.Meta == key).FirstOrDefault(); if (detail == null) { if (value == null) return; detail = new ContentDetail(collection.EnclosingItem, collection.Name, value) { Meta = key }; detail.AddTo(collection); } else if (value == null) { collection.Details.Remove(detail); } else { detail.StringValue = value; } } public static IDictionary<string, string> GetTranslations(this IContentList<DetailCollection> collections, string collectionKey = DefaultCollectionKey) { return collections[collectionKey].Details.ToDictionary(cd => cd.Meta, cd => cd.StringValue); } } }
using N2.Collections; using N2.Details; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace N2.Engine.Globalization { public static class TranslationExtensions { public const string DefaultCollectionKey = "Translations"; public static string GetTranslation(this IContentList<DetailCollection> collections, string key, string collectionKey = DefaultCollectionKey) { return collections[collectionKey].Details.Where(cd => cd.Meta == key).Select(cd => cd.StringValue).FirstOrDefault(); } public static void SetTranslation(this IContentList<DetailCollection> collections, string key, string value, string collectionKey = DefaultCollectionKey) { if (string.IsNullOrEmpty(key)) return; var collection = collections[collectionKey]; var detail = collection.Details.Where(cd => cd.Meta == key).FirstOrDefault(); if (detail == null) { if (value == null) return; detail = new ContentDetail(collection.EnclosingItem, collection.Name, value) { Meta = key }; detail.AddTo(collection); } else if (value == null) { collection.Details.Remove(detail); } else { detail.StringValue = value; } } public static IDictionary<string, string> GetTranslations(this IContentList<DetailCollection> collections, string collectionKey = DefaultCollectionKey) { return collections[collectionKey].Details .Where(cd => !string.IsNullOrEmpty(cd.Meta)) .ToDictionary(cd => cd.Meta, cd => cd.StringValue); } } }
lgpl-2.1
C#
0a521325a1a955e5a500d75293224789c40ec25d
Update OpeningEncryptedExcelFiles.cs
maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Files/Handling/OpeningEncryptedExcelFiles.cs
Examples/CSharp/Files/Handling/OpeningEncryptedExcelFiles.cs
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Files.Handling { public class OpeningEncryptedExcelFiles { public static void Main(string[] args) { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate LoadOptions LoadOptions loadOptions6 = new LoadOptions(); //Specify the password loadOptions6.Password = "1234"; //Create a Workbook object and opening the file from its path Workbook wbEncrypted = new Workbook(dataDir + "encryptedBook.xls", loadOptions6); Console.WriteLine("Encrypted excel file opened successfully!"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; namespace Aspose.Cells.Examples.Files.Handling { public class OpeningEncryptedExcelFiles { public static void Main(string[] args) { //Exstart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Instantiate LoadOptions LoadOptions loadOptions6 = new LoadOptions(); //Specify the password loadOptions6.Password = "1234"; //Create a Workbook object and opening the file from its path Workbook wbEncrypted = new Workbook(dataDir + "encryptedBook.xls", loadOptions6); Console.WriteLine("Encrypted excel file opened successfully!"); //ExEnd:1 } } }
mit
C#
50158b74fe4c5e87d49fc8cd009173e96259569a
Add XML comments to UIComponentDefinitionAttribute
YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/Attributes/UIComponentDefinitionAttribute.cs
src/Atata/Attributes/UIComponentDefinitionAttribute.cs
using System.Linq; namespace Atata { /// <summary> /// Represents the base attribute class for UI component (page object, control) definition. /// </summary> public abstract class UIComponentDefinitionAttribute : ScopeDefinitionAttribute { protected UIComponentDefinitionAttribute(string scopeXPath = DefaultScopeXPath) : base(scopeXPath) { } /// <summary> /// Gets or sets the name of the component type. /// It is used in report log messages to describe the component type. /// </summary> public string ComponentTypeName { get; set; } /// <summary> /// Gets or sets the property name endings to ignore/truncate. /// Accepts a string containing a set of values separated by comma, for example <c>"Button,Link"</c>. /// </summary> public string IgnoreNameEndings { get; set; } /// <summary> /// Gets the values of property name endings to ignore. /// </summary> /// <returns>An array of name endings to ignore.</returns> public string[] GetIgnoreNameEndingValues() { return IgnoreNameEndings != null ? IgnoreNameEndings.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray() : new string[0]; } /// <summary> /// Normalizes the name considering value of <see cref="IgnoreNameEndings"/>. /// </summary> /// <param name="name">The name.</param> /// <returns>Normalized name.</returns> public string NormalizeNameIgnoringEnding(string name) { string endingToIgnore = GetIgnoreNameEndingValues(). FirstOrDefault(x => name.EndsWith(x) && name.Length > x.Length); return endingToIgnore != null ? name.Substring(0, name.Length - endingToIgnore.Length).TrimEnd() : name; } } }
using System.Linq; namespace Atata { public abstract class UIComponentDefinitionAttribute : ScopeDefinitionAttribute { protected UIComponentDefinitionAttribute(string scopeXPath = DefaultScopeXPath) : base(scopeXPath) { } public string ComponentTypeName { get; set; } public string IgnoreNameEndings { get; set; } public string[] GetIgnoreNameEndingValues() { return IgnoreNameEndings != null ? IgnoreNameEndings.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)).ToArray() : new string[0]; } public string NormalizeNameIgnoringEnding(string name) { string endingToIgnore = GetIgnoreNameEndingValues(). FirstOrDefault(x => name.EndsWith(x) && name.Length > x.Length); return endingToIgnore != null ? name.Substring(0, name.Length - endingToIgnore.Length).TrimEnd() : name; } } }
apache-2.0
C#
80a02df51cc347437a60af3d973ea09f90bfb95b
upgrade enode.equeue version.
tangxuehua/enode,Aaron-Liu/enode
src/Extensions/ENode.EQueue/Properties/AssemblyInfo.cs
src/Extensions/ENode.EQueue/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("ENode.EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode.EQueue")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e534ee24-4ea0-410e-847a-227e53faed7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.9")] [assembly: AssemblyFileVersion("1.3.9")]
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("ENode.EQueue")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ENode.EQueue")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e534ee24-4ea0-410e-847a-227e53faed7c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.3.8")] [assembly: AssemblyFileVersion("1.3.8")]
mit
C#
0cc77ddda55f3204a86e471515fcd2a3978c4c6a
Access always to list of branches
MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure,MCLD/greatreadingadventure
src/GRA.Controllers/ParticipatingBranchesController.cs
src/GRA.Controllers/ParticipatingBranchesController.cs
using GRA.Domain.Service; using GRA.Controllers.ViewModel.ParticipatingBranches; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace GRA.Controllers { public class ParticipatingBranchesController : Base.UserController { private readonly SiteService _siteService; public static string Name { get { return "ParticipatingBranches"; } } public ParticipatingBranchesController(ServiceFacade.Controller context, SiteService siteService) : base(context) { _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService)); } public async Task<IActionResult> Index() { var site = await GetCurrentSiteAsync(); var viewModel = new ParticipatingBranchesViewModel { Systems = await _siteService.GetSystemList() }; return View(nameof(Index), viewModel); } } }
using GRA.Domain.Service; using GRA.Controllers.ViewModel.ParticipatingBranches; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; namespace GRA.Controllers { public class ParticipatingBranchesController : Base.UserController { private readonly SiteService _siteService; public static string Name { get { return "ParticipatingBranches"; } } public ParticipatingBranchesController(ServiceFacade.Controller context, SiteService siteService) : base(context) { _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService)); } public async Task<IActionResult> Index() { var site = await GetCurrentSiteAsync(); if(await _siteLookupService.GetSiteSettingBoolAsync(site.Id, SiteSettingKey.Users.ShowLinkToParticipatingBranches)) { var viewModel = new ParticipatingBranchesViewModel { Systems = await _siteService.GetSystemList() }; return View(nameof(Index), viewModel); } else { return StatusCode(404); } } } }
mit
C#
94e8ebf81b6381cc99e83c92042cfc598ab9104b
Delete unnecessary method in ILuceneSearcher.
ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton,ZooPin/CK-Glouton
src/CK.Glouton.Model/Lucene/ILuceneSearcher.cs
src/CK.Glouton.Model/Lucene/ILuceneSearcher.cs
using System.Collections.Generic; using Lucene.Net.Search; using Lucene.Net.Documents; using CK.Glouton.Model.Logs; namespace CK.Glouton.Model.Lucene { public interface ILuceneSearcher { List<string> GetAllMonitorID(); Document GetDocument(Query query, int maxResult); Document GetDocument(ScoreDoc scoreDoc); TopDocs QuerySearch(Query query, int maxResult); } }
using System.Collections.Generic; using Lucene.Net.Search; using Lucene.Net.Documents; using CK.Glouton.Model.Logs; namespace CK.Glouton.Model.Lucene { public interface ILuceneSearcher { Query CreateQuery(ILuceneSearcherConfiguration configuration); List<string> GetAllMonitorID(); Document GetDocument(Query query, int maxResult); Document GetDocument(ScoreDoc scoreDoc); TopDocs QuerySearch(Query query, int maxResult); } }
mit
C#
7b47f445df19cbb846aa902ea20b08bc09b4f44f
Increase version number
ProgramFOX/Chess.NET
ChessDotNet/Properties/AssemblyInfo.cs
ChessDotNet/Properties/AssemblyInfo.cs
using System; 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("Chess.NET")] [assembly: AssemblyDescription("A .NET chess library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ProgramFOX")] [assembly: AssemblyProduct("ChessDotNet")] [assembly: AssemblyCopyright("Copyright © ProgramFOX 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f089f32e-0218-4f80-a65d-484f6eb806bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.6.0")] [assembly: AssemblyFileVersion("0.9.6.0")] [assembly: CLSCompliant(true)]
using System; 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("Chess.NET")] [assembly: AssemblyDescription("A .NET chess library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("ProgramFOX")] [assembly: AssemblyProduct("ChessDotNet")] [assembly: AssemblyCopyright("Copyright © ProgramFOX 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f089f32e-0218-4f80-a65d-484f6eb806bd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.5.5")] [assembly: AssemblyFileVersion("0.9.5.5")] [assembly: CLSCompliant(true)]
mit
C#
a0b6e6207eebb7ec5d938f539d9e1a2ac8bf9eff
Update ShouldMatchConfiguration.cs
JoeMighty/shouldly
src/Shouldly/Configuration/ShouldMatchConfiguration.cs
src/Shouldly/Configuration/ShouldMatchConfiguration.cs
#if ShouldMatchApproved using System; namespace Shouldly.Configuration { public delegate string FilenameGenerator( TestMethodInfo testMethodInfo, string descriminator, string fileType, string fileExtension); public class ShouldMatchConfiguration { public ShouldMatchConfiguration() { } public ShouldMatchConfiguration(ShouldMatchConfiguration initialConfig) { StringCompareOptions = initialConfig.StringCompareOptions; FilenameDescriminator = initialConfig.FilenameDescriminator; PreventDiff = initialConfig.PreventDiff; FileExtension = initialConfig.FileExtension; TestMethodFinder = initialConfig.TestMethodFinder; ApprovalFileSubFolder = initialConfig.ApprovalFileSubFolder; Scrubber = initialConfig.Scrubber; FilenameGenerator = initialConfig.FilenameGenerator; } public StringCompareShould StringCompareOptions { get; set; } public string FilenameDescriminator { get; set; } public bool PreventDiff { get; set; } /// <summary> /// File extension without the. /// </summary> public string FileExtension { get; set; } public ITestMethodFinder TestMethodFinder { get; set; } public string ApprovalFileSubFolder { get; set; } /// <summary> /// Scrubbers allow you to alter the received document before comparing it to approved. /// /// This is useful for replacing dates or dynamic data with fixed data /// </summary> public Func<string, string> Scrubber { get; set; } public FilenameGenerator FilenameGenerator { get; set; } } } #endif
#if ShouldMatchApproved using System; namespace Shouldly.Configuration { public delegate string FilenameGenerator( TestMethodInfo testMethodInfo, string descriminator, string fileType, string fileExtension); public class ShouldMatchConfiguration { public ShouldMatchConfiguration() { } public ShouldMatchConfiguration(ShouldMatchConfiguration initialConfig) { StringCompareOptions = initialConfig.StringCompareOptions; FilenameDescriminator = initialConfig.FilenameDescriminator; PreventDiff = initialConfig.PreventDiff; FileExtension = initialConfig.FileExtension; TestMethodFinder = initialConfig.TestMethodFinder; ApprovalFileSubFolder = initialConfig.ApprovalFileSubFolder; Scrubber = initialConfig.Scrubber; FilenameGenerator = initialConfig.FilenameGenerator; } public StringCompareShould StringCompareOptions { get; set; } public string FilenameDescriminator { get; set; } public bool PreventDiff { get; set; } /// <summary> /// File extension without the . /// </summary> public string FileExtension { get; set; } public ITestMethodFinder TestMethodFinder { get; set; } public string ApprovalFileSubFolder { get; set; } /// <summary> /// Scrubbers allow you to alter the received document before comparing it to approved. /// /// This is useful for replacing dates or dynamic data with fixed data /// </summary> public Func<string, string> Scrubber { get; set; } public FilenameGenerator FilenameGenerator { get; set; } } } #endif
bsd-3-clause
C#
cab8c0ce87cfb4ab28e3856d81157fe7bb253dbd
Remove random tag data from RaygunWebApiExceptionLogger
ddunkin/raygun4net,ddunkin/raygun4net,nelsonsar/raygun4net,articulate/raygun4net,tdiehl/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,tdiehl/raygun4net,nelsonsar/raygun4net,articulate/raygun4net
Mindscape.Raygun4Net45/WebApi/RaygunWebApiExceptionLogger.cs
Mindscape.Raygun4Net45/WebApi/RaygunWebApiExceptionLogger.cs
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web.Http.ExceptionHandling; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionLogger : ExceptionLogger { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionLogger(IRaygunWebApiClientProvider generateRaygunClient) { _clientCreator = generateRaygunClient; } public override void Log(ExceptionLoggerContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception); } public override Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient() .CurrentHttpRequest(context.Request) .Send(context.Exception), cancellationToken); } } }
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Web.Http.ExceptionHandling; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionLogger : ExceptionLogger { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionLogger(IRaygunWebApiClientProvider generateRaygunClient) { _clientCreator = generateRaygunClient; } public override void Log(ExceptionLoggerContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception, new List<string> { "Exception Logger" }); } public override Task LogAsync(ExceptionLoggerContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception, new List<string> { "Exception Logger" }), cancellationToken); } } }
mit
C#
ad82862ecee3a3e43170c0eacc003a5370ee9048
Improve assertion.
yfakariya/msgpack-rpc-cli,yonglehou/msgpack-rpc-cli
src/MsgPack.Rpc.Client/Rpc/Client/ErrorInterpreter.cs
src/MsgPack.Rpc.Client/Rpc/Client/ErrorInterpreter.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.Diagnostics.Contracts; using System.Linq; using MsgPack.Rpc.Client.Protocols; namespace MsgPack.Rpc.Client { /// <summary> /// Interprets error stream. /// </summary> internal static class ErrorInterpreter { // TODO: Configurable private const int _unknownErrorQuota = 1024; /// <summary> /// Unpacks <see cref="RpcErrorMessage"/> from stream in the specified context. /// </summary> /// <param name="context"><see cref="ClientResponseContext"/> which stores serialized error.</param> /// <returns>An unpacked <see cref="RpcErrorMessage"/>.</returns> internal static RpcErrorMessage UnpackError( ClientResponseContext context ) { Contract.Assert( context != null ); Contract.Assert( context.ErrorBuffer != null ); Contract.Assert( context.ErrorBuffer.Length > 0 ); Contract.Assert( context.ResultBuffer != null ); Contract.Assert( context.ResultBuffer.Length > 0 ); MessagePackObject error; try { error = Unpacking.UnpackObject( context.ErrorBuffer ); } catch ( UnpackException ) { error = new MessagePackObject( context.ErrorBuffer.GetBuffer( 0, _unknownErrorQuota ).SelectMany( segment => segment.AsEnumerable() ).ToArray() ); } if ( error.IsNil ) { return RpcErrorMessage.Success; } RpcError errorIdentifier; if ( error.IsTypeOf<string>().GetValueOrDefault() ) { errorIdentifier = RpcError.FromIdentifier( error.AsString(), null ); } else if ( error.IsTypeOf<int>().GetValueOrDefault() ) { errorIdentifier = RpcError.FromIdentifier( null, error.AsInt32() ); } else { errorIdentifier = RpcError.Unexpected; } MessagePackObject detail; if ( context.ResultBuffer.Length == 0 ) { detail = MessagePackObject.Nil; } else { try { detail = Unpacking.UnpackObject( context.ResultBuffer ); } catch ( UnpackException ) { detail = new MessagePackObject( context.ResultBuffer.GetBuffer( 0, _unknownErrorQuota ).SelectMany( segment => segment.AsEnumerable() ).ToArray() ); } } return new RpcErrorMessage( errorIdentifier, detail ); } } }
#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.Diagnostics.Contracts; using System.Linq; using MsgPack.Rpc.Client.Protocols; namespace MsgPack.Rpc.Client { /// <summary> /// Interprets error stream. /// </summary> internal static class ErrorInterpreter { // TODO: Configurable private const int _unknownErrorQuota = 1024; /// <summary> /// Unpacks <see cref="RpcErrorMessage"/> from stream in the specified context. /// </summary> /// <param name="context"><see cref="ClientResponseContext"/> which stores serialized error.</param> /// <returns>An unpacked <see cref="RpcErrorMessage"/>.</returns> internal static RpcErrorMessage UnpackError( ClientResponseContext context ) { Contract.Assert( context.ErrorBuffer.Length > 0 ); MessagePackObject error; try { error = Unpacking.UnpackObject( context.ErrorBuffer ); } catch ( UnpackException ) { error = new MessagePackObject( context.ErrorBuffer.GetBuffer( 0, _unknownErrorQuota ).SelectMany( segment => segment.AsEnumerable() ).ToArray() ); } if ( error.IsNil ) { return RpcErrorMessage.Success; } RpcError errorIdentifier; if ( error.IsTypeOf<string>().GetValueOrDefault() ) { errorIdentifier = RpcError.FromIdentifier( error.AsString(), null ); } else if ( error.IsTypeOf<int>().GetValueOrDefault() ) { errorIdentifier = RpcError.FromIdentifier( null, error.AsInt32() ); } else { errorIdentifier = RpcError.Unexpected; } MessagePackObject detail; if ( context.ResultBuffer.Length == 0 ) { detail = MessagePackObject.Nil; } else { try { detail = Unpacking.UnpackObject( context.ResultBuffer ); } catch ( UnpackException ) { detail = new MessagePackObject( context.ResultBuffer.GetBuffer( 0, _unknownErrorQuota ).SelectMany( segment => segment.AsEnumerable() ).ToArray() ); } } return new RpcErrorMessage( errorIdentifier, detail ); } } }
apache-2.0
C#
e61b19f263fb15d43f15b132c471c5e64e474d66
Fix path in ConfigureNLog
NLog/NLog.Framework.Logging,NLog/NLog.Extensions.Logging,NLog/NLog.Framework.Logging
src/NLog.Framework.logging/AspNetExtensions.cs
src/NLog.Framework.logging/AspNetExtensions.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.PlatformAbstractions; using NLog.Config; namespace NLog.Framework.Logging { /// <summary> /// Helpers for ASP.NET /// </summary> public static class AspNetExtensions { /// <summary> /// Enable NLog as logging provider in ASP.NET 5. /// </summary> /// <param name="factory"></param> /// <returns></returns> public static ILoggerFactory AddNLog(this ILoggerFactory factory) { //ignore this LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly); var provider = new NLogLoggerProvider(); factory.AddProvider(provider); return factory; } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(Directory.GetParent(env.WebRootPath).FullName, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IApplicationEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(env.ApplicationBasePath, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="fileName">absolute path NLog configuration file.</param> private static void ConfigureNLog(string fileName) { LogManager.Configuration = new XmlLoggingConfiguration(fileName, true); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Extensions.Logging; using Microsoft.AspNet.Hosting; using Microsoft.Extensions.PlatformAbstractions; using NLog.Config; namespace NLog.Framework.Logging { /// <summary> /// Helpers for ASP.NET /// </summary> public static class AspNetExtensions { /// <summary> /// Enable NLog /// </summary> /// <param name="factory"></param> /// <returns></returns> public static ILoggerFactory AddNLog(this ILoggerFactory factory) { //ignore this LogManager.AddHiddenAssembly(typeof(AspNetExtensions).GetTypeInfo().Assembly); var provider = new NLogLoggerProvider(); factory.AddProvider(provider); return factory; } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IHostingEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(Directory.GetParent(env.WebRootPath).ToString(), configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="env"></param> /// <param name="configFileRelativePath">relative path to NLog configuration file.</param> public static void ConfigureNLog(this IApplicationEnvironment env, string configFileRelativePath) { var fileName = Path.Combine(env.ApplicationBasePath, configFileRelativePath); ConfigureNLog(fileName); } /// <summary> /// Apply NLog configuration from XML config. /// </summary> /// <param name="fileName">absolute path NLog configuration file.</param> private static void ConfigureNLog(string fileName) { LogManager.Configuration = new XmlLoggingConfiguration(fileName, true); } } }
bsd-2-clause
C#
5ff8c6310d42441b61eccbe8b8043f052578fc4c
Refactor exception dialog (release)
ethanmoffat/EndlessClient
EndlessClient/EndlessClient/Program.cs
EndlessClient/EndlessClient/Program.cs
using System; using System.Windows.Forms; namespace EndlessClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { #if !DEBUG try { using (EOGame.Instance) { #endif EOGame.Instance.Run(); #if !DEBUG } } catch (Exception ex) { Application.EnableVisualStyles(); Form exForm = new Form { Width = 350, Height = 200, MaximizeBox = false, MinimizeBox = false, Padding = new Padding(10), Text = "Application Error", BackColor = System.Drawing.Color.White, Icon = System.Drawing.SystemIcons.Error, StartPosition = FormStartPosition.CenterScreen, MinimumSize = new System.Drawing.Size(350, 200) }; exForm.FormClosed += (sender, e) => Environment.Exit(1); Label exLabel1 = new Label {AutoEllipsis = true, Dock = DockStyle.Top}; exLabel1.Font = new System.Drawing.Font(exLabel1.Font, System.Drawing.FontStyle.Bold); exLabel1.Text = "An unhandled exception has caused the game to crash:"; Label exLabel2 = new Label { AutoEllipsis = true, Dock = DockStyle.Top, Padding = new Padding(5, 0, 0, 0), Text = ex.Message }; Label exLabel3 = new Label {AutoEllipsis = true, Dock = DockStyle.Top}; exLabel3.Font = new System.Drawing.Font(exLabel3.Font, System.Drawing.FontStyle.Bold); exLabel3.Text = "Stack trace:"; TextBox exTextBox1 = new TextBox { Dock = DockStyle.Fill, Multiline = true, ReadOnly = true, ScrollBars = ScrollBars.Vertical, Text = ex.StackTrace }; exForm.Controls.Add(exTextBox1); exForm.Controls.Add(exLabel3); exForm.Controls.Add(exLabel2); exForm.Controls.Add(exLabel1); exForm.ShowDialog(); } #endif Logger.Close(); } } }
using System; using System.Windows.Forms; namespace EndlessClient { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { #if !DEBUG try { using (EOGame.Instance) { #endif EOGame.Instance.Run(); #if !DEBUG } } catch (Exception ex) { Application.EnableVisualStyles(); Form exForm = new Form(); exForm.Width = 350; exForm.Height = 200; exForm.MaximizeBox = false; exForm.MinimizeBox = false; exForm.Padding = new Padding(10); exForm.Text = "Application Error"; exForm.BackColor = System.Drawing.Color.White; exForm.Icon = System.Drawing.SystemIcons.Error; exForm.StartPosition = FormStartPosition.CenterScreen; exForm.MinimumSize = new System.Drawing.Size(350, 200); exForm.FormClosed += (object sender, FormClosedEventArgs e) => { // Report the Exception? Environment.Exit(1); }; Label exLabel1 = new Label(); exLabel1.AutoEllipsis = true; exLabel1.Dock = DockStyle.Top; exLabel1.Font = new System.Drawing.Font(exLabel1.Font, System.Drawing.FontStyle.Bold); exLabel1.Text = "An unhandled exception has caused the game to crash:"; Label exLabel2 = new Label(); exLabel2.AutoEllipsis = true; exLabel2.Dock = DockStyle.Top; exLabel2.Padding = new Padding(5, 0, 0, 0); exLabel2.Text = ex.Message; Label exLabel3 = new Label(); exLabel3.AutoEllipsis = true; exLabel3.Dock = DockStyle.Top; exLabel3.Font = new System.Drawing.Font(exLabel3.Font, System.Drawing.FontStyle.Bold); exLabel3.Text = "Stack trace:"; TextBox exTextBox1 = new TextBox(); exTextBox1.Dock = DockStyle.Fill; exTextBox1.Multiline = true; exTextBox1.ReadOnly = true; exTextBox1.ScrollBars = ScrollBars.Vertical; exTextBox1.Text = ex.ToString(); exForm.Controls.Add(exTextBox1); exForm.Controls.Add(exLabel3); exForm.Controls.Add(exLabel2); exForm.Controls.Add(exLabel1); exForm.ShowDialog(); } #endif Logger.Close(); } } }
mit
C#