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
79e9239eee8a958021ce1025cc0310db38b86100
Add areFinesEnabled method to FineCalculations class.
Programazing/Open-School-Library,Programazing/Open-School-Library
src/Open-School-Library/Helpers/FineCalculations.cs
src/Open-School-Library/Helpers/FineCalculations.cs
using Open_School_Library.Data; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Open_School_Library.Helpers { public class FineCalculations { private static LibraryContext _context; public FineCalculations(LibraryContext context) { _context = context; } public static double CalculateFine(DateTime CheckedOutOn, DateTime ReturnedOn) { return 90; } public static bool areFinesEnabled() { bool checkFines = _context.Settings.Select(x => x.AreFinesEnabled).FirstOrDefault(); return checkFines; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Open_School_Library.Helpers { public class FineCalculations { public static double CalculateFine(DateTime CheckedOutOn, DateTime ReturnedOn) { return 90; } } }
mit
C#
43640002f54064acbc75820edc5ba6ab1ab31e2b
update PipelineBuilder add empty complete delegate as default
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Helpers/PipelineBuilder.cs
src/WeihanLi.Common/Helpers/PipelineBuilder.cs
using System; using System.Threading.Tasks; namespace WeihanLi.Common.Helpers { public static class PipelineBuilder { public static IPipelineBuilder<TContext> Create<TContext>() { return new PipelineBuilder<TContext>(c => { }); } public static IPipelineBuilder<TContext> Create<TContext>(Action<TContext> completeAction) { return new PipelineBuilder<TContext>(completeAction); } public static IAsyncPipelineBuilder<TContext> CreateAsync<TContext>() { return new AsyncPipelineBuilder<TContext>(c => TaskHelper.CompletedTask); } public static IAsyncPipelineBuilder<TContext> CreateAsync<TContext>(Func<TContext, Task> completeFunc) { return new AsyncPipelineBuilder<TContext>(completeFunc); } } }
using System; using System.Threading.Tasks; namespace WeihanLi.Common.Helpers { public static class PipelineBuilder { public static IPipelineBuilder<TContext> Create<TContext>(Action<TContext> completeAction) { return new PipelineBuilder<TContext>(completeAction); } public static IAsyncPipelineBuilder<TContext> CreateAsync<TContext>(Func<TContext, Task> completeFunc) { return new AsyncPipelineBuilder<TContext>(completeFunc); } } }
mit
C#
1efbcfa881284c710cd06b06a3683ce863ab1d6b
Fix typo
cucumber-ltd/shouty.net
Shouty/Coordinate.cs
Shouty/Coordinate.cs
namespace Shouty { public class Coordinate { private readonly int xCoord; private readonly int yCoord; public Coordinate(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } public int DistanceFrom(Coordinate coordinate) { // TODO: actually calculate distance beteen the coordinates. // e.g. return Math.Abs(xCoord - coordinate.xCoord); return 0; } } }
namespace Shouty { public class Coordinate { private readonly int xCoord; private readonly int yCoord; public Coordinate(int xCoord, int yCoord) { this.xCoord = xCoord; this.yCoord = yCoord; } public int DistanceFrom(Coordinate coordinate) { // TODO: actually calculate distance beteen the coordinates. // e.g. return Math.Abs(xCoord - other.xCoord); return 0; } } }
mit
C#
68dba2b45fa50cb9fbaf79261e110e1e0c3b4ff3
Fix viewer crash when GameView doesn't have enough space
feliwir/openSage,feliwir/openSage
src/OpenSage.Viewer/UI/Views/GameView.cs
src/OpenSage.Viewer/UI/Views/GameView.cs
using System.Numerics; using ImGuiNET; using Veldrid; namespace OpenSage.Viewer.UI.Views { internal abstract class GameView : AssetView { private readonly AssetViewContext _context; protected GameView(AssetViewContext context) { _context = context; } private Vector2 GetTopLeftUV() { return _context.GraphicsDevice.IsUvOriginTopLeft ? new Vector2(0, 0) : new Vector2(0, 1); } private Vector2 GetBottomRightUV() { return _context.GraphicsDevice.IsUvOriginTopLeft ? new Vector2(1, 1) : new Vector2(1, 0); } public override void Draw(ref bool isGameViewFocused) { var windowPos = ImGui.GetCursorScreenPos(); var availableSize = ImGui.GetContentRegionAvail(); // If there's not enough space for the game view, don't draw anything. if (availableSize.X <= 0 || availableSize.Y <= 0) { return; } _context.GamePanel.EnsureFrame( new Mathematics.Rectangle( (int) windowPos.X, (int) windowPos.Y, (int) availableSize.X, (int) availableSize.Y)); _context.Game.Tick(); ImGuiNative.igSetItemAllowOverlap(); var imagePointer = _context.ImGuiRenderer.GetOrCreateImGuiBinding( _context.GraphicsDevice.ResourceFactory, _context.Game.Panel.Framebuffer.ColorTargets[0].Target); if (ImGui.ImageButton( imagePointer, ImGui.GetContentRegionAvail(), GetTopLeftUV(), GetBottomRightUV(), 0, Vector4.Zero, Vector4.One)) { isGameViewFocused = true; } } } }
using System.Numerics; using ImGuiNET; using Veldrid; namespace OpenSage.Viewer.UI.Views { internal abstract class GameView : AssetView { private readonly AssetViewContext _context; protected GameView(AssetViewContext context) { _context = context; } private Vector2 GetTopLeftUV() { return _context.GraphicsDevice.IsUvOriginTopLeft ? new Vector2(0, 0) : new Vector2(0, 1); } private Vector2 GetBottomRightUV() { return _context.GraphicsDevice.IsUvOriginTopLeft ? new Vector2(1, 1) : new Vector2(1, 0); } public override void Draw(ref bool isGameViewFocused) { var windowPos = ImGui.GetCursorScreenPos(); var availableSize = ImGui.GetContentRegionAvail(); _context.GamePanel.EnsureFrame( new Mathematics.Rectangle( (int) windowPos.X, (int) windowPos.Y, (int) availableSize.X, (int) availableSize.Y)); _context.Game.Tick(); ImGuiNative.igSetItemAllowOverlap(); var imagePointer = _context.ImGuiRenderer.GetOrCreateImGuiBinding( _context.GraphicsDevice.ResourceFactory, _context.Game.Panel.Framebuffer.ColorTargets[0].Target); if (ImGui.ImageButton( imagePointer, ImGui.GetContentRegionAvail(), GetTopLeftUV(), GetBottomRightUV(), 0, Vector4.Zero, Vector4.One)) { isGameViewFocused = true; } } } }
mit
C#
4b35fb0200249a1bc068d8218df309b4963c6d8b
Make nonfatalerrorhandler work with old libpalaso for 3.5
JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop
src/BloomExe/NonFatalProblem.cs
src/BloomExe/NonFatalProblem.cs
using System; using System.Collections.Generic; using System.Linq; using SIL.Reporting; namespace Bloom { public enum ThrowIf { Alpha, Beta, Release } public enum InformIf { Alpha, Beta, Release } /// <summary> /// Provides a way to note a problem in the log and, depending on channel, notify the user. /// Enhance: wire up to a passive notification "toast" in the UI /// </summary> public class NonFatalProblem { /// <summary> /// Always log, possibly inform the user, possibly throw the exception /// </summary> /// <param name="whenToThrow">Will throw if the channel is this or lower</param> /// <param name="whenToPassivelyInform">Ignored for now</param> /// <param name="shortUserLevelMessage">Should make sense in a small toast notification</param> /// <param name="exception"></param> public static void Handle(ThrowIf whenToThrow, InformIf whenToPassivelyInform, string shortUserLevelMessage = null, Exception exception = null) { shortUserLevelMessage = shortUserLevelMessage == null ? "" : shortUserLevelMessage; // not in this version libpalaso: Logger.WriteError("NonFatalProblem: " + shortUserLevelMessage, exception); Logger.WriteEvent("NonFatalProblem: {0}",shortUserLevelMessage); var channel = ApplicationUpdateSupport.ChannelName.ToLower(); if(exception != null && Matches(whenToThrow).Any(s => channel.Contains(s))) { throw exception; } if (!string.IsNullOrEmpty(shortUserLevelMessage) && Matches(whenToPassivelyInform).Any(s => channel.Contains(s))) { //Future } } private static string[] Matches(ThrowIf t) { switch (t) { case ThrowIf.Release: return new string[] {"developer", "alpha", "beta", "release"}; case ThrowIf.Beta: return new string[] { "developer", "alpha", "beta" }; case ThrowIf.Alpha: return new string[] { "developer", "alpha" }; default: return new string[] {}; } } private static string[] Matches(InformIf t) { switch (t) { case InformIf.Release: return new string[] { "developer", "alpha", "beta", "release" }; case InformIf.Beta: return new string[] { "developer", "alpha", "beta" }; case InformIf.Alpha: return new string[] { "developer", "alpha" }; default: return new string[] { }; } } } }
using System; using System.Collections.Generic; using System.Linq; using SIL.Reporting; namespace Bloom { public enum ThrowIf { Alpha, Beta, Release } public enum InformIf { Alpha, Beta, Release } /// <summary> /// Provides a way to note a problem in the log and, depending on channel, notify the user. /// Enhance: wire up to a passive notification "toast" in the UI /// </summary> public class NonFatalProblem { /// <summary> /// Always log, possibly inform the user, possibly throw the exception /// </summary> /// <param name="whenToThrow">Will throw if the channel is this or lower</param> /// <param name="whenToPassivelyInform">Ignored for now</param> /// <param name="shortUserLevelMessage">Should make sense in a small toast notification</param> /// <param name="exception"></param> public static void Handle(ThrowIf whenToThrow, InformIf whenToPassivelyInform, string shortUserLevelMessage = null, Exception exception = null) { shortUserLevelMessage = shortUserLevelMessage == null ? "" : shortUserLevelMessage; Logger.WriteError("NonFatalProblem: " + shortUserLevelMessage, exception); var channel = ApplicationUpdateSupport.ChannelName.ToLower(); if(exception != null && Matches(whenToThrow).Any(s => channel.Contains(s))) { throw exception; } if (!string.IsNullOrEmpty(shortUserLevelMessage) && Matches(whenToPassivelyInform).Any(s => channel.Contains(s))) { //Future } } private static string[] Matches(ThrowIf t) { switch (t) { case ThrowIf.Release: return new string[] {"developer", "alpha", "beta", "release"}; case ThrowIf.Beta: return new string[] { "developer", "alpha", "beta" }; case ThrowIf.Alpha: return new string[] { "developer", "alpha" }; default: return new string[] {}; } } private static string[] Matches(InformIf t) { switch (t) { case InformIf.Release: return new string[] { "developer", "alpha", "beta", "release" }; case InformIf.Beta: return new string[] { "developer", "alpha", "beta" }; case InformIf.Alpha: return new string[] { "developer", "alpha" }; default: return new string[] { }; } } } }
mit
C#
f2ed67f4ea3af1cd1694298b04d982eadc437a56
Update version to 1.0.4 - Protocol version: 102
InPvP/MiNET,yungtechboy1/MiNET
src/MiNET/MiNET/MotdProvider.cs
src/MiNET/MiNET/MotdProvider.cs
using System; using System.Net; using MiNET.Utils; namespace MiNET { public class MotdProvider { public string Motd { get; set; } public string SecondLine { get; set; } public int MaxNumberOfPlayers { get; set; } public int NumberOfPlayers { get; set; } public MotdProvider() { Motd = Config.GetProperty("motd", "MiNET: MCPE Server"); SecondLine = Config.GetProperty("motd-2nd", "MiNET"); } public virtual string GetMotd(ServerInfo serverInfo, IPEndPoint caller) { NumberOfPlayers = serverInfo.NumberOfPlayers; MaxNumberOfPlayers = serverInfo.MaxNumberOfPlayers; return string.Format($"MCPE;{Motd};102;1.0.4;{NumberOfPlayers};{MaxNumberOfPlayers};{Motd.GetHashCode() + caller.Address.Address + caller.Port};{SecondLine};Survival;"); } } }
using System; using System.Net; using MiNET.Utils; namespace MiNET { public class MotdProvider { public string Motd { get; set; } public string SecondLine { get; set; } public int MaxNumberOfPlayers { get; set; } public int NumberOfPlayers { get; set; } public MotdProvider() { Motd = Config.GetProperty("motd", "MiNET: MCPE Server"); SecondLine = Config.GetProperty("motd-2nd", "MiNET"); } public virtual string GetMotd(ServerInfo serverInfo, IPEndPoint caller) { NumberOfPlayers = serverInfo.NumberOfPlayers; MaxNumberOfPlayers = serverInfo.MaxNumberOfPlayers; return string.Format($"MCPE;{Motd};100;1.0.0.7;{NumberOfPlayers};{MaxNumberOfPlayers};{Motd.GetHashCode() + caller.Address.Address + caller.Port};{SecondLine};Survival;"); } } }
mpl-2.0
C#
a326f1d40d3a3cb333cdf05fd91ae89a3a579871
make tests more compact
icarus-consulting/Yaapii.Atoms
tests/Yaapii.Atoms.Tests/IO/MemoryInputTest.cs
tests/Yaapii.Atoms.Tests/IO/MemoryInputTest.cs
// MIT License // // Copyright(c) 2020 ICARUS Consulting GmbH // // 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.Collections.Generic; using System.IO; using System.Text; using Xunit; using Yaapii.Atoms.IO; namespace Yaapii.Atoms.IO.Tests { public sealed class MemoryInputTest { [Fact] public void CreateMemoryInput() { var memoryInput = new MemoryInput( new InputOf( "This is my input!" ) ); var memoryContent = ""; using (var reader = new StreamReader(memoryInput.Stream())) { memoryContent = reader.ReadToEnd(); } Assert.Equal( "This is my input!", memoryContent ); } [Fact] public void CreateEmptyMemoryInput() { var memoryInput = new MemoryInput( new InputOf( "" ) ); var memoryContent = ""; using (var reader = new StreamReader(memoryInput.Stream())) { memoryContent = reader.ReadToEnd(); } Assert.Equal( "", memoryContent ); } } }
// MIT License // // Copyright(c) 2020 ICARUS Consulting GmbH // // 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.Collections.Generic; using System.IO; using System.Text; using Xunit; using Yaapii.Atoms.IO; namespace Yaapii.Atoms.IO.Tests { public sealed class MemoryInputTest { [Fact] public void CreateMemoryInput() { var content = "This is my input!"; var input = new InputOf(content); var memoryInput = new MemoryInput(input); var memoryContent = ""; using (var reader = new StreamReader(memoryInput.Stream())) { memoryContent = reader.ReadToEnd(); } Assert.Equal( content, memoryContent ); } [Fact] public void CreateEmptyMemoryInput() { var input = new InputOf(""); var memoryInput = new MemoryInput(input); var memoryContent = ""; using (var reader = new StreamReader(memoryInput.Stream())) { memoryContent = reader.ReadToEnd(); } Assert.Equal( "", memoryContent ); } } }
mit
C#
6084491c692b5ca7108885e9bab3e86715227d03
Update index.cshtml
reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website
input/slack/index.cshtml
input/slack/index.cshtml
<meta http-equiv="refresh" content="1;url=https://join.slack.com/t/reactivex/shared_invite/zt-lt48skpz-G5WDYOAuzA80_MByZrLT0g" /> Join by visiting <a href="https://join.slack.com/t/reactivex/shared_invite/zt-lt48skpz-G5WDYOAuzA80_MByZrLT0g">Slack</a>
<meta http-equiv="refresh" content="1;url=https://join.slack.com/t/reactivex/shared_invite/enQtMzM2NzIxNTg0MTYxLTdiMzRhZGI3MDA4NWVkMzZiZTA3MGNhODQ4MDFjZGM2M2JiNmNkZTM2NzMyNDE3ZTIyZGJlMmU0OTVkOWJmYzU" /> Join by visiting <a href="https://join.slack.com/t/reactivex/shared_invite/enQtMzM2NzIxNTg0MTYxLTdiMzRhZGI3MDA4NWVkMzZiZTA3MGNhODQ4MDFjZGM2M2JiNmNkZTM2NzMyNDE3ZTIyZGJlMmU0OTVkOWJmYzU">Slack</a>
mit
C#
6d889c8a37b3f83978fc5020c59857608ff5f5d2
Revert unintended change
UselessToucan/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,EVAST9919/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ZLima12/osu,ZLima12/osu,johnneijzen/osu,peppy/osu,UselessToucan/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,peppy/osu-new,NeoAdonis/osu
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/RingPiece.cs
osu.Game.Rulesets.Osu/Objects/Drawables/Pieces/RingPiece.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : Container { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; InternalChild = new SkinnableDrawable("Play/osu/hitcircleoverlay", _ => new Container { Masking = true, CornerRadius = Size.X / 2, BorderThickness = 10, BorderColour = Color4.White, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both } } }); } } }
// 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.Graphics; using osu.Framework.Graphics.Containers; using osuTK; using osuTK.Graphics; using osu.Framework.Graphics.Shapes; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Objects.Drawables.Pieces { public class RingPiece : Container { public RingPiece() { Size = new Vector2(OsuHitObject.OBJECT_RADIUS * 2); Anchor = Anchor.Centre; Origin = Anchor.Centre; InternalChild = new SkinnableDrawable("Play/osu/hitcircleoverlay", _ => new Container { Masking = true, CornerRadius = Size.X / 2, BorderThickness = 10, BorderColour = Color4.White, RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { AlwaysPresent = true, Alpha = 0, RelativeSizeAxes = Axes.Both } } }, confineMode: ConfineMode.NoScaling); } } }
mit
C#
d66a26cd116bc45f9fd240cefbfd0acfc7f727b8
Add JsonProperty hinting
ZLima12/osu,EVAST9919/osu,peppy/osu-new,smoogipooo/osu,peppy/osu,2yangk23/osu,ppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,UselessToucan/osu,UselessToucan/osu,2yangk23/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,peppy/osu
osu.Game/Online/API/Requests/Responses/APIChangelogIndex.cs
osu.Game/Online/API/Requests/Responses/APIChangelogIndex.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 Newtonsoft.Json; namespace osu.Game.Online.API.Requests.Responses { public class APIChangelogIndex { [JsonProperty] public List<APIChangelogBuild> Builds; [JsonProperty] public List<APIUpdateStream> Streams; } }
// 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; namespace osu.Game.Online.API.Requests.Responses { public class APIChangelogIndex { public List<APIChangelogBuild> Builds; public List<APIUpdateStream> Streams; } }
mit
C#
6cd306813de03f8b6d47e38381a1276111434121
check for null capability
rit-sse-mycroft/core
Mycroft/Cmd/Msg/UndirectedQuery.cs
Mycroft/Cmd/Msg/UndirectedQuery.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mycroft.Messages.Msg; using Mycroft.App; using System.Diagnostics; namespace Mycroft.Cmd.Msg { class UndirectedQuery : Query { public UndirectedQuery(MsgQuery query, AppInstance instance) : base(query, instance) { } public override void VisitRegistry(Registry registry) { if (!HasValidGuid) { Debug.WriteLine("GUID " + this.guid + " is invalid, not sending query"); return; } var cap = GetCapability(); var msg = "MSG_QUERY " + query.Serialize(); if (cap != null) { foreach (AppInstance other in registry.GetProviders(cap)) { other.Send(msg); ShouldArchive = true; } } else { Debug.WriteLine("Warning: App did not declare a " + query.Capability + " dependency, not sending message"); } } /// <summary> /// Get the capability to which this query is referring. /// This is determined by the version number supplied in the /// dependency that it declared and the name that was supplied /// in the query. /// </summary> /// <returns>the capability or null if not found</returns> private Capability GetCapability() { foreach (Capability cap in instance.Capabilities) { if (cap.Name == this.query.Capability) return cap; } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Mycroft.Messages.Msg; using Mycroft.App; using System.Diagnostics; namespace Mycroft.Cmd.Msg { class UndirectedQuery : Query { public UndirectedQuery(MsgQuery query, AppInstance instance) : base(query, instance) { } public override void VisitRegistry(Registry registry) { if (!HasValidGuid) { Debug.WriteLine("GUID " + this.guid + " is invalid, not sending query"); return; } var cap = GetCapability(); var msg = "MSG_QUERY " + query.Serialize(); foreach (AppInstance other in registry.GetProviders(cap)) { other.Send(msg); ShouldArchive = true; } } /// <summary> /// Get the capability to which this query is referring. /// This is determined by the version number supplied in the /// dependency that it declared and the name that was supplied /// in the query. /// </summary> /// <returns>the capability or null if not found</returns> private Capability GetCapability() { foreach (Capability cap in instance.Capabilities) { if (cap.Name == this.query.Capability) return cap; } return null; } } }
bsd-3-clause
C#
092a408911f53dab80a55b3e810b69fe8cb12221
Update the version number to 1.4.0
tpierrain/NFluent,NFluent/NFluent,dupdob/NFluent,tpierrain/NFluent,NFluent/NFluent,dupdob/NFluent,tpierrain/NFluent,dupdob/NFluent
Version.cs
Version.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs" company=""> // Copyright 2013 Thomas PIERRAIN // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs" company=""> // Copyright 2013 Thomas PIERRAIN // 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. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; // 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.2.0")] [assembly: AssemblyFileVersion("1.3.2.0")]
apache-2.0
C#
c3b3ebc40a47b3daa1151e06d82247d87585037c
Check background job worker before using that in jobs info controller
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
src/Server/Bit.OData/ODataControllers/JobsInfoController.cs
src/Server/Bit.OData/ODataControllers/JobsInfoController.cs
using Bit.Core.Contracts; using Bit.Core.Models; using Bit.Model.Dtos; using System; using System.Threading; using System.Threading.Tasks; namespace Bit.OData.ODataControllers { public class JobsInfoController : DtoController<JobInfoDto> { public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; } [Get] public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken) { if (key == null) throw new ArgumentNullException(nameof(key)); if (BackgroundJobWorker == null) throw new InvalidOperationException("No background job worker is configured"); JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken); return new JobInfoDto { Id = jobInfo.Id, CreatedAt = jobInfo.CreatedAt, State = jobInfo.State }; } } }
using System; using System.Threading; using System.Threading.Tasks; using Bit.Core.Contracts; using Bit.Core.Models; using Bit.Model.Dtos; namespace Bit.OData.ODataControllers { public class JobsInfoController : DtoController<JobInfoDto> { public virtual IBackgroundJobWorker BackgroundJobWorker { get; set; } [Get] public virtual async Task<JobInfoDto> Get(string key, CancellationToken cancellationToken) { if (key == null) throw new ArgumentNullException(nameof(key)); JobInfo jobInfo = await BackgroundJobWorker.GetJobInfoAsync(key, cancellationToken); return new JobInfoDto { Id = jobInfo.Id, CreatedAt = jobInfo.CreatedAt, State = jobInfo.State }; } } }
mit
C#
25dc37cc5a7702ee7db07c19c2087bed0956b985
Add using
marihachi/MSharp
src/MSharpSample/SampleForm.cs
src/MSharpSample/SampleForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using MSharp; namespace MSharpSample { public partial class SampleForm : Form { public SampleForm() { InitializeComponent(); } private Misskey mi { set; get; } private async void StartAuthButton_Click(object sender, EventArgs e) { mi = new Misskey(Config.AppKey); await mi.StartAuthorize(); } private async void PinOKButton_Click(object sender, EventArgs e) { mi = await mi.AuthorizePIN(PinBox.Text); } private async void StatusUpdateButton_Click(object sender, EventArgs e) { var res = await mi.Request( HttpRequest.MethodType.POST, "status/update", new Dictionary<string, string> { { "text", StatusUpdateBox.Text } }); Console.WriteLine(res); StatusUpdateBox.Text = ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MSharpSample { public partial class SampleForm : Form { public SampleForm() { InitializeComponent(); } private MSharp.Misskey mi { set; get; } private async void StartAuthButton_Click(object sender, EventArgs e) { mi = new MSharp.Misskey(Config.AppKey); await mi.StartAuthorize(); } private async void PinOKButton_Click(object sender, EventArgs e) { mi = await mi.AuthorizePIN(PinBox.Text); Console.WriteLine("AppKey: " + mi.AppKey); Console.WriteLine("UserKey: " + mi.UserKey); Console.WriteLine("UserId: " + mi.UserId); } private async void StatusUpdateButton_Click(object sender, EventArgs e) { var res = await mi.Request( MSharp.HttpRequest.MethodType.POST, "status/update", new Dictionary<string, string> { { "text", StatusUpdateBox.Text } }); Console.WriteLine(res); StatusUpdateBox.Text = ""; } } }
mit
C#
0ddb4dc9014906db27a3d9616fc9db5993266726
Fix missing reward bug
ywcui1990/htmresearch,BoltzmannBrain/nupic.research,numenta/htmresearch,ThomasMiconi/htmresearch,mrcslws/htmresearch,ThomasMiconi/htmresearch,cogmission/nupic.research,BoltzmannBrain/nupic.research,ThomasMiconi/htmresearch,neuroidss/nupic.research,numenta/htmresearch,cogmission/nupic.research,ThomasMiconi/nupic.research,neuroidss/nupic.research,subutai/htmresearch,ywcui1990/htmresearch,ThomasMiconi/nupic.research,marionleborgne/nupic.research,mrcslws/htmresearch,marionleborgne/nupic.research,BoltzmannBrain/nupic.research,chanceraine/nupic.research,ThomasMiconi/nupic.research,BoltzmannBrain/nupic.research,ywcui1990/nupic.research,numenta/htmresearch,ywcui1990/htmresearch,subutai/htmresearch,ywcui1990/nupic.research,ywcui1990/nupic.research,cogmission/nupic.research,numenta/htmresearch,ywcui1990/nupic.research,mrcslws/htmresearch,chanceraine/nupic.research,marionleborgne/nupic.research,mrcslws/htmresearch,numenta/htmresearch,ThomasMiconi/htmresearch,mrcslws/htmresearch,neuroidss/nupic.research,BoltzmannBrain/nupic.research,chanceraine/nupic.research,ywcui1990/htmresearch,ywcui1990/nupic.research,BoltzmannBrain/nupic.research,BoltzmannBrain/nupic.research,chanceraine/nupic.research,mrcslws/htmresearch,cogmission/nupic.research,ThomasMiconi/nupic.research,ThomasMiconi/htmresearch,neuroidss/nupic.research,chanceraine/nupic.research,ThomasMiconi/nupic.research,subutai/htmresearch,neuroidss/nupic.research,ThomasMiconi/htmresearch,BoltzmannBrain/nupic.research,ThomasMiconi/nupic.research,cogmission/nupic.research,numenta/htmresearch,ThomasMiconi/nupic.research,subutai/htmresearch,cogmission/nupic.research,subutai/htmresearch,cogmission/nupic.research,cogmission/nupic.research,marionleborgne/nupic.research,subutai/htmresearch,neuroidss/nupic.research,neuroidss/nupic.research,subutai/htmresearch,marionleborgne/nupic.research,numenta/htmresearch,marionleborgne/nupic.research,neuroidss/nupic.research,mrcslws/htmresearch,ThomasMiconi/nupic.research,chanceraine/nupic.research,ywcui1990/nupic.research,subutai/htmresearch,ThomasMiconi/htmresearch,marionleborgne/nupic.research,marionleborgne/nupic.research,ywcui1990/htmresearch,ThomasMiconi/htmresearch,ywcui1990/htmresearch,ywcui1990/nupic.research,ywcui1990/nupic.research,mrcslws/htmresearch,ywcui1990/htmresearch,numenta/htmresearch,ywcui1990/htmresearch
vehicle-control/simulation/Assets/Scripts/Reward.cs
vehicle-control/simulation/Assets/Scripts/Reward.cs
using UnityEngine; using System.Collections; public class Reward : MonoBehaviour { public float reward = 100f; private bool collided = false; IEnumerator ResetLevel() { float lastSyncTime = API.instance.LastSyncTime(); while (lastSyncTime == API.instance.LastSyncTime()) { yield return null; } Application.LoadLevel(Application.loadedLevel); } void OnCollisionEnter(Collision collision) { if (collided) return; API.instance.SetOutput("reward", reward); collided = true; StartCoroutine(ResetLevel()); } }
using UnityEngine; using System.Collections; public class Reward : MonoBehaviour { public float reward = 100f; private bool collided = false; IEnumerator ResetLevel() { yield return new WaitForSeconds(1.0f); Application.LoadLevel(Application.loadedLevel); } void OnCollisionEnter(Collision collision) { if (collided) return; API.instance.SetOutput("reward", reward); collided = true; StartCoroutine(ResetLevel()); } }
agpl-3.0
C#
dd512d1b619888ef0171ba2f75420dfb6462f615
fix compile error
guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft,guibec/rpgcraft
unity/Assets/Scripts/Game/Player/Experience.cs
unity/Assets/Scripts/Game/Player/Experience.cs
using UnityEngine; using System.Collections; using UnityEngine.Assertions; public class Experience { public Experience() { XP = 0; } public int Level { get { for (int i = MaxLevel-1; i >= 0; --i) { if (XP >= NextLevels[i]) return i + 1; } Assert.IsTrue(false, "Invalid level state"); return 1; } } public int XP { get; private set; } public int MaxLevel { get { return NextLevels.Length; } } private int[] NextLevels = { 0, 50, 150, 375, 790, 1400, 2300, 3300}; }
using UnityEngine; using System.Collections; using UnityEngine.Assertions; public class Experience { public int Level { get { for (int i = MaxLevel-1; i >= 0; --i) { if (XP >= NextLevels[i]) return i + 1; } Assert.IsTrue(false, "Invalid level state"); return 1; } } public int XP { get; private set; } = 0; public int MaxLevel => NextLevels.Length; private int[] NextLevels = { 0, 50, 150, 375, 790, 1400, 2300, 3300}; }
mit
C#
9a3f9adfa218a67956afe2986ed34fe2d3944d18
Add xml comment on namespace.
YoshinoriN/Kinugasa
Source/Kinugasa.UI/BindingProxy.cs
Source/Kinugasa.UI/BindingProxy.cs
using System.Windows; /// <summary> /// Provide userinterface components. /// </summary> namespace Kinugasa.UI { /// <summary> /// Proxy class for binding sorce. /// </summary> public class BindingProxy : Freezable { /// <summary> /// Define dependencyProperty. /// </summary> public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null)); /// <summary> /// Create freezable object's instance. /// </summary> /// <returns></returns> protected override Freezable CreateInstanceCore() { return new BindingProxy(); } /// <summary> /// Proxy property. /// </summary> public object Data { get { return (object)GetValue(DataProperty); } set { SetValue(DataProperty, value); } } } }
using System.Windows; namespace Kinugasa.UI { /// <summary> /// Proxy class for binding sorce. /// </summary> public class BindingProxy : Freezable { /// <summary> /// Define dependencyProperty. /// </summary> public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null)); /// <summary> /// Create freezable object's instance. /// </summary> /// <returns></returns> protected override Freezable CreateInstanceCore() { return new BindingProxy(); } /// <summary> /// Proxy property. /// </summary> public object Data { get { return (object)GetValue(DataProperty); } set { SetValue(DataProperty, value); } } } }
mit
C#
866fc9fc6ae6367a70e3c2dd4a819213bfaf214e
Fix GitHub_3449 test (#12683)
botaberg/coreclr,kyulee1/coreclr,kyulee1/coreclr,mmitche/coreclr,cshung/coreclr,dpodder/coreclr,russellhadley/coreclr,dpodder/coreclr,wtgodbe/coreclr,mmitche/coreclr,botaberg/coreclr,botaberg/coreclr,botaberg/coreclr,rartemev/coreclr,wateret/coreclr,gkhanna79/coreclr,cydhaselton/coreclr,poizan42/coreclr,wateret/coreclr,AlexGhiondea/coreclr,gkhanna79/coreclr,yizhang82/coreclr,cshung/coreclr,russellhadley/coreclr,krk/coreclr,JonHanna/coreclr,dpodder/coreclr,ragmani/coreclr,JosephTremoulet/coreclr,rartemev/coreclr,yizhang82/coreclr,JonHanna/coreclr,cydhaselton/coreclr,mmitche/coreclr,parjong/coreclr,kyulee1/coreclr,krk/coreclr,mmitche/coreclr,ragmani/coreclr,cydhaselton/coreclr,poizan42/coreclr,JonHanna/coreclr,dpodder/coreclr,JosephTremoulet/coreclr,russellhadley/coreclr,mskvortsov/coreclr,ruben-ayrapetyan/coreclr,AlexGhiondea/coreclr,yizhang82/coreclr,russellhadley/coreclr,poizan42/coreclr,JosephTremoulet/coreclr,botaberg/coreclr,JonHanna/coreclr,ruben-ayrapetyan/coreclr,wateret/coreclr,hseok-oh/coreclr,tijoytom/coreclr,mskvortsov/coreclr,krk/coreclr,mskvortsov/coreclr,AlexGhiondea/coreclr,ruben-ayrapetyan/coreclr,cshung/coreclr,yizhang82/coreclr,tijoytom/coreclr,ruben-ayrapetyan/coreclr,JonHanna/coreclr,wtgodbe/coreclr,wateret/coreclr,kyulee1/coreclr,YongseopKim/coreclr,cydhaselton/coreclr,rartemev/coreclr,gkhanna79/coreclr,parjong/coreclr,parjong/coreclr,ragmani/coreclr,JosephTremoulet/coreclr,cydhaselton/coreclr,dpodder/coreclr,rartemev/coreclr,hseok-oh/coreclr,JosephTremoulet/coreclr,poizan42/coreclr,rartemev/coreclr,poizan42/coreclr,yizhang82/coreclr,JosephTremoulet/coreclr,tijoytom/coreclr,YongseopKim/coreclr,wateret/coreclr,kyulee1/coreclr,AlexGhiondea/coreclr,YongseopKim/coreclr,botaberg/coreclr,ragmani/coreclr,YongseopKim/coreclr,ruben-ayrapetyan/coreclr,mskvortsov/coreclr,hseok-oh/coreclr,krk/coreclr,YongseopKim/coreclr,YongseopKim/coreclr,mmitche/coreclr,hseok-oh/coreclr,hseok-oh/coreclr,hseok-oh/coreclr,gkhanna79/coreclr,kyulee1/coreclr,JonHanna/coreclr,dpodder/coreclr,mmitche/coreclr,tijoytom/coreclr,russellhadley/coreclr,mskvortsov/coreclr,wateret/coreclr,russellhadley/coreclr,mskvortsov/coreclr,poizan42/coreclr,gkhanna79/coreclr,rartemev/coreclr,tijoytom/coreclr,yizhang82/coreclr,krk/coreclr,parjong/coreclr,cshung/coreclr,parjong/coreclr,cshung/coreclr,ruben-ayrapetyan/coreclr,krk/coreclr,parjong/coreclr,cshung/coreclr,wtgodbe/coreclr,ragmani/coreclr,wtgodbe/coreclr,AlexGhiondea/coreclr,ragmani/coreclr,gkhanna79/coreclr,wtgodbe/coreclr,AlexGhiondea/coreclr,cydhaselton/coreclr,wtgodbe/coreclr,tijoytom/coreclr
tests/src/JIT/Regression/JitBlue/GitHub_3449/GitHub_3449.cs
tests/src/JIT/Regression/JitBlue/GitHub_3449/GitHub_3449.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using System; public class Program { // RyuJIT codegen, VC++, clang and gcc may produce different results for casting uint64 to // double. // 1) (double)0x84595161401484A0UL --> 43e08b2a2c280290 (RyuJIT codegen or VC++) // 2) (double)0x84595161401484A0UL --> 43e08b2a2c280291 (clang or gcc) // Constant folding in RyuJIT simply does (double)0x84595161401484A0UL in its C++ implementation. // If it is compiled by clang or gcc, the example unsigned value and cast tree node are folded into // 43e08b2a2c280291, which is different from what RyuJIT codegen or VC++ produces. // // We don't have a good way to tell if the CLR is compiled by clang or VC++, so we simply allow // both answers. public static int Main(string[] args) { ulong u64 = 0x84595161401484A0UL; double f64 = (double)u64; long h64 = BitConverter.DoubleToInt64Bits(f64); long expected_h64_1 = 0x43e08b2a2c280291L; long expected_h64_2 = 0x43e08b2a2c280290L; if ((h64 != expected_h64_1) && (h64 != expected_h64_2)) { Console.WriteLine(String.Format("Expected: 0x{0:x} or 0x{1:x}\nActual: 0x{2:x}", expected_h64_1, expected_h64_2, h64)); return -1; } return 100; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information using System; public class Program { // RyuJIT codegen and clang (or gcc) may produce different results for casting uint64 to // double, and the clang result is more accurate. For example, // 1) (double)0x84595161401484A0UL --> 43e08b2a2c280290 (RyuJIT codegen or VC++) // 2) (double)0x84595161401484A0UL --> 43e08b2a2c280291 (clang or gcc) // Constant folding in RyuJIT simply does (double)0x84595161401484A0UL in its C++ implementation. // If it is compiled by clang, the example unsigned value and cast tree node are folded into // 43e08b2a2c280291, which is different from what the codegen produces. To fix this inconsistency, // the constant folding is forced to have the same behavior as the codegen, and the result // must be always 43e08b2a2c280290. public static int Main(string[] args) { //Check if the test is being executed on ARMARCH bool isProcessorArmArch = false; string processorArchEnvVar = null; processorArchEnvVar = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"); if ((processorArchEnvVar != null) && (processorArchEnvVar.Equals("ARM", StringComparison.CurrentCultureIgnoreCase) || processorArchEnvVar.Equals("ARM64", StringComparison.CurrentCultureIgnoreCase))) { isProcessorArmArch = true; } ulong u64 = 0x84595161401484A0UL; double f64 = (double)u64; long h64 = BitConverter.DoubleToInt64Bits(f64); long expected_h64 = isProcessorArmArch ? 0x43e08b2a2c280291L : 0x43e08b2a2c280290L; if (h64 != expected_h64) { Console.WriteLine(String.Format("Expected: 0x{0:x}\nActual: 0x{1:x}", expected_h64, h64)); return -1; } return 100; } }
mit
C#
29ff7bc34014a80df54ce9598570d89d58e50d0a
Handle checkbox value conversion from Nested Content
marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,madsoulswe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS
src/Umbraco.Core/PropertyEditors/ValueConverters/YesNoValueConverter.cs
src/Umbraco.Core/PropertyEditors/ValueConverters/YesNoValueConverter.cs
using System; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class YesNoValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => propertyType.EditorAlias == Constants.PropertyEditors.Aliases.Boolean; public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (bool); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { // in xml a boolean is: string // in the database a boolean is: string "1" or "0" or empty // typically the converter does not need to handle anything else ("true"...) // however there are cases where the value passed to the converter could be a non-string object, e.g. int, bool if (source is string s) { if (s.Length == 0 || s == "0") return false; if (s == "1") return true; return bool.TryParse(s, out bool result) && result; } if (source is int) return (int)source == 1; // this is required for correct true/false handling in nested content elements if (source is long) return (long)source == 1; if (source is bool) return (bool)source; // default value is: false return false; } // default ConvertSourceToObject just returns source ie a boolean value public override object ConvertIntermediateToXPath(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { // source should come from ConvertSource and be a boolean already return (bool)inter ? "1" : "0"; } } }
using System; using Umbraco.Core.Models.PublishedContent; namespace Umbraco.Core.PropertyEditors.ValueConverters { [DefaultPropertyValueConverter] public class YesNoValueConverter : PropertyValueConverterBase { public override bool IsConverter(PublishedPropertyType propertyType) => propertyType.EditorAlias == Constants.PropertyEditors.Aliases.Boolean; public override Type GetPropertyValueType(PublishedPropertyType propertyType) => typeof (bool); public override PropertyCacheLevel GetPropertyCacheLevel(PublishedPropertyType propertyType) => PropertyCacheLevel.Element; public override object ConvertSourceToIntermediate(IPublishedElement owner, PublishedPropertyType propertyType, object source, bool preview) { // in xml a boolean is: string // in the database a boolean is: string "1" or "0" or empty // typically the converter does not need to handle anything else ("true"...) // however there are cases where the value passed to the converter could be a non-string object, e.g. int, bool if (source is string s) { if (s.Length == 0 || s == "0") return false; if (s == "1") return true; return bool.TryParse(s, out bool result) && result; } if (source is int) return (int)source == 1; if (source is bool) return (bool)source; // default value is: false return false; } // default ConvertSourceToObject just returns source ie a boolean value public override object ConvertIntermediateToXPath(IPublishedElement owner, PublishedPropertyType propertyType, PropertyCacheLevel referenceCacheLevel, object inter, bool preview) { // source should come from ConvertSource and be a boolean already return (bool)inter ? "1" : "0"; } } }
mit
C#
d3615d7deea12f8b2a8d863c6959003b624b5c72
Check IsTogglePatternAvailable insted of using ControlType
jorik041/Winium.Desktop,2gis/Winium.Desktop,zebraxxl/Winium.Desktop
src/Winium.Desktop.Driver/CommandExecutors/IsElementSelectedExecutor.cs
src/Winium.Desktop.Driver/CommandExecutors/IsElementSelectedExecutor.cs
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System.Windows.Automation; using Winium.Cruciatus.Exceptions; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class IsElementSelectedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); var isSelected = false; try { var isTogglePattrenAvailable = element.GetAutomationPropertyValue<bool>(AutomationElement.IsTogglePatternAvailableProperty); if (isTogglePattrenAvailable) { var toggleStateProperty = TogglePattern.ToggleStateProperty; var toggleState = element.GetAutomationPropertyValue<ToggleState>(toggleStateProperty); isSelected = toggleState == ToggleState.On; } } catch (CruciatusException) { var selectionItemProperty = SelectionItemPattern.IsSelectedProperty; isSelected = element.GetAutomationPropertyValue<bool>(selectionItemProperty); } return this.JsonResponse(ResponseStatus.Success, isSelected); } #endregion } }
namespace Winium.Desktop.Driver.CommandExecutors { #region using using System.Windows.Automation; using Winium.Cruciatus.Extensions; using Winium.StoreApps.Common; #endregion internal class IsElementSelectedExecutor : CommandExecutorBase { #region Methods protected override string DoImpl() { var registeredKey = this.ExecutedCommand.Parameters["ID"].ToString(); var element = this.Automator.Elements.GetRegisteredElement(registeredKey); var controlType = element.GetAutomationPropertyValue<ControlType>(AutomationElement.ControlTypeProperty); if (controlType.Equals(ControlType.CheckBox)) { return this.JsonResponse(ResponseStatus.Success, element.ToCheckBox().IsToggleOn); } var property = SelectionItemPattern.IsSelectedProperty; var isSelected = element.GetAutomationPropertyValue<bool>(property); return this.JsonResponse(ResponseStatus.Success, isSelected); } #endregion } }
mpl-2.0
C#
030e7a1178cf93dd94176e54c94a4bfd15b0b0ac
address issue #100
fandrei/AppMetrics,fandrei/AppMetrics
AppMetrics/Config.aspx.cs
AppMetrics/Config.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AppMetrics.WebUtils; namespace AppMetrics { public partial class Config : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { WebUtil.CheckIpAddress(); LogEvent.Init(); if (!Page.IsPostBack) { RequireAccessKey.Checked = AppSettings.Instance.RequireAccessKey; if (AppSettings.Instance.AccessKeys != null) { var text = new StringBuilder(); foreach (var accessKey in AppSettings.Instance.AccessKeys) { text.AppendLine(accessKey); } AccessKeysList.Text = text.ToString(); } } } catch (UnauthorizedAccessException) { } } protected void OkButton_Click(object sender, EventArgs e) { try { WebUtil.CheckIpAddress(); AppSettings.Instance.RequireAccessKey = RequireAccessKey.Checked; var text = AccessKeysList.Text; var keys = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); AppSettings.Instance.AccessKeys = keys; AppSettings.Instance.Save(); } catch (UnauthorizedAccessException) { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using AppMetrics.WebUtils; namespace AppMetrics { public partial class Config : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { WebUtil.CheckIpAddress(); LogEvent.Init(); if (!Page.IsPostBack) { RequireAccessKey.Checked = AppSettings.Instance.RequireAccessKey; var text = new StringBuilder(); foreach (var accessKey in AppSettings.Instance.AccessKeys) { text.AppendLine(accessKey); } AccessKeysList.Text = text.ToString(); } } catch (UnauthorizedAccessException) { } } protected void OkButton_Click(object sender, EventArgs e) { try { WebUtil.CheckIpAddress(); AppSettings.Instance.RequireAccessKey = RequireAccessKey.Checked; var text = AccessKeysList.Text; var keys = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); AppSettings.Instance.AccessKeys = keys; AppSettings.Instance.Save(); } catch (UnauthorizedAccessException) { } } } }
apache-2.0
C#
1d094f5ef612ab98a104394946e5629a1002248c
hide in inspector
sapphiredev/mutsuki
Assets/Scripts/MObject.cs
Assets/Scripts/MObject.cs
using UnityEngine; using Mutsuki; public class MObject : MonoBehaviour { [HideInInspector] public Category category; [HideInInspector] public int id; [HideInInspector] public Vector3 pos; [HideInInspector] public int hp; private float cooltime; [HideInInspector] public Vector3 targetPos; [HideInInspector] public enum Status { Stop, Move, } [HideInInspector] public Status status; public void SetUp(NewObjectPacket packet) { status = Status.Stop; category = packet.category; id = packet.movableId; pos = new Vector3 (packet.x, 0.0f, packet.y); if (category == Category.Player) { hp = Constants.PLAYER_HP; } else { hp = Constants.ENEMY_HP; } cooltime = 0.0f; if (category == Category.Player) { transform.localPosition = (pos + new Vector3 (0.5f, 0.0f, 0.5f)); } else { transform.localPosition = (pos + new Vector3 (0.5f, 0.5f, 0.5f)); } } void Update() { if (cooltime > 0.0f) { var deltaTime = Time.deltaTime; if (cooltime < deltaTime) { deltaTime = cooltime; } var diff = targetPos - pos; if (category == Category.Player) { diff *= (deltaTime / cooltime); } else { diff *= (deltaTime / cooltime); } pos += diff; transform.Translate (diff); cooltime -= deltaTime; } else { status = Status.Stop; } } private Vector3 nameplatePos; private string nameplateStr; void OnGUI() { nameplatePos = Camera.main.WorldToScreenPoint(gameObject.transform.position); nameplateStr = "object_" + id + "\n" + hp + "/"; switch (category) { case Category.Player: nameplateStr += Constants.PLAYER_HP; break; case Category.Enemy: nameplateStr += Constants.ENEMY_HP; break; } GUI.Label(new Rect(nameplatePos.x + 10, (Screen.height - nameplatePos.y - 36), 100, 50), nameplateStr); } void OnMouseDown() { if (category == Category.Enemy) { var packet = PacketFactory.requestAttack(id); Main.request (packet); } } public bool updateTarget(Vector3 targetPos) { if (cooltime > 0.0f) { return false; } else { this.targetPos = targetPos; if(category == Category.Player) { cooltime = Constants.PLAYER_COOLTIME_MOVE; } else { cooltime = Constants.ENEMY_COOLTIME_MOVE; } status = Status.Move; return true; } } }
using UnityEngine; using Mutsuki; public class MObject : MonoBehaviour { public Category category; public int id; public Vector3 pos; public int hp; private float cooltime; public Vector3 targetPos; public enum Status { Stop, Move, } public Status status; public void SetUp(NewObjectPacket packet) { status = Status.Stop; category = packet.category; id = packet.movableId; pos = new Vector3 (packet.x, 0.0f, packet.y); if (category == Category.Player) { hp = Constants.PLAYER_HP; } else { hp = Constants.ENEMY_HP; } cooltime = 0.0f; if (category == Category.Player) { transform.localPosition = (pos + new Vector3 (0.5f, 0.0f, 0.5f)); } else { transform.localPosition = (pos + new Vector3 (0.5f, 0.5f, 0.5f)); } } void Update() { if (cooltime > 0.0f) { var deltaTime = Time.deltaTime; if (cooltime < deltaTime) { deltaTime = cooltime; } var diff = targetPos - pos; if (category == Category.Player) { diff *= (deltaTime / cooltime); } else { diff *= (deltaTime / cooltime); } pos += diff; transform.Translate (diff); cooltime -= deltaTime; } else { status = Status.Stop; } } private Vector3 nameplatePos; private string nameplateStr; void OnGUI() { nameplatePos = Camera.main.WorldToScreenPoint(gameObject.transform.position); nameplateStr = "object_" + id + "\n" + hp + "/"; switch (category) { case Category.Player: nameplateStr += Constants.PLAYER_HP; break; case Category.Enemy: nameplateStr += Constants.ENEMY_HP; break; } GUI.Label(new Rect(nameplatePos.x + 10, (Screen.height - nameplatePos.y - 36), 100, 50), nameplateStr); } void OnMouseDown() { if (category == Category.Enemy) { var packet = PacketFactory.requestAttack(id); Main.request (packet); } } public bool updateTarget(Vector3 targetPos) { if (cooltime > 0.0f) { return false; } else { this.targetPos = targetPos; if(category == Category.Player) { cooltime = Constants.PLAYER_COOLTIME_MOVE; } else { cooltime = Constants.ENEMY_COOLTIME_MOVE; } status = Status.Move; return true; } } }
mit
C#
0aa198d1b0b1df5e590f0dc4ee349673157739ca
Bump version to 5.6
glorylee/FluentValidation,deluxetiky/FluentValidation,GDoronin/FluentValidation,mgmoody42/FluentValidation,robv8r/FluentValidation,IRlyDontKnow/FluentValidation,cecilphillip/FluentValidation,olcayseker/FluentValidation,regisbsb/FluentValidation,ruisebastiao/FluentValidation
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; [assembly : AssemblyVersion("5.6.0.0")] [assembly : AssemblyFileVersion("5.6.0.0")]
using System.Reflection; [assembly : AssemblyVersion("5.5.0.0")] [assembly : AssemblyFileVersion("5.5.0.0")]
apache-2.0
C#
049500633e9e22c9530f8cc2ccaea2da6e177861
Update ViewLocator.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/ViewLocator.cs
src/Core2D/ViewLocator.cs
#nullable disable using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using Core2D.ViewModels; using Dock.Model.ReactiveUI.Core; namespace Core2D { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public IControl Build(object data) { var type = data.GetType(); if (s_views.TryGetValue(type, out var func)) { return func?.Invoke(); } throw new Exception($"Unable to create view for type: {type}"); } public bool Match(object data) { return data is ViewModelBase or DockableBase; } } }
#nullable disable using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using Core2D.ViewModels; using Dock.Model.ReactiveUI.Core; namespace Core2D { [StaticViewLocator] public partial class ViewLocator : IDataTemplate { public IControl Build(object data) { var type = data.GetType(); if (s_views.TryGetValue(type, out var func)) { return func?.Invoke(); } throw new Exception($"Unable to create view for type: {type}"); } public bool Match(object data) { return data is ViewModelBase or DockableBase; } } }
mit
C#
13b3931d92ff2871eefe85ba9e5899acad95c48f
Update tests
LinqToDB4iSeries/linq2db,MaceWindu/linq2db,genusP/linq2db,lvaleriu/linq2db,linq2db/linq2db,lvaleriu/linq2db,MaceWindu/linq2db,ronnyek/linq2db,LinqToDB4iSeries/linq2db,genusP/linq2db,linq2db/linq2db,enginekit/linq2db
Tests/Linq/Data/RetryPolicyTest.cs
Tests/Linq/Data/RetryPolicyTest.cs
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using LinqToDB; using LinqToDB.Data; using NUnit.Framework; namespace Tests.Data { [TestFixture] public class RetryPolicyTest : TestBase { class Retry : IRetryPolicy { public int Count { get; private set; } public TResult Execute<TResult>(Func<TResult> operation) { Count++; try { return operation(); } catch { throw new RetryLimitExceededException(); } } public Task<TResult> ExecuteAsync<TResult>(Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default(CancellationToken)) { Count++; try { var res = operation(cancellationToken); res.Wait(cancellationToken); return res; } catch { throw new RetryLimitExceededException(); } } } public class FakeClass { } [Test, DataContextSource(false)] public void RetryPoliceTest(string context) { var ret = new Retry(); Assert.Throws<RetryLimitExceededException>(() => { using (var db = new DataConnection(context, ret)) { db.GetTable<FakeClass>().ToList(); } }); Assert.AreEqual(2, ret.Count); // 1 - open connection, 1 - execute command } [Test, DataContextSource(false)] public void RetryPoliceTestAsync(string context) { var ret = new Retry(); try { using (var db = new DataConnection(context, ret)) { var r = db.GetTable<FakeClass>().ToListAsync(); r.Wait(); } } catch (AggregateException ex) { Assert.IsNotNull(ex.InnerExceptions.OfType<RetryLimitExceededException>().Single()); } Assert.AreEqual(2, ret.Count); // 1 - open connection, 1 - execute command } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using LinqToDB; using LinqToDB.Data; using NUnit.Framework; namespace Tests.Data { [TestFixture] public class RetryPolicyTest : TestBase { class Retry : IRetryPolicy { public int Count { get; private set; } public TResult Execute<TResult>(Func<TResult> operation) { Count++; try { return operation(); } catch { throw new RetryLimitExceededException(); } } public Task<TResult> ExecuteAsync<TResult>(Func<CancellationToken, Task<TResult>> operation, CancellationToken cancellationToken = default(CancellationToken)) { Count++; try { var res = operation(cancellationToken); res.Wait(cancellationToken); return res; } catch { throw new RetryLimitExceededException(); } } } public class FakeClass { } [Test, DataContextSource(false)] public void RetryPoliceTest(string context) { var ret = new Retry(); Assert.Throws<RetryLimitExceededException>(() => { using (var db = new DataConnection(context, ret)) { db.GetTable<FakeClass>().ToList(); } }); Assert.AreEqual(1, ret.Count); } [Test, DataContextSource(false)] public void RetryPoliceTestAsync(string context) { var ret = new Retry(); try { using (var db = new DataConnection(context, ret)) { var r = db.GetTable<FakeClass>().ToListAsync(); r.Wait(); } } catch (AggregateException ex) { Assert.IsNotNull(ex.InnerExceptions.OfType<RetryLimitExceededException>().Single()); } Assert.AreEqual(1, ret.Count); } } }
mit
C#
34840513a1986efe28ff1bbca0a5e3560c1ce064
Add VariantEnd to GameStatus
ProgramFOX/Chess.NET
ChessDotNet/GameStatus.cs
ChessDotNet/GameStatus.cs
namespace ChessDotNet { public class GameStatus { public enum Events { Check, Checkmate, Stalemate, Draw, Custom, VariantEnd, // to be used for chess variants, which can be derived from ChessBoard None } public Events Event { get; private set; } public Players PlayerWhoCausedEvent { get; private set; } public string EventExplanation { get; private set; } public GameStatus(Events _event, Players whoCausedEvent, string eventExplanation) { Event = _event; PlayerWhoCausedEvent = whoCausedEvent; EventExplanation = eventExplanation; } } }
namespace ChessDotNet { public class GameStatus { public enum Events { Check, Checkmate, Stalemate, Draw, Custom, None } public Events Event { get; private set; } public Players PlayerWhoCausedEvent { get; private set; } public string EventExplanation { get; private set; } public GameStatus(Events _event, Players whoCausedEvent, string eventExplanation) { Event = _event; PlayerWhoCausedEvent = whoCausedEvent; EventExplanation = eventExplanation; } } }
mit
C#
4002f3e98b27d1a3c6af390b219ab13899e9eb54
make WpfFileStoreConfig as implementation of IMvxPluginConfiguration
Didux/MvvmCross-Plugins,lothrop/MvvmCross-Plugins,martijn00/MvvmCross-Plugins
File/MvvmCross.Plugins.File.Wpf/WpfFileStoreConfiguration.cs
File/MvvmCross.Plugins.File.Wpf/WpfFileStoreConfiguration.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cirrious.CrossCore.Plugins; namespace MvvmCross.Plugins.File.Wpf { public class WpfFileStoreConfiguration: IMvxPluginConfiguration { public string RootFolder { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MvvmCross.Plugins.File.Wpf { public class WpfFileStoreConfiguration { public string RootFolder { get; set; } } }
mit
C#
68b599fc96a4cf3b62b48abcc4708021767953cd
Update AssemblyInfo to reference Couchbase as owner / copyright
couchbaselabs/meep-meep
src/SharedAssemblyInfo.cs
src/SharedAssemblyInfo.cs
using System.Reflection; #if DEBUG [assembly: AssemblyProduct("MeepMeep (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("MeepMeep (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .NET client.")] [assembly: AssemblyCompany("Couchbase")] [assembly: AssemblyCopyright("Copyright © 2017 Couchbase")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.1.0.*")] [assembly: AssemblyFileVersion("0.1.0")]
using System.Runtime.InteropServices; using System.Reflection; #if DEBUG [assembly: AssemblyProduct("MeepMeep (Debug)")] [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyProduct("MeepMeep (Release)")] [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyDescription("MeepMeep - A super simple workload utility for the Couchbase .Net client.")] [assembly: AssemblyCompany("Daniel Wertheim")] [assembly: AssemblyCopyright("Copyright © 2013 Daniel Wertheim")] [assembly: AssemblyTrademark("")] [assembly: AssemblyVersion("0.1.0.*")] [assembly: AssemblyFileVersion("0.1.0")]
apache-2.0
C#
1791a853068fff01adff5cc448b19a5e1b6aef6e
Fix accidently pushed bug
feliwir/openSage,feliwir/openSage
src/OpenSage.Game/Network/Packets/SkirmishOrderPacket.cs
src/OpenSage.Game/Network/Packets/SkirmishOrderPacket.cs
using System.Collections.Generic; using OpenSage.Logic.Orders; namespace OpenSage.Network.Packets { public class SkirmishOrderPacket { public uint Frame { get; set; } public Order[] Orders { get; set; } } }
using System.Collections.Generic; using OpenSage.Logic.Orders; namespace OpenSage.Network.Packets { public class SkirmishOrderPacket { public uint Frame { get; set; } public List<Order> Orders { get; set; } } }
mit
C#
0867be327c2a2500e7f30f6c34eb2a96be414a7b
remove spaces
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/Shared/SocialMediaLinks.cshtml
src/StockportWebapp/Views/Shared/SocialMediaLinks.cshtml
@model IEnumerable<StockportWebapp.Models.SocialMediaLink> @inject StockportWebapp.Config.BusinessId BusinessId <div class="footer-social-links"> @{ var nameOfSite = ""; } @if (BusinessId.ToString() == "stockportgov") { nameOfSite = "stockport council"; } else if (BusinessId.ToString() == "healthystockport") { nameOfSite = "healthy stockport "; } @foreach (var socialMediaLink in Model) { string socialMediaCSS = socialMediaLink.Icon.Replace("fa-", "icon-"); <a href="@socialMediaLink.Url" aria-label="@socialMediaLink.ScreenReader"> <div class="icon-bordered icon-bordered-fixed icon-container icon-twitter @socialMediaCSS"> <span class="fa fab fa-2x @socialMediaLink.Icon"></span> </div> </a> } </div>
@model IEnumerable<StockportWebapp.Models.SocialMediaLink> @inject StockportWebapp.Config.BusinessId BusinessId <div class="footer-social-links"> @{ var nameOfSite = ""; } @if (BusinessId.ToString() == "stockportgov") { nameOfSite = "stockport council"; } else if (BusinessId.ToString() == "healthystockport") { nameOfSite = "healthy stockport "; } @foreach (var socialMediaLink in Model) { string socialMediaCSS = socialMediaLink.Icon.Replace("fa-", "icon-"); <a href="@socialMediaLink.Url" aria-label="@socialMediaLink.ScreenReader"> <div class="icon-bordered icon-bordered-fixed icon-container icon-twitter @socialMediaCSS"> <span class="fa fab fa-2x @socialMediaLink.Icon"></span> </div> </a> } </div>
mit
C#
17283a0844515e045329cf48b025aab5c4ab5059
Update catalog list item style
Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net,Jeffiy/ZBlog-Net
src/ZBlog/Views/Shared/Components/Catalog/Default.cshtml
src/ZBlog/Views/Shared/Components/Catalog/Default.cshtml
@model List<Catalog> <div class="am-panel-hd">Catalog</div> <div class="am-panel-bd"> @foreach (var catalog in Model) { <a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url"> @catalog.Title <span class="am-badge am-badge-success am-round">@catalog.Posts.Count()</span> </a> } </div>
@model List<Catalog> <div class="am-panel-hd">Catalog</div> <div class="am-panel-bd"> @foreach (var catalog in Model) { <a asp-controller="Home" asp-action="Catalog" asp-route-title="@catalog.Url"> @catalog.Title <span class="am-badge am-badge-secondary am-round">@catalog.Posts.Count()</span> </a> } </div>
mit
C#
a9afade3770d57ab9b7dc75b3a73a30ecc10a3a8
Update StringIsNotEmptyAttribute.cs
Gibe/Gibe.DittoProcessors
Gibe.DittoProcessors/Processors/StringIsNotEmptyAttribute.cs
Gibe.DittoProcessors/Processors/StringIsNotEmptyAttribute.cs
using System; namespace Gibe.DittoProcessors.Processors { public class StringIsNotNullOrEmptyAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() { if (Value == null) throw new NullReferenceException(); var stringValue = Value as string; return !String.IsNullOrEmpty(stringValue); } } }
using System; namespace Gibe.DittoProcessors.Processors { public class StringIsNotEmptyAttribute : TestableDittoProcessorAttribute { public override object ProcessValue() { if (Value == null) throw new NullReferenceException(); var stringValue = Value as string; return !String.IsNullOrEmpty(stringValue); } } }
mit
C#
39663ea43c1f58808b90119e3f1ed8df806bc8ff
Support for custom watch expressions
tmds/Tmds.DBus
Monitor.cs
Monitor.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]"); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); //custom match rules if (args.Length > 1) for (int i = 1 ; i != args.Length ; i++) bus.AddMatch (args[i]); while (true) { Message msg = conn.ReadMessage (); Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } Console.WriteLine (); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session]"); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); while (true) { Message msg = conn.ReadMessage (); Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } Console.WriteLine (); } } }
mit
C#
d8c7a16aa1e40bea247787ec8dc943449cc395bc
Return whether the target has any dispellable debuff
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Extensions/TorCharacterExtensions.cs
trunk/DefaultCombat/Extensions/TorCharacterExtensions.cs
using System.Collections.Generic; using System.Linq; using Buddy.Swtor.Objects; namespace DefaultCombat.Extensions { public static class TorCharacterExtensions { private static readonly IReadOnlyList<string> _dispellableDebuffs = new List<string> { "Hunting Trap", "Burning (Physical)" }; public static bool ShouldDispel(this TorCharacter target) { return target != null && _dispellableDebuffs.Any(target.HasDebuff); } } }
using Buddy.Swtor.Objects; namespace DefaultCombat.Extensions { public static class TorCharacterExtensions { public static bool ShouldDispel(this TorCharacter target, string debuffName) { if (target == null) return false; return target.HasDebuff(debuffName); } } }
apache-2.0
C#
3705dae4ea3df67300e9605661b1b391561683ec
simplify Console Trace Listener
lontivero/DreamBot,lontivero/vinchuca
ColorConsoleTraceListener.cs
ColorConsoleTraceListener.cs
using System; using System.Diagnostics; using System.Collections.Generic; namespace DreamBot { public class ColorConsoleTraceListener : ConsoleTraceListener { private static readonly Dictionary<TraceEventType, ConsoleColor> EventColor = new Dictionary<TraceEventType, ConsoleColor>(); static ColorConsoleTraceListener() { EventColor.Add(TraceEventType.Verbose, ConsoleColor.DarkGray); EventColor.Add(TraceEventType.Information, ConsoleColor.Gray); EventColor.Add(TraceEventType.Warning, ConsoleColor.Yellow); EventColor.Add(TraceEventType.Error, ConsoleColor.DarkRed); EventColor.Add(TraceEventType.Critical, ConsoleColor.Red); EventColor.Add(TraceEventType.Start, ConsoleColor.DarkCyan); EventColor.Add(TraceEventType.Stop, ConsoleColor.DarkCyan); } public ColorConsoleTraceListener(int identLevel) { _il = identLevel; } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { TraceEvent(eventCache, source, eventType, id, "{0}", message); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { IndentLevel = _il; IndentSize = 2; var originalColor = Console.ForegroundColor; Console.ForegroundColor = GetEventColor(eventType, originalColor); Console.Write("{0} {1}: ", source, eventType); Console.WriteLine(format, args); Console.ForegroundColor = originalColor; } private static ConsoleColor GetEventColor(TraceEventType eventType, ConsoleColor defaultColor) { return !EventColor.ContainsKey(eventType) ? defaultColor : EventColor[eventType]; } public int _il { get; set; } } }
using System; using System.Diagnostics; using System.Collections.Generic; namespace DreamBot { public class ColorConsoleTraceListener : ConsoleTraceListener { private static readonly Dictionary<TraceEventType, ConsoleColor> EventColor = new Dictionary<TraceEventType, ConsoleColor>(); static ColorConsoleTraceListener() { EventColor.Add(TraceEventType.Verbose, ConsoleColor.DarkGray); EventColor.Add(TraceEventType.Information, ConsoleColor.Gray); EventColor.Add(TraceEventType.Warning, ConsoleColor.Yellow); EventColor.Add(TraceEventType.Error, ConsoleColor.DarkRed); EventColor.Add(TraceEventType.Critical, ConsoleColor.Red); EventColor.Add(TraceEventType.Start, ConsoleColor.DarkCyan); EventColor.Add(TraceEventType.Stop, ConsoleColor.DarkCyan); } public ColorConsoleTraceListener(int identLevel) { _il = identLevel; } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string message) { TraceEvent(eventCache, source, eventType, id, "{0}", message); } public override void TraceEvent(TraceEventCache eventCache, string source, TraceEventType eventType, int id, string format, params object[] args) { IndentLevel = _il; IndentSize = 2; var originalColor = Console.ForegroundColor; Console.ForegroundColor = GetEventColor(eventType, originalColor); base.TraceEvent(eventCache, source, eventType, id, format, args); Console.ForegroundColor = originalColor; } private static ConsoleColor GetEventColor(TraceEventType eventType, ConsoleColor defaultColor) { return !EventColor.ContainsKey(eventType) ? defaultColor : EventColor[eventType]; } public int _il { get; set; } } }
mit
C#
d161a21265346b34a7949a79710e6676b5566c9c
Add link to game
TeamLeoTolstoy/Leo
Game/tempor/GameObject.cs
Game/tempor/GameObject.cs
//http://www.flasharcade.com/tower-defence-games/play/stalingrad-tower-defence.html using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tempor { public abstract class GameObject { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace tempor { public abstract class GameObject { } }
mit
C#
efdba516da6d515897929a64c345fbcecffadcae
Fix for QueueStart
Thundernerd/Unity3D-Automatron
Automatron/Assets/Automatron/Editor/Automations/System.cs
Automatron/Assets/Automatron/Editor/Automations/System.cs
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace TNRD.Automatron.Automations { #pragma warning disable 0649 [Automation( "System/Start" )] class QueueStart : Automation { private GUIStyle textStyle; public bool IsInitial { get; set; } public QueueStart() { } protected override void OnInitialize() { base.OnInitialize(); if ( IsInitial ) { showCloseButton = false; showInArrow = false; } } protected override void OnInitializeGUI() { CreateStyle(); } protected override void OnAfterSerialize() { base.OnAfterSerialize(); RunOnGUIThread( CreateStyle ); if ( IsInitial ) { showCloseButton = false; showInArrow = false; } } private void CreateStyle() { textStyle = new GUIStyle( EditorStyles.label ); textStyle.alignment = TextAnchor.MiddleCenter; textStyle.fontSize = 22; textStyle.fontStyle = FontStyle.Italic; } protected override void OnGUI() { base.OnGUI(); Size.x = 150; Size.y = 100; var rect = Rectangle; //rect.position += ( Window as AutomatronEditor ).Camera; GUI.Label( rect, "Entry Point", textStyle ); } public override IEnumerator Execute() { yield break; } } #pragma warning restore 0649 }
using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; namespace TNRD.Automatron.Automations { #pragma warning disable 0649 [Automation( "System/Start" )] class QueueStart : Automation { private GUIStyle textStyle; public QueueStart() : this( true ) { } public QueueStart( bool showCloseButton ) { this.showCloseButton = showCloseButton; showInArrow = showCloseButton; } protected override void OnInitializeGUI() { CreateStyle(); } protected override void OnAfterSerialize() { base.OnAfterSerialize(); RunOnGUIThread( CreateStyle ); } private void CreateStyle() { textStyle = new GUIStyle( EditorStyles.label ); textStyle.alignment = TextAnchor.MiddleCenter; textStyle.fontSize = 22; textStyle.fontStyle = FontStyle.Italic; } protected override void OnGUI() { base.OnGUI(); Size.x = 150; Size.y = 100; var rect = Rectangle; //rect.position += ( Window as AutomatronEditor ).Camera; GUI.Label( rect, "Entry Point", textStyle ); } public override IEnumerator Execute() { yield break; } } #pragma warning restore 0649 }
mit
C#
a16ce73c3708ce32d26c6c96db18c386ae39735b
Fix typos in TagJsonConverter.
peeedge/mobile,masterrr/mobile,ZhangLeiCharles/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,peeedge/mobile,eatskolnikov/mobile,eatskolnikov/mobile
Phoebe/Data/Json/Converters/TagJsonConverter.cs
Phoebe/Data/Json/Converters/TagJsonConverter.cs
using System; using System.Threading.Tasks; using Toggl.Phoebe.Data.DataObjects; namespace Toggl.Phoebe.Data.Json.Converters { public sealed class TagJsonConverter : BaseJsonConverter { public async Task<TagJson> Export (TagData data) { var workspaceIdTask = GetRemoteId<WorkspaceData> (data.WorkspaceId); return new TagJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt, Name = data.Name, WorkspaceId = await workspaceIdTask.ConfigureAwait (false), }; } private static async Task Merge (TagData data, TagJson json) { var workspaceIdTask = GetLocalId<WorkspaceData> (json.WorkspaceId); data.Name = json.Name; data.WorkspaceId = await workspaceIdTask.ConfigureAwait (false); MergeCommon (data, json); } public async Task<TagData> Import (TagJson json) { var data = await GetByRemoteId<TagData> (json.Id.Value).ConfigureAwait (false); // TODO: Should fall back to name lookup? if (json.DeletedAt.HasValue) { if (data != null) { await DataStore.DeleteAsync (data).ConfigureAwait (false); data = null; } } else if (data == null || data.ModifiedAt < json.ModifiedAt) { data = data ?? new TagData (); await Merge (data, json).ConfigureAwait (false); data = await DataStore.PutAsync (data).ConfigureAwait (false); } return data; } } }
using System; using System.Threading.Tasks; using Toggl.Phoebe.Data.DataObjects; namespace Toggl.Phoebe.Data.Json.Converters { public sealed class TagJsonConverter : BaseJsonConverter { public async Task<TagJson> ToJsonAsync (TagData data) { var workspaceIdTask = GetRemoteId<WorkspaceData> (data.WorkspaceId); return new TagJson () { Id = data.RemoteId, ModifiedAt = data.ModifiedAt, Name = data.Name, WorkspaceId = await workspaceIdTask.ConfigureAwait (false), }; } private static async Task Merge (TagData data, TagJson json) { var workspaceIdTask = GetLocalId<WorkspaceData> (json.WorkspaceId); data.Name = json.Name; data.WorkspaceId = await workspaceIdTask.ConfigureAwait (false); MergeCommon (data, json); } public static async Task<TagData> Import (TagJson json) { var data = await GetByRemoteId<TagData> (json.Id.Value).ConfigureAwait (false); // TODO: Should fall back to name lookup? if (json.DeletedAt.HasValue) { if (data != null) { await DataStore.DeleteAsync (data).ConfigureAwait (false); data = null; } } else if (data == null || data.ModifiedAt < json.ModifiedAt) { data = data ?? new TagData (); await Merge (data, json).ConfigureAwait (false); data = await DataStore.PutAsync (data).ConfigureAwait (false); } return data; } } }
bsd-3-clause
C#
fe041ae55f1dff70995f725ce22347cf8c47b707
Fix borked rejex
ArcticEcho/Hatman
Hatman/Commands/Should.cs
Hatman/Commands/Should.cs
using System.Text.RegularExpressions; using ChatExchangeDotNet; namespace Hatman.Commands { class Should : ICommand { private readonly Regex ptn = new Regex(@"(?i)^((sh|[cw])ould|can|are|did|will|is|has|does|do).*\?", Extensions.RegOpts); private readonly string[] phrases = new[] { "No.", "Yes.", "Yup.", "Nope.", "Indubitably", "Never. Ever. *EVER*.", "I'll tell ya, only if I get my coffee.", "Nah.", "Ask The Skeet.", "... do I look like I know everything?", "Ask me no questions, and I shall tell no lies.", "Sure, when it rains imaginary internet points.", "Yeah.", "Ofc.", "NOOOOOOOOOOOOOOOO", "Sure..." }; public Regex CommandPattern { get { return ptn; } } public string Description { get { return "Decides whether or not something should happen."; } } public string Usage { get { return "(sh|[wc])ould|will|did and many words alike"; } } public void ProcessMessage(Message msg, ref Room rm) { rm.PostReplyFast(msg, phrases.PickRandom()); } } }
using System.Text.RegularExpressions; using ChatExchangeDotNet; namespace Hatman.Commands { class Should : ICommand { private readonly Regex ptn = new Regex(@"(?i)^(sh|[cw])ould|can|are|did|will|is|has|does|do).*\?", Extensions.RegOpts); private readonly string[] phrases = new[] { "No.", "Yes.", "Yup.", "Nope.", "Indubitably", "Never. Ever. *EVER*.", "I'll tell ya, only if I get my coffee.", "Nah.", "Ask The Skeet.", "... do I look like I know everything?", "Ask me no questions, and I shall tell no lies.", "Sure, when it rains imaginary internet points.", "Yeah.", "Ofc.", "NOOOOOOOOOOOOOOOO", "Sure..." }; public Regex CommandPattern { get { return ptn; } } public string Description { get { return "Decides whether or not something should happen."; } } public string Usage { get { return "(sh|[wc])ould|will|did and many words alike"; } } public void ProcessMessage(Message msg, ref Room rm) { rm.PostReplyFast(msg, phrases.PickRandom()); } } }
isc
C#
20c4a6ffcc734f8be8d7596c11cb35735c5767c5
Allow empty enumerables in MinBy/MaxBy
ygra/Diablo3ItemCollage,ygra/Diablo3ItemCollage
ItemCollage/Extensions.cs
ItemCollage/Extensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace ItemCollage { public static class Extensions { private static IEnumerable<KeyValuePair<TVal, TMapped>> MapSortBy<TVal, TMapped>( this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.Select(o => new KeyValuePair<TVal, TMapped>(o, selector(o))) .OrderBy(a => a.Value); } public static TVal MaxBy<TVal, TMapped>(this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.MapSortBy(selector).LastOrDefault().Key; } public static TVal MinBy<TVal, TMapped>(this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.MapSortBy(selector).FirstOrDefault().Key; } public static bool IsBlackAt(this Bitmap b, int x, int y) { if (x < 0 || y < 0 || x >= b.Width || y >= b.Height) return false; Color c = b.GetPixel(x, y); return c.R == 0 && c.G == 0 && c.B == 0; } public class FuncEqualityComparer<TSource, TResult> : EqualityComparer<TSource> { Func<TSource, TResult> func; public FuncEqualityComparer(Func<TSource, TResult> func) { this.func = func; } public override bool Equals(TSource x, TSource y) { return func(x).Equals(func(y)); } public override int GetHashCode(TSource obj) { return func(obj).GetHashCode(); } } public static IEnumerable<TSource> Distinct<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> func) { return source.Distinct(new FuncEqualityComparer<TSource, TResult>(func)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace ItemCollage { public static class Extensions { private static IEnumerable<KeyValuePair<TVal, TMapped>> MapSortBy<TVal, TMapped>( this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.Select(o => new KeyValuePair<TVal, TMapped>(o, selector(o))) .OrderBy(a => a.Value); } public static TVal MaxBy<TVal, TMapped>(this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.MapSortBy(selector).Last().Key; } public static TVal MinBy<TVal, TMapped>(this IEnumerable<TVal> source, Func<TVal, TMapped> selector) { return source.MapSortBy(selector).First().Key; } public static bool IsBlackAt(this Bitmap b, int x, int y) { if (x < 0 || y < 0 || x >= b.Width || y >= b.Height) return false; Color c = b.GetPixel(x, y); return c.R == 0 && c.G == 0 && c.B == 0; } public class FuncEqualityComparer<TSource, TResult> : EqualityComparer<TSource> { Func<TSource, TResult> func; public FuncEqualityComparer(Func<TSource, TResult> func) { this.func = func; } public override bool Equals(TSource x, TSource y) { return func(x).Equals(func(y)); } public override int GetHashCode(TSource obj) { return func(obj).GetHashCode(); } } public static IEnumerable<TSource> Distinct<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> func) { return source.Distinct(new FuncEqualityComparer<TSource, TResult>(func)); } } }
mit
C#
4362752ad8e976bb4e3e4c7304655b07466935e7
Prepare for release 1.0.0.
SolinkCorp/Solink.AddIn.Helpers
Solink.AddIn.Helpers/Properties/AssemblyInfo.cs
Solink.AddIn.Helpers/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("Solink.AddIn.Helpers")] [assembly: AssemblyDescription("A class library to help with System.AddIn")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Solink Corporation")] [assembly: AssemblyProduct("Solink.AddIn.Helpers")] [assembly: AssemblyCopyright("Copyright © Solink Corporation 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("956b811b-1344-406d-bed3-6458e51c358a")] // 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")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0" /*+ "-SNAPSHOT" */)] [assembly: InternalsVisibleTo("Solink.AddIn.Helpers.Test")]
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("Solink.AddIn.Helpers")] [assembly: AssemblyDescription("A class library to help with System.AddIn")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Solink Corporation")] [assembly: AssemblyProduct("Solink.AddIn.Helpers")] [assembly: AssemblyCopyright("Copyright © Solink Corporation 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("956b811b-1344-406d-bed3-6458e51c358a")] // 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")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0" + "-SNAPSHOT")] [assembly: InternalsVisibleTo("Solink.AddIn.Helpers.Test")]
mit
C#
767668711b7c1344d6b2e35ba78b841bd418c535
Fix integration tests
ASP-NET-MVC-Boilerplate/Templates,ASP-NET-MVC-Boilerplate/Templates
Source/GraphQLTemplate/Tests/GraphQLTemplate.IntegrationTest/QueryTest.cs
Source/GraphQLTemplate/Tests/GraphQLTemplate.IntegrationTest/QueryTest.cs
namespace GraphQLTemplate.IntegrationTest.Controllers { using System.Net; using System.Net.Http; using System.Threading.Tasks; using GraphQLTemplate.IntegrationTest.Constants; using GraphQLTemplate.IntegrationTest.Models; using Xunit; using Xunit.Abstractions; public class QueryTest : CustomWebApplicationFactory<Startup> { private readonly HttpClient client; public QueryTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => this.client = this.CreateClient(); [Fact(Skip = "TODO: Fix tests")] public async Task IntrospectionQuery_Default_Returns200OkAsync() { var response = await this.client.PostGraphQLAsync(GraphQlQuery.Introspection).ConfigureAwait(false); var graphQlResponse = await response.Content.ReadAsAsync<GraphQLResponse>().ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(graphQlResponse.Errors); } } }
namespace GraphQLTemplate.IntegrationTest.Controllers { using System.Net; using System.Net.Http; using System.Threading.Tasks; using GraphQLTemplate.IntegrationTest.Constants; using GraphQLTemplate.IntegrationTest.Models; using Xunit; using Xunit.Abstractions; public class QueryTest : CustomWebApplicationFactory<Startup> { private readonly HttpClient client; public QueryTest(ITestOutputHelper testOutputHelper) : base(testOutputHelper) => this.client = this.CreateClient(); [Fact] public async Task IntrospectionQuery_Default_Returns200OkAsync() { var response = await this.client.PostGraphQLAsync(GraphQlQuery.Introspection).ConfigureAwait(false); var graphQlResponse = await response.Content.ReadAsAsync<GraphQLResponse>().ConfigureAwait(false); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Empty(graphQlResponse.Errors); } } }
mit
C#
76129871147d2471d1c76f687b7486fd84ae93e1
add submite to ijourneyclient
MiXTelematics/MiX.Integrate.Api.Client
MiX.Integrate.API.Client/Journeys/IJourneysClient.cs
MiX.Integrate.API.Client/Journeys/IJourneysClient.cs
using System.Threading.Tasks; using System.Collections.Generic; using MiX.Integrate.Shared.Entities.Journeys; using MiX.Integrate.Api.Client.Base; namespace MiX.Integrate.Api.Client.Journeys { public interface IJourneysClient : IBaseClient { Journey GetJourney(long journeyId); Task<Journey> GetJourneyAsync(long journeyId); long AddJourney(CreateJourney newjourney); Task<long> AddJourneyAsync(CreateJourney newjourney); List<Route> GetRouteList(long groupId); Task<List<Route>> GetRouteListAsync(long groupId); AutomatedMonitoring GetJourneyProgress(long journeyId); Task<AutomatedMonitoring> GetJourneyProgressAsync(long journeyId); List<JourneyInProgressCurrentStatus> GetJourneyInProgressCurrentStatus(long groupId); Task<List<JourneyInProgressCurrentStatus>> GetJourneyInProgressCurrentStatusAsync(long groupId); Task<List<JourneyRouteLocation>> GetJourneyRouteLocationsAsync(long journeyId); Task<bool> RemoveJourneyAsync(long journeyId); Task<bool> UpdateJourneyAssetDriversAsync(long journeyId, List<JourneyAssetDriver> journeyAssetDriver); Task<List<JourneyAssetDriver>> GetJourneyAssetsAndDriversAsync(long journeyId); List<JourneyAssetDriver> GetJourneyAssetsAndDrivers(long journeyId); bool UpdateJourneyAssetDrivers(long journeyId, List<JourneyAssetDriver> journeyAssetDriver); bool RemoveJourney(long journeyId); List<JourneyRouteLocation> GetJourneyRouteLocations(long journeyId); Task<bool> SubmitJourneyAsync(long journeyId); bool SubmitJourney(long journeyId); } }
using System.Threading.Tasks; using System.Collections.Generic; using MiX.Integrate.Shared.Entities.Journeys; using MiX.Integrate.Api.Client.Base; namespace MiX.Integrate.Api.Client.Journeys { public interface IJourneysClient : IBaseClient { Journey GetJourney(long journeyId); Task<Journey> GetJourneyAsync(long journeyId); long AddJourney(CreateJourney newjourney); Task<long> AddJourneyAsync(CreateJourney newjourney); List<Route> GetRouteList(long groupId); Task<List<Route>> GetRouteListAsync(long groupId); AutomatedMonitoring GetJourneyProgress(long journeyId); Task<AutomatedMonitoring> GetJourneyProgressAsync(long journeyId); List<JourneyInProgressCurrentStatus> GetJourneyInProgressCurrentStatus(long groupId); Task<List<JourneyInProgressCurrentStatus>> GetJourneyInProgressCurrentStatusAsync(long groupId); Task<List<JourneyRouteLocation>> GetJourneyRouteLocationsAsync(long journeyId); Task<bool> RemoveJourneyAsync(long journeyId); Task<bool> UpdateJourneyAssetDriversAsync(long journeyId, List<JourneyAssetDriver> journeyAssetDriver); Task<List<JourneyAssetDriver>> GetJourneyAssetsAndDriversAsync(long journeyId); List<JourneyAssetDriver> GetJourneyAssetsAndDrivers(long journeyId); bool UpdateJourneyAssetDrivers(long journeyId, List<JourneyAssetDriver> journeyAssetDriver); bool RemoveJourney(long journeyId); List<JourneyRouteLocation> GetJourneyRouteLocations(long journeyId); } }
mit
C#
bc1fed2dbd569237546d7cdd599d10545eaa18c3
clean up random seed generation
bpowers/Raft.NET
Program.cs
Program.cs
// Copyright 2017 Bobby Powers. All rights reserved. // Use of this source code is governed by the ISC // license that can be found in the LICENSE file. namespace Raft { using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; class Program { static IDictionary<PeerId, KeyValueStore<int>> peers = new Dictionary<PeerId, KeyValueStore<int>>(); static Task<IPeerResponse> HandlePeerRpc(PeerId peer, IPeerRequest request) { return peers[peer].Server.HandlePeerRpc(request); } static int RandomInt32(RandomNumberGenerator rng) { var bytes = new byte[4]; rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } static IDictionary<PeerId, int> GenerateRandomSeeds(List<PeerId> peerIds) { using (var rng = RandomNumberGenerator.Create()) { return peerIds.ToDictionary(p => p, p => RandomInt32(rng)); } } static async Task Main(string[] args) { var peerIds = new List<PeerId>() { new PeerId(1), new PeerId(2), new PeerId(3), }; var config = new Config() { Peers = peerIds, PrngSeed = GenerateRandomSeeds(peerIds), PeerRpcDelegate = HandlePeerRpc, }; peers = peerIds.ToDictionary(id => id, id => new KeyValueStore<int>(id, config)); await Task.WhenAll(peers.Values.Select(async (peer) => await peer.Init()).ToArray()); Console.WriteLine("All peers initialized."); await Task.Delay(Timeout.Infinite); } } }
// Copyright 2017 Bobby Powers. All rights reserved. // Use of this source code is governed by the ISC // license that can be found in the LICENSE file. namespace Raft { using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Threading; using System.Threading.Tasks; class Program { static IDictionary<PeerId, KeyValueStore<int>> peers = new Dictionary<PeerId, KeyValueStore<int>>(); static Task<IPeerResponse> HandlePeerRpc(PeerId peer, IPeerRequest request) { return peers[peer].Server.HandlePeerRpc(request); } static int RandomInt32(RandomNumberGenerator rng) { var bytes = new byte[4]; rng.GetBytes(bytes); return BitConverter.ToInt32(bytes, 0); } static async Task Main(string[] args) { var peerIds = new List<PeerId>() { new PeerId(1), new PeerId(2), new PeerId(3), }; var rng = RandomNumberGenerator.Create(); var seeds = peerIds.ToDictionary(p => p, p => RandomInt32(rng)); rng.Dispose(); rng = null; var config = new Config() { Peers = peerIds, PrngSeed = seeds, PeerRpcDelegate = HandlePeerRpc, }; peers = peerIds.ToDictionary(id => id, id => new KeyValueStore<int>(id, config)); await Task.WhenAll(peers.Values.Select(async (peer) => await peer.Init()).ToArray()); Console.WriteLine("All peers initialized."); await Task.Delay(Timeout.Infinite); } } }
isc
C#
086810a701f97ef95fb88055e8bb4e3afe13cadd
Document some offsets in 0x67
HelloKitty/Booma.Proxy
src/Booma.Packet.Game/Block/Payloads/Server/BlockLobbyJoinEventPayload.cs
src/Booma.Packet.Game/Block/Payloads/Server/BlockLobbyJoinEventPayload.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Packet sent to the client telling it to join a lobby. /// </summary> [WireDataContract] [GameServerPacketPayload(GameNetworkOperationCode.LOBBY_JOIN_TYPE)] public sealed class BlockLobbyJoinEventPayload : PSOBBGamePacketPayloadServer { //TODO: We can't currently handle this packet. It does something odd the serializer can't handle /// <summary> /// The ID granted to the client that is joining the lobby. /// 0x08 /// </summary> [WireMember(1)] public byte ClientId { get; } //TODO: What is this? /// <summary> /// 0x09 /// </summary> [WireMember(2)] public byte LeaderId { get; } //Why is this in some of the packets? /// <summary> /// 0x0A /// </summary> [WireMember(3)] private byte One { get; } //Why is this sent? Shouldn't we be in the same lobby? /// <summary> /// The number of the lobby being joined. /// 0x0B /// </summary> [WireMember(4)] public byte LobbyNumber { get; } //Once again, why is this sent? Shouldn't we know what block we're in? /// <summary> /// The number of the block. /// 0x0C /// </summary> [WireMember(5)] public short BlockNumber { get; } //TODO: What is this for? /// <summary> /// 0x0E /// </summary> [WireMember(6)] public short EventId { get; } //Sylverant lists this as padding. [WireMember(7)] private int Padding { get; } //TODO: There is more to the packet here: https://github.com/Sylverant/ship_server/blob/b3bffc84b558821ca2002775ab2c3af5c6dde528/src/packets.h#L517 [ReadToEnd] [WireMember(10)] public CharacterJoinData[] LobbyCharacterData { get; } private BlockLobbyJoinEventPayload() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using FreecraftCore.Serializer; namespace Booma.Proxy { /// <summary> /// Packet sent to the client telling it to join a lobby. /// </summary> [WireDataContract] [GameServerPacketPayload(GameNetworkOperationCode.LOBBY_JOIN_TYPE)] public sealed class BlockLobbyJoinEventPayload : PSOBBGamePacketPayloadServer { //TODO: We can't currently handle this packet. It does something odd the serializer can't handle /// <summary> /// The ID granted to the client that is joining the lobby. /// </summary> [WireMember(1)] public byte ClientId { get; } //TODO: What is this? [WireMember(2)] public byte LeaderId { get; } //Why is this in some of the packets? [WireMember(3)] private byte One { get; } //Why is this sent? Shouldn't we be in the same lobby? /// <summary> /// The number of the lobby being joined. /// </summary> [WireMember(4)] public byte LobbyNumber { get; } //Once again, why is this sent? Shouldn't we know what block we're in? /// <summary> /// The number of the block. /// </summary> [WireMember(5)] public short BlockNumber { get; } //TODO: What is this for? [WireMember(6)] public short EventId { get; } //Sylverant lists this as padding. [WireMember(7)] private int Padding { get; } //TODO: There is more to the packet here: https://github.com/Sylverant/ship_server/blob/b3bffc84b558821ca2002775ab2c3af5c6dde528/src/packets.h#L517 [ReadToEnd] [WireMember(10)] public CharacterJoinData[] LobbyCharacterData { get; } private BlockLobbyJoinEventPayload() { } } }
agpl-3.0
C#
894e90f485bd7c024e19152154d75e51c8883c83
Use new ActionLink extension method.
fortunearterial/Orchard,huoxudong125/Orchard,JRKelso/Orchard,li0803/Orchard,qt1/Orchard,qt1/Orchard,brownjordaninternational/OrchardCMS,Serlead/Orchard,SeyDutch/Airbrush,dmitry-urenev/extended-orchard-cms-v10.1,sfmskywalker/Orchard,alejandroaldana/Orchard,Fogolan/OrchardForWork,cooclsee/Orchard,aaronamm/Orchard,dcinzona/Orchard,emretiryaki/Orchard,aaronamm/Orchard,Fogolan/OrchardForWork,cooclsee/Orchard,qt1/Orchard,Ermesx/Orchard,bedegaming-aleksej/Orchard,geertdoornbos/Orchard,TalaveraTechnologySolutions/Orchard,Ermesx/Orchard,vairam-svs/Orchard,abhishekluv/Orchard,yersans/Orchard,fassetar/Orchard,rtpHarry/Orchard,SouleDesigns/SouleDesigns.Orchard,jimasp/Orchard,jagraz/Orchard,jtkech/Orchard,xiaobudian/Orchard,johnnyqian/Orchard,RoyalVeterinaryCollege/Orchard,vairam-svs/Orchard,hannan-azam/Orchard,Serlead/Orchard,yonglehou/Orchard,jersiovic/Orchard,escofieldnaxos/Orchard,jimasp/Orchard,SouleDesigns/SouleDesigns.Orchard,mvarblow/Orchard,geertdoornbos/Orchard,abhishekluv/Orchard,TalaveraTechnologySolutions/Orchard,xkproject/Orchard,rtpHarry/Orchard,huoxudong125/Orchard,Sylapse/Orchard.HttpAuthSample,alejandroaldana/Orchard,Lombiq/Orchard,vairam-svs/Orchard,kouweizhong/Orchard,jtkech/Orchard,Fogolan/OrchardForWork,Ermesx/Orchard,li0803/Orchard,openbizgit/Orchard,Codinlab/Orchard,brownjordaninternational/OrchardCMS,Dolphinsimon/Orchard,jtkech/Orchard,tobydodds/folklife,armanforghani/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,rtpHarry/Orchard,jagraz/Orchard,yonglehou/Orchard,SeyDutch/Airbrush,JRKelso/Orchard,kouweizhong/Orchard,TaiAivaras/Orchard,AdvantageCS/Orchard,hannan-azam/Orchard,neTp9c/Orchard,johnnyqian/Orchard,openbizgit/Orchard,hbulzy/Orchard,vairam-svs/Orchard,mvarblow/Orchard,huoxudong125/Orchard,huoxudong125/Orchard,neTp9c/Orchard,JRKelso/Orchard,openbizgit/Orchard,yersans/Orchard,Lombiq/Orchard,dburriss/Orchard,mvarblow/Orchard,bedegaming-aleksej/Orchard,LaserSrl/Orchard,jimasp/Orchard,jtkech/Orchard,yonglehou/Orchard,ehe888/Orchard,AdvantageCS/Orchard,jersiovic/Orchard,AdvantageCS/Orchard,omidnasri/Orchard,Ermesx/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,phillipsj/Orchard,johnnyqian/Orchard,johnnyqian/Orchard,jtkech/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,jersiovic/Orchard,Serlead/Orchard,Dolphinsimon/Orchard,planetClaire/Orchard-LETS,rtpHarry/Orchard,escofieldnaxos/Orchard,RoyalVeterinaryCollege/Orchard,xiaobudian/Orchard,grapto/Orchard.CloudBust,LaserSrl/Orchard,spraiin/Orchard,hbulzy/Orchard,dcinzona/Orchard,cooclsee/Orchard,kgacova/Orchard,sfmskywalker/Orchard,omidnasri/Orchard,spraiin/Orchard,li0803/Orchard,RoyalVeterinaryCollege/Orchard,Sylapse/Orchard.HttpAuthSample,rtpHarry/Orchard,LaserSrl/Orchard,abhishekluv/Orchard,geertdoornbos/Orchard,SouleDesigns/SouleDesigns.Orchard,sfmskywalker/Orchard,brownjordaninternational/OrchardCMS,hannan-azam/Orchard,spraiin/Orchard,Sylapse/Orchard.HttpAuthSample,jagraz/Orchard,jchenga/Orchard,IDeliverable/Orchard,bedegaming-aleksej/Orchard,TalaveraTechnologySolutions/Orchard,TaiAivaras/Orchard,jchenga/Orchard,Lombiq/Orchard,Sylapse/Orchard.HttpAuthSample,spraiin/Orchard,AdvantageCS/Orchard,abhishekluv/Orchard,bedegaming-aleksej/Orchard,ehe888/Orchard,armanforghani/Orchard,IDeliverable/Orchard,tobydodds/folklife,fassetar/Orchard,Lombiq/Orchard,grapto/Orchard.CloudBust,hannan-azam/Orchard,emretiryaki/Orchard,jagraz/Orchard,yersans/Orchard,jagraz/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,dcinzona/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,OrchardCMS/Orchard,IDeliverable/Orchard,gcsuk/Orchard,neTp9c/Orchard,bedegaming-aleksej/Orchard,fortunearterial/Orchard,Serlead/Orchard,omidnasri/Orchard,cooclsee/Orchard,SzymonSel/Orchard,omidnasri/Orchard,emretiryaki/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,Fogolan/OrchardForWork,TalaveraTechnologySolutions/Orchard,mvarblow/Orchard,infofromca/Orchard,xkproject/Orchard,emretiryaki/Orchard,jimasp/Orchard,omidnasri/Orchard,li0803/Orchard,omidnasri/Orchard,infofromca/Orchard,kgacova/Orchard,grapto/Orchard.CloudBust,planetClaire/Orchard-LETS,dburriss/Orchard,Dolphinsimon/Orchard,cooclsee/Orchard,hbulzy/Orchard,jchenga/Orchard,sfmskywalker/Orchard,dcinzona/Orchard,TalaveraTechnologySolutions/Orchard,phillipsj/Orchard,phillipsj/Orchard,LaserSrl/Orchard,OrchardCMS/Orchard,dburriss/Orchard,TaiAivaras/Orchard,aaronamm/Orchard,armanforghani/Orchard,li0803/Orchard,ehe888/Orchard,Dolphinsimon/Orchard,TaiAivaras/Orchard,kouweizhong/Orchard,IDeliverable/Orchard,tobydodds/folklife,sfmskywalker/Orchard,SzymonSel/Orchard,geertdoornbos/Orchard,sfmskywalker/Orchard-Off-The-Grid-Sample-Code,SeyDutch/Airbrush,openbizgit/Orchard,fassetar/Orchard,Dolphinsimon/Orchard,qt1/Orchard,TalaveraTechnologySolutions/Orchard,emretiryaki/Orchard,Codinlab/Orchard,Codinlab/Orchard,huoxudong125/Orchard,planetClaire/Orchard-LETS,escofieldnaxos/Orchard,yersans/Orchard,TalaveraTechnologySolutions/Orchard,SzymonSel/Orchard,hbulzy/Orchard,sfmskywalker/Orchard,alejandroaldana/Orchard,AdvantageCS/Orchard,armanforghani/Orchard,brownjordaninternational/OrchardCMS,kouweizhong/Orchard,yersans/Orchard,OrchardCMS/Orchard,brownjordaninternational/OrchardCMS,tobydodds/folklife,escofieldnaxos/Orchard,fortunearterial/Orchard,grapto/Orchard.CloudBust,planetClaire/Orchard-LETS,ehe888/Orchard,gcsuk/Orchard,xiaobudian/Orchard,geertdoornbos/Orchard,OrchardCMS/Orchard,Sylapse/Orchard.HttpAuthSample,xiaobudian/Orchard,kgacova/Orchard,sfmskywalker/Orchard,kouweizhong/Orchard,tobydodds/folklife,xkproject/Orchard,neTp9c/Orchard,SzymonSel/Orchard,LaserSrl/Orchard,qt1/Orchard,hbulzy/Orchard,OrchardCMS/Orchard,Codinlab/Orchard,openbizgit/Orchard,RoyalVeterinaryCollege/Orchard,aaronamm/Orchard,Praggie/Orchard,SeyDutch/Airbrush,Praggie/Orchard,kgacova/Orchard,infofromca/Orchard,hannan-azam/Orchard,tobydodds/folklife,jersiovic/Orchard,planetClaire/Orchard-LETS,vairam-svs/Orchard,SzymonSel/Orchard,SouleDesigns/SouleDesigns.Orchard,phillipsj/Orchard,fassetar/Orchard,yonglehou/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,fortunearterial/Orchard,johnnyqian/Orchard,jimasp/Orchard,mvarblow/Orchard,dcinzona/Orchard,jchenga/Orchard,abhishekluv/Orchard,kgacova/Orchard,Praggie/Orchard,gcsuk/Orchard,dburriss/Orchard,omidnasri/Orchard,Praggie/Orchard,JRKelso/Orchard,jchenga/Orchard,grapto/Orchard.CloudBust,fortunearterial/Orchard,Praggie/Orchard,TalaveraTechnologySolutions/Orchard,Lombiq/Orchard,ehe888/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,RoyalVeterinaryCollege/Orchard,JRKelso/Orchard,omidnasri/Orchard,Codinlab/Orchard,spraiin/Orchard,alejandroaldana/Orchard,infofromca/Orchard,yonglehou/Orchard,neTp9c/Orchard,xkproject/Orchard,jersiovic/Orchard,abhishekluv/Orchard,aaronamm/Orchard,Serlead/Orchard,xkproject/Orchard,alejandroaldana/Orchard,SouleDesigns/SouleDesigns.Orchard,SeyDutch/Airbrush,gcsuk/Orchard,Ermesx/Orchard,armanforghani/Orchard,escofieldnaxos/Orchard,gcsuk/Orchard,phillipsj/Orchard,grapto/Orchard.CloudBust,infofromca/Orchard,fassetar/Orchard,sfmskywalker/Orchard,omidnasri/Orchard,TaiAivaras/Orchard,dburriss/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,xiaobudian/Orchard
src/Orchard.Web/Modules/Orchard.Lists/Views/Parts.Container.Manage.cshtml
src/Orchard.Web/Modules/Orchard.Lists/Views/Parts.Container.Manage.cshtml
@using Orchard.ContentManagement.MetaData.Models @{ var containerId = (int) Model.ContainerId; var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes; } <div class="item-properties actions"> <p> @Html.ActionLink(T("{0} Properties", (string)Model.ContainerDisplayName), "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl }) </p> </div> <div class="manage"> @if (itemContentTypes.Any()) { foreach (var contentType in itemContentTypes) { @Html.ActionLink(T("New {0}", contentType.DisplayName), "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" }) } } else { @Html.ActionLink(T("New Content"), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" }) } <a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a> </div>
@using Orchard.ContentManagement.MetaData.Models @{ var containerId = (int) Model.ContainerId; var itemContentTypes = (IList<ContentTypeDefinition>)Model.ItemContentTypes; } <div class="item-properties actions"> <p> @Html.ActionLink(T("{0} Properties", Html.Raw((string)Model.ContainerDisplayName)).Text, "Edit", new { Area = "Contents", Id = (int)Model.ContainerId, ReturnUrl = Html.ViewContext.HttpContext.Request.RawUrl }) </p> </div> <div class="manage"> @if (itemContentTypes.Any()) { foreach (var contentType in itemContentTypes) { @Html.ActionLink(T("New {0}", Html.Raw(contentType.DisplayName)).Text, "Create", "Admin", new { area = "Contents", id = contentType.Name, containerId }, new { @class = "button primaryAction create-content" }) } } else { @Html.ActionLink(T("New Content").ToString(), "Create", "Admin", new { area = "Contents", containerId }, new { @class = "button primaryAction create-content" }) } <a id="chooseItems" href="#" class="button primaryAction">@T("Choose Items")</a> </div>
bsd-3-clause
C#
2628ecf9e85c8122042d1d7726d034220d29d9bf
Fix exclusiveTrack threading and disposal issues
ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,naoey/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,RedNesto/osu-framework,smoogipooo/osu-framework,RedNesto/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,default0/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,default0/osu-framework,ppy/osu-framework
osu.Framework/Audio/Track/TrackManager.cs
osu.Framework/Audio/Track/TrackManager.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Linq; using osu.Framework.IO.Stores; using System; namespace osu.Framework.Audio.Track { public class TrackManager : AudioCollectionManager<Track> { IResourceStore<byte[]> store; private Track exclusiveTrack; private object exclusiveMutex = new object(); public TrackManager(IResourceStore<byte[]> store) { this.store = store; } public Track Get(string name) { TrackBass track = new TrackBass(store.GetStream(name)); AddItem(track); return track; } /// <summary> /// Specify an AudioTrack which should get exclusive playback over everything else. /// Will pause all other tracks and throw away any existing exclusive track. /// </summary> public void SetExclusive(Track track) { if (track == null) throw new ArgumentNullException(nameof(track)); Track last; lock (exclusiveMutex) { if (exclusiveTrack == track) return; last = exclusiveTrack; exclusiveTrack = track; } PendingActions.Enqueue(() => { foreach (var item in Items) if (!item.HasCompleted) item.Stop(); last?.Dispose(); AddItem(track); }); } public override void Update() { if (exclusiveTrack?.HasCompleted != false) lock (exclusiveMutex) // We repeat the if-check inside the lock to make sure exclusiveTrack // has not been overwritten prior to us taking the lock. if (exclusiveTrack?.HasCompleted != false) exclusiveTrack = Items.FirstOrDefault(); base.Update(); } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Linq; using osu.Framework.IO.Stores; using System; namespace osu.Framework.Audio.Track { public class TrackManager : AudioCollectionManager<Track> { IResourceStore<byte[]> store; Track exclusiveTrack; public TrackManager(IResourceStore<byte[]> store) { this.store = store; } public Track Get(string name) { TrackBass track = new TrackBass(store.GetStream(name)); AddItem(track); return track; } /// <summary> /// Specify an AudioTrack which should get exclusive playback over everything else. /// Will pause all other tracks and throw away any existing exclusive track. /// </summary> public void SetExclusive(Track track) { if (track == null) throw new ArgumentNullException(nameof(track)); if (exclusiveTrack == track) return; var last = exclusiveTrack; PendingActions.Enqueue(() => { foreach (var item in Items) item.Stop(); if (last != null) { Items.Remove(last); last.Dispose(); } }); AddItem(track); PendingActions.Enqueue(() => exclusiveTrack = track); } public override void Update() { base.Update(); if (exclusiveTrack?.HasCompleted != false) exclusiveTrack = Items.FirstOrDefault(); } } }
mit
C#
2b89993a031d5d8e8d262ed4b994b06e9c67c0ab
Change accessibility levels of science container object
Kerbas-ad-astra/Orbital-Science,DMagic1/Orbital-Science
Source/DMScienceContainer.cs
Source/DMScienceContainer.cs
#region license /* DMagic Orbital Science - DMScienceContainer * Object to store experiment properties * * Copyright (c) 2014, David Grandy <david.grandy@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #endregion namespace DMagic { public class DMScienceContainer { private int sitMask, bioMask; private float transmit; private DMScienceType type; private ScienceExperiment exp; private string sciPart, agent; internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName, float Transmit) { sitMask = sciSitMask; bioMask = sciBioMask; exp = sciExp; sciPart = sciPartID; agent = agentName; type = Type; transmit = Transmit; } public int SitMask { get { return sitMask; } } public int BioMask { get { return bioMask; } } public float Transmit { get { return transmit; } } public DMScienceType DMType { get { return type; } } public ScienceExperiment Exp { get { return exp; } } public string SciPart { get { return sciPart; } } public string Agent { get { return agent; } } } public enum DMScienceType { None = 0, Surface = 1, Aerial = 2, Space = 4, Biological = 8, Asteroid = 16, Anomaly = 32, } }
#region license /* DMagic Orbital Science - DMScienceContainer * Object to store experiment properties * * Copyright (c) 2014, David Grandy <david.grandy@gmail.com> * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #endregion namespace DMagic { internal class DMScienceContainer { internal int sitMask, bioMask; internal float transmit; internal DMScienceType type; internal ScienceExperiment exp; internal string sciPart, agent; internal DMScienceContainer(ScienceExperiment sciExp, int sciSitMask, int sciBioMask, DMScienceType Type, string sciPartID, string agentName, float Transmit) { sitMask = sciSitMask; bioMask = sciBioMask; exp = sciExp; sciPart = sciPartID; agent = agentName; type = Type; transmit = Transmit; } } internal enum DMScienceType { None = 0, Surface = 1, Aerial = 2, Space = 4, Biological = 8, Asteroid = 16, Anomaly = 32, } }
bsd-3-clause
C#
5425b9777fe4f71e47eec04d909d2e83f9eeb496
Change ChildOrder Side property to Enum type
kiyoaki/bitflyer-api-dotnet-client
src/BitFlyer.Apis/ResponseData/ChildOrder.cs
src/BitFlyer.Apis/ResponseData/ChildOrder.cs
using Newtonsoft.Json; namespace BitFlyer.Apis { public class ChildOrder { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("child_order_id")] public string ChildOrderId { get; set; } [JsonProperty("product_code")] public ProductCode ProductCode { get; set; } [JsonProperty("side")] public Side Side { get; set; } [JsonProperty("child_order_type")] public string ChildOrderType { get; set; } [JsonProperty("price")] public double Price { get; set; } [JsonProperty("average_price")] public double AveragePrice { get; set; } [JsonProperty("size")] public double Size { get; set; } [JsonProperty("child_order_state")] public ChildOrderState ChildOrderState { get; set; } [JsonProperty("expire_date")] public string ExpireDate { get; set; } [JsonProperty("child_order_date")] public string ChildOrderDate { get; set; } [JsonProperty("child_order_acceptance_id")] public string ChildOrderAcceptanceId { get; set; } [JsonProperty("outstanding_size")] public double OutstandingSize { get; set; } [JsonProperty("cancel_size")] public double CancelSize { get; set; } [JsonProperty("executed_size")] public double ExecutedSize { get; set; } [JsonProperty("total_commission")] public double TotalCommission { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
using Newtonsoft.Json; namespace BitFlyer.Apis { public class ChildOrder { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("child_order_id")] public string ChildOrderId { get; set; } [JsonProperty("product_code")] public ProductCode ProductCode { get; set; } [JsonProperty("side")] public string Side { get; set; } [JsonProperty("child_order_type")] public string ChildOrderType { get; set; } [JsonProperty("price")] public double Price { get; set; } [JsonProperty("average_price")] public double AveragePrice { get; set; } [JsonProperty("size")] public double Size { get; set; } [JsonProperty("child_order_state")] public ChildOrderState ChildOrderState { get; set; } [JsonProperty("expire_date")] public string ExpireDate { get; set; } [JsonProperty("child_order_date")] public string ChildOrderDate { get; set; } [JsonProperty("child_order_acceptance_id")] public string ChildOrderAcceptanceId { get; set; } [JsonProperty("outstanding_size")] public double OutstandingSize { get; set; } [JsonProperty("cancel_size")] public double CancelSize { get; set; } [JsonProperty("executed_size")] public double ExecutedSize { get; set; } [JsonProperty("total_commission")] public double TotalCommission { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this); } } }
mit
C#
80ee6b3a69613ba2f5f9c832e6e18c28860154cd
Update Assembly Info
SneakyPeet/Dirtybase
src/Dirtybase.App/Properties/AssemblyInfo.cs
src/Dirtybase.App/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Dirtybase.App")] [assembly: AssemblyDescription("Dirtybase is a persistence version/migration command line tool. Dirtybase will compare version files in a folder to the version of a data store, then apply the version files in order to migrate the data store to the latest version. This is useful for keeping data stores on different environments up to date and automating deployments.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Pieter Koornhof")] [assembly: AssemblyProduct("Dirtybase.App")] [assembly: AssemblyCopyright("")] [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("d2154d74-9be9-4bc4-9a21-85b01d961167")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Dirtybase.Tests")]
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("Dirtybase.App")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Dirtybase.App")] [assembly: AssemblyCopyright("")] [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("d2154d74-9be9-4bc4-9a21-85b01d961167")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Dirtybase.Tests")]
mit
C#
f4d7ba226d545b346d98054c87aa3e64bd8f5f02
Update package version to 0.1.1
vadimzozulya/FakeHttpContext
src/FakeHttpContext/Properties/AssemblyInfo.cs
src/FakeHttpContext/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("FakeHttpContext.Tests")] [assembly: AssemblyTitle("FakeHttpContext")] [assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Vadim Zozulya")] [assembly: AssemblyProduct("FakeHttpContext")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")] [assembly: AssemblyVersion("0.1.1")] [assembly: AssemblyFileVersion("0.1.1")] [assembly: AssemblyInformationalVersion("0.1.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: InternalsVisibleTo("FakeHttpContext.Tests")] [assembly: AssemblyTitle("FakeHttpContext")] [assembly: AssemblyDescription("Unit testing utilite for simulate HttpContext.Current.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Vadim Zozulya")] [assembly: AssemblyProduct("FakeHttpContext")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("36df5624-6d1a-4c88-8ba2-cb63e6d5dd0e")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")] [assembly: AssemblyInformationalVersion("0.1.0")]
mit
C#
1f984e3dfd4c8109e0de20ef437c2115a50c1327
Update feed path
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/ChristianHoejsager.cs
src/Firehose.Web/Authors/ChristianHoejsager.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/index.xml"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class ChristianHoejsager : IAmACommunityMember { public string FirstName => "Christian"; public string LastName => "Hoejsager"; public string ShortBioOrTagLine => "Systems Administrator, author of scriptingchris.tech and automation enthusiast"; public string StateOrRegion => "Denmark"; public string EmailAddress => "christian@scriptingchris.tech"; public string TwitterHandle => "_ScriptingChris"; public string GitHubHandle => "ScriptingChris"; public string GravatarHash => "d406f408c17d8a42f431cd6f90b007b1"; public GeoPosition Position => new GeoPosition(55.709830, 9.536208); public Uri WebSite => new Uri("https://scriptingchris.tech/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptingchris.tech/feed"); } } public string FeedLanguageCode => "en"; } }
mit
C#
05bcde73d58f1396447ed9ecd09e81744c673cbd
Fix create smtpclient with UseDefaultCredentials
hermanho/postal
src/Postal.AspNetCore/EmailServiceOptions.cs
src/Postal.AspNetCore/EmailServiceOptions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace Postal.AspNetCore { public class EmailServiceOptions { public EmailServiceOptions() { CreateSmtpClient = () => new SmtpClient(Host, Port) { UseDefaultCredentials = string.IsNullOrWhiteSpace(UserName), Credentials = string.IsNullOrWhiteSpace(UserName) ? null : new NetworkCredential(UserName, Password), EnableSsl = EnableSSL }; } public string Host { get; set; } public int Port { get; set; } public bool EnableSSL { get; set; } public string FromAddress { get; set; } public string UserName { get; set; } public string Password { get; set; } public Func<SmtpClient> CreateSmtpClient { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading.Tasks; namespace Postal.AspNetCore { public class EmailServiceOptions { public EmailServiceOptions() { CreateSmtpClient = () => new SmtpClient(Host, Port) { Credentials = new NetworkCredential(UserName, Password), EnableSsl = EnableSSL }; } public string Host { get; set; } public int Port { get; set; } public bool EnableSSL { get; set; } public string FromAddress { get; set; } public string UserName { get; set; } public string Password { get; set; } public Func<SmtpClient> CreateSmtpClient { get; set; } } }
mit
C#
1d4e589ad7ed4d42d088a4cd2a41465ecda48105
normalize file line ending
zhaoboqiang/FileFormat
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileFormat { class Program { private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption) { return filters.Split(',').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray(); } private static string ProcessText(string srcText) { var text = srcText.Replace("\r\n", "\n").Replace("\r", ""); return text; } static void ProcessDirectory(string srcDir, string dstDir, string searchPattern) { var srcFiles = GetFiles(srcDir, searchPattern, System.IO.SearchOption.AllDirectories); var ansiEncoding = Encoding.GetEncoding(936); foreach (var srcFile in srcFiles) { var dstFile = srcFile.Replace(srcDir, dstDir); var srcText = System.IO.File.ReadAllText(srcFile, ansiEncoding); var dstText = ProcessText(srcText); System.IO.File.WriteAllText(dstFile, dstText, ansiEncoding); } } static void Main(string[] args) { if (args.Length < 2) { Console.WriteLine("srcpath dstpath [searchPattern]"); } string searchPattern = "*.h,*.cpp,*.c"; if (args.Length == 3) { searchPattern = args[2]; } ProcessDirectory(args[0], args[1], searchPattern); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileFormat { class Program { private static string[] GetFiles(string sourceFolder, string filters, System.IO.SearchOption searchOption) { return filters.Split(',').SelectMany(filter => System.IO.Directory.GetFiles(sourceFolder, filter, searchOption)).ToArray(); } private static void ProcessFile(UTF8Encoding utf8Encoding, string path) { var text = System.IO.File.ReadAllText(path); text.Replace("\r\n", "\n"); System.IO.File.WriteAllText(path, text, utf8Encoding); } static void ProcessDirectory(string path, string searchPattern) { var srcs = GetFiles(path, searchPattern, System.IO.SearchOption.AllDirectories); var utf8Encoding = new System.Text.UTF8Encoding(true); foreach (var src in srcs) { ProcessFile(utf8Encoding, src); } } static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("path [searchPattern]"); } string searchPattern = "*.h,*.cpp,*.c"; if (args.Length == 2) { searchPattern = args[1]; } ProcessDirectory(args[0], searchPattern); } } }
mit
C#
f90359dbf44519aeb69125e212c9f1061a37b5cc
remove readline
kreuzhofer/AzureLargeFileUploader
Program.cs
Program.cs
using System; using System.IO; namespace AzureLargeFileUploader { class Program { static int Main(string[] args) { if (args.Length != 4) { Help(); return -1; } var fileToUpload = args[0]; if (!File.Exists(fileToUpload)) { Console.WriteLine("File does not exist: "+fileToUpload); Help(); } var containerName = args[1]; var storageAccountName = args[2]; var storageAccountKey = args[3]; var connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}"; LargeFileUploaderUtils.Log = Console.WriteLine; LargeFileUploaderUtils.UploadAsync(fileToUpload, connectionString, containerName, (sender, i) => { }); return 0; } private static void Help() { Console.WriteLine(); Console.WriteLine("********************************************************************************"); Console.WriteLine("Azure Large File Uploader, (C)2016 by Daniel Kreuzhofer (@dkreuzh), MIT License"); Console.WriteLine("Source code is available at https://github.com/kreuzhofer/AzureLargeFileUploader"); Console.WriteLine("********************************************************************************"); Console.WriteLine("USAGE: AzureLargeFileUploader.exe <FileToUpload> <Container> <StorageAccountName> <StorageAccountKey>"); } } }
using System; using System.IO; namespace AzureLargeFileUploader { class Program { static int Main(string[] args) { if (args.Length != 4) { Help(); return -1; } var fileToUpload = args[0]; if (!File.Exists(fileToUpload)) { Console.WriteLine("File does not exist: "+fileToUpload); Help(); } var containerName = args[1]; var storageAccountName = args[2]; var storageAccountKey = args[3]; var connectionString = $"DefaultEndpointsProtocol=https;AccountName={storageAccountName};AccountKey={storageAccountKey}"; LargeFileUploaderUtils.Log = Console.WriteLine; LargeFileUploaderUtils.UploadAsync(fileToUpload, connectionString, containerName, (sender, i) => { }); Console.ReadLine(); return 0; } private static void Help() { Console.WriteLine(); Console.WriteLine("********************************************************************************"); Console.WriteLine("Azure Large File Uploader, (C)2016 by Daniel Kreuzhofer (@dkreuzh), MIT License"); Console.WriteLine("Source code is available at https://github.com/kreuzhofer/AzureLargeFileUploader"); Console.WriteLine("********************************************************************************"); Console.WriteLine("USAGE: AzureLargeFileUploader.exe <FileToUpload> <Container> <StorageAccountName> <StorageAccountKey>"); } } }
mit
C#
6bb0506f8bc927b88961b31d82a7fa80913fe31a
Fix allocator handling
jorik041/maccore,cwensley/maccore,mono/maccore
src/CoreMedia/CMMemoryPool.cs
src/CoreMedia/CMMemoryPool.cs
// // CMMemoryPool.cs: Implements the managed CMMemoryPool // // Authors: Marek Safar (marek.safar@gmail.com) // // Copyright 2012 Xamarin Inc // using System; using System.Runtime.InteropServices; using MonoMac; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.ObjCRuntime; namespace MonoMac.CoreMedia { [Since (6,0)] public class CMMemoryPool : IDisposable, INativeObject { IntPtr handle; static readonly IntPtr AgeOutPeriodSelector; static CMMemoryPool () { var handle = Dlfcn.dlopen (Constants.CoreMediaLibrary, 0); try { AgeOutPeriodSelector = Dlfcn.GetIntPtr (handle, "kCMMemoryPoolOption_AgeOutPeriod"); } finally { Dlfcn.dlclose (handle); } } [DllImport(Constants.CoreMediaLibrary)] extern static IntPtr CMMemoryPoolCreate (IntPtr options); public CMMemoryPool () { handle = CMMemoryPoolCreate (IntPtr.Zero); } #if !COREBUILD public CMMemoryPool (TimeSpan ageOutPeriod) { using (var dict = new NSMutableDictionary ()) { dict.LowlevelSetObject (AgeOutPeriodSelector, new NSNumber (ageOutPeriod.TotalSeconds).Handle); handle = CMMemoryPoolCreate (dict.Handle); } } #endif ~CMMemoryPool () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (Handle != IntPtr.Zero){ CFObject.CFRelease (Handle); handle = IntPtr.Zero; } } public IntPtr Handle { get { return handle; } } [DllImport(Constants.CoreMediaLibrary)] extern static IntPtr CMMemoryPoolGetAllocator (IntPtr pool); public CFAllocator GetAllocator () { return new CFAllocator (CMMemoryPoolGetAllocator (Handle), false); } [DllImport(Constants.CoreMediaLibrary)] extern static void CMMemoryPoolFlush (IntPtr pool); public void Flush () { CMMemoryPoolFlush (Handle); } [DllImport(Constants.CoreMediaLibrary)] extern static void CMMemoryPoolInvalidate (IntPtr pool); public void Invalidate () { CMMemoryPoolInvalidate (Handle); } } }
// // CMMemoryPool.cs: Implements the managed CMMemoryPool // // Authors: Marek Safar (marek.safar@gmail.com) // // Copyright 2012 Xamarin Inc // using System; using System.Runtime.InteropServices; using MonoMac; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.ObjCRuntime; namespace MonoMac.CoreMedia { [Since (6,0)] public class CMMemoryPool : IDisposable, INativeObject { IntPtr handle; static readonly IntPtr AgeOutPeriodSelector; static CMMemoryPool () { var handle = Dlfcn.dlopen (Constants.CoreMediaLibrary, 0); try { AgeOutPeriodSelector = Dlfcn.GetIntPtr (handle, "kCMMemoryPoolOption_AgeOutPeriod"); } finally { Dlfcn.dlclose (handle); } } [DllImport(Constants.CoreMediaLibrary)] extern static IntPtr CMMemoryPoolCreate (IntPtr options); public CMMemoryPool () { handle = CMMemoryPoolCreate (IntPtr.Zero); } #if !COREBUILD public CMMemoryPool (TimeSpan ageOutPeriod) { using (var dict = new NSMutableDictionary ()) { dict.LowlevelSetObject (AgeOutPeriodSelector, new NSNumber (ageOutPeriod.TotalSeconds).Handle); handle = CMMemoryPoolCreate (dict.Handle); } } #endif ~CMMemoryPool () { Dispose (false); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } protected virtual void Dispose (bool disposing) { if (Handle != IntPtr.Zero){ CFObject.CFRelease (Handle); handle = IntPtr.Zero; } } public IntPtr Handle { get { return handle; } } [DllImport(Constants.CoreMediaLibrary)] extern static IntPtr CMMemoryPoolGetAllocator (IntPtr pool); public CFAllocator GetAllocator () { return new CFAllocator (CMMemoryPoolGetAllocator (Handle)); } [DllImport(Constants.CoreMediaLibrary)] extern static void CMMemoryPoolFlush (IntPtr pool); public void Flush () { CMMemoryPoolFlush (Handle); } [DllImport(Constants.CoreMediaLibrary)] extern static void CMMemoryPoolInvalidate (IntPtr pool); public void Invalidate () { CMMemoryPoolInvalidate (Handle); } } }
apache-2.0
C#
0f2c49445bb42e16bd5d2569cd8754c31946e854
Add helper functions for ApiKind
ericstj/buildtools,crummel/dotnet_buildtools,AlexGhiondea/buildtools,ChadNedzlek/buildtools,mmitche/buildtools,jthelin/dotnet-buildtools,crummel/dotnet_buildtools,JeremyKuhne/buildtools,alexperovich/buildtools,joperezr/buildtools,tarekgh/buildtools,karajas/buildtools,nguerrera/buildtools,weshaggard/buildtools,tarekgh/buildtools,dotnet/buildtools,JeremyKuhne/buildtools,stephentoub/buildtools,tarekgh/buildtools,dotnet/buildtools,MattGal/buildtools,chcosta/buildtools,joperezr/buildtools,weshaggard/buildtools,dotnet/buildtools,joperezr/buildtools,chcosta/buildtools,stephentoub/buildtools,ChadNedzlek/buildtools,crummel/dotnet_buildtools,karajas/buildtools,jthelin/dotnet-buildtools,alexperovich/buildtools,joperezr/buildtools,alexperovich/buildtools,chcosta/buildtools,AlexGhiondea/buildtools,weshaggard/buildtools,ericstj/buildtools,alexperovich/buildtools,AlexGhiondea/buildtools,nguerrera/buildtools,karajas/buildtools,weshaggard/buildtools,MattGal/buildtools,ericstj/buildtools,jthelin/dotnet-buildtools,tarekgh/buildtools,jthelin/dotnet-buildtools,mmitche/buildtools,dotnet/buildtools,mmitche/buildtools,MattGal/buildtools,karajas/buildtools,JeremyKuhne/buildtools,mmitche/buildtools,alexperovich/buildtools,ericstj/buildtools,mmitche/buildtools,MattGal/buildtools,joperezr/buildtools,nguerrera/buildtools,ChadNedzlek/buildtools,stephentoub/buildtools,crummel/dotnet_buildtools,ChadNedzlek/buildtools,stephentoub/buildtools,JeremyKuhne/buildtools,tarekgh/buildtools,AlexGhiondea/buildtools,chcosta/buildtools,nguerrera/buildtools,MattGal/buildtools
src/Microsoft.Cci.Extensions/Extensions/ApiKindExtensions.cs
src/Microsoft.Cci.Extensions/Extensions/ApiKindExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.Cci.Extensions { public static class ApiKindExtensions { public static bool IsInfrastructure(this ApiKind kind) { switch (kind) { case ApiKind.EnumField: case ApiKind.DelegateMember: case ApiKind.PropertyAccessor: case ApiKind.EventAccessor: return true; default: return false; } } public static bool IsNamespace(this ApiKind kind) { return kind == ApiKind.Namespace; } public static bool IsType(this ApiKind kind) { switch (kind) { case ApiKind.Interface: case ApiKind.Delegate: case ApiKind.Enum: case ApiKind.Struct: case ApiKind.Class: return true; default: return false; } } public static bool IsMember(this ApiKind kind) { switch (kind) { case ApiKind.EnumField: case ApiKind.DelegateMember: case ApiKind.Field: case ApiKind.Property: case ApiKind.Event: case ApiKind.Constructor: case ApiKind.PropertyAccessor: case ApiKind.EventAccessor: case ApiKind.Method: return true; default: return false; } } public static bool IsAccessor(this ApiKind kind) { switch (kind) { case ApiKind.PropertyAccessor: case ApiKind.EventAccessor: return true; default: return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.Cci.Extensions { public static class ApiKindExtensions { public static bool IsInfrastructure(this ApiKind kind) { switch (kind) { case ApiKind.EnumField: case ApiKind.DelegateMember: case ApiKind.PropertyAccessor: case ApiKind.EventAccessor: return true; default: return false; } } } }
mit
C#
510ac35fc8133551fb80d3dd6df7298639aa4c87
Remove usage of StartingGuildsService.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Modules/Utility/Services/RemindService.cs
src/MitternachtBot/Modules/Utility/Services/RemindService.cs
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Mitternacht.Common.Replacements; using Mitternacht.Extensions; using Mitternacht.Services; using Mitternacht.Services.Database; using Mitternacht.Services.Database.Models; using Mitternacht.Services.Impl; using NLog; namespace Mitternacht.Modules.Utility.Services { public class RemindService : IMService { private readonly Logger _log; private readonly CancellationToken _cancelAllToken; private readonly DiscordSocketClient _client; private readonly DbService _db; private readonly IBotConfigProvider _bcp; public string RemindMessageFormat => _bcp.BotConfig.RemindMessageFormat; public RemindService(DiscordSocketClient client, IBotConfigProvider bcp, DbService db) { _log = LogManager.GetCurrentClassLogger(); _client = client; _db = db; _bcp = bcp; var cancelSource = new CancellationTokenSource(); _cancelAllToken = cancelSource.Token; using var uow = _db.UnitOfWork; var reminders = uow.Reminders.GetRemindersForGuilds(client.Guilds.Select(g => g.Id).ToArray()).ToList(); foreach(var r in reminders) { Task.Run(() => StartReminder(r)); } } public async Task StartReminder(Reminder r) { var t = _cancelAllToken; var now = DateTime.UtcNow; var time = r.When - now; if(time.TotalMilliseconds > int.MaxValue) return; await Task.Delay(time, t).ConfigureAwait(false); try { IMessageChannel ch; if(r.IsPrivate) { var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); if(user == null) return; ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if(ch == null) return; var rep = new ReplacementBuilder() .WithOverride("%user%", () => $"<@!{r.UserId}>") .WithOverride("%message%", () => r.Message) .WithOverride("%target%", () => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>") .Build(); await ch.SendMessageAsync(rep.Replace(RemindMessageFormat).SanitizeMentions()).ConfigureAwait(false); } catch(Exception ex) { _log.Warn(ex); } finally { using var uow = _db.UnitOfWork; uow.Reminders.Remove(r); await uow.SaveChangesAsync(); } } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.WebSocket; using Mitternacht.Common.Replacements; using Mitternacht.Extensions; using Mitternacht.Services; using Mitternacht.Services.Database; using Mitternacht.Services.Database.Models; using Mitternacht.Services.Impl; using NLog; namespace Mitternacht.Modules.Utility.Services { public class RemindService : IMService { private readonly Logger _log; private readonly CancellationToken _cancelAllToken; private readonly DiscordSocketClient _client; private readonly DbService _db; private readonly IBotConfigProvider _bcp; public string RemindMessageFormat => _bcp.BotConfig.RemindMessageFormat; public RemindService(DiscordSocketClient client, IBotConfigProvider bcp, DbService db, StartingGuildsService guilds) { _log = LogManager.GetCurrentClassLogger(); _client = client; _db = db; _bcp = bcp; var cancelSource = new CancellationTokenSource(); _cancelAllToken = cancelSource.Token; using var uow = _db.UnitOfWork; var reminders = uow.Reminders.GetRemindersForGuilds(guilds.ToArray()).ToList(); foreach(var r in reminders) { Task.Run(() => StartReminder(r)); } } public async Task StartReminder(Reminder r) { var t = _cancelAllToken; var now = DateTime.UtcNow; var time = r.When - now; if(time.TotalMilliseconds > int.MaxValue) return; await Task.Delay(time, t).ConfigureAwait(false); try { IMessageChannel ch; if(r.IsPrivate) { var user = _client.GetGuild(r.ServerId).GetUser(r.ChannelId); if(user == null) return; ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if(ch == null) return; var rep = new ReplacementBuilder() .WithOverride("%user%", () => $"<@!{r.UserId}>") .WithOverride("%message%", () => r.Message) .WithOverride("%target%", () => r.IsPrivate ? "Direct Message" : $"<#{r.ChannelId}>") .Build(); await ch.SendMessageAsync(rep.Replace(RemindMessageFormat).SanitizeMentions()).ConfigureAwait(false); } catch(Exception ex) { _log.Warn(ex); } finally { using var uow = _db.UnitOfWork; uow.Reminders.Remove(r); await uow.SaveChangesAsync(); } } } }
mit
C#
634235af9871efd8a62b05f8d0cb1a1fcbbc3213
Add under load sample module
DSaunders/Nancy.JohnnyFive
src/Nancy.JohnnyFive/Nancy.JohnnyFive.Sample/SampleModule.cs
src/Nancy.JohnnyFive/Nancy.JohnnyFive.Sample/SampleModule.cs
namespace Nancy.JohnnyFive.Sample { using System; using System.Collections.Generic; using System.IO; using Circuits; public class SampleModule : NancyModule { public SampleModule() { Get["/"] = _ => { this.CanShortCircuit(new NoContentOnErrorCircuit() .ForException<FileNotFoundException>() .WithCircuitOpenTimeInSeconds(10)); this.CanShortCircuit(new NoContentOnErrorCircuit() .ForException<KeyNotFoundException>() .WithCircuitOpenTimeInSeconds(30)); if (this.Request.Query["fileNotFound"] != null) throw new FileNotFoundException(); if (this.Request.Query["keyNotFound"] != null) throw new KeyNotFoundException(); return "Hello, World!"; }; Get["/underload"] = _ => { this.CanShortCircuit(new NoContentUnderLoadCircuit() .WithRequestSampleTimeInSeconds(10) .WithRequestThreshold(5)); return "Under load " + DateTime.Now; }; } } }
namespace Nancy.JohnnyFive.Sample { using System.Collections.Generic; using System.IO; using Circuits; public class SampleModule : NancyModule { public SampleModule() { Get["/"] = _ => { this.CanShortCircuit(new NoContentOnErrorCircuit() .ForException<FileNotFoundException>() .WithCircuitOpenTimeInSeconds(10)); this.CanShortCircuit(new NoContentOnErrorCircuit() .ForException<KeyNotFoundException>() .WithCircuitOpenTimeInSeconds(30)); if (this.Request.Query["fileNotFound"] != null) throw new FileNotFoundException(); if (this.Request.Query["keyNotFound"] != null) throw new KeyNotFoundException(); return "Hello, World!"; }; Get["/underload"] = _ => { this.CanShortCircuit(new LastGoodResponseUnderLoad() .WithRequestSampleTimeInSeconds(10) .WithRequestThreshold(40)); }; } } }
mit
C#
52698a82452e4fe6ab0a948d212c0ee279c4e9a4
Fix null-reference exception on null Tags list inside LogglyConfigAdapter.cs.
serilog/serilog-sinks-loggly
src/Serilog.Sinks.Loggly/Sinks/Loggly/LogglyConfigAdapter.cs
src/Serilog.Sinks.Loggly/Sinks/Loggly/LogglyConfigAdapter.cs
using System; using Loggly.Config; namespace Serilog.Sinks.Loggly { class LogglyConfigAdapter { public void ConfigureLogglyClient(LogglyConfiguration logglyConfiguration) { var config = LogglyConfig.Instance; if (!string.IsNullOrWhiteSpace(logglyConfiguration.ApplicationName)) config.ApplicationName = logglyConfiguration.ApplicationName; if (string.IsNullOrWhiteSpace(logglyConfiguration.CustomerToken)) throw new ArgumentNullException("CustomerToken", "CustomerToken is required"); config.CustomerToken = logglyConfiguration.CustomerToken; config.IsEnabled = logglyConfiguration.IsEnabled; if (logglyConfiguration.Tags != null) { foreach (var tag in logglyConfiguration.Tags) { config.TagConfig.Tags.Add(tag); } } config.ThrowExceptions = logglyConfiguration.ThrowExceptions; if (logglyConfiguration.LogTransport != TransportProtocol.Https) config.Transport.LogTransport = (LogTransport)Enum.Parse(typeof(LogTransport), logglyConfiguration.LogTransport.ToString()); if (!string.IsNullOrWhiteSpace(logglyConfiguration.EndpointHostName)) config.Transport.EndpointHostname = logglyConfiguration.EndpointHostName; if (logglyConfiguration.EndpointPort > 0 && logglyConfiguration.EndpointPort <= ushort.MaxValue) config.Transport.EndpointPort = logglyConfiguration.EndpointPort; config.Transport.IsOmitTimestamp = logglyConfiguration.OmitTimestamp; config.Transport = config.Transport.GetCoercedToValidConfig(); } } }
using System; using Loggly.Config; namespace Serilog.Sinks.Loggly { class LogglyConfigAdapter { public void ConfigureLogglyClient(LogglyConfiguration logglyConfiguration) { var config = LogglyConfig.Instance; if (!string.IsNullOrWhiteSpace(logglyConfiguration.ApplicationName)) config.ApplicationName = logglyConfiguration.ApplicationName; if (string.IsNullOrWhiteSpace(logglyConfiguration.CustomerToken)) throw new ArgumentNullException("CustomerToken", "CustomerToken is required"); config.CustomerToken = logglyConfiguration.CustomerToken; config.IsEnabled = logglyConfiguration.IsEnabled; foreach (var tag in logglyConfiguration.Tags) { config.TagConfig.Tags.Add(tag); } config.ThrowExceptions = logglyConfiguration.ThrowExceptions; if (logglyConfiguration.LogTransport != TransportProtocol.Https) config.Transport.LogTransport = (LogTransport)Enum.Parse(typeof(LogTransport), logglyConfiguration.LogTransport.ToString()); if (!string.IsNullOrWhiteSpace(logglyConfiguration.EndpointHostName)) config.Transport.EndpointHostname = logglyConfiguration.EndpointHostName; if (logglyConfiguration.EndpointPort > 0 && logglyConfiguration.EndpointPort <= ushort.MaxValue) config.Transport.EndpointPort = logglyConfiguration.EndpointPort; config.Transport.IsOmitTimestamp = logglyConfiguration.OmitTimestamp; config.Transport = config.Transport.GetCoercedToValidConfig(); } } }
apache-2.0
C#
b08c6a4f9ac7a48ac9def4832af4745646304622
Remove Assert.True(weakSwitch.IsAlive); from PruneTest() in SwitchClassTests.cs under System.Diagnostics.TraceSourceTests (#17424)
seanshpark/corefx,cydhaselton/corefx,DnlHarvey/corefx,krytarowski/corefx,Jiayili1/corefx,DnlHarvey/corefx,MaggieTsang/corefx,rahku/corefx,ViktorHofer/corefx,alexperovich/corefx,richlander/corefx,tijoytom/corefx,Jiayili1/corefx,billwert/corefx,ravimeda/corefx,marksmeltzer/corefx,yizhang82/corefx,ViktorHofer/corefx,shimingsg/corefx,jlin177/corefx,ericstj/corefx,nchikanov/corefx,marksmeltzer/corefx,yizhang82/corefx,shimingsg/corefx,ptoonen/corefx,DnlHarvey/corefx,the-dwyer/corefx,shimingsg/corefx,MaggieTsang/corefx,stone-li/corefx,dotnet-bot/corefx,zhenlan/corefx,yizhang82/corefx,stephenmichaelf/corefx,krytarowski/corefx,nbarbettini/corefx,alexperovich/corefx,Ermiar/corefx,fgreinacher/corefx,ravimeda/corefx,elijah6/corefx,weltkante/corefx,seanshpark/corefx,dhoehna/corefx,krytarowski/corefx,ericstj/corefx,ViktorHofer/corefx,Jiayili1/corefx,gkhanna79/corefx,billwert/corefx,Ermiar/corefx,ericstj/corefx,rjxby/corefx,krytarowski/corefx,axelheer/corefx,krk/corefx,rahku/corefx,the-dwyer/corefx,ptoonen/corefx,seanshpark/corefx,twsouthwick/corefx,cydhaselton/corefx,ravimeda/corefx,mmitche/corefx,the-dwyer/corefx,krk/corefx,parjong/corefx,alexperovich/corefx,Ermiar/corefx,BrennanConroy/corefx,shimingsg/corefx,Petermarcu/corefx,parjong/corefx,elijah6/corefx,ravimeda/corefx,DnlHarvey/corefx,mmitche/corefx,rjxby/corefx,stone-li/corefx,mmitche/corefx,rjxby/corefx,billwert/corefx,ptoonen/corefx,jlin177/corefx,dotnet-bot/corefx,elijah6/corefx,DnlHarvey/corefx,MaggieTsang/corefx,wtgodbe/corefx,krk/corefx,rjxby/corefx,seanshpark/corefx,richlander/corefx,dotnet-bot/corefx,elijah6/corefx,krytarowski/corefx,ViktorHofer/corefx,richlander/corefx,krk/corefx,zhenlan/corefx,ptoonen/corefx,cydhaselton/corefx,MaggieTsang/corefx,parjong/corefx,stephenmichaelf/corefx,rubo/corefx,nchikanov/corefx,dotnet-bot/corefx,mazong1123/corefx,ViktorHofer/corefx,twsouthwick/corefx,yizhang82/corefx,YoupHulsebos/corefx,alexperovich/corefx,mmitche/corefx,rahku/corefx,cydhaselton/corefx,dhoehna/corefx,twsouthwick/corefx,richlander/corefx,Petermarcu/corefx,rubo/corefx,seanshpark/corefx,Petermarcu/corefx,ptoonen/corefx,ravimeda/corefx,yizhang82/corefx,marksmeltzer/corefx,rahku/corefx,nchikanov/corefx,stone-li/corefx,Petermarcu/corefx,Petermarcu/corefx,tijoytom/corefx,krytarowski/corefx,MaggieTsang/corefx,elijah6/corefx,wtgodbe/corefx,jlin177/corefx,weltkante/corefx,zhenlan/corefx,mazong1123/corefx,YoupHulsebos/corefx,nbarbettini/corefx,rubo/corefx,ptoonen/corefx,ericstj/corefx,rahku/corefx,Jiayili1/corefx,twsouthwick/corefx,jlin177/corefx,krytarowski/corefx,nchikanov/corefx,krk/corefx,parjong/corefx,rjxby/corefx,stephenmichaelf/corefx,wtgodbe/corefx,billwert/corefx,zhenlan/corefx,nbarbettini/corefx,jlin177/corefx,tijoytom/corefx,the-dwyer/corefx,ptoonen/corefx,marksmeltzer/corefx,mmitche/corefx,MaggieTsang/corefx,Petermarcu/corefx,weltkante/corefx,ViktorHofer/corefx,axelheer/corefx,dhoehna/corefx,mmitche/corefx,stone-li/corefx,fgreinacher/corefx,stone-li/corefx,alexperovich/corefx,YoupHulsebos/corefx,seanshpark/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,cydhaselton/corefx,the-dwyer/corefx,weltkante/corefx,Jiayili1/corefx,stephenmichaelf/corefx,billwert/corefx,gkhanna79/corefx,billwert/corefx,stephenmichaelf/corefx,JosephTremoulet/corefx,krk/corefx,YoupHulsebos/corefx,zhenlan/corefx,mazong1123/corefx,mazong1123/corefx,marksmeltzer/corefx,parjong/corefx,twsouthwick/corefx,jlin177/corefx,MaggieTsang/corefx,parjong/corefx,alexperovich/corefx,nbarbettini/corefx,weltkante/corefx,twsouthwick/corefx,mazong1123/corefx,ravimeda/corefx,stone-li/corefx,dhoehna/corefx,rubo/corefx,gkhanna79/corefx,axelheer/corefx,yizhang82/corefx,gkhanna79/corefx,JosephTremoulet/corefx,nchikanov/corefx,nbarbettini/corefx,tijoytom/corefx,zhenlan/corefx,YoupHulsebos/corefx,dhoehna/corefx,cydhaselton/corefx,twsouthwick/corefx,the-dwyer/corefx,Ermiar/corefx,shimingsg/corefx,JosephTremoulet/corefx,rahku/corefx,axelheer/corefx,axelheer/corefx,ericstj/corefx,dhoehna/corefx,BrennanConroy/corefx,YoupHulsebos/corefx,Jiayili1/corefx,tijoytom/corefx,stephenmichaelf/corefx,nbarbettini/corefx,BrennanConroy/corefx,rjxby/corefx,fgreinacher/corefx,marksmeltzer/corefx,dotnet-bot/corefx,elijah6/corefx,zhenlan/corefx,weltkante/corefx,krk/corefx,tijoytom/corefx,Ermiar/corefx,mmitche/corefx,JosephTremoulet/corefx,nchikanov/corefx,ViktorHofer/corefx,dhoehna/corefx,jlin177/corefx,JosephTremoulet/corefx,nbarbettini/corefx,gkhanna79/corefx,rjxby/corefx,axelheer/corefx,dotnet-bot/corefx,gkhanna79/corefx,JosephTremoulet/corefx,alexperovich/corefx,fgreinacher/corefx,richlander/corefx,richlander/corefx,Jiayili1/corefx,wtgodbe/corefx,nchikanov/corefx,DnlHarvey/corefx,weltkante/corefx,ericstj/corefx,rubo/corefx,mazong1123/corefx,elijah6/corefx,gkhanna79/corefx,tijoytom/corefx,stone-li/corefx,cydhaselton/corefx,rahku/corefx,the-dwyer/corefx,wtgodbe/corefx,billwert/corefx,richlander/corefx,Ermiar/corefx,yizhang82/corefx,wtgodbe/corefx,stephenmichaelf/corefx,ericstj/corefx,parjong/corefx,seanshpark/corefx,Ermiar/corefx,ravimeda/corefx,mazong1123/corefx,YoupHulsebos/corefx,shimingsg/corefx,shimingsg/corefx,DnlHarvey/corefx,dotnet-bot/corefx,wtgodbe/corefx,Petermarcu/corefx
src/System.Diagnostics.TraceSource/tests/SwitchClassTests.cs
src/System.Diagnostics.TraceSource/tests/SwitchClassTests.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 Xunit; namespace System.Diagnostics.TraceSourceTests { public class SwitchClassTests { class TestSwitch : Switch { public TestSwitch(String description = null) : base(null, description) { } public String SwitchValue { get { return this.Value; } set { this.Value = value; } } } [Fact] public void ValueTest() { var item = new TestSwitch(); item.SwitchValue = "1"; item.SwitchValue = "0"; item.SwitchValue = "-1"; } [Fact] public void DescriptionTest() { var item = new TestSwitch("Desc"); Assert.Equal("Desc", item.Description); item = new TestSwitch(); Assert.Equal("", item.Description); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static WeakReference PruneMakeRef() { return new WeakReference(new TestSwitch()); } [Fact] public void PruneTest() { var strongSwitch = new TestSwitch(); var weakSwitch = PruneMakeRef(); GC.Collect(2); Trace.Refresh(); Assert.False(weakSwitch.IsAlive); GC.Collect(2); Trace.Refresh(); } } }
// 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 Xunit; namespace System.Diagnostics.TraceSourceTests { public class SwitchClassTests { class TestSwitch : Switch { public TestSwitch(String description = null) : base(null, description) { } public String SwitchValue { get { return this.Value; } set { this.Value = value; } } } [Fact] public void ValueTest() { var item = new TestSwitch(); item.SwitchValue = "1"; item.SwitchValue = "0"; item.SwitchValue = "-1"; } [Fact] public void DescriptionTest() { var item = new TestSwitch("Desc"); Assert.Equal("Desc", item.Description); item = new TestSwitch(); Assert.Equal("", item.Description); } [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] static WeakReference PruneMakeRef() { return new WeakReference(new TestSwitch()); } [Fact] public void PruneTest() { var strongSwitch = new TestSwitch(); var weakSwitch = PruneMakeRef(); Assert.True(weakSwitch.IsAlive); GC.Collect(2); Trace.Refresh(); Assert.False(weakSwitch.IsAlive); GC.Collect(2); Trace.Refresh(); } } }
mit
C#
2eafceb9bb3b2f94366e1bac589a9a2d920c5963
Add batch client to IViagogoClient
viagogo/gogokit.net
src/GogoKit/IViagogoClient.cs
src/GogoKit/IViagogoClient.cs
using GogoKit.Clients; using GogoKit.Services; using HalKit; namespace GogoKit { public interface IViagogoClient { IGogoKitConfiguration Configuration { get; } IHalClient Hypermedia { get; } IOAuth2TokenStore TokenStore { get; } IOAuth2Client OAuth2 { get; } IUserClient User { get; } ISearchClient Search { get; } IAddressesClient Addresses { get; } IPurchasesClient Purchases { get; } ISalesClient Sales { get; } ICountriesClient Countries { get; } ICurrenciesClient Currencies { get; } IPaymentMethodsClient PaymentMethods { get; } ICategoriesClient Categories { get; } IEventsClient Events { get; } IListingsClient Listings { get; } ISellerListingsClient SellerListings { get; } IVenuesClient Venues { get; } IWebhooksClient Webhooks { get; } IBatchClient BatchClient { get; } } }
using GogoKit.Clients; using GogoKit.Services; using HalKit; namespace GogoKit { public interface IViagogoClient { IGogoKitConfiguration Configuration { get; } IHalClient Hypermedia { get; } IOAuth2TokenStore TokenStore { get; } IOAuth2Client OAuth2 { get; } IUserClient User { get; } ISearchClient Search { get; } IAddressesClient Addresses { get; } IPurchasesClient Purchases { get; } ISalesClient Sales { get; } ICountriesClient Countries { get; } ICurrenciesClient Currencies { get; } IPaymentMethodsClient PaymentMethods { get; } ICategoriesClient Categories { get; } IEventsClient Events { get; } IListingsClient Listings { get; } ISellerListingsClient SellerListings { get; } IVenuesClient Venues { get; } IWebhooksClient Webhooks { get; } } }
mit
C#
89afbe0362f3629ac200ffac51083c2fcc301b9c
Refactor Resolver to use path element factories
Domysee/Pather.CSharp
src/Pather.CSharp/Resolver.cs
src/Pather.CSharp/Resolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Reflection; using Pather.CSharp.PathElements; namespace Pather.CSharp { public class Resolver { private IList<IPathElementFactory> pathElementTypes; public Resolver() { pathElementTypes = new List<IPathElementFactory>(); pathElementTypes.Add(new PropertyFactory()); } public object Resolve(object target, string path) { var pathElementStrings = path.Split('.'); var pathElements = pathElementStrings.Select(pe => createPathElement(pe)); var tempResult = target; foreach(var pathElement in pathElements) { tempResult = pathElement.Apply(tempResult); } var result = tempResult; return result; } private IPathElement createPathElement(string pathElement) { //get the first applicable path element type var pathElementFactory = pathElementTypes.Where(f => isApplicable(f, pathElement)).FirstOrDefault(); if (pathElementFactory == null) throw new InvalidOperationException($"There is no applicable path element type for {pathElement}"); IPathElement result = pathElementFactory.Create(pathElement); return result; } private bool isApplicable(IPathElementFactory factory, string pathElement) { return factory.IsApplicable(pathElement); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Reflection; using Pather.CSharp.PathElements; namespace Pather.CSharp { public class Resolver { private IList<Type> pathElementTypes; public Resolver() { pathElementTypes = new List<Type>(); pathElementTypes.Add(typeof(Property)); } public object Resolve(object target, string path) { var pathElementStrings = path.Split('.'); var pathElements = pathElementStrings.Select(pe => createPathElement(pe)); var tempResult = target; foreach(var pathElement in pathElements) { tempResult = pathElement.Apply(tempResult); } var result = tempResult; return result; } private IPathElement createPathElement(string pathElement) { //get the first applicable path element type var pathElementType = pathElementTypes.Where(t => isApplicable(t, pathElement)).FirstOrDefault(); if (pathElementType == null) throw new InvalidOperationException($"There is no applicable path element type for {pathElement}"); var result = Activator.CreateInstance(pathElementType, pathElement); //each path element type must have a constructor that takes a string parameter return result as IPathElement; } private bool isApplicable(Type t, string pathElement) { MethodInfo applicableMethod = t.GetMethod("IsApplicable", BindingFlags.Static | BindingFlags.Public); if (applicableMethod == null) throw new InvalidOperationException($"The type {t.Name} does not have a static method IsApplicable"); bool? applicable = applicableMethod.Invoke(null, new[] { pathElement }) as bool?; if (applicable == null) throw new InvalidOperationException($"IsApplicable of type {t.Name} does not return bool"); return applicable.Value; } } }
mit
C#
6cb8fb37b0b3372fbdbee689d1cce58f2dcd07e5
swap image url
wharri220/OrchardDoc,MetSystem/OrchardDoc,MetSystem/OrchardDoc,MetSystem/OrchardDoc,armanforghani/OrchardDoc,abhishekluv/OrchardDoc,rtpHarry/OrchardDoc,OrchardCMS/OrchardDoc,SzymonSel/OrchardDoc,armanforghani/OrchardDoc,rtpHarry/OrchardDoc,phillipsj/OrchardDoc,abhishekluv/OrchardDoc,phillipsj/OrchardDoc,dcinzona/OrchardDoc,phillipsj/OrchardDoc,SzymonSel/OrchardDoc,SzymonSel/OrchardDoc,OrchardCMS/OrchardDoc,rtpHarry/OrchardDoc,wharri220/OrchardDoc,dcinzona/OrchardDoc,abhishekluv/OrchardDoc,armanforghani/OrchardDoc,dcinzona/OrchardDoc,wharri220/OrchardDoc
Contributors.cshtml
Contributors.cshtml
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script> <script src="/contributor.js"></script> <div ng-controller="OrchardContributor"> <ul> <li ng-repeat = "contributor in totalContribtors"> <a href="https://www.github.com/{{ contributor.login }}" target="_blank">{{ contributor.login }}</a> <br/> <img src="{{ contributor.avatar_url }}" alt="{{ contributor.login}}" /> <br/> <div> Number of Contributions by {{ contributor.login }} : {{ contributor.contributions }}</div> </li> </ul> </div> <style type="text/css"> ul li{ list-style : none; } </style>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.20/angular.js"></script> <script src="/contributor.js"></script> <div ng-controller="OrchardContributor"> <ul> <li ng-repeat = "contributor in totalContribtors"> <a href="https://www.github.com/{{ contributor.login }}" target="_blank">{{ contributor.login }}</a> <br/> <img src="http://www.gravatar.com/avatar/{{ contributor.gravatar_id}}" alt="{{ contributor.login}}" /> <br/> <div> Number of Contributions by {{ contributor.login }} : {{ contributor.contributions }}</div> </li> </ul> </div> <style type="text/css"> ul li{ list-style : none; } </style>
bsd-3-clause
C#
daf0ec2b54d494ac01686dc1d7d1ec4824e30c06
use static singletons in demo app
Insire/MvvmScarletToolkit,Insire/MvvmScarletToolkit
DemoApp/App.xaml.cs
DemoApp/App.xaml.cs
using MvvmScarletToolkit; using MvvmScarletToolkit.Commands; using MvvmScarletToolkit.Observables; using System.Windows; namespace DemoApp { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var commandBuilder = new CommandBuilder(ScarletDispatcher.Default, ScarletCommandManager.Default, ScarletMessenger.Default, ExitService.Default, ScarletWeakEventManager.Default, (lambda) => new BusyStack(lambda, ScarletDispatcher.Default)); var navigation = new NavigationViewModel(commandBuilder, new LocalizationsViewModel(new LocalizationProvider())); var window = new MainWindow { DataContext = navigation }; window.Show(); } } }
using MvvmScarletToolkit; using MvvmScarletToolkit.Commands; using MvvmScarletToolkit.Observables; using System.Windows; namespace DemoApp { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var commandManager = new ScarletCommandManager(); var dispatcher = ScarletDispatcher.Default; var commandBuilder = new CommandBuilder(dispatcher, commandManager, ScarletMessenger.Default, ExitService.Default, ScarletWeakEventManager.Default, (lambda) => new BusyStack(lambda, dispatcher)); var navigation = new NavigationViewModel(commandBuilder, new LocalizationsViewModel(new LocalizationProvider())); var window = new MainWindow { DataContext = navigation }; window.Show(); } } }
mit
C#
ca2e097685a3cce1fe6365094ad43e28b01844ce
Test to ensure TearDown run when test fails
yawaramin/TDDUnit
Program.cs
Program.cs
using System; namespace TDDUnit { class TestTestCase : TestCase { public TestTestCase(string name) : base(name) { } public override void SetUp() { base.SetUp(); m_result = new TestResult(); } public void TestTemplateMethod() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(m_result); Assert.Equal("SetUp TestMethod TearDown ", test.Log); } public void TestResult() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(m_result); Assert.Equal("1 run, 0 failed", m_result.Summary); } public void TestFailedResult() { WasRunObj test = new WasRunObj("TestBrokenMethod"); test.Run(m_result); Assert.Equal("1 run, 1 failed", m_result.Summary); } public void TestFailedResultFormatting() { m_result.TestStarted(); m_result.TestFailed(); Assert.Equal("1 run, 1 failed", m_result.Summary); } public void TestFailedSetUp() { WasRunSetUpFailed test = new WasRunSetUpFailed("TestMethod"); m_result.TestStarted(); try { test.Run(new TestResult()); } catch (Exception) { m_result.TestFailed(); } Assert.Equal("1 run, 0 failed", m_result.Summary); } public void TestSuite() { TestSuite suite = new TestSuite(); suite.Add(new WasRunObj("TestMethod")); suite.Add(new WasRunObj("TestBrokenMethod")); suite.Run(m_result); Assert.Equal("2 run, 1 failed", m_result.Summary); } public void TestRunAllTests() { TestSuite suite = new TestSuite(typeof (WasRunObj)); suite.Run(m_result); Assert.Equal("2 run, 1 failed", m_result.Summary); } public void TestTearDownWhenTestFailed() { WasRunObj test = new WasRunObj("TestBrokenMethod"); test.Run(m_result); Assert.Equal("SetUp TestBrokenMethod TearDown ", test.Log); } private TestResult m_result; } class Program { static void Main() { TestSuite suite = new TestSuite(typeof (TestTestCase)); TestResult result = new TestResult(); suite.Run(result); Console.WriteLine(result.Summary); } } }
using System; namespace TDDUnit { class TestTestCase : TestCase { public TestTestCase(string name) : base(name) { } public override void SetUp() { base.SetUp(); m_result = new TestResult(); } public void TestTemplateMethod() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(m_result); Assert.Equal("SetUp TestMethod TearDown ", test.Log); } public void TestResult() { WasRunObj test = new WasRunObj("TestMethod"); test.Run(m_result); Assert.Equal("1 run, 0 failed", m_result.Summary); } public void TestFailedResult() { WasRunObj test = new WasRunObj("TestBrokenMethod"); test.Run(m_result); Assert.Equal("1 run, 1 failed", m_result.Summary); } public void TestFailedResultFormatting() { m_result.TestStarted(); m_result.TestFailed(); Assert.Equal("1 run, 1 failed", m_result.Summary); } public void TestFailedSetUp() { WasRunSetUpFailed test = new WasRunSetUpFailed("TestMethod"); m_result.TestStarted(); try { test.Run(new TestResult()); } catch (Exception) { m_result.TestFailed(); } Assert.Equal("1 run, 0 failed", m_result.Summary); } public void TestSuite() { TestSuite suite = new TestSuite(); suite.Add(new WasRunObj("TestMethod")); suite.Add(new WasRunObj("TestBrokenMethod")); suite.Run(m_result); Assert.Equal("2 run, 1 failed", m_result.Summary); } public void TestRunAllTests() { TestSuite suite = new TestSuite(typeof (WasRunObj)); suite.Run(m_result); Assert.Equal("2 run, 1 failed", m_result.Summary); } private TestResult m_result; } class Program { static void Main() { TestSuite suite = new TestSuite(typeof (TestTestCase)); TestResult result = new TestResult(); suite.Run(result); Console.WriteLine(result.Summary); } } }
apache-2.0
C#
bab2459ee8e37bbc93be3f377d8c67f81216fbf6
Fix displaying talk time
DotNetRu/App,DotNetRu/App
DotNetRu.Clients.UI/Converters/SessionTimeDisplayConverter.cs
DotNetRu.Clients.UI/Converters/SessionTimeDisplayConverter.cs
namespace DotNetRu.Clients.UI.Converters { using System; using System.Diagnostics; using System.Globalization; using DotNetRu.DataStore.Audit.Models; using Xamarin.Forms; public class SessionTimeDisplayConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { if (!(value is SessionModel session)) { return string.Empty; } var startString = session.StartTime.LocalDateTime.ToString("t"); var endString = session.EndTime.LocalDateTime.ToString("t"); return $"{startString}–{endString}"; } catch (Exception ex) { Debug.WriteLine("Unable to convert: " + ex); } return string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
namespace DotNetRu.Clients.UI.Converters { using System; using System.Diagnostics; using System.Globalization; using DotNetRu.DataStore.Audit.Models; using Xamarin.Forms; public class SessionTimeDisplayConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { try { if (!(value is SessionModel session)) { return string.Empty; } var startString = session.StartTime.ToString("t"); var endString = session.EndTime.ToString("t"); return $"{startString}–{endString}"; } catch (Exception ex) { Debug.WriteLine("Unable to convert: " + ex); } return string.Empty; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
mit
C#
c710a00c577234fb4c90f1ac70644bb5f0fe13f4
Mark sample UI tests as Explicit
cezarypiatek/MaintainableSelenium,cezarypiatek/MaintainableSelenium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/Tellurium,cezarypiatek/MaintainableSelenium
Src/MaintainableSelenium/Sample.UITests/SampleFormTest.cs
Src/MaintainableSelenium/Sample.UITests/SampleFormTest.cs
using System.Collections.Generic; using System.IO; using MaintainableSelenium.Sample.Website.Mvc; using MaintainableSelenium.Toolbox; using MaintainableSelenium.Toolbox.Drivers; using MaintainableSelenium.Toolbox.Screenshots; using MaintainableSelenium.Toolbox.WebPages; using MaintainableSelenium.Toolbox.WebPages.WebForms.DefaultInputAdapters; using NUnit.Framework; using Sample.Website.Controllers; using Sample.Website.Models; namespace MaintainableSelenium.Sample.UITests { //INFO: Run Sample.Website and detach debugger before running test [TestFixture, Explicit] public class SampleFormTest { [TestCase(SeleniumDriverType.Firefox)] [TestCase(SeleniumDriverType.Chrome)] [TestCase(SeleniumDriverType.InternetExplorer)] public void should_be_able_to_fill_sample_form(SeleniumDriverType driverType) { //Prepare infrastructure for test var driver = SeleniumDriverFactory.CreateLocalDriver(driverType, Path.Combine(TestContext.CurrentContext.TestDirectory, "Drivers")); driver.Manage().Window.Maximize(); var camera = new BrowserCamera(driver, "SampleForm", "C:\\MaintainableSelenium\\screenshots", new List<BlindRegion>()); var navigator = new Navigator(driver, "http://localhost:51767"); //Test navigator.NavigateTo<TestFormsController>(c=>c.Index()); camera.TakeScreenshot("Sample1"); var form = driver.GetForm<SampleFormViewModel>(FormsIds.TestForm); form.SetFieldValue(x=>x.TextInput, "Hello world!!!"); form.SetFieldValue(x=>x.TextAreaInput, "Long test message"); form.SetFieldValue(x=>x.PasswordInput, "Secret_Password"); form.SetFieldValue(x=>x.CheckboxInput, CheckboxFormInputAdapter.Checked); camera.TakeScreenshot("Sample2"); //Clean up driver.Close(); driver.Quit(); } } }
using System.Collections.Generic; using System.IO; using MaintainableSelenium.Sample.Website.Mvc; using MaintainableSelenium.Toolbox; using MaintainableSelenium.Toolbox.Drivers; using MaintainableSelenium.Toolbox.Screenshots; using MaintainableSelenium.Toolbox.WebPages; using MaintainableSelenium.Toolbox.WebPages.WebForms.DefaultInputAdapters; using NUnit.Framework; using Sample.Website.Controllers; using Sample.Website.Models; namespace MaintainableSelenium.Sample.UITests { //INFO: Run Sample.Website and detach debugger before running test [TestFixture] public class SampleFormTest { [TestCase(SeleniumDriverType.Firefox)] [TestCase(SeleniumDriverType.Chrome)] [TestCase(SeleniumDriverType.InternetExplorer)] public void should_be_able_to_fill_sample_form(SeleniumDriverType driverType) { //Prepare infrastructure for test var driver = SeleniumDriverFactory.CreateLocalDriver(driverType, Path.Combine(TestContext.CurrentContext.TestDirectory, "Drivers")); driver.Manage().Window.Maximize(); var camera = new BrowserCamera(driver, "SampleForm", "C:\\MaintainableSelenium\\screenshots", new List<BlindRegion>()); var navigator = new Navigator(driver, "http://localhost:51767"); //Test navigator.NavigateTo<TestFormsController>(c=>c.Index()); camera.TakeScreenshot("Sample1"); var form = driver.GetForm<SampleFormViewModel>(FormsIds.TestForm); form.SetFieldValue(x=>x.TextInput, "Hello world!!!"); form.SetFieldValue(x=>x.TextAreaInput, "Long test message"); form.SetFieldValue(x=>x.PasswordInput, "Secret_Password"); form.SetFieldValue(x=>x.CheckboxInput, CheckboxFormInputAdapter.Checked); camera.TakeScreenshot("Sample2"); //Clean up driver.Close(); driver.Quit(); } } }
mit
C#
fb5580db666fa00b8ac85be68daffffa286e01ff
rectify the assembly name.
jwChung/Experimentalism,jwChung/Experimentalism
test/ExperimentalUnitTest/AssemblyLevelTest.cs
test/ExperimentalUnitTest/AssemblyLevelTest.cs
using System.Linq; using System.Reflection; using Xunit; namespace Jwc.Experiment { public class AssemblyLevelTest { [Fact] public void SutOnlyReferencesSpecifiedAssemblies() { var sut = Assembly.LoadFrom("Jwc.Experiment.dll"); Assert.NotNull(sut); var specifiedAssemblies = new [] { "mscorlib", "xunit", "xunit.extensions" }; var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray(); Assert.Equal(specifiedAssemblies.Length, actual.Length); Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty"); } } }
using System.Linq; using System.Reflection; using Xunit; namespace Jwc.Experiment { public class AssemblyLevelTest { [Fact] public void SutOnlyReferencesSpecifiedAssemblies() { var sut = Assembly.LoadFrom("Jwc.Experimental.dll"); Assert.NotNull(sut); var specifiedAssemblies = new [] { "mscorlib", "xunit", "xunit.extensions" }; var actual = sut.GetReferencedAssemblies().Select(an => an.Name).Distinct().ToArray(); Assert.Equal(specifiedAssemblies.Length, actual.Length); Assert.False(specifiedAssemblies.Except(actual).Any(), "Empty"); } } }
mit
C#
d6a8ca15e2880edbaf9a4d3b66d8b5ee25e753b0
Revert "Try bumping up the test timeout"
danbarua/NEventSocket,pragmatrix/NEventSocket,pragmatrix/NEventSocket,danbarua/NEventSocket
test/NEventSocket.Tests/TestSupport/TimeOut.cs
test/NEventSocket.Tests/TestSupport/TimeOut.cs
namespace NEventSocket.Tests.TestSupport { public class TimeOut { public const int TestTimeOutMs = 10000; } }
namespace NEventSocket.Tests.TestSupport { public class TimeOut { public const int TestTimeOutMs = 30 * 1000; } }
mpl-2.0
C#
742e208316fab4c35da7505410dd6e620fa4ff0d
Fix SRLRaceViewer link format
LiveSplit/LiveSplit
LiveSplit/LiveSplit.Core/Web/SRL/RaceViewers/SRLRaceViewer.cs
LiveSplit/LiveSplit.Core/Web/SRL/RaceViewers/SRLRaceViewer.cs
using LiveSplit.Model; using System.Diagnostics; namespace LiveSplit.Web.SRL.RaceViewers { public class SRLRaceViewer : IRaceViewer { public void ShowRace(IRaceInfo race) { var url = string.Format("http://speedrunslive.com/race/{0}", race.Id); Process.Start(url); } public string Name => "SpeedRunsLive"; } }
using LiveSplit.Model; using System.Diagnostics; namespace LiveSplit.Web.SRL.RaceViewers { public class SRLRaceViewer : IRaceViewer { public void ShowRace(IRaceInfo race) { var url = string.Format("http://speedrunslive.com/race/?id={0}", race.Id); Process.Start(url); } public string Name => "SpeedRunsLive"; } }
mit
C#
98feaa1f9dcdada1d0fc6d35b847d52335db7a18
Update scripts for WP
jamesmontemagno/Xamarin.Plugins,monostefan/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins
Settings/build.cake
Settings/build.cake
#addin "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Build")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Build").Does (() => { const string sln = "./Refractored.XamPlugins.Settings.sln"; const string cfg = "Release"; NuGetRestore (sln); if (IsRunningOnWindows ()) DotNetBuild (sln, c => c.Configuration = cfg); else MSBuild ("./Battery.", c => { c.Configuration = cfg; c.MSBuildPlatform = MSBuildPlatform.x86; }); }); Task ("NuGetPack") .IsDependentOn ("Build") .Does (() => { NuGetPack ("./Common/Xam.Plugins.Settings.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 (() => { NuGetRestore ("./Refractored.XamPlugins.Settings.sln"); DotNetBuild ("./Refractored.XamPlugins.Settings.sln", c => c.Configuration = "Release"); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./Common/Xam.Plugins.Settings.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
mit
C#
ad024ad9be2e2d3b889251e543d8b8bfb4eaffbf
Add helper methods for XORing byte arrays
0culus/ElectronicCash
ElectronicCash/SecretSplittingProvider.cs
ElectronicCash/SecretSplittingProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// This portion of the protocol is critical...Alice splits her bit committed packets so that /// they are not accessible except when the bank requires it. /// </summary> class SecretSplittingProvider { List<byte[]> RandomBytes { get; set; } byte[] RandomOne { get; set; } byte[] RandomTwo { get; set; } private byte[] SecretMessage { get; set; } /// <summary> /// Splitting between an arbitrary number of actors /// </summary> /// <param name="secretMessage"></param> /// <param name="randMessagesBytes"></param> public SecretSplittingProvider(byte[] secretMessage, IEnumerable<byte[]> randMessagesBytes) { SecretMessage = secretMessage; RandomBytes = new List<byte[]>(randMessagesBytes); } /// <summary> /// Splitting between two actors /// </summary> /// <param name="secretMessage"></param> /// <param name="randomBytesOne"></param> /// <param name="randomBytesTwo"></param> public SecretSplittingProvider(byte[] secretMessage, byte[] randomBytesOne, byte[] randomBytesTwo) { SecretMessage = secretMessage; RandomOne = randomBytesOne; RandomTwo = randomBytesTwo; } /// <summary> /// Compute XOR of an arbitrary number of byte arrays /// </summary> /// <param name="toXor"></param> /// <returns></returns> private static byte[] ExclusiveOr(List<byte[]> toXor) { //if (toXor.Any(p => p.Length != toXor.First().Length)) //{ // throw new ArgumentException("Arguments must be the same length"); //} throw new NotImplementedException(); } /// <summary> /// Compute XOR of two byte arrays /// </summary> /// <param name="arr1"></param> /// <param name="arr2"></param> /// <returns></returns> private static byte[] ExclusiveOr(byte[] arr1, byte[] arr2) { if (arr1.Length != arr2.Length) { throw new ArgumentException("arr1 and arr2 must be the same length"); } var result = new byte[arr1.Length]; for (var i = 0; i < arr1.Length; ++i) { result[i] = (byte)(arr1[i] ^ arr2[i]); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicCash { /// <summary> /// This portion of the protocol is critical...Alice splits her bit committed packets so that /// they are not accessible except when the bank requires it. /// </summary> class SecretSplittingProvider { List<byte[]> RandomBytes { get; set; } byte[] RandomOne { get; set; } byte[] RandomTwo { get; set; } private byte[] SecretMessage { get; set; } /// <summary> /// Splitting between an arbitrary number of actors /// </summary> /// <param name="secretMessage"></param> /// <param name="randMessagesBytes"></param> public SecretSplittingProvider(byte[] secretMessage, IEnumerable<byte[]> randMessagesBytes) { SecretMessage = secretMessage; RandomBytes = new List<byte[]>(randMessagesBytes); } /// <summary> /// Splitting between two actors /// </summary> /// <param name="secretMessage"></param> /// <param name="randomBytesOne"></param> /// <param name="randomBytesTwo"></param> public SecretSplittingProvider(byte[] secretMessage, byte[] randomBytesOne, byte[] randomBytesTwo) { SecretMessage = secretMessage; RandomOne = randomBytesOne; RandomTwo = randomBytesTwo; } } }
mit
C#
3fc62f760f8ab6cb76ec0f48187854c0c8856d5f
UPDATE Renames IOperationObject to IDynamic
rickyah/DynoBind,rickyah/DynoBind
projects/Core/IDynamic.cs
projects/Core/IDynamic.cs
using System; namespace LateBindingHelper { /// <summary> /// Implements an interface to perform operations over a type using /// late binding calls /// </summary> public interface IDynamic : IPropertyCall, IMethodCall, IIndexerCall, IFieldCall, IOperationLastCallParameters { /// <summary> /// Object which late binding calls will be dispatched to /// </summary> object InstanceObject { get; } } }
namespace LateBindingHelper { /// <summary> /// Implements an interface to perform operations over a type using /// late binding calls /// </summary> public interface IDynamic : IPropertyCall, IMethodCall, IIndexerCall, IFieldCall, IOperationLastCallParameters { /// <summary> /// Object which late binding calls will be dispatched to /// </summary> object InstanceObject { get; } } }
mit
C#
b0aca027558bf8c84f57a381b92468550880171e
Update logic that keeps a fixed FPS
RagingBool/RagingBool.Carcosa
projects/RagingBool.Carcosa.Core_cs/Stage/Controller/ControllerModeBase.cs
projects/RagingBool.Carcosa.Core_cs/Stage/Controller/ControllerModeBase.cs
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using Epicycle.Commons.Time; using RagingBool.Carcosa.Devices; namespace RagingBool.Carcosa.Core.Stage.Controller { internal abstract class ControllerModeBase : IControllerMode { private readonly ControllerUi _controllerUi; private readonly IClock _clock; private readonly ILpd8 _controller; private double _lastUpdateTime; public ControllerModeBase(ControllerUi controllerUi, IClock clock, ILpd8 controller) { _controllerUi = controllerUi; _clock = clock; _controller = controller; Fps = 1; } protected ILpd8 Controller { get { return _controller; } } protected ControllerUi ControllerUi { get { return _controllerUi; } } protected double Fps { get; set; } public virtual void Enter() { ClearLights(); _lastUpdateTime = _clock.Time; } public virtual void Exit() { ClearLights(); } public virtual void Update() { var curTime = _clock.Time; var timeSinceLastUpdate = curTime - _lastUpdateTime; if(timeSinceLastUpdate < (1 / Fps)) { return; } NewFrame(); _lastUpdateTime = curTime; } protected virtual void NewFrame() { } protected void ClearLights() { for (int i = 0; i < _controller.NumberOfButtons; i++) { _controller.SetKeyLightState(i, false); } } public abstract void ProcessButtonEventHandler(ButtonEventArgs e); public abstract void ProcessControllerChangeEvent(ControllerChangeEventArgs e); } }
// [[[[INFO> // Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool) // // 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. // // For more information check https://github.com/RagingBool/RagingBool.Carcosa // ]]]] using RagingBool.Carcosa.Devices; namespace RagingBool.Carcosa.Core.Stage.Controller { internal abstract class ControllerModeBase : IControllerMode { private readonly ILpd8 _controller; public ControllerModeBase(ILpd8 controller) { _controller = controller; } protected ILpd8 Controller { get { return _controller; } } public virtual void Enter() { ClearLights(); } public virtual void Exit() { ClearLights(); } public virtual void Update() { } protected void ClearLights() { for (int i = 0; i < _controller.NumberOfButtons; i++) { _controller.SetKeyLightState(i, false); } } public abstract void ProcessButtonEventHandler(ButtonEventArgs e); public abstract void ProcessControllerChangeEvent(ControllerChangeEventArgs e); } }
apache-2.0
C#
8395d5199487c79864bccf79fe8a1d739d22fb80
Use uppercase letters ONLY
12joan/hangman
hangman.cs
hangman.cs
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("HANG THE MAN"); game.GuessLetter('H'); var output = game.ShownWord(); Console.WriteLine(output); // Table table = new Table(2, 3); // string output = table.Draw(); // Console.WriteLine(output); } } }
using System; namespace Hangman { public class Hangman { public static void Main(string[] args) { var game = new Game("hang the man"); game.GuessLetter('h'); var output = game.ShownWord(); Console.WriteLine(output); // Table table = new Table(2, 3); // string output = table.Draw(); // Console.WriteLine(output); } } }
unlicense
C#
6f83719c50450dd7b047ef91822a9fb2470f4b8a
use NetworkService account (minimal rights)
fandrei/CiapiLatencyCollector,fandrei/CiapiLatencyCollector
LatencyCollectorService/ProjectInstaller.Designer.cs
LatencyCollectorService/ProjectInstaller.Designer.cs
namespace CiapiLatencyCollector { partial class ProjectInstaller { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.NetworkService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.ServiceName = "CIAPI Latency Collector"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); } #endregion private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; } }
namespace CiapiLatencyCollector { partial class ProjectInstaller { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalService; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.ServiceName = "CIAPI Latency Collector"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] { this.serviceProcessInstaller1, this.serviceInstaller1}); } #endregion private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; } }
apache-2.0
C#
cfae91ef56708baa22601989382abf66bd80d38f
Fix whitespace
Logicalshift/Reason
LogicalShift.Reason/Literals/BasicAtom.cs
LogicalShift.Reason/Literals/BasicAtom.cs
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Threading; namespace LogicalShift.Reason.Literals { /// <summary> /// Represents a basic atomic literal /// </summary> public class BasicAtom : ILiteral, IEquatable<BasicAtom> { /// <summary> /// A unique identifier for this atom /// </summary> private readonly long _identifier; /// <summary> /// The identifier to assign to the next atom /// </summary> private static long _nextIdentifier; public BasicAtom() { // Assign a unique (within this session) identifier to this atom _identifier = Interlocked.Increment(ref _nextIdentifier); } public void UnifyQuery(IQueryUnifier unifier) { unifier.PutStructure(this, 0, this); } public void UnifyProgram(IProgramUnifier unifier) { unifier.GetStructure(this, 0, this); } public ILiteral RebuildWithParameters(IEnumerable<ILiteral> parameters) { // We don't have any parameters return this; } public bool Equals(BasicAtom other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (other._identifier == _identifier) return true; return false; } public bool Equals(ILiteral other) { return Equals(other as BasicAtom); } public override bool Equals(object obj) { return Equals(obj as BasicAtom); } public override int GetHashCode() { return _identifier.GetHashCode(); } public override string ToString() { return string.Format("atom_{0}", _identifier); } } }
using LogicalShift.Reason.Api; using System; using System.Collections.Generic; using System.Threading; namespace LogicalShift.Reason.Literals { /// <summary> /// Represents a basic atomic literal /// </summary> public class BasicAtom : ILiteral, IEquatable<BasicAtom> { /// <summary> /// A unique identifier for this atom /// </summary> private readonly long _identifier; /// <summary> /// The identifier to assign to the next atom /// </summary> private static long _nextIdentifier; public BasicAtom() { // Assign a unique (within this session) identifier to this atom _identifier = Interlocked.Increment(ref _nextIdentifier); } public void UnifyQuery(IQueryUnifier unifier) { unifier.PutStructure(this, 0, this); } public void UnifyProgram(IProgramUnifier unifier) { unifier.GetStructure(this, 0, this); } public ILiteral RebuildWithParameters(IEnumerable<ILiteral> parameters) { // We don't have any parameters return this; } public bool Equals(BasicAtom other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; if (other._identifier == _identifier) return true; return false; } public bool Equals(ILiteral other) { return Equals(other as BasicAtom); } public override bool Equals(object obj) { return Equals(obj as BasicAtom); } public override int GetHashCode() { return _identifier.GetHashCode(); } public override string ToString() { return string.Format("atom_{0}", _identifier); } } }
apache-2.0
C#
085dbe9afc2a0b65a2dbe1d87d383cafd4477c27
Add legacy exchange-rate API
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Backend/Controllers/LegacyController.cs
WalletWasabi.Backend/Controllers/LegacyController.cs
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WalletWasabi.Backend.Controllers { /// <summary> /// Provides legacy, never changing API for legacy applications. /// </summary> [Produces("application/json")] public class LegacyController : ControllerBase { public LegacyController(BlockchainController blockchainController, OffchainController offchainController) { BlockchainController = blockchainController; OffchainController = offchainController; } public BlockchainController BlockchainController { get; } public OffchainController OffchainController { get; } [HttpGet("api/v3/btc/Blockchain/all-fees")] [ResponseCache(Duration = 300, Location = ResponseCacheLocation.Client)] public async Task<IActionResult> GetAllFeesV3Async([FromQuery, Required] string estimateSmartFeeMode) => await BlockchainController.GetAllFeesAsync(estimateSmartFeeMode); [HttpGet("api/v3/btc/Offchain/exchange-rates")] public async Task<IActionResult> GetExchangeRatesV3Async() => await OffchainController.GetExchangeRatesAsync(); } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace WalletWasabi.Backend.Controllers { /// <summary> /// Provides legacy, never changing API for legacy applications. /// </summary> [Produces("application/json")] public class LegacyController : ControllerBase { public LegacyController(BlockchainController blockchainController) { BlockchainController = blockchainController; } public BlockchainController BlockchainController { get; } [HttpGet("api/v3/btc/Blockchain/all-fees")] [ResponseCache(Duration = 300, Location = ResponseCacheLocation.Client)] public async Task<IActionResult> GetAllFeesV3Async([FromQuery, Required] string estimateSmartFeeMode) => await BlockchainController.GetAllFeesAsync(estimateSmartFeeMode); } }
mit
C#
366dae22365f2c68771b22666274e03ac9adfaf9
Remove ResourceManager
thomaslevesque/NString
NString/Properties/Resources.cs
NString/Properties/Resources.cs
namespace NString.Properties { internal static class Resources { public static string TemplateKeyNotFound(string key) => $"No value found for key '{key}'."; public static string SubstringCountOutOfRange => "The number of characters must be greater than or equal to zero, and less than or equal to the length of the string."; public static string NumberMustBePositiveOrZero(string argumentName) => $"{argumentName} must be greater than or equal to zero."; public static string MaxLengthCantBeLessThan(int minValue) => $"maxLength can't be less than {minValue}."; public static string MaxLengthCantBeLessThanLengthOfEllipsisString => "maxLength can't be less than the length of ellipsisString."; } }
using System.Resources; using System.Reflection; namespace NString.Properties { internal static class Resources { public static ResourceManager ResourceManager { get; } = new ResourceManager("NString.Properties.Resources", typeof(Resources).GetTypeInfo().Assembly); public static string TemplateKeyNotFound(string key) => $"No value found for key '{key}'."; public static string SubstringCountOutOfRange => "The number of characters must be greater than or equal to zero, and less than or equal to the length of the string."; public static string NumberMustBePositiveOrZero(string argumentName) => $"{argumentName} must be greater than or equal to zero."; public static string MaxLengthCantBeLessThan(int minValue) => $"maxLength can't be less than {minValue}."; public static string MaxLengthCantBeLessThanLengthOfEllipsisString => "maxLength can't be less than the length of ellipsisString."; } }
apache-2.0
C#
886886aa17a771e57b6542153b2b9f5f520e7aee
Update parameters usage
wbsimms/GitStats
src/GitStats/Program.cs
src/GitStats/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using GitStats.Lib; using Microsoft.Practices.Unity; namespace GitStats { class Program { static int Main(string[] args) { if (args.Length != 3) { Usage(); return -1; } if (!Directory.Exists(args[0])) { Usage(); Console.WriteLine("Directory does not exist :" + args[0] ); return -1; } var repo = args[0]; int count; if (!Int32.TryParse(args[1], out count)) { Usage(); Console.WriteLine("Commit Count is not a number :" + args[1]); return -1; } string branch = null; if (!string.IsNullOrEmpty(args[2])) { branch = args[2]; } IGetStatsCollection collection = GitStats.Lib.Resolver.Instance.Container.Resolve<IGetStatsCollection>(); foreach (var stats in collection) { stats.Get(repo, count, branch); } return 0; } static void Usage() { Console.WriteLine("Usage: GitStats.exe <path to local git repo> <commit count> [branch name]"); Console.WriteLine(@"Example: GitStats.exe C:\projects\GitStats\ 200 master"); Console.WriteLine(@"Example: GitStats.exe C:\projects\GitStats\ 200 // Defaults to your current branch"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using GitStats.Lib; using Microsoft.Practices.Unity; namespace GitStats { class Program { static int Main(string[] args) { if (args.Length != 3) { Usage(); return -1; } if (!Directory.Exists(args[0])) { Usage(); Console.WriteLine("Directory does not exist :" + args[0] ); return -1; } var repo = args[0]; int count; if (!Int32.TryParse(args[1], out count)) { Usage(); Console.WriteLine("Commit Count is not a number :" + args[1]); return -1; } string branch = null; if (!string.IsNullOrEmpty(args[2])) { branch = args[2]; } IGetStatsCollection collection = GitStats.Lib.Resolver.Instance.Container.Resolve<IGetStatsCollection>(); foreach (var stats in collection) { stats.Get(repo, count, branch); } return 0; } static void Usage() { Console.WriteLine("Usage: GitStats.exe <path to local git repo> <commit count> [branch name]"); Console.WriteLine(@"Example: GitStats.exe 'C:\projects\GitStats\' 200 master"); Console.WriteLine(@"Example: GitStats.exe 'C:\projects\GitStats\' 200 // Defaults to your current branch"); } } }
mit
C#
1a0dfb7b8030da36152751c79dee006c74842f41
update message
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; using Appleseed.Base.Alerts.Model; using Appleseed.Base.Alerts.Controller; using Appleseed.Base.Alerts.Providers; namespace Appleseed.Base.Alerts { /// <summary> /// Main Program for Alert Notifications /// </summary> class Program { #region App Config Values #endregion static void Main(string[] args) { Console.WriteLine("INFO : Starting Alert Engine."); CheckAlertsProvider(); Console.WriteLine("INFO : Ending Alert Engine."); } static void CheckAlertsProvider() { IAlert aAlertProvider = new EmailAlertProvider(); bool runSuccess = false; runSuccess = aAlertProvider.Run(); if (runSuccess) { Console.WriteLine("INFO : All Alerts sent successfully."); } else { Console.WriteLine("INFO : There were error(s) during the Alert Engine rune."); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using System.Net; using System.IO; using Newtonsoft.Json; using System.Data.SqlClient; using System.Data; using System.Configuration; using Dapper; using Appleseed.Base.Alerts.Model; using Appleseed.Base.Alerts.Controller; using Appleseed.Base.Alerts.Providers; namespace Appleseed.Base.Alerts { /// <summary> /// Main Program for Alert Notifications /// </summary> class Program { #region App Config Values #endregion static void Main(string[] args) { Console.WriteLine("INFO : Starting Alert Engine."); CheckAlertsProvider(); Console.WriteLine("INFO : Ending Alert Engine."); } static void CheckAlertsProvider() { IAlert aAlertProvider = new EmailAlertProvider(); bool runSuccess = false; runSuccess = aAlertProvider.Run(); if (runSuccess) { Console.WriteLine("INFO : Alerts sent successfully."); } else { Console.WriteLine("INFO : There were error(s) during the Alert Engine rune."); } } } }
apache-2.0
C#
8ed9062d00843ab06f868bd6a885e6c1704dbcd6
Allow mirror to accept parameters to specify what to mount and where
TrabacchinLuigi/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet,dokan-dev/dokan-dotnet,TrabacchinLuigi/dokan-dotnet,dokan-dev/dokan-dotnet
sample/DokanNetMirror/Program.cs
sample/DokanNetMirror/Program.cs
using System; using System.Linq; using DokanNet; namespace DokanNetMirror { internal class Program { private const string MirrorKey = "-what"; private const string MountKey = "-where"; private const string UseUnsafeKey = "-unsafe"; private static void Main(string[] args) { try { var arguments = args .Select(x => x.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries)) .ToDictionary(x => x[0], x => x.Length > 1 ? x[1] as object : true, StringComparer.OrdinalIgnoreCase); var mirrorPath = arguments.ContainsKey(MirrorKey) ? arguments[MirrorKey] as string : @"C:\"; var mountPath = arguments.ContainsKey(MountKey) ? arguments[MountKey] as string : @"N:\"; var unsafeReadWrite = arguments.ContainsKey(UseUnsafeKey); Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}"); var mirror = unsafeReadWrite ? new UnsafeMirror(mirrorPath) : new Mirror(mirrorPath); mirror.Mount(mountPath, DokanOptions.DebugMode, 5); Console.WriteLine(@"Success"); } catch (DokanException ex) { Console.WriteLine(@"Error: " + ex.Message); } } } }
using System; using DokanNet; namespace DokanNetMirror { internal class Program { private static void Main(string[] args) { try { bool unsafeReadWrite = args.Length > 0 && args[0].Equals("-unsafe", StringComparison.OrdinalIgnoreCase); Console.WriteLine($"Using unsafe methods: {unsafeReadWrite}"); var mirror = unsafeReadWrite ? new UnsafeMirror("C:") : new Mirror("C:"); mirror.Mount("n:\\", DokanOptions.DebugMode, 5); Console.WriteLine(@"Success"); } catch (DokanException ex) { Console.WriteLine(@"Error: " + ex.Message); } } } }
mit
C#
650a23276c74e0b93cf6b28bc4c0d5235ea5f956
Tweak to the Readme
haysclark/strangeioc-examples
Assets/scripts/strange/ReadMe.cs
Assets/scripts/strange/ReadMe.cs
/** \mainpage StrangeIoC * * \section intro_sec Introduction * * Strange is a super-lightweight and highly extensible Inversion-of-Control (IoC) framework, written specifically for C# and Unity. We’ve validated Strange on web and standalone, iOS and Android. It contains the following features, most of which are optional: * <ul> * <li>A core binding framework that pretty much lets you bind one or more of anything to one or more of anything else.</li> * <li>Dependency Injection</li> * <li>A shared event bus</li> * <li>MonoBehaviour mediation</li> * <li>Optional MVCS (Model/View/Controller/Service) structure</li> * <li>Multiple contexts</li> * <li>Don’t see what you need? The core binding framework is simple to extend. Build new Binders like:</li> * </ul> * In addition to organizing your project into a sensible structure, Strange offers the following benefits: * <ul> * <li>Designed to play well with Unity3D. Also designed to play well without it.</li> * <li>Separate UnityEngine code from the rest of your app, improving portability and unit testability.</li> * <li>A common event bus makes information flow easy and highly decoupled.</li> * <li>The extensible binder really is amazing (a friend used to tell me “it’s good to like your own cookin’!”). The number of things you can accomplish with the tiny core framework would justify Strange all on its own.</li> * <li>Multiple contexts allow you to “bootstrap” subcomponents so they operate fine either on their own or in-app. This can hugely speed up your development process and allow developers to work in isolation, then integrate in later stages of development.</li> * </ul> * An executive overview of the benefits of IoC in general and StrangeIoC in particular is available here: <a href="">TODO</a> * <br /> * Some fun documentation and tutorials are available here: <a href="">TODO</a>. * <br /> * Already know RobotLegs? Good news, we've written <a href="">this page</a> just for you! */
/** \mainpage StrangeIoC * * \section intro_sec Introduction * * Strange is a super-lightweight and highly extensible Inversion-of-Control (IoC) framework, written specifically for C# and Unity. We’ve validated Strange on web and standalone, iOS and Android. It contains the following features, most of which are optional: * <ul> * <li>A core binding framework that pretty much lets you bind one or more of anything to one or more of anything else.</li> * <li>Dependency Injection</li> * <li>A shared event bus</li> * <li>MonoBehaviour mediation</li> * <li>Optional MVCS (Model/View/Controller/Service) structure</li> * <li>Multiple contexts</li> * <li>Don’t see what you need? The core binding framework is simple to extend. Build new Binders like:</li> * </ul> * In addition to organizing your project into a sensible structure, Strange offers the following benefits: * <ul> * <li>Designed to play well with Unity3D. Also designed to play well without it.</li> * <li>Separate UnityEngine code from the rest of your app, improving portability and unit testability.</li> * <li>A common event bus makes information flow easy and highly decoupled.</li> * <li>The extensible binder really is amazing (a friend used to tell me “it’s good to like your own cookin’!”). The number of things you can accomplish with the tiny core framework would justify Strange all on its own.</li> * <li>Multiple contexts allow you to “bootstrap” subcomponents so they operate fine either on their own or in-app. This can hugely speed up your development process and allow developers to work in isolation, then integrate in later stages of development.</li> * </ul> * An executive overview of the benefits of IoC in general and StrangeIoC in particular is available here: <a href="">TODO</a> * <br /> * Some fun documentation and tutorials are available here: <a href="">TODO</a>. */
apache-2.0
C#
722a0298f8f35603aaab0ae63247c0de610e62d4
Add prototype movement for MetallKefer
emazzotta/unity-tower-defense
Assets/Scripts/Enemies/MetallKeferController.cs
Assets/Scripts/Enemies/MetallKeferController.cs
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { public GameObject gameControllerObject; private GameController gameController; private GameObject[] towerBasesBuildable; private GameObject nextWaypiont; private int currentWaypointIndex = 0; private int movementSpeed = 2; private float step = 10f; void Start () { this.gameController = this.gameControllerObject.GetComponent<GameController>(); this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex]; } void Update() { this.moveToNextWaypoint (); } void SetNextWaypoint() { if (this.currentWaypointIndex < this.gameController.getWaypoints ().Length - 1) { this.currentWaypointIndex += 1; this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex]; this.nextWaypiont.GetComponent<Renderer> ().material.color = this.getRandomColor(); } } private Color getRandomColor() { Color newColor = new Color( Random.value, Random.value, Random.value, 1.0f ); return newColor; } private void moveToNextWaypoint() { float step = movementSpeed * Time.deltaTime; this.transform.LookAt (this.nextWaypiont.transform); this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step); this.SetNextWaypoint (); } }
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { public GameObject gameControllerObject; private GameController gameController; private GameObject[] towerBasesBuildable; void Start () { this.gameController = this.gameControllerObject.GetComponent<GameController>(); this.FindInititalWaypoint (); } void FindInititalWaypoint() { } }
mit
C#
b8199e3b2e37f344aa23ebf73bd3e2710427d167
Fix DataField not renamed in compressor stub
yuligang1234/ConfuserEx,modulexcite/ConfuserEx,Desolath/ConfuserEx3,jbeshir/ConfuserEx,mirbegtlax/ConfuserEx,mirbegtlax/ConfuserEx,JPVenson/ConfuserEx,yeaicc/ConfuserEx,AgileJoshua/ConfuserEx,HalidCisse/ConfuserEx,manojdjoshi/ConfuserEx,farmaair/ConfuserEx,yuligang1234/ConfuserEx,timnboys/ConfuserEx,KKKas/ConfuserEx,Immortal-/ConfuserEx,arpitpanwar/ConfuserEx,fretelweb/ConfuserEx,HalidCisse/ConfuserEx,JPVenson/ConfuserEx,MetSystem/ConfuserEx,engdata/ConfuserEx,Desolath/Confuserex,apexrichard/ConfuserEx
Confuser.Protections/Compress/StubProtection.cs
Confuser.Protections/Compress/StubProtection.cs
using System; using System.Diagnostics; using System.Security.Cryptography; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; using Confuser.Renamer; namespace Confuser.Protections.Compress { internal class StubProtection : Protection { private readonly CompressorContext ctx; internal StubProtection(CompressorContext ctx) { this.ctx = ctx; } public override string Name { get { return "Compressor Stub Protection"; } } public override string Description { get { return "Do some extra works on the protected stub."; } } public override string Id { get { return "Ki.Compressor.Protection"; } } public override string FullId { get { return "Ki.Compressor.Protection"; } } public override ProtectionPreset Preset { get { return ProtectionPreset.None; } } protected override void Initialize(ConfuserContext context) { // } protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.BeginModule, new SigPhase(this)); } private class SigPhase : ProtectionPhase { public SigPhase(StubProtection parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info encoding"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { var field = context.CurrentModule.Types[0].FindField("DataField"); Debug.Assert(field != null); context.Registry.GetService<INameService>().SetCanRename(field, true); context.CurrentModuleWriterListener.OnWriterEvent += (sender, e) => { if (e.WriterEvent == ModuleWriterEvent.MDBeginCreateTables) { // Add key signature var writer = (ModuleWriter)sender; var prot = (StubProtection)Parent; uint blob = writer.MetaData.BlobHeap.Add(prot.ctx.KeySig); uint rid = writer.MetaData.TablesHeap.StandAloneSigTable.Add(new RawStandAloneSigRow(blob)); Debug.Assert((0x11000000 | rid) == prot.ctx.KeyToken); // Add File reference byte[] hash = SHA1.Create().ComputeHash(prot.ctx.OriginModule); uint hashBlob = writer.MetaData.BlobHeap.Add(hash); MDTable<RawFileRow> fileTbl = writer.MetaData.TablesHeap.FileTable; uint fileRid = fileTbl.Add(new RawFileRow( (uint)FileAttributes.ContainsMetaData, writer.MetaData.StringsHeap.Add("koi"), hashBlob)); } }; } } } }
using System; using System.Diagnostics; using System.Security.Cryptography; using Confuser.Core; using dnlib.DotNet; using dnlib.DotNet.MD; using dnlib.DotNet.Writer; namespace Confuser.Protections.Compress { internal class StubProtection : Protection { private readonly CompressorContext ctx; internal StubProtection(CompressorContext ctx) { this.ctx = ctx; } public override string Name { get { return "Compressor Stub Protection"; } } public override string Description { get { return "Do some extra works on the protected stub."; } } public override string Id { get { return "Ki.Compressor.Protection"; } } public override string FullId { get { return "Ki.Compressor.Protection"; } } public override ProtectionPreset Preset { get { return ProtectionPreset.None; } } protected override void Initialize(ConfuserContext context) { // } protected override void PopulatePipeline(ProtectionPipeline pipeline) { pipeline.InsertPostStage(PipelineStage.BeginModule, new SigPhase(this)); } private class SigPhase : ProtectionPhase { public SigPhase(StubProtection parent) : base(parent) { } public override ProtectionTargets Targets { get { return ProtectionTargets.Modules; } } public override string Name { get { return "Packer info encoding"; } } protected override void Execute(ConfuserContext context, ProtectionParameters parameters) { context.CurrentModuleWriterListener.OnWriterEvent += (sender, e) => { if (e.WriterEvent == ModuleWriterEvent.MDBeginCreateTables) { // Add key signature var writer = (ModuleWriter)sender; var prot = (StubProtection)Parent; uint blob = writer.MetaData.BlobHeap.Add(prot.ctx.KeySig); uint rid = writer.MetaData.TablesHeap.StandAloneSigTable.Add(new RawStandAloneSigRow(blob)); Debug.Assert((0x11000000 | rid) == prot.ctx.KeyToken); // Add File reference byte[] hash = SHA1.Create().ComputeHash(prot.ctx.OriginModule); uint hashBlob = writer.MetaData.BlobHeap.Add(hash); MDTable<RawFileRow> fileTbl = writer.MetaData.TablesHeap.FileTable; uint fileRid = fileTbl.Add(new RawFileRow( (uint)FileAttributes.ContainsMetaData, writer.MetaData.StringsHeap.Add("koi"), hashBlob)); } }; } } } }
mit
C#
f4abbb91be32064bfdc1e9cbabd48ac16ee03c4a
Revert "Improve CrawlDecision"
tru3d3v/abot,sjdirect/abot,fyang0321/WebCrawler,obender/abot,fyang0321/WebCrawler,RoninWest/abot,RoninWest/abot,coveo/abot,vladimir-pecanac-main/abot,xavivars/abot
Abot/Poco/CrawlDecision.cs
Abot/Poco/CrawlDecision.cs
 namespace Abot.Poco { public class CrawlDecision { public CrawlDecision() { Reason = ""; } /// <summary> /// Whether to allow the crawl decision /// </summary> public bool Allow { get; set; } /// <summary> /// The reason the crawl decision was NOT allowed /// </summary> public string Reason { get; set; } /// <summary> /// Whether the crawl should be stopped. Will clear all scheduled pages but will allow any threads that are currently crawling to complete. /// </summary> public bool ShouldStopCrawl { get; set; } /// <summary> /// Whether the crawl should be "hard stopped". Will clear all scheduled pages and cancel any threads that are currently crawling. /// </summary> public bool ShouldHardStopCrawl { get; set; } } }
 namespace Abot.Poco { public class CrawlDecision { public CrawlDecision() { Reason = ""; } public CrawlDecision(bool allow, string reason = "") { Allow = allow; Reason = reason; } /// <summary> /// Whether to allow the crawl decision /// </summary> public bool Allow { get; set; } /// <summary> /// The reason the crawl decision was NOT allowed /// </summary> public string Reason { get; set; } /// <summary> /// Whether the crawl should be stopped. Will clear all scheduled pages but will allow any threads that are currently crawling to complete. /// </summary> public bool ShouldStopCrawl { get; set; } /// <summary> /// Whether the crawl should be "hard stopped". Will clear all scheduled pages and cancel any threads that are currently crawling. /// </summary> public bool ShouldHardStopCrawl { get; set; } } }
apache-2.0
C#
ea5db46ce85acc6ef66fa3a25a853769720860f1
Update image resolution to UHD (#3)
kfstorm/BingWallpaper
BingWallpaper/Constants.cs
BingWallpaper/Constants.cs
using System; using System.IO; namespace Kfstorm.BingWallpaper { public static class Constants { public static string DataPath { get { string path = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), @"K.F.Storm\BingWallpaper"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } public static string LogFile { get { return "log.log"; } } public static string StateFile { get { return "state.xml"; } } public static string JpgFile { get { return "image.jpg"; } } public static string BmpFile { get { return "image.bmp"; } } public static string WallpaperInfoUrl { get { return string.Format("http://www.bing.com/hpimagearchive.aspx?format=xml&idx={0}&n={1}&mkt={2}", PictureIndex, PictureCount, Market); } } public static int PictureCount { get { return 1; } } public static int PictureIndex { get { return 0; } } public static string Market { get { return "zh-cn"; } } public static string PictureUrlFormat { get { return "http://www.bing.com{0}_UHD.jpg"; } } public static TimeZoneInfo TimeZone { get { return TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); } } } }
using System; using System.IO; namespace Kfstorm.BingWallpaper { public static class Constants { public static string DataPath { get { string path = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.ApplicationData), @"K.F.Storm\BingWallpaper"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } return path; } } public static string LogFile { get { return "log.log"; } } public static string StateFile { get { return "state.xml"; } } public static string JpgFile { get { return "image.jpg"; } } public static string BmpFile { get { return "image.bmp"; } } public static string WallpaperInfoUrl { get { return string.Format("http://www.bing.com/hpimagearchive.aspx?format=xml&idx={0}&n={1}&mkt={2}", PictureIndex, PictureCount, Market); } } public static int PictureCount { get { return 1; } } public static int PictureIndex { get { return 0; } } public static string Market { get { return "zh-cn"; } } public static string PictureUrlFormat { get { return "http://www.bing.com{0}_1920x1080.jpg"; } } public static TimeZoneInfo TimeZone { get { return TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time"); } } } }
mit
C#
a8365539f26509c5ef301fc6aaa83bdd36257f17
Fix field attributes
setchi/n_back_tracer,setchi/n_back_tracer
Assets/Scripts/Main/TimeKeeper.cs
Assets/Scripts/Main/TimeKeeper.cs
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using UniRx; public class TimeKeeper : MonoBehaviour { public event Action TimeUp; [SerializeField] float timeLimit; [SerializeField] Slider slider; public void StartCountdown() { Observable.EveryUpdate() .TakeUntil(Observable.Timer(TimeSpan.FromSeconds(timeLimit))) .Select(_ => Time.deltaTime) .Scan((total, delta) => total + delta) .Subscribe(elapsedTime => slider.value = (timeLimit - elapsedTime) / timeLimit, TimeUp); } }
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using UniRx; public class TimeKeeper : MonoBehaviour { public event Action TimeUp; public float timeLimit; public Slider slider; public void StartCountdown() { Observable.EveryUpdate() .TakeUntil(Observable.Timer(TimeSpan.FromSeconds(timeLimit))) .Select(_ => Time.deltaTime) .Scan((total, delta) => total + delta) .Subscribe(elapsedTime => slider.value = (timeLimit - elapsedTime) / timeLimit, TimeUp); } }
mit
C#
11d406aa0c2d3acaf6137538af20f9de85d41639
Fix osu!catch conversion expecting full positional data, rather than just X.
ppy/osu,ZLima12/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,EVAST9919/osu,smoogipooo/osu,2yangk23/osu,DrabWeb/osu,2yangk23/osu,naoey/osu,UselessToucan/osu,naoey/osu,UselessToucan/osu,Frontear/osuKyzer,smoogipoo/osu,johnneijzen/osu,naoey/osu,DrabWeb/osu,Nabile-Rahmani/osu,DrabWeb/osu,peppy/osu,ZLima12/osu,ppy/osu
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapConverter.cs
osu.Game.Rulesets.Catch/Beatmaps/CatchBeatmapConverter.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using System.Collections.Generic; using System; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapConverter : BeatmapConverter<CatchBaseHit> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override IEnumerable<CatchBaseHit> ConvertHitObject(HitObject obj, Beatmap beatmap) { var curveData = obj as IHasCurve; var positionData = obj as IHasXPosition; var comboData = obj as IHasCombo; if (positionData == null) yield break; if (curveData != null) { yield return new JuiceStream { StartTime = obj.StartTime, Samples = obj.Samples, ControlPoints = curveData.ControlPoints, CurveType = curveData.CurveType, Distance = curveData.Distance, RepeatSamples = curveData.RepeatSamples, RepeatCount = curveData.RepeatCount, X = positionData.X / CatchPlayfield.BASE_WIDTH, NewCombo = comboData?.NewCombo ?? false }; yield break; } yield return new Fruit { StartTime = obj.StartTime, Samples = obj.Samples, NewCombo = comboData?.NewCombo ?? false, X = positionData.X / CatchPlayfield.BASE_WIDTH }; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using System.Collections.Generic; using System; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Catch.Beatmaps { internal class CatchBeatmapConverter : BeatmapConverter<CatchBaseHit> { protected override IEnumerable<Type> ValidConversionTypes { get; } = new[] { typeof(IHasXPosition) }; protected override IEnumerable<CatchBaseHit> ConvertHitObject(HitObject obj, Beatmap beatmap) { var curveData = obj as IHasCurve; var positionData = obj as IHasPosition; var comboData = obj as IHasCombo; if (positionData == null) yield break; if (curveData != null) { yield return new JuiceStream { StartTime = obj.StartTime, Samples = obj.Samples, ControlPoints = curveData.ControlPoints, CurveType = curveData.CurveType, Distance = curveData.Distance, RepeatSamples = curveData.RepeatSamples, RepeatCount = curveData.RepeatCount, X = positionData.X / CatchPlayfield.BASE_WIDTH, NewCombo = comboData?.NewCombo ?? false }; yield break; } yield return new Fruit { StartTime = obj.StartTime, Samples = obj.Samples, NewCombo = comboData?.NewCombo ?? false, X = positionData.X / CatchPlayfield.BASE_WIDTH }; } } }
mit
C#
9046002e20bc59511d48996d30c27e65509ed212
Add lock around Get in session cache, and add default "unknown" username.
pgina/pgina,pgina/pgina,daviddumas/pgina,daviddumas/pgina,pgina/pgina,daviddumas/pgina,stefanwerfling/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina,stefanwerfling/pgina,stefanwerfling/pgina
Plugins/MySQLLogger/MySQLLogger/SessionCache.cs
Plugins/MySQLLogger/MySQLLogger/SessionCache.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace pGina.Plugin.MySqlLogger { class SessionCache { private Dictionary<int, string> m_cache; public SessionCache() { m_cache = new Dictionary<int, string>(); } public void Add(int sessId, string userName) { lock(this) { if (!m_cache.ContainsKey(sessId)) m_cache.Add(sessId, userName); else m_cache[sessId] = userName; } } public string Get(int sessId) { string result = "--Unknown--"; lock (this) { if (m_cache.ContainsKey(sessId)) result = m_cache[sessId]; } return result; } public void Clear() { lock (this) { m_cache.Clear(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace pGina.Plugin.MySqlLogger { class SessionCache { private Dictionary<int, string> m_cache; public SessionCache() { m_cache = new Dictionary<int, string>(); } public void Add(int sessId, string userName) { lock(this) { if (!m_cache.ContainsKey(sessId)) m_cache.Add(sessId, userName); else m_cache[sessId] = userName; } } public string Get(int sessId) { if (m_cache.ContainsKey(sessId)) return m_cache[sessId]; return ""; } public void Clear() { lock (this) { m_cache.Clear(); } } } }
bsd-3-clause
C#
ea5a19592d9daf277874e1531f7152ff72337034
Update the blog URL
TheSeleniumGuys/Code-Drills
selenium-hello-world-001.cs
selenium-hello-world-001.cs
//See the blog post at: http://theseleniumguys.com/2016/11/07/code-drill-1-selenium-c-hello-world/ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpendQA.Selenium.IE; IWebdriver.driver = new InternetExplorerDriver(); driver.Navigate().GoToURL("http://www.google.com"); driver.FindElement(By.XPath("//input[@value='Google Search']")).SendKeys("Hello, World!"); driver.FindElement(By.XPath("//input[@value='Google Search']")).Click(); driver.Quit();
//See the blog post at: http://theseleniumguys.com/2016/12/05/code-drill-1-selenium-c-hello-world/ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpendQA.Selenium.IE; IWebdriver.driver = new InternetExplorerDriver(); driver.Navigate().GoToURL("http://www.google.com"); driver.FindElement(By.XPath("//input[@value='Google Search']")).SendKeys("Hello, World!"); driver.FindElement(By.XPath("//input[@value='Google Search']")).Click(); driver.Quit();
mit
C#
42f446faa9a8d19a0a49d970b8139e7bf28cf4c1
Fix remaining test failure
peppy/osu-new,UselessToucan/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
osu.Game/Overlays/Settings/Sections/General/UpdateSettings.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework; using osu.Framework.Allocation; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Overlays.Settings.Sections.Maintenance; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [BackgroundDependencyLoader(true)] private void load(Storage storage, OsuConfigManager config, OsuGame game) { Add(new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }); if (RuntimeInfo.IsDesktop) { Add(new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, }); Add(new SettingsButton { Text = "Change folder location...", Action = () => game?.PerformFromScreen(menu => menu.Push(new MigrationSelectScreen())) }); } } } }
// 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; using osu.Framework.Allocation; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Configuration; using osu.Game.Overlays.Settings.Sections.Maintenance; namespace osu.Game.Overlays.Settings.Sections.General { public class UpdateSettings : SettingsSubsection { protected override string Header => "Updates"; [BackgroundDependencyLoader] private void load(Storage storage, OsuConfigManager config, OsuGame game) { Add(new SettingsEnumDropdown<ReleaseStream> { LabelText = "Release stream", Bindable = config.GetBindable<ReleaseStream>(OsuSetting.ReleaseStream), }); if (RuntimeInfo.IsDesktop) { Add(new SettingsButton { Text = "Open osu! folder", Action = storage.OpenInNativeExplorer, }); Add(new SettingsButton { Text = "Change folder location...", Action = () => game.PerformFromScreen(menu => menu.Push(new MigrationSelectScreen())) }); } } } }
mit
C#
831a40d8ad71a306cd54a1ff623f78b2a3ef0877
Change assembly version
danielchalmers/SteamAccountSwitcher
SteamAccountSwitcher/Properties/AssemblyInfo.cs
SteamAccountSwitcher/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("SteamAccountSwitcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SteamAccountSwitcher")] [assembly: AssemblyCopyright("Copyright © 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)] //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.*")] [assembly: AssemblyFileVersion("1.0.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("SteamAccountSwitcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SteamAccountSwitcher")] [assembly: AssemblyCopyright("Copyright © 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)] //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#
5727d07e0e020b28abbff9be25ba2b3c19c08934
add AggressiveInlining to the ReadOnly wrapper
uwx/DSharpPlus,uwx/DSharpPlus
DSharpPlus/Utilities.ReadOnly.cs
DSharpPlus/Utilities.ReadOnly.cs
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; namespace DSharpPlus { // Read-only ConcurrentDictionary wrapper for Standard 1.1 but is very low-overhead so might as well use it // everywhere internal readonly struct ReadOnlyDictionaryWrapper<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { private readonly ConcurrentDictionary<TKey, TValue> _implementation; public ReadOnlyDictionaryWrapper(ConcurrentDictionary<TKey, TValue> implementation) { _implementation = implementation; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => _implementation.GetEnumerator(); [MethodImpl(MethodImplOptions.AggressiveInlining)] IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) _implementation).GetEnumerator(); public int Count => _implementation.Count; [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ContainsKey(TKey key) => _implementation.ContainsKey(key); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool TryGetValue(TKey key, out TValue value) => _implementation.TryGetValue(key, out value); public TValue this[TKey key] => _implementation[key]; public IEnumerable<TKey> Keys => _implementation.Keys; public IEnumerable<TValue> Values => _implementation.Values; } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.Serialization; using System.Threading; namespace DSharpPlus { internal readonly struct ReadOnlyDictionaryWrapper<TKey, TValue> : IReadOnlyDictionary<TKey, TValue> { private readonly ConcurrentDictionary<TKey, TValue> _implementation; public ReadOnlyDictionaryWrapper(ConcurrentDictionary<TKey, TValue> implementation) { _implementation = implementation; } public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => _implementation.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable) _implementation).GetEnumerator(); public int Count => _implementation.Count; public bool ContainsKey(TKey key) => _implementation.ContainsKey(key); public bool TryGetValue(TKey key, out TValue value) => _implementation.TryGetValue(key, out value); public TValue this[TKey key] => _implementation[key]; public IEnumerable<TKey> Keys => _implementation.Keys; public IEnumerable<TValue> Values => _implementation.Values; } }
mit
C#
68650a319cec800a02d893427a1abdb8313d56e8
fix stagning uris
wikibus/Argolis
src/Nancy.Hydra/HydraModule.cs
src/Nancy.Hydra/HydraModule.cs
using Hydra; namespace Nancy.Hydra { /// <summary> /// Server Hydra API documentation /// </summary> public abstract class HydraModule : NancyModule { /// <summary> /// Initializes a new instance of the <see cref="HydraModule"/> class. /// </summary> protected HydraModule() { Get[Path] = route => CreateApiDocumentation(); } /// <summary> /// Gets the API Documentation path. /// </summary> protected virtual string Path { get { return "doc"; } } /// <summary> /// Creates the API documentation. /// </summary> protected abstract ApiDocumentation CreateApiDocumentation(); } }
using Hydra; namespace Nancy.Hydra { /// <summary> /// Server Hydra API documentation /// </summary> public abstract class HydraModule : NancyModule { /// <summary> /// Initializes a new instance of the <see cref="HydraModule"/> class. /// </summary> protected HydraModule() : base("doc") { Get["/"] = route => CreateApiDocumentation(); } /// <summary> /// Creates the API documentation. /// </summary> protected abstract ApiDocumentation CreateApiDocumentation(); } }
mit
C#
d14165bb44276a71c66bac22cc43a974cece86ab
Update AssemblyInfo.cs
ilya-murzinov/WhiteSharp
src/Properties/AssemblyInfo.cs
src/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("WhiteSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("WhiteSharp")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7fbfa96e-e84b-4fc4-81b0-abdd323840d9")] // 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")]
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("WhiteExtension")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("WhiteExtension")] [assembly: AssemblyCopyright("Copyright © Microsoft 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7fbfa96e-e84b-4fc4-81b0-abdd323840d9")] // 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#
d0da000af9c5166afe3eb172c4124a616574a004
Add order constructor and Payment
jontansey/.Net-Core-Ecommerce-Base,jontansey/.Net-Core-Ecommerce-Base
src/Shop.Core/Entites/Order.cs
src/Shop.Core/Entites/Order.cs
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Shop.Core.BaseObjects; using Shop.Core.Interfaces; namespace Shop.Core.Entites { public class Order : LifetimeBase, IReferenceable<Order> { [Key] public int OrderId { get; set; } public string OrderReference { get; set; } public List<ProductConfiguration> Products { get; set; } public DiscountCode DiscountCode { get; set; } public ShippingDetails ShippingMethod { get; set; } public Address ShippingAddress { get; set; } public Address BillingAddress { get; set; } public Payment Payment { get; set; } public Order() { OrderId = 0; OrderReference = string.Empty; Products = new List<ProductConfiguration>(); } public Order CreateReference(IReferenceGenerator referenceGenerator) { OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength); return this; } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Shop.Core.BaseObjects; using Shop.Core.Interfaces; namespace Shop.Core.Entites { public class Order : LifetimeBase, IReferenceable<Order> { [Key] public int OrderId { get; set; } public string OrderReference { get; set; } public List<OrderProduct> Products { get; set; } public DiscountCode DiscountCode { get; set; } public ShippingDetails ShippingMethod { get; set; } public Address ShippingAddress { get; set; } public Address BillingAddress { get; set; } public Order CreateReference(IReferenceGenerator referenceGenerator) { OrderReference = referenceGenerator.CreateReference("B-", Constants.Constants.ReferenceLength); return this; } } }
mit
C#
1d551217bf11ca6394981902a0d27fb4f82b93f7
fix build
WojcikMike/docs.particular.net
samples/header-manipulation/Version_6/Sample/MyHandler.cs
samples/header-manipulation/Version_6/Sample/MyHandler.cs
using System.Linq; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; #region handler public class MyHandler : IHandleMessages<MyMessage> { static ILog logger = LogManager.GetLogger(typeof(MyHandler)); public Task Handle(MyMessage message, IMessageHandlerContext context) { logger.Info("Hello from MyHandler"); foreach (string line in context.MessageHeaders.OrderBy(x => x.Key) .Select(x => string.Format("Key={0}, Value={1}", x.Key, x.Value))) { logger.Info(line); } return Task.FromResult(0); } } #endregion
using System.Linq; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Logging; #region handler public class MyHandler : IHandleMessages<MyMessage> { IBus bus; static ILog logger = LogManager.GetLogger(typeof(MyHandler)); public MyHandler(IBus bus) { this.bus = bus; } public Task Handle(MyMessage message) { logger.Info("Hello from MyHandler"); foreach (string line in bus.CurrentMessageContext .Headers.OrderBy(x => x.Key) .Select(x => string.Format("Key={0}, Value={1}", x.Key, x.Value))) { logger.Info(line); } return Task.FromResult(0); } } #endregion
apache-2.0
C#
7e7053ad77717d114dedb986df63d839c43d2d09
maintain original ReplyTo address
WojcikMike/docs.particular.net
samples/throttling/Version_6/Sample/ThrottlingBehavior.cs
samples/throttling/Version_6/Sample/ThrottlingBehavior.cs
using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Pipeline; using Octokit; #region ThrottlingBehavior public class ThrottlingBehavior : Behavior<IInvokeHandlerContext> { static DateTime? nextRateLimitReset; public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next) { DateTime? rateLimitReset = nextRateLimitReset; if (rateLimitReset.HasValue && rateLimitReset >= DateTime.UtcNow) { Console.WriteLine($"rate limit already exceeded. Retry after {rateLimitReset} UTC"); await DelayMessage(context, rateLimitReset.Value).ConfigureAwait(false); return; } try { await next().ConfigureAwait(false); } catch (RateLimitExceededException ex) { DateTime? nextReset = nextRateLimitReset = ex.Reset.UtcDateTime; Console.WriteLine($"rate limit exceeded. Limit resets resets at {nextReset} UTC"); await DelayMessage(context, nextReset.Value).ConfigureAwait(false); } } Task DelayMessage(IInvokeHandlerContext context, DateTime deliverAt) { SendOptions sendOptions = new SendOptions(); // delay the message to the specified delivery date sendOptions.DoNotDeliverBefore(deliverAt); // send message to this endpoint sendOptions.RouteToThisEndpoint(); // maintain the original ReplyTo address sendOptions.RouteReplyTo(context.Headers[Headers.ReplyToAddress]); return context.Send(context.MessageBeingHandled, sendOptions); } } #endregion
using System; using System.Threading.Tasks; using NServiceBus; using NServiceBus.Pipeline; using Octokit; #region ThrottlingBehavior public class ThrottlingBehavior : Behavior<IInvokeHandlerContext> { static DateTime? nextRateLimitReset; public override async Task Invoke(IInvokeHandlerContext context, Func<Task> next) { DateTime? rateLimitReset = nextRateLimitReset; if (rateLimitReset.HasValue && rateLimitReset >= DateTime.UtcNow) { Console.WriteLine($"rate limit already exceeded. Retry after {rateLimitReset} UTC"); await DelayMessage(context, rateLimitReset.Value).ConfigureAwait(false); return; } try { await next().ConfigureAwait(false); } catch (RateLimitExceededException ex) { DateTime? nextReset = nextRateLimitReset = ex.Reset.UtcDateTime; Console.WriteLine($"rate limit exceeded. Limit resets resets at {nextReset} UTC"); await DelayMessage(context, nextReset.Value).ConfigureAwait(false); } } Task DelayMessage(IInvokeHandlerContext context, DateTime deliverAt) { SendOptions sendOptions = new SendOptions(); sendOptions.RouteToThisEndpoint(); sendOptions.DoNotDeliverBefore(deliverAt); return context.Send(context.MessageBeingHandled, sendOptions); } } #endregion
apache-2.0
C#