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
8da69e42cca4a125aee1544a9cd903b2f5d3c84b
remove unused using
EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework
osu.Framework/Graphics/Video/VideoTextureUpload.cs
osu.Framework/Graphics/Video/VideoTextureUpload.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Primitives; using osuTK.Graphics.ES30; using FFmpeg.AutoGen; using SixLabors.ImageSharp.PixelFormats; namespace osu.Framework.Graphics.Textures { public unsafe class VideoTextureUpload : ITextureUpload { public ReadOnlySpan<Rgba32> Data => Span<Rgba32>.Empty; public AVFrame* Frame; /// <summary> /// The target mipmap level to upload into. /// </summary> public int Level { get; set; } /// <summary> /// The texture format for this upload. /// </summary> public PixelFormat Format => PixelFormat.Red; /// <summary> /// The target bounds for this upload. If not specified, will assume to be (0, 0, width, height). /// </summary> public RectangleI Bounds { get; set; } /// <summary> /// Sets the frame cotaining the data to be uploaded /// </summary> /// <param name="frame">The libav frame to upload.</param> public VideoTextureUpload(AVFrame* frame) { Frame = frame; } // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter public bool HasBeenUploaded => disposed; #region IDisposable Support #pragma warning disable IDE0032 // Use auto property private bool disposed; #pragma warning restore IDE0032 // Use auto property protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; fixed (AVFrame** ptr = &Frame) ffmpeg.av_frame_free(ptr); } } ~VideoTextureUpload() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Graphics.Primitives; using osuTK.Graphics.ES30; using FFmpeg.AutoGen; using AGffmpeg = FFmpeg.AutoGen.ffmpeg; using SixLabors.ImageSharp.PixelFormats; namespace osu.Framework.Graphics.Textures { public unsafe class VideoTextureUpload : ITextureUpload { public ReadOnlySpan<Rgba32> Data => Span<Rgba32>.Empty; public AVFrame* Frame; /// <summary> /// The target mipmap level to upload into. /// </summary> public int Level { get; set; } /// <summary> /// The texture format for this upload. /// </summary> public PixelFormat Format => PixelFormat.Red; /// <summary> /// The target bounds for this upload. If not specified, will assume to be (0, 0, width, height). /// </summary> public RectangleI Bounds { get; set; } /// <summary> /// Sets the frame cotaining the data to be uploaded /// </summary> /// <param name="frame">The libav frame to upload.</param> public VideoTextureUpload(AVFrame* frame) { Frame = frame; } // ReSharper disable once ConvertToAutoPropertyWithPrivateSetter public bool HasBeenUploaded => disposed; #region IDisposable Support #pragma warning disable IDE0032 // Use auto property private bool disposed; #pragma warning restore IDE0032 // Use auto property protected virtual void Dispose(bool disposing) { if (!disposed) { disposed = true; fixed (AVFrame** ptr = &Frame) ffmpeg.av_frame_free(ptr); } } ~VideoTextureUpload() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
mit
C#
2a0db8aeac74ba0dc41d7ee53c3cf96c10be8829
add missing access modifier
ppy/osu,2yangk23/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu-new,EVAST9919/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu
osu.Game.Rulesets.Catch/UI/CatchCursorContainer.cs
osu.Game.Rulesets.Catch/UI/CatchCursorContainer.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.Game.Rulesets.UI; namespace osu.Game.Rulesets.Catch.UI { public class CatchCursorContainer : GameplayCursorContainer { protected override Drawable CreateCursor() => new InvisibleCursor(); private class InvisibleCursor : Drawable { } } }
// 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.Game.Rulesets.UI; namespace osu.Game.Rulesets.Catch.UI { class CatchCursorContainer : GameplayCursorContainer { protected override Drawable CreateCursor() => new InvisibleCursor(); private class InvisibleCursor : Drawable { } } }
mit
C#
e24a5949c5a61c105e9f4670c07cdbccf0d7def6
Fix resolve
UselessToucan/osu,peppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu
osu.Game/Screens/OnlinePlay/OnlinePlayComposite.cs
osu.Game/Screens/OnlinePlay/OnlinePlayComposite.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Users; namespace osu.Game.Screens.OnlinePlay { public class OnlinePlayComposite : CompositeDrawable { [Resolved(typeof(Room))] protected Bindable<int?> RoomID { get; private set; } [Resolved(typeof(Room), nameof(Room.Name))] protected Bindable<string> RoomName { get; private set; } [Resolved(typeof(Room))] protected Bindable<User> Host { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomStatus> Status { get; private set; } [Resolved(typeof(Room))] protected Bindable<GameType> Type { get; private set; } [Resolved(typeof(Room))] protected BindableList<PlaylistItem> Playlist { get; private set; } [Resolved(typeof(Room))] protected BindableList<User> RecentParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int> ParticipantCount { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxAttempts { get; private set; } [Resolved(typeof(Room))] protected Bindable<DateTimeOffset?> EndDate { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomAvailability> Availability { get; private set; } [Resolved(typeof(Room))] protected Bindable<TimeSpan?> Duration { get; private set; } /// <summary> /// The currently selected item in the <see cref="RoomSubScreen"/>. /// May be null if this <see cref="OnlinePlayComposite"/> is not inside a <see cref="RoomSubScreen"/>. /// </summary> [CanBeNull] [Resolved(CanBeNull = true)] protected IBindable<PlaylistItem> SelectedItem { get; private set; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics.Containers; using osu.Game.Online.Rooms; using osu.Game.Screens.OnlinePlay.Match; using osu.Game.Users; namespace osu.Game.Screens.OnlinePlay { public class OnlinePlayComposite : CompositeDrawable { [Resolved(typeof(Room))] protected Bindable<int?> RoomID { get; private set; } [Resolved(typeof(Room), nameof(Room.Name))] protected Bindable<string> RoomName { get; private set; } [Resolved(typeof(Room))] protected Bindable<User> Host { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomStatus> Status { get; private set; } [Resolved(typeof(Room))] protected Bindable<GameType> Type { get; private set; } [Resolved(typeof(Room))] protected BindableList<PlaylistItem> Playlist { get; private set; } [Resolved(typeof(Room))] protected BindableList<User> RecentParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int> ParticipantCount { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxParticipants { get; private set; } [Resolved(typeof(Room))] protected Bindable<int?> MaxAttempts { get; private set; } [Resolved(typeof(Room))] protected Bindable<DateTimeOffset?> EndDate { get; private set; } [Resolved(typeof(Room))] protected Bindable<RoomAvailability> Availability { get; private set; } [Resolved(typeof(Room))] protected Bindable<TimeSpan?> Duration { get; private set; } /// <summary> /// The currently selected item in the <see cref="RoomSubScreen"/>. /// May be null if this <see cref="OnlinePlayComposite"/> is not inside a <see cref="RoomSubScreen"/>. /// </summary> [CanBeNull] [Resolved(typeof(Room), CanBeNull = true)] protected IBindable<PlaylistItem> SelectedItem { get; private set; } } }
mit
C#
d5f2aab52e4ba4f155118fe3450dc7e57a3979a5
Tidy up SkinnableComboCounter class slightly
ppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,UselessToucan/osu,peppy/osu,peppy/osu-new
osu.Game/Screens/Play/HUD/SkinnableComboCounter.cs
osu.Game/Screens/Play/HUD/SkinnableComboCounter.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.Bindables; using osu.Game.Skinning; namespace osu.Game.Screens.Play.HUD { public class SkinnableComboCounter : SkinnableDrawable, IComboCounter { public Bindable<int> Current { get; } = new Bindable<int>(); public SkinnableComboCounter() : base(new HUDSkinComponent(HUDSkinComponents.ComboCounter), skinComponent => new DefaultComboCounter()) { CentreComponent = false; } private IComboCounter skinnedCounter; protected override void SkinChanged(ISkinSource skin, bool allowFallback) { base.SkinChanged(skin, allowFallback); skinnedCounter = Drawable as IComboCounter; skinnedCounter?.Current.BindTo(Current); } } }
// 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.Bindables; using osu.Framework.Graphics; using osu.Game.Skinning; namespace osu.Game.Screens.Play.HUD { public class SkinnableComboCounter : SkinnableDrawable, IComboCounter { public SkinnableComboCounter() : base(new HUDSkinComponent(HUDSkinComponents.ComboCounter), createDefault) { CentreComponent = false; } private IComboCounter skinnedCounter; protected override void SkinChanged(ISkinSource skin, bool allowFallback) { base.SkinChanged(skin, allowFallback); skinnedCounter = Drawable as IComboCounter; skinnedCounter?.Current.BindTo(Current); } private static Drawable createDefault(ISkinComponent skinComponent) => new DefaultComboCounter(); public Bindable<int> Current { get; } = new Bindable<int>(); } }
mit
C#
e169de659c365560b13b8c657fcea40458b5d064
Fix typo
vertica-as/AnalyticsTracker,larsbj1988/AnalyticsTracker,larsbj1988/AnalyticsTracker,vertica-as/AnalyticsTracker
src/AnalyticsTracker.Tests/Commands/CookieGuardedCommandTester.cs
src/AnalyticsTracker.Tests/Commands/CookieGuardedCommandTester.cs
using System; using NUnit.Framework; using Vertica.AnalyticsTracker.Commands; using Vertica.AnalyticsTracker.Commands.Events; namespace AnalyticsTracker.Tests.Commands { [TestFixture] public class CookieGuardedCommandTester { [Test] public void Render_CleanId_CookieSetAndChecked() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "myid", 365, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("if (document.cookie.search(/AnalyticsTrackerGuardmyid=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmyid=true; Expires=' + new Date(2015, 08, 05).toUTCString();")); } [Test] public void Render_WeirdId_IdIsEncoded() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "my id = weird;stuff", 365, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("if (document.cookie.search(/AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true; Expires=' + new Date(2015, 08, 05).toUTCString();")); } [Test] public void Render_CustomTimeSpan_CorrectTimespanSet() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "my id = weird;stuff", 7, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("if (document.cookie.search(/AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true; Expires=' + new Date(2014, 08, 12).toUTCString();")); } } }
using System; using NUnit.Framework; using Vertica.AnalyticsTracker.Commands; using Vertica.AnalyticsTracker.Commands.Events; namespace AnalyticsTracker.Tests.Commands { [TestFixture] public class CookieGuardedCommandTester { [Test] public void Render_CleanId_CookieSetAndChecked() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "myid", 365, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("dif (document.cookie.search(/AnalyticsTrackerGuardmyid=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmyid=true; Expires=' + new Date(2015, 08, 05).toUTCString();")); } [Test] public void Render_WeirdId_IdIsEncoded() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "my id = weird;stuff", 365, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("if (document.cookie.search(/AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true; Expires=' + new Date(2015, 08, 05).toUTCString();")); } [Test] public void Render_CustomTimeSpan_CorrectTimespanSet() { DateTime? now = new DateTime(2014, 09, 05); var cmd = new CookieGuardedCommand(new EventCommand("cat", "act"), "my id = weird;stuff", 7, now); var rendered = cmd.RenderCommand(); Assert.That(rendered, Is.StringContaining("if (document.cookie.search(/AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true/) === -1)")); Assert.That(rendered, Is.StringContaining("document.cookie = 'AnalyticsTrackerGuardmy%20id%20%3D%20weird%3Bstuff=true; Expires=' + new Date(2014, 08, 12).toUTCString();")); } } }
mit
C#
44ba93eb49ec2acf25736ebcacc1313ee3d9716c
Hide internals from Peachpie.LanguageServer
iolevel/peachpie-concept,iolevel/peachpie-concept,iolevel/peachpie,peachpiecompiler/peachpie,peachpiecompiler/peachpie,iolevel/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,iolevel/peachpie
src/Peachpie.CodeAnalysis/Properties/AssemblyInfo.cs
src/Peachpie.CodeAnalysis/Properties/AssemblyInfo.cs
using System.Resources; 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: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo(@"peach, PublicKey=002400000480000094000000060200000024000052534131000400000100010009c58cd335e058f85ad6d68e0369a31a9f6a999127e452d7714cb4db355f0321d5c2e766d68c0beb766afc4289ad1304161afca7e6212d7abd6142b070e13e4a5e314d303d10ada6cd77c6fc52fa778532f30c02b419b1b72c1f594cdcabc999174c5633b90e99eeb641af3eaafc64c3a238edc81d8c3587bd08809abb79c8ad")]
using System.Resources; 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: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] [assembly: InternalsVisibleTo(@"peach, PublicKey=002400000480000094000000060200000024000052534131000400000100010009c58cd335e058f85ad6d68e0369a31a9f6a999127e452d7714cb4db355f0321d5c2e766d68c0beb766afc4289ad1304161afca7e6212d7abd6142b070e13e4a5e314d303d10ada6cd77c6fc52fa778532f30c02b419b1b72c1f594cdcabc999174c5633b90e99eeb641af3eaafc64c3a238edc81d8c3587bd08809abb79c8ad")] [assembly: InternalsVisibleTo(@"Peachpie.LanguageServer, PublicKey=002400000480000094000000060200000024000052534131000400000100010009c58cd335e058f85ad6d68e0369a31a9f6a999127e452d7714cb4db355f0321d5c2e766d68c0beb766afc4289ad1304161afca7e6212d7abd6142b070e13e4a5e314d303d10ada6cd77c6fc52fa778532f30c02b419b1b72c1f594cdcabc999174c5633b90e99eeb641af3eaafc64c3a238edc81d8c3587bd08809abb79c8ad")]
apache-2.0
C#
80edc6389654eea5fe3b8b092c2c653b3b4d7bcd
support Any and IPv6 as listening IP
kerryjiang/SuperSocket,kerryjiang/SuperSocket,memleaks/SuperSocket
src/SuperSocket.Server/Internal/SuperSocketEndPointInformation.cs
src/SuperSocket.Server/Internal/SuperSocketEndPointInformation.cs
using System; using System.IO.Pipelines; using System.Net.Sockets; using System.Threading.Tasks; using System.Buffers; using SuperSocket.Channel; using SuperSocket.ProtoBase; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using System.Net; namespace SuperSocket.Server { internal class SuperSocketEndPointInformation : IEndPointInformation { public SuperSocketEndPointInformation(ListenOptions listenOptions) { Type = ListenType.IPEndPoint; var ip = IPAddress.None; if ("any".Equals(listenOptions.Ip, StringComparison.OrdinalIgnoreCase)) { ip = IPAddress.Any; } else if ("ipv6any".Equals(listenOptions.Ip, StringComparison.OrdinalIgnoreCase)) { ip = IPAddress.IPv6Any; } else { ip = IPAddress.Parse(listenOptions.Ip); } IPEndPoint = new IPEndPoint(ip, listenOptions.Port); } public ListenType Type { get; set; } public IPEndPoint IPEndPoint { get; set; } public string SocketPath { get; set; } public ulong FileHandle { get; set; } public FileHandleType HandleType { get; set; } public bool NoDelay { get; set; } } }
using System; using System.IO.Pipelines; using System.Net.Sockets; using System.Threading.Tasks; using System.Buffers; using SuperSocket.Channel; using SuperSocket.ProtoBase; using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal; using System.Net; namespace SuperSocket.Server { internal class SuperSocketEndPointInformation : IEndPointInformation { public SuperSocketEndPointInformation(ListenOptions listenOptions) { Type = ListenType.IPEndPoint; IPEndPoint = new IPEndPoint(IPAddress.Parse(listenOptions.Ip), listenOptions.Port); } public ListenType Type { get; set; } public IPEndPoint IPEndPoint { get; set; } public string SocketPath { get; set; } public ulong FileHandle { get; set; } public FileHandleType HandleType { get; set; } public bool NoDelay { get; set; } } }
apache-2.0
C#
4caf74c0293e6daaeebef4e22d6d84560dc9d40f
indent changes
yoghadj/or-tools,LeslieW/or-tools2,LeslieW/or-tools,petesburgh/or-tools,zafar-hussain/or-tools,gtara/or-tools,petesburgh/or-tools,LeslieW/or-tools2,petesburgh/or-tools,omerucn/or-tools,bulentsoykan/or-tools,bulentsoykan/or-tools,LeslieW/or-tools,omerucn/or-tools,zafar-hussain/or-tools,gtara/or-tools,LeslieW/or-tools2,jggtrujillo/or-tools,jggtrujillo/or-tools,LeslieW/or-tools,jggtrujillo/or-tools,omerucn/or-tools,LeslieW/or-tools2,petesburgh/or-tools,zafar-hussain/or-tools,omerucn/or-tools,zafar-hussain/or-tools,LeslieW/or-tools,jggtrujillo/or-tools,gtara/or-tools,LeslieW/or-tools,LeslieW/or-tools,gtara/or-tools,bulentsoykan/or-tools,yoghadj/or-tools,LeslieW/or-tools2,zafar-hussain/or-tools,LeslieW/or-tools2,jggtrujillo/or-tools,bulentsoykan/or-tools,omerucn/or-tools,yoghadj/or-tools,gtara/or-tools,zafar-hussain/or-tools,gtara/or-tools,petesburgh/or-tools,yoghadj/or-tools,jggtrujillo/or-tools,omerucn/or-tools,yoghadj/or-tools,bulentsoykan/or-tools,petesburgh/or-tools,bulentsoykan/or-tools,yoghadj/or-tools
src/com/google/ortools/constraintsolver/IntervalVarArrayHelper.cs
src/com/google/ortools/constraintsolver/IntervalVarArrayHelper.cs
// Copyright 2010-2012 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Google.OrTools.ConstraintSolver { using System; using System.Collections.Generic; // IntervalVar[] helper class. public static class IntervalVarArrayHelper { // get solver from array of interval variables private static Solver GetSolver(IntervalVar[] vars) { if (vars == null || vars.Length <= 0) throw new ArgumentException("Array <vars> cannot be null or empty"); return vars[0].solver(); } public static Constraint Disjunctive(this IntervalVar[] vars) { Solver solver = GetSolver(vars); return solver.MakeDisjunctiveConstraint(vars); } public static SequenceVar SequenceVar(this IntervalVar[] vars, String name) { Solver solver = GetSolver(vars); return solver.MakeSequenceVar(vars, name); } public static Constraint Cumulative(this IntervalVar[] vars, long[] demands, long capacity, String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } public static Constraint Cumulative(this IntervalVar[] vars, int[] demands, long capacity, String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } } } // namespace Google.OrTools.ConstraintSolver
// Copyright 2010-2012 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Google.OrTools.ConstraintSolver { using System; using System.Collections.Generic; // IntervalVar[] helper class. public static class IntervalVarArrayHelper { // get solver from array of interval variables private static Solver GetSolver(IntervalVar[] vars) { if (vars == null || vars.Length <= 0) throw new ArgumentException("Array <vars> cannot be null or empty"); return vars[0].solver(); } public static Constraint Disjunctive(this IntervalVar[] vars) { Solver solver = GetSolver(vars); return solver.MakeDisjunctiveConstraint(vars); } public static SequenceVar SequenceVar(this IntervalVar[] vars, String name) { Solver solver = GetSolver(vars); return solver.MakeSequenceVar(vars, name); } public static Constraint Cumulative(this IntervalVar[] vars, long[] demands, long capacity, String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } public static Constraint Cumulative(this IntervalVar[] vars, int[] demands, long capacity, String name) { Solver solver = GetSolver(vars); return solver.MakeCumulative(vars, demands, capacity, name); } } } // namespace Google.OrTools.ConstraintSolver
apache-2.0
C#
b3cb45de37bf6983780b9960265abaef0be398b4
Add ToBitArray overload with length
killnine/s7netplus
S7.Net/Types/Bit.cs
S7.Net/Types/Bit.cs
using System; using System.Collections; namespace S7.Net.Types { /// <summary> /// Contains the conversion methods to convert Bit from S7 plc to C#. /// </summary> public static class Bit { /// <summary> /// Converts a Bit to bool /// </summary> public static bool FromByte(byte v, byte bitAdr) { return (((int)v & (1 << bitAdr)) != 0); } /// <summary> /// Converts an array of bytes to a BitArray. /// </summary> /// <param name="bytes">The bytes to convert.</param> /// <returns>A BitArray with the same number of bits and equal values as <paramref name="bytes"/>.</returns> public static BitArray ToBitArray(byte[] bytes) => ToBitArray(bytes, bytes.Length * 8); /// <summary> /// Converts an array of bytes to a BitArray. /// </summary> /// <param name="bytes">The bytes to convert.</param> /// <param name="length">The number of bits to return.</param> /// <returns>A BitArray with <paramref name="length"/> bits.</returns> public static BitArray ToBitArray(byte[] bytes, int length) { if (length > bytes.Length * 8) throw new ArgumentException($"Not enough data in bytes to return {length} bits.", nameof(bytes)); var bitArr = new BitArray(bytes); var bools = new bool[length]; for (var i = 0; i < length; i++) bools[i] = bitArr[i]; return new BitArray(bools); } } }
using System.Collections; namespace S7.Net.Types { /// <summary> /// Contains the conversion methods to convert Bit from S7 plc to C#. /// </summary> public static class Bit { /// <summary> /// Converts a Bit to bool /// </summary> public static bool FromByte(byte v, byte bitAdr) { return (((int)v & (1 << bitAdr)) != 0); } /// <summary> /// Converts an array of bytes to a BitArray /// </summary> public static BitArray ToBitArray(byte[] bytes) { BitArray bitArr = new BitArray(bytes); return bitArr; } } }
mit
C#
908bf539b320acfa63b7c1b706617d5e3f3e099f
Add some missing user statuses
Goz3rr/SkypeSharp
SkypeSharp/IUser.cs
SkypeSharp/IUser.cs
namespace SkypeSharp { public enum UserStatus { OnlineStatus, BuddyStatus, ReceivedAuthRequest, IsAuthorized, IsBlocked, Timezone, NROF_AUTHED_BUDDIES } public interface IUser : ISkypeObject { string FullName { get; } string Language { get; } string Country { get; } string City { get; } void Authorize(); } }
namespace SkypeSharp { public enum UserStatus { OnlineStatus, BuddyStatus, ReceivedAuthRequest } public interface IUser : ISkypeObject { string FullName { get; } string Language { get; } string Country { get; } string City { get; } void Authorize(); } }
mit
C#
e39d90fe4965ead6262994b4e59976095bdc410e
fix brace layout
NickStrupat/CacheLineSize.NET
CacheLine.cs
CacheLine.cs
using System; using System.Runtime.InteropServices; namespace NickStrupat { public static class CacheLine { public static readonly Int32 Size = GetSize(); private static Int32 GetSize() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Windows.GetSize(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return Linux.GetSize(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return OSX.GetSize(); throw new Exception("Unrecognized OS platform."); } } }
using System; using System.Runtime.InteropServices; namespace NickStrupat { public static class CacheLine { public static readonly Int32 Size = GetSize(); private static Int32 GetSize() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return Windows.GetSize(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return Linux.GetSize(); if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return OSX.GetSize(); throw new Exception("Unrecognized OS platform."); } } }
mit
C#
1ca84a751a39503215f8ca0cc2f25cfc5615d5ad
Fix load issue with UnknownMapEntity (NullReferenceException)
ethanmoffat/EndlessClient
EOLib.IO/Map/UnknownMapEntity.cs
EOLib.IO/Map/UnknownMapEntity.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; namespace EOLib.IO.Map { public class UnknownMapEntity : IMapEntity { public const int DATA_SIZE = 4; public int X { get; private set; } public int Y { get; private set; } public byte[] RawData { get; private set; } public UnknownMapEntity() : this(-1, -1, new byte[0]) { } private UnknownMapEntity(int x, int y, byte[] rawData) { X = x; Y = y; RawData = rawData; } public UnknownMapEntity WithX(int x) { var newEntity = MakeCopy(this); newEntity.X = x; return newEntity; } public UnknownMapEntity WithY(int y) { var newEntity = MakeCopy(this); newEntity.Y = y; return newEntity; } public UnknownMapEntity WithRawData(byte[] rawData) { var newEntity = MakeCopy(this); newEntity.RawData = rawData; return newEntity; } private static UnknownMapEntity MakeCopy(UnknownMapEntity src) { var copy = new byte[src.RawData.Length]; Array.Copy(src.RawData, copy, copy.Length); return new UnknownMapEntity(src.X, src.Y, copy); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; namespace EOLib.IO.Map { public class UnknownMapEntity : IMapEntity { public const int DATA_SIZE = 4; public int X { get; private set; } public int Y { get; private set; } public byte[] RawData { get; private set; } public UnknownMapEntity() : this(-1, -1, null) { } private UnknownMapEntity(int x, int y, byte[] rawData) { X = x; Y = y; RawData = rawData; } public UnknownMapEntity WithX(int x) { var newEntity = MakeCopy(this); newEntity.X = x; return newEntity; } public UnknownMapEntity WithY(int y) { var newEntity = MakeCopy(this); newEntity.Y = y; return newEntity; } public UnknownMapEntity WithRawData(byte[] rawData) { var newEntity = MakeCopy(this); newEntity.RawData = rawData; return newEntity; } private static UnknownMapEntity MakeCopy(UnknownMapEntity src) { var copy = new byte[src.RawData.Length]; Array.Copy(src.RawData, copy, copy.Length); return new UnknownMapEntity(src.X, src.Y, copy); } } }
mit
C#
f7b519fe2c78254dd38d15ecc23025c2e9965e6e
Change NuGetRestore to be executed unconditionally.
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
bootstrapping/DefaultBuild.cs
bootstrapping/DefaultBuild.cs
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.FileSystem.FileSystemTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.EnvironmentInfo; class DefaultBuild : GitHubBuild { public static void Main () => Execute<DefaultBuild>(x => x.Compile); Target Restore => _ => _ .Executes(() => { NuGetRestore(SolutionFile); if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild(s => DefaultSettings.MSBuildRestore); }); Target Compile => _ => _ .DependsOn(Restore) .Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile .SetMSBuildVersion(MSBuildVersion))); MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles(SolutionDirectory, "*.xproj").Any() ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default(MSBuildVersion); }
using System; using System.Linq; using Nuke.Common; using Nuke.Common.Tools.MSBuild; using Nuke.Core; using static Nuke.Common.FileSystem.FileSystemTasks; using static Nuke.Common.Tools.MSBuild.MSBuildTasks; using static Nuke.Common.Tools.NuGet.NuGetTasks; using static Nuke.Core.EnvironmentInfo; // ReSharper disable CheckNamespace class DefaultBuild : GitHubBuild { public static void Main () => Execute<DefaultBuild> (x => x.Compile); Target Restore => _ => _ .Executes (() => { if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017) MSBuild (s => DefaultSettings.MSBuildRestore); else NuGetRestore (SolutionFile); }); Target Compile => _ => _ .DependsOn (Restore) .Executes (() => MSBuild (s => DefaultSettings.MSBuildCompile .SetMSBuildVersion (MSBuildVersion))); MSBuildVersion? MSBuildVersion => !IsUnix ? GlobFiles (SolutionDirectory, "*.xproj").Any () ? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015 : Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017 : default (MSBuildVersion); }
mit
C#
289f87cbc3e4992484c8571bf63af531b45ad891
Switch to version 1.2.9
Abc-Arbitrage/Zebus,Abc-Arbitrage/Zebus.Directory
src/SharedVersionInfo.cs
src/SharedVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.2.9")] [assembly: AssemblyFileVersion("1.2.9")] [assembly: AssemblyInformationalVersion("1.2.9")]
using System.Reflection; [assembly: AssemblyVersion("1.2.8")] [assembly: AssemblyFileVersion("1.2.8")] [assembly: AssemblyInformationalVersion("1.2.8")]
mit
C#
434253517ef27f08d1ad6edf22f2fdb16ec459b5
Update WalletWasabi.Gui/CommandLine/MixerCommand.cs
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/CommandLine/MixerCommand.cs
WalletWasabi.Gui/CommandLine/MixerCommand.cs
using Mono.Options; using System; using System.Collections.Generic; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Gui.CommandLine { internal class MixerCommand : Command { public MixerCommand(Daemon daemon) : base("mix", "Start mixing without the GUI with the specified wallet.") { Daemon = daemon; Options = new OptionSet() { "usage: mix --wallet:WalletName --keepalive", "", "Start mixing without the GUI with the specified wallet.", "eg: ./wassabee mix --wallet:MyWalletName --keepalive", { "h|help", "Displays help page and exit.", x => ShowHelp = x != null }, { "w|wallet=", "The name of the wallet file.", x => WalletName = x }, { "destination=", "The name of the destination wallet file.", x => DestinationWalletName = x }, { "keepalive", "Do not exit the software after mixing has been finished, rather keep mixing when new money arrives.", x => KeepMixAlive = x != null } }; } public string WalletName { get; set; } public string DestinationWalletName { get; set; } public bool KeepMixAlive { get; set; } public bool ShowHelp { get; set; } public Daemon Daemon { get; } public override async Task<int> InvokeAsync(IEnumerable<string> args) { var error = false; try { var extra = Options.Parse(args); if (ShowHelp) { Options.WriteOptionDescriptions(CommandSet.Out); } if (!error && !ShowHelp) { await Daemon.RunAsync(WalletName, DestinationWalletName ?? WalletName, KeepMixAlive); } } catch (Exception ex) { if (!(ex is OperationCanceledException)) { Logger.LogCritical(ex); } Console.WriteLine($"commands: There was a problem interpreting the command, please review it."); Logger.LogDebug(ex); error = true; } Environment.Exit(error ? 1 : 0); return 0; } } }
using Mono.Options; using System; using System.Collections.Generic; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Gui.CommandLine { internal class MixerCommand : Command { public MixerCommand(Daemon daemon) : base("mix", "Start mixing without the GUI with the specified wallet.") { Daemon = daemon; Options = new OptionSet() { "usage: mix --wallet:WalletName --keepalive", "", "Start mixing without the GUI with the specified wallet.", "eg: ./wassabee mix --wallet:MyWalletName --keepalive", { "h|help", "Displays help page and exit.", x => ShowHelp = x != null }, { "w|wallet=", "The name of the wallet file.", x => WalletName = x }, { "destination:", "The name of the destination wallet file.", x => DestinationWalletName = x }, { "keepalive", "Do not exit the software after mixing has been finished, rather keep mixing when new money arrives.", x => KeepMixAlive = x != null } }; } public string WalletName { get; set; } public string DestinationWalletName { get; set; } public bool KeepMixAlive { get; set; } public bool ShowHelp { get; set; } public Daemon Daemon { get; } public override async Task<int> InvokeAsync(IEnumerable<string> args) { var error = false; try { var extra = Options.Parse(args); if (ShowHelp) { Options.WriteOptionDescriptions(CommandSet.Out); } if (!error && !ShowHelp) { await Daemon.RunAsync(WalletName, DestinationWalletName ?? WalletName, KeepMixAlive); } } catch (Exception ex) { if (!(ex is OperationCanceledException)) { Logger.LogCritical(ex); } Console.WriteLine($"commands: There was a problem interpreting the command, please review it."); Logger.LogDebug(ex); error = true; } Environment.Exit(error ? 1 : 0); return 0; } } }
mit
C#
723562727cdaae5f564f9ee6d473709eeda873fb
Update XmlnsDefinitionsDock.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D/Serializer/Xaml/XmlnsDefinitionsDock.cs
src/Core2D/Serializer/Xaml/XmlnsDefinitionsDock.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Serializer.Xaml; using Portable.Xaml.Markup; [assembly: XmlnsDefinition(XamlConstants.DockNamespace, "Dock.Model", AssemblyName = "Dock.Model")] [assembly: XmlnsPrefix(XamlConstants.DockNamespace, "c")]
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Portable.Xaml.Markup; using Core2D.Serializer.Xaml; [assembly: XmlnsDefinition(XamlConstants.DockNamespace, "Dock.Model", AssemblyName = "Dock.Model")] [assembly: XmlnsPrefix(XamlConstants.DockNamespace, "c")]
mit
C#
f87afa79017ebf8939d39dbc58303df7f8af4199
align source
marufbd/Zephyr.NET,marufbd/Zephyr.NET
src/DemoApp.Web/Controllers/PublisherController.cs
src/DemoApp.Web/Controllers/PublisherController.cs
using System; using System.Web.Mvc; using DemoApp.Web.DomainModels; using Microsoft.Practices.ServiceLocation; using Zephyr.Data.Repository; using Zephyr.Data.Repository.Contract; using Zephyr.Data.UnitOfWork; using Zephyr.Web.Mvc.Controllers; using System.Linq; using Zephyr.Web.Mvc.Extentions; using Zephyr.Web.Mvc.Html.Flash; using Zephyr.Web.Mvc.ViewModels; namespace DemoApp.Web.Controllers { [Authorize] public class PublisherController : ZephyrCRUDController<Publisher> { [HttpPost] public ActionResult Edit(Publisher publisher) { if(ModelState.IsValid) { //always use Unit of work for save/update using (UnitOfWorkScope.Start()) { var repo = ServiceLocator.Current.GetInstance<IRepository<Publisher>>(); repo.SaveOrUpdate(publisher); return RedirectToAction("List").WithFlash(new { alert_success = "New <strong>Publisher</strong> added successfully" }); } } return View("Edit", new EditViewModel<Publisher>(){Model = publisher}); } } }
using System; using System.Web.Mvc; using DemoApp.Web.DomainModels; using Microsoft.Practices.ServiceLocation; using Zephyr.Data.Repository; using Zephyr.Data.Repository.Contract; using Zephyr.Data.UnitOfWork; using Zephyr.Web.Mvc.Controllers; using System.Linq; using Zephyr.Web.Mvc.Extentions; using Zephyr.Web.Mvc.Html.Flash; using Zephyr.Web.Mvc.ViewModels; namespace DemoApp.Web.Controllers { public class PublisherController : ZephyrCRUDController<Publisher> { [HttpPost] public ActionResult Edit(Publisher publisher) { if(ModelState.IsValid) { //always use Unit of work for save/update using (UnitOfWorkScope.Start()) { var repo = ServiceLocator.Current.GetInstance<IRepository<Publisher>>(); repo.SaveOrUpdate(publisher); return RedirectToAction("List").WithFlash(new { alert_success = "New <strong>Publisher</strong> added successfully" }); } } return View("Edit", new EditViewModel<Publisher>(){Model = publisher}); } } }
apache-2.0
C#
5ee5a8a0a11af78adfbbe5d40d6727c064da93cf
Improve usage of pointers in StringBuilder.Append(ROS)
thnetii/dotnet-common
src/THNETII.Common/Text/StringBuilderExtensions.cs
src/THNETII.Common/Text/StringBuilderExtensions.cs
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace THNETII.Common.Text { /// <summary> /// Provides extension methods for the <see cref="StringBuilder"/> class. /// </summary> public static class StringBuilderExtensions { /// <summary> /// Appends a span of Unicode characters to the specified /// <see cref="StringBuilder"/> instance. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append to. Must not be <see langword="null"/>.</param> /// <param name="value">A read-only span of unicode characters to append.</param> /// <returns>The same instance as specified by <paramref name="builder"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Enlarging the value of <paramref name="builder"/> would exceed the /// <see cref="StringBuilder.MaxCapacity"/> property of <paramref name="builder"/>. /// </exception> /// <seealso href="https://github.com/dotnet/coreclr/pull/13163">Add StringBuilder Span-based APIs #13163</seealso> public static StringBuilder Append(this StringBuilder builder, ReadOnlySpan<char> value) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (value.Length > 0) { unsafe { fixed (char* valueChars = value) { builder.Append(valueChars, value.Length); } } } return builder; } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace THNETII.Common.Text { /// <summary> /// Provides extension methods for the <see cref="StringBuilder"/> class. /// </summary> public static class StringBuilderExtensions { /// <summary> /// Appends a span of Unicode characters to the specified /// <see cref="StringBuilder"/> instance. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append to. Must not be <see langword="null"/>.</param> /// <param name="value">A read-only span of unicode characters to append.</param> /// <returns>The same instance as specified by <paramref name="builder"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="builder"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// Enlarging the value of <paramref name="builder"/> would exceed the /// <see cref="StringBuilder.MaxCapacity"/> property of <paramref name="builder"/>. /// </exception> /// <seealso href="https://github.com/dotnet/coreclr/pull/13163">Add StringBuilder Span-based APIs #13163</seealso> public static StringBuilder Append(this StringBuilder builder, ReadOnlySpan<char> value) { if (builder is null) { throw new ArgumentNullException(nameof(builder)); } if (value.Length > 0) { unsafe { fixed (char* valueChars = &MemoryMarshal.GetReference(value)) { builder.Append(valueChars, value.Length); } } } return builder; } } }
mit
C#
289aa829ed18b17161f5abfd2920e41f4eb01765
Update WebSocketManagerExtensions.cs
radu-matei/websocket-manager,radu-matei/websocket-manager,radu-matei/websocket-manager
src/WebSocketManager/WebSocketManagerExtensions.cs
src/WebSocketManager/WebSocketManagerExtensions.cs
using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace WebSocketManager { public static class WebSocketManagerExtensions { public static IServiceCollection AddWebSocketManager(this IServiceCollection services, Assembly assembly = null) { services.AddTransient<WebSocketConnectionManager>(); Assembly ass = assembly ?? Assembly.GetEntryAssembly(); foreach (var type in ass.ExportedTypes) { if (type.GetTypeInfo().BaseType == typeof(WebSocketHandler)) { services.AddSingleton(type); } } return services; } public static IApplicationBuilder MapWebSocketManager(this IApplicationBuilder app, PathString path, WebSocketHandler handler) { return app.Map(path, (_app) => _app.UseMiddleware<WebSocketManagerMiddleware>(handler)); } } }
using System.Reflection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; namespace WebSocketManager { public static class WebSocketManagerExtensions { public static IServiceCollection AddWebSocketManager(this IServiceCollection services) { services.AddTransient<WebSocketConnectionManager>(); foreach (var type in Assembly.GetEntryAssembly().ExportedTypes) { if (type.GetTypeInfo().BaseType == typeof(WebSocketHandler)) { services.AddSingleton(type); } } return services; } public static IApplicationBuilder MapWebSocketManager(this IApplicationBuilder app, PathString path, WebSocketHandler handler) { return app.Map(path, (_app) => _app.UseMiddleware<WebSocketManagerMiddleware>(handler)); } } }
mit
C#
a4330e7204fb7def83ebab8369caaf85d31db24a
add default help screen for parser
nmklotas/GitLabCLI
src/GitlabCmd.Console/App/Container.cs
src/GitlabCmd.Console/App/Container.cs
using Castle.MicroKernel.Registration; using Castle.Windsor; using CommandLine; using GitlabCmd.Console.Configuration; using GitlabCmd.Console.GitLab; using Microsoft.Extensions.Configuration; namespace GitlabCmd.Console.App { public static class Container { public static WindsorContainer Build() { var container = new WindsorContainer(); container.Register(Component.For<Parser>().UsingFactoryMethod(c => Parser.Default)); container.Register(Component.For<GitLabFacade>()); container.Register(Component.For<LaunchHandler>()); container.Register(Component.For<ParametersHandler>()); container.Register(Component.For<OutputPresenter>()); container.Register(Component.For<ConfigurationHandler>()); container.Register(Component.For<GitLabIssueHandler>()); container.Register(Component.For<MergeRequestsHandler>()); container.Register(Component.For<AppSettingsValidationHandler>()); container.Register(Component.For<GitLabClientFactory>()); RegisterAppSettings(container); return container; } private static void RegisterAppSettings(WindsorContainer container) { var builder = new ConfigurationBuilder(). AddJsonFile("appsettings.json", optional: true, reloadOnChange: true). AddEnvironmentVariables(); container.Register(Component.For<AppSettings>().UsingFactoryMethod(c => { var appSettings = new AppSettings(); builder.Build().GetSection("appConfiguration").Bind(appSettings); return appSettings; })); } } }
using System; using Castle.MicroKernel.Registration; using Castle.Windsor; using CommandLine; using GitlabCmd.Console.Configuration; using GitlabCmd.Console.GitLab; using Microsoft.Extensions.Configuration; using NGitLab; namespace GitlabCmd.Console.App { public static class Container { public static WindsorContainer Build() { var container = new WindsorContainer(); container.Register(Component.For<Parser>()); container.Register(Component.For<GitLabFacade>()); container.Register(Component.For<LaunchHandler>()); container.Register(Component.For<ParametersHandler>()); container.Register(Component.For<OutputPresenter>()); container.Register(Component.For<GitLabIssueHandler>()); container.Register(Component.For<MergeRequestsHandler>()); container.Register(Component.For<AppSettingsValidationHandler>()); container.Register(Component.For<GitLabClientFactory>()); RegisterAppSettings(container); return container; } private static void RegisterAppSettings(WindsorContainer container) { var builder = new ConfigurationBuilder(). AddJsonFile("appsettings.json", optional: true, reloadOnChange: true). AddEnvironmentVariables(); container.Register(Component.For<AppSettings>().UsingFactoryMethod(c => { var appSettings = new AppSettings(); builder.Build().GetSection("appConfiguration").Bind(appSettings); return appSettings; })); } } }
mit
C#
6a44f9d7a4b318d0193460faf761af24ae350112
fix - missing AssemblyVersion for AppVeyor Assembly Patching
jdevillard/JmesPath.Net
src/jmespath.net.signed/Properties/AssemblyInfo.cs
src/jmespath.net.signed/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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("jmespath.net")] [assembly: AssemblyTrademark("")] // 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("c1b8ba55-2115-406f-944d-39efa384879d")] [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("jmespath.net")] [assembly: AssemblyTrademark("")] // 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("c1b8ba55-2115-406f-944d-39efa384879d")]
apache-2.0
C#
9bf2c450615aa6ef5c3050d8467a7a7a082f6ca4
fix destoryitem2 bug.
kanonmelodis/ElectronicObserver,tsanie/ElectronicObserver,CNA-Bld/ElectronicObserver
ElectronicObserver/Observer/kcsapi/api_req_kousyou/destroyitem2.cs
ElectronicObserver/Observer/kcsapi/api_req_kousyou/destroyitem2.cs
using ElectronicObserver.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicObserver.Observer.kcsapi.api_req_kousyou { public class destroyitem2 : APIBase { public override void OnRequestReceived( Dictionary<string, string> data ) { KCDatabase db = KCDatabase.Instance; // 削除処理が終わってからだと装備データが取れないため db.QuestProgress.EquipmentDiscarded( APIName, data ); foreach ( string sid in data["api_slotitem_ids"].Split( ",".ToCharArray() ) ) { int id = int.Parse( sid ); Utility.Logger.Add( 2, KCDatabase.Instance.Equipments[id].NameWithLevel + " を廃棄しました。" ); db.Equipments.Remove( id ); } base.OnRequestReceived( data ); } public override void OnResponseReceived( dynamic data ) { KCDatabase.Instance.Material.LoadFromResponse( APIName, data ); base.OnResponseReceived( (object)data ); } public override bool IsRequestSupported { get { return true; } } public override bool IsResponseSupported { get { return true; } } public override string APIName { get { return "api_req_kousyou/destroyitem2"; } } } }
using ElectronicObserver.Data; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ElectronicObserver.Observer.kcsapi.api_req_kousyou { public class destroyitem2 : APIBase { Dictionary<string, string> request; public override void OnRequestReceived( Dictionary<string, string> data ) { request = data; base.OnRequestReceived( data ); } public override void OnResponseReceived( dynamic data ) { if ( request != null ) { KCDatabase db = KCDatabase.Instance; // 削除処理が終わってからだと装備データが取れないため db.QuestProgress.EquipmentDiscarded( APIName, data ); foreach ( string sid in data["api_slotitem_ids"].Split( ",".ToCharArray() ) ) { int id = int.Parse( sid ); Utility.Logger.Add( 2, KCDatabase.Instance.Equipments[id].NameWithLevel + " 已废弃。" ); db.Equipments.Remove( id ); } } KCDatabase.Instance.Material.LoadFromResponse( APIName, data ); base.OnResponseReceived( (object)data ); } public override bool IsRequestSupported { get { return true; } } public override bool IsResponseSupported { get { return true; } } public override string APIName { get { return "api_req_kousyou/destroyitem2"; } } } }
mit
C#
985dc93d17c6e388de9ab70d009b260ab7b2c83d
fix misspelling of Kubernetes (#904)
ILMTitan/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,GoogleCloudPlatform/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio,ILMTitan/google-cloud-visualstudio
GoogleCloudExtension/GoogleCloudExtension.GCloud/Models/GkeList.cs
GoogleCloudExtension/GoogleCloudExtension.GCloud/Models/GkeList.cs
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Newtonsoft.Json; using System.Collections.Generic; namespace GoogleCloudExtension.GCloud.Models { /// <summary> /// Common class for all of the lists returned from Kubernetes. /// </summary> /// <typeparam name="T"></typeparam> public class GkeList<T> { /// <summary> /// The items in the list. /// </summary> [JsonProperty("items")] public IList<T> Items { get; set; } } }
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Newtonsoft.Json; using System.Collections.Generic; namespace GoogleCloudExtension.GCloud.Models { /// <summary> /// Common class for all of the lists returned from Kuberentes. /// </summary> /// <typeparam name="T"></typeparam> public class GkeList<T> { /// <summary> /// The items in the list. /// </summary> [JsonProperty("items")] public IList<T> Items { get; set; } } }
apache-2.0
C#
0c4e27fbab2b23095cece63594856197dfa1d3ff
Remove some initialzation code
PeterOrneholm/session-aspnetcore,PeterOrneholm/session-aspnetcore
AspNetCore/MyWebappCore/Startup.cs
AspNetCore/MyWebappCore/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MyWebappCore { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvcWithDefaultRoute(); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MyWebappCore { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseMvcWithDefaultRoute(); } } }
mit
C#
ea0146dc85eae657cd72e3aae5b42baa9e0df16a
Fix for using (IDisposable) statement
phenixdotnet/cake,mholo65/cake,UnbelievablyRitchie/cake,gep13/cake,vlesierse/cake,yvschmid/cake,cake-build/cake,DixonD-git/cake,adamhathcock/cake,danielrozo/cake,ferventcoder/cake,daveaglick/cake,marcosnz/cake,UnbelievablyRitchie/cake,DavidDeSloovere/cake,devlead/cake,wallymathieu/cake,Invenietis/cake,daveaglick/cake,cake-build/cake,mholo65/cake,Invenietis/cake,gep13/cake,michael-wolfenden/cake,SharpeRAD/Cake,andycmaj/cake,RichiCoder1/cake,ferventcoder/cake,RehanSaeed/cake,SharpeRAD/Cake,danielrozo/cake,vlesierse/cake,thomaslevesque/cake,adamhathcock/cake,jrnail23/cake,jrnail23/cake,andycmaj/cake,michael-wolfenden/cake,Sam13/cake,RichiCoder1/cake,robgha01/cake,Sam13/cake,yvschmid/cake,Julien-Mialon/cake,phrusher/cake,thomaslevesque/cake,RehanSaeed/cake,robgha01/cake,Julien-Mialon/cake,patriksvensson/cake,marcosnz/cake,patriksvensson/cake,phrusher/cake,devlead/cake,phenixdotnet/cake
src/Cake.Core/Scripting/Processors/UsingStatementProcessor.cs
src/Cake.Core/Scripting/Processors/UsingStatementProcessor.cs
using System; using Cake.Core.IO; namespace Cake.Core.Scripting.Processors { /// <summary> /// Processor for using statements. /// </summary> public sealed class UsingStatementProcessor : LineProcessor { /// <summary> /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class. /// </summary> /// <param name="environment">The environment.</param> public UsingStatementProcessor(ICakeEnvironment environment) : base(environment) { } /// <summary> /// Processes the specified line. /// </summary> /// <param name="processor">The script processor.</param> /// <param name="context">The script processor context.</param> /// <param name="currentScriptPath">The current script path.</param> /// <param name="line">The line to process.</param> /// <returns> /// <c>true</c> if the processor handled the line; otherwise <c>false</c>. /// </returns> public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line) { if (context == null) { throw new ArgumentNullException("context"); } var tokens = Split(line); if (tokens.Length <= 1) { return false; } if (!tokens[0].Equals("using", StringComparison.Ordinal)) { return false; } var @namespace = tokens[1].TrimEnd(';'); if (@namespace.StartsWith("(")) { return false; } context.AddNamespace(@namespace); return true; } } }
using System; using Cake.Core.IO; namespace Cake.Core.Scripting.Processors { /// <summary> /// Processor for using statements. /// </summary> public sealed class UsingStatementProcessor : LineProcessor { /// <summary> /// Initializes a new instance of the <see cref="UsingStatementProcessor"/> class. /// </summary> /// <param name="environment">The environment.</param> public UsingStatementProcessor(ICakeEnvironment environment) : base(environment) { } /// <summary> /// Processes the specified line. /// </summary> /// <param name="processor">The script processor.</param> /// <param name="context">The script processor context.</param> /// <param name="currentScriptPath">The current script path.</param> /// <param name="line">The line to process.</param> /// <returns> /// <c>true</c> if the processor handled the line; otherwise <c>false</c>. /// </returns> public override bool Process(IScriptProcessor processor, ScriptProcessorContext context, FilePath currentScriptPath, string line) { if (context == null) { throw new ArgumentNullException("context"); } var tokens = Split(line); if (tokens.Length <= 0) { return false; } if (!tokens[0].Equals("using", StringComparison.Ordinal)) { return false; } var @namespace = tokens[1].TrimEnd(';'); context.AddNamespace(@namespace); return true; } } }
mit
C#
c521dd85115ea5b71f2b6ec36196d57b2875274e
Improve CheckLinkPresence
Free1man/SeleniumTestFramework,Free1man/SeleniumTestsRunner
SeleniumFramework/SeleniumInfrastructure/Browsers/DriverService.cs
SeleniumFramework/SeleniumInfrastructure/Browsers/DriverService.cs
using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; using System.Net; namespace SeleniumFramework.SeleniumInfrastructure.Browsers { public class DriverService { public IWebDriver GetDriver(string browser) { string path = AppDomain.CurrentDomain.BaseDirectory; switch (browser) { case "Firefox": //TO DO: hotfix for Firefox 47, should be refactored, all parameters should go to app.config FirefoxOptions option1 = new FirefoxOptions(); //Copy wires.exe file to output directory or this code will fail. FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(path, "wires.exe"); service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; return new FirefoxDriver(service); case "Chrome": return new ChromeDriver(); case "PhantomJS": return new PhantomJSDriver(); case "RemoteFirefox": //TO DO: create separate service for Selenium Grid Drivers, this is just example Environment.SetEnvironmentVariable("webdriver.gecko.driver", @"C:\"); //WebClient Client = new WebClient(); //Client.DownloadFile("http://chromedriver.storage.googleapis.com/2.22/chromedriver_linux32.zip", @"C:\Report\stackoverflowlogo.png"); var capability = DesiredCapabilities.Firefox(); //capability.SetCapability("marionette", true); return new RemoteWebDriver(new Uri("http://172.17.16.45:5555/wd/hub"), capability); default: throw new ArgumentException(browser + "- Not supported browser"); } } } }
using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Remote; namespace SeleniumFramework.SeleniumInfrastructure.Browsers { public class DriverService { public IWebDriver GetDriver(string browser) { switch (browser) { case "Firefox": //TO DO: hotfix for Firefox 47, should be refactored, all parameters should go to app.config FirefoxOptions option1 = new FirefoxOptions(); //Copy wires.exe file to output directory or this code will fail. string path = AppDomain.CurrentDomain.BaseDirectory; FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(path, "wires.exe"); service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"; return new FirefoxDriver(service, option1, TimeSpan.FromSeconds(10)); case "Chrome": return new ChromeDriver(); case "PhantomJS": return new PhantomJSDriver(); case "RemoteFirefox": //TO DO: create separate service for Selenium Grid Drivers, this is just example var capability = DesiredCapabilities.Firefox(); return new RemoteWebDriver(new Uri("http://172.17.16.45:5555/wd/hub"), capability); default: throw new ArgumentException(browser + "- Not supported browser"); } } } }
mit
C#
f9e7b6e81729eb8904d79778ba97dbbca789a809
fix merge solution
LayoutFarm/PixelFarm
src/Tools/BuildMergeProject/Program.cs
src/Tools/BuildMergeProject/Program.cs
//MIT, 2017, WinterDev using System; using System.Collections.Generic; using System.Windows.Forms; namespace BuildMergeProject { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); StartupConfig.defaultSln = @"D:\projects\PixelFarm\src\MiniDev.sln"; Application.Run(new FormBuildMergeProject()); } } }
//MIT, 2017, WinterDev using System; using System.Collections.Generic; using System.Windows.Forms; namespace BuildMergeProject { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); StartupConfig.defaultSln = @"D:\projects\PixelFarm\a_mini\projects\MiniDev.sln"; Application.Run(new FormBuildMergeProject()); } } }
bsd-2-clause
C#
b270db360f8b17feac55223c2b5c71fac5fd680f
Improve cancellation behavior in ListFileSource
adv12/FileSharper
src/FileSharper/FileSharperCore/FileSources/ListFileSource.cs
src/FileSharper/FileSharperCore/FileSources/ListFileSource.cs
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license. // See license.txt in the FileSharper distribution or repository for the // full text of the license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace FileSharperCore.FileSources { public class FileListParameters { [PropertyOrder(1, UsageContextEnum.Both)] public List<string> Files { get; set; } = new List<string>(); } public class ListFileSource : FileSourceBase { private FileListParameters m_Parameters = new FileListParameters(); public override IEnumerable<FileInfo> Files { get { foreach (string filename in m_Parameters.Files) { if (RunInfo.StopRequested) { yield break; } RunInfo.CancellationToken.ThrowIfCancellationRequested(); yield return new FileInfo(filename); } } } public override string Name => "List"; public override string Description => "A list of file paths"; public override object Parameters => m_Parameters; } }
// Copyright (c) 2017 Andrew Vardeman. Published under the MIT license. // See license.txt in the FileSharper distribution or repository for the // full text of the license. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; namespace FileSharperCore.FileSources { public class FileListParameters { [PropertyOrder(1, UsageContextEnum.Both)] public List<string> Files { get; set; } = new List<string>(); } public class ListFileSource : FileSourceBase { private FileListParameters m_Parameters = new FileListParameters(); public override IEnumerable<FileInfo> Files { get { foreach (string filename in m_Parameters.Files) { yield return new FileInfo(filename); } } } public override string Name => "List"; public override string Description => "A list of file paths"; public override object Parameters => m_Parameters; } }
mit
C#
fdf0fc5fc4332a8ac8f86a455a9175ef38f704eb
Hide PrefixProcess from outside
lou1306/CIV,lou1306/CIV
CIV.Ccs/Processes/PrefixProcess.cs
CIV.Ccs/Processes/PrefixProcess.cs
using System; using System.Collections.Generic; using CIV.Interfaces; namespace CIV.Ccs { class PrefixProcess : CcsProcess { public String Label { get; set; } public CcsProcess Inner { get; set; } public override bool Equals(CcsProcess other) { var otherPrefix = other as PrefixProcess; return otherPrefix != null && (Label == otherPrefix.Label) && Inner.Equals(otherPrefix.Inner); } public override IEnumerable<Transition> Transitions() { return new List<Transition>{ new Transition{ Label = Label, Process = Inner } }; } } }
using System; using System.Collections.Generic; using CIV.Interfaces; namespace CIV.Ccs { public class PrefixProcess : CcsProcess { public String Label { get; set; } public CcsProcess Inner { get; set; } public override bool Equals(CcsProcess other) { var otherPrefix = other as PrefixProcess; return otherPrefix != null && (Label == otherPrefix.Label) && Inner.Equals(otherPrefix.Inner); } public override IEnumerable<Transition> Transitions() { return new List<Transition>{ new Transition{ Label = Label, Process = Inner } }; } } }
mit
C#
4c940a6ea78947466adb8915de18e286a7718382
add Foreach support for ControlPersistenceData for backward compatibility
danielgerlag/workflow-core
src/WorkflowCore/Primitives/Foreach.cs
src/WorkflowCore/Primitives/Foreach.cs
using System.Linq; using System.Collections; using System.Collections.Generic; using WorkflowCore.Interface; using WorkflowCore.Models; namespace WorkflowCore.Primitives { public class Foreach : ContainerStepBody { public IEnumerable Collection { get; set; } public bool RunParallel { get; set; } = true; public override ExecutionResult Run(IStepExecutionContext context) { if (context.PersistenceData == null) { var values = Collection.Cast<object>(); if (RunParallel) { return ExecutionResult.Branch(new List<object>(values), new IteratorPersistenceData() { ChildrenActive = true }); } else { return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(0) }), new IteratorPersistenceData() { ChildrenActive = true }); } } if (context.PersistenceData is IteratorPersistenceData persistenceData && persistenceData?.ChildrenActive == true) { if (context.Workflow.IsBranchComplete(context.ExecutionPointer.Id)) { if (!RunParallel) { var values = Collection.Cast<object>(); persistenceData.Index++; if (persistenceData.Index < values.Count()) { return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(persistenceData.Index) }), persistenceData); } } return ExecutionResult.Next(); } return ExecutionResult.Persist(persistenceData); } if (context.PersistenceData is ControlPersistenceData controlPersistenceData && controlPersistenceData?.ChildrenActive == true) { if (context.Workflow.IsBranchComplete(context.ExecutionPointer.Id)) { return ExecutionResult.Next(); } } return ExecutionResult.Persist(context.PersistenceData); } } }
using System.Linq; using System.Collections; using System.Collections.Generic; using WorkflowCore.Interface; using WorkflowCore.Models; namespace WorkflowCore.Primitives { public class Foreach : ContainerStepBody { public IEnumerable Collection { get; set; } public bool RunParallel { get; set; } = true; public override ExecutionResult Run(IStepExecutionContext context) { if (context.PersistenceData == null) { var values = Collection.Cast<object>(); if (RunParallel) { return ExecutionResult.Branch(new List<object>(values), new IteratorPersistenceData() { ChildrenActive = true }); } else { return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(0) }), new IteratorPersistenceData() { ChildrenActive = true }); } } if (context.PersistenceData is IteratorPersistenceData persistanceData && persistanceData?.ChildrenActive == true) { if (context.Workflow.IsBranchComplete(context.ExecutionPointer.Id)) { if (!RunParallel) { var values = Collection.Cast<object>(); persistanceData.Index++; if (persistanceData.Index < values.Count()) { return ExecutionResult.Branch(new List<object>(new object[] { values.ElementAt(persistanceData.Index) }), persistanceData); } } return ExecutionResult.Next(); } return ExecutionResult.Persist(persistanceData); } return ExecutionResult.Persist(context.PersistenceData); } } }
mit
C#
fb2794321c5ed7c9db7b25fde85767b23726fa59
Fix a bug that causes the parameter created by the method DataParameters.CreateParameter to not be automatically included in the related DbCommand object.
nohros/must,nohros/must,nohros/must
src/base/common/data/DataParameters.cs
src/base/common/data/DataParameters.cs
using System; using System.Data; namespace Nohros.Data { /// <summary> /// Provides facilities methods for create data parameters. /// </summary> public sealed class DataParameters { /// <summary> /// Initializes a new instance of the <see cref="IDbDataParameter"/> class /// that uses the parameter name and the data type. /// </summary> /// <param name="command"> /// The <see cref="IDbCommand"/> object to which the created parameter /// should be associated. /// </param> /// <param name="parameter_name"> /// The name of the parameter to map. /// </param> /// <param name="db_type"> /// One of the <see cref="DbType"/> values that best represents the value /// of the parameter. /// </param> /// <returns> /// A instance of the <see cref="IDbDataParameter"/> class associated with /// the given <see cref="IDbCommand"/> object. /// </returns> public static IDbDataParameter CreateParameter(IDbCommand command, string parameter_name, DbType db_type) { IDbDataParameter parameter = command.CreateParameter(); parameter.ParameterName = parameter_name; parameter.DbType = db_type; command.Parameters.Add(parameter); return parameter; } /// <summary> /// Initializes a new instance of the <see cref="IDbDataParameter"/> class /// that uses the parameter name and the data type. /// </summary> /// <param name="command"> /// The <see cref="IDbCommand"/> object to which the created parameter /// should be associated. /// </param> /// <param name="parameter_name"> /// The name of the parameter to map. /// </param> /// <param name="db_type"> /// One of the <see cref="DbType"/> values that best represents the value /// of the parameter. /// </param> /// <param name="size"> /// The length of the parameter. /// </param> /// <returns> /// A instance of the <see cref="IDbDataParameter"/> class associated with /// the given <see cref="IDbCommand"/> object. /// </returns> public static IDbDataParameter CreateParameter(IDbCommand command, string parameter_name, DbType db_type, int size) { IDbDataParameter parameter = CreateParameter(command, parameter_name, db_type); parameter.Size = size; return parameter; } } }
using System; using System.Data; namespace Nohros.Data { /// <summary> /// Provides facilities methods for create data parameters. /// </summary> public sealed class DataParameters { /// <summary> /// Initializes a new instance of the <see cref="IDbDataParameter"/> class /// that uses the parameter name and the data type. /// </summary> /// <param name="command"> /// The <see cref="IDbCommand"/> object to which the created parameter /// should be associated. /// </param> /// <param name="parameter_name"> /// The name of the parameter to map. /// </param> /// <param name="db_type"> /// One of the <see cref="DbType"/> values that best represents the value /// of the parameter. /// </param> /// <returns> /// A instance of the <see cref="IDbDataParameter"/> class associated with /// the given <see cref="IDbCommand"/> object. /// </returns> public static IDbDataParameter CreateParameter(IDbCommand command, string parameter_name, DbType db_type) { IDbDataParameter parameter = command.CreateParameter(); parameter.ParameterName = parameter_name; parameter.DbType = db_type; return parameter; } /// <summary> /// Initializes a new instance of the <see cref="IDbDataParameter"/> class /// that uses the parameter name and the data type. /// </summary> /// <param name="command"> /// The <see cref="IDbCommand"/> object to which the created parameter /// should be associated. /// </param> /// <param name="parameter_name"> /// The name of the parameter to map. /// </param> /// <param name="db_type"> /// One of the <see cref="DbType"/> values that best represents the value /// of the parameter. /// </param> /// <param name="size"> /// The length of the parameter. /// </param> /// <returns> /// A instance of the <see cref="IDbDataParameter"/> class associated with /// the given <see cref="IDbCommand"/> object. /// </returns> public static IDbDataParameter CreateParameter(IDbCommand command, string parameter_name, DbType db_type, int size) { IDbDataParameter parameter = CreateParameter(command, parameter_name, db_type); parameter.Size = size; return parameter; } } }
mit
C#
5ee7966318f426377361eadff32f2ac7d69f00b9
Use a stub of ITimer instead of an actual implementation
dotNetNocturne/Pacman_Episode1_GreenTeam
PacManGameTests/GameTimerTest.cs
PacManGameTests/GameTimerTest.cs
using System; using System.Threading; using FluentAssertions; using Moq; using NUnit.Framework; using PacManGame; namespace PacManGameTests { [TestFixture] public class GameTimerTest { [Test] public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1() { //Arrange Board b = new Board(3, 4); ITimer gameTimer = new GameTimer(500); GameController gameController = new GameController(b, gameTimer); gameTimer.Start(); //Act Thread.Sleep(TimeSpan.FromMilliseconds(600)); // Assert b.PacMan.Position.Should().Be(new Position(1, 1)); } [Test] public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled() { //Arrange ITickable boardMock = Mock.Of<ITickable>(); ITimer timerMock = Mock.Of<ITimer>(); GameController gameController = new GameController(boardMock, timerMock); //Act Mock.Get(timerMock).Raise(t => t.Elapsed += null, new EventArgs()); //Assert Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once); } } }
using System; using System.Threading; using FluentAssertions; using Moq; using NUnit.Framework; using PacManGame; namespace PacManGameTests { [TestFixture] public class GameTimerTest { [Test] public void GivenABoard3x4WithPacmanLookingUpAt1x2_When500msPass_ThenPacmanIsAt1x1() { //Arrange Board b = new Board(3, 4); ITimer gameTimer = new GameTimer(500); GameController gameController = new GameController(b, gameTimer); gameTimer.Start(); //Act Thread.Sleep(TimeSpan.FromMilliseconds(600)); // Assert b.PacMan.Position.Should().Be(new Position(1, 1)); } [Test] public void GivenABoardTickableAndAGameController_WhenTimerElapsed_ThenATickIsCalled() { //Arrange ITickable boardMock = Mock.Of<ITickable>(); FakeTimer timer = new FakeTimer(); GameController gameController = new GameController(boardMock, timer); //Act timer.OnElapsed(); //Assert Mock.Get(boardMock).Verify(b => b.Tick(), Times.Once); } } public class FakeTimer : ITimer { public event EventHandler Elapsed; public void Start() { throw new NotImplementedException(); } public void OnElapsed() { if (Elapsed != null) { Elapsed(this, new EventArgs()); } } } }
mit
C#
b8be6f0f5247f7e942a819033587282fedcadad9
Fix for making the library work on Meteor v1.4.1.2
green-coder/unity3d-ddp-client,green-coder/unity3d-ddp-client,green-coder/unity3d-ddp-client,green-coder/unity3d-ddp-client
unity-project/Assets/unity3d-ddp-client/account/DdpAccount.cs
unity-project/Assets/unity3d-ddp-client/account/DdpAccount.cs
using UnityEngine; using System; using System.Text; using System.Security.Cryptography; using System.Collections; public class DdpAccount { private DdpConnection connection; public bool isLogged; public string userId; public string token; public DateTime tokenExpiration; public DdpError error; public DdpAccount(DdpConnection connection) { this.connection = connection; } private JSONObject GetPasswordObj(string password) { string digest = BitConverter.ToString( new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(password))) .Replace("-", ""); JSONObject passwordObj = JSONObject.Create(); passwordObj.AddField("digest", digest); passwordObj.AddField("algorithm", "sha-256"); return passwordObj; } private void HandleLoginResult(MethodCall loginCall) { error = loginCall.error; if (error == null) { JSONObject result = loginCall.result; isLogged = true; this.userId = result["id"].str; this.token = result["token"].str; this.tokenExpiration = result["tokenExpires"].GetDateTime(); } } private void HandleLogoutResult(MethodCall logoutCall) { error = logoutCall.error; if (error == null) { isLogged = false; this.userId = null; this.token = null; this.tokenExpiration = default(DateTime); } } public IEnumerator CreateUserAndLogin(string username, string password) { JSONObject loginPasswordObj = JSONObject.Create(); loginPasswordObj.AddField("username", username); loginPasswordObj.AddField("password", GetPasswordObj(password)); MethodCall loginCall = connection.Call("createUser", loginPasswordObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator Login(string username, string password) { JSONObject userObj = JSONObject.Create(); userObj.AddField("username", username); JSONObject loginPasswordObj = JSONObject.Create(); loginPasswordObj.AddField("user", userObj); loginPasswordObj.AddField("password", GetPasswordObj(password)); MethodCall loginCall = connection.Call("login", loginPasswordObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator ResumeSession(string token) { JSONObject tokenObj = JSONObject.Create(); tokenObj.AddField("resume", token); MethodCall loginCall = connection.Call("login", tokenObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator Logout() { MethodCall logoutCall = connection.Call("logout"); yield return logoutCall.WaitForResult(); HandleLogoutResult(logoutCall); } }
using UnityEngine; using System; using System.Text; using System.Security.Cryptography; using System.Collections; public class DdpAccount { private DdpConnection connection; public bool isLogged; public string username; public string userId; public string token; public DateTime tokenExpiration; public DdpError error; public DdpAccount(DdpConnection connection) { this.connection = connection; } private JSONObject GetPasswordObj(string password) { string digest = BitConverter.ToString( new SHA256Managed().ComputeHash(Encoding.UTF8.GetBytes(password))) .Replace("-", ""); JSONObject passwordObj = JSONObject.Create(); passwordObj.AddField("digest", digest); passwordObj.AddField("algorithm", "sha-256"); return passwordObj; } private void HandleLoginResult(MethodCall loginCall) { error = loginCall.error; if (error == null) { JSONObject result = loginCall.result; isLogged = true; this.username = result["username"].str; this.userId = result["id"].str; this.token = result["token"].str; this.tokenExpiration = result["tokenExpires"].GetDateTime(); } } private void HandleLogoutResult(MethodCall logoutCall) { error = logoutCall.error; if (error == null) { isLogged = false; this.username = null; this.userId = null; this.token = null; this.tokenExpiration = default(DateTime); } } public IEnumerator CreateUserAndLogin(string username, string password) { JSONObject loginPasswordObj = JSONObject.Create(); loginPasswordObj.AddField("username", username); loginPasswordObj.AddField("password", GetPasswordObj(password)); MethodCall loginCall = connection.Call("createUser", loginPasswordObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator Login(string username, string password) { JSONObject userObj = JSONObject.Create(); userObj.AddField("username", username); JSONObject loginPasswordObj = JSONObject.Create(); loginPasswordObj.AddField("user", userObj); loginPasswordObj.AddField("password", GetPasswordObj(password)); MethodCall loginCall = connection.Call("login", loginPasswordObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator ResumeSession(string token) { JSONObject tokenObj = JSONObject.Create(); tokenObj.AddField("resume", token); MethodCall loginCall = connection.Call("login", tokenObj); yield return loginCall.WaitForResult(); HandleLoginResult(loginCall); } public IEnumerator Logout() { MethodCall logoutCall = connection.Call("logout"); yield return logoutCall.WaitForResult(); HandleLogoutResult(logoutCall); } }
mit
C#
f20c643b625027c0917df6949fceabdd762d12b1
Fix DatePicker.cshtml
atata-framework/atata-kendoui,atata-framework/atata-kendoui
test/Atata.KendoUI.TestApp/Pages/DatePicker.cshtml
test/Atata.KendoUI.TestApp/Pages/DatePicker.cshtml
@page @{ ViewBag.Title = "DatePicker"; } <label for="regular">Regular</label> <input id="regular" /> <label for="using-date-input">Using Date Input</label> <input id="using-date-input" /> <label for="using-date-input-with-value">Using Date Input With Value</label> <input id="using-date-input-with-value" value="2.11.1988" /> <br /> <br /> <label> Disabled <input id="disabled" value="10/10/2000" /> </label> <label> Read Only <input id="readonly" value="7/20/2005" /> </label> <script> $(function () { $('#regular').kendoDatePicker({ format: "MM/dd/yyyy" }); $("#using-date-input").kendoDatePicker({ format: "dd-MM-yyyy", dateInput: true }); $("#using-date-input-with-value").kendoDatePicker({ format: "d.M.yyyy", dateInput: true }); $('#disabled').kendoDatePicker().data('kendoDatePicker').enable(false); $('#readonly').kendoDatePicker().data('kendoDatePicker').readonly(); }); </script>
@page @{ ViewBag.Title = "DatePicker"; } <label for="regular">Regular</label> <input id="regular" /> <label for="using-date-input">Using Date Input</label> <input id="using-date-input" /> <label for="using-date-input-with-value">Using Date Input with Value</label> <input id="using-date-input-with-value" value="2.11.1988" /> <br /> <br /> <label> Disabled <input id="disabled" value="10/10/2000" /> </label> <label> Read Only <input id="readonly" value="7/20/2005" /> </label> <script> $(function () { $('#regular').kendoDatePicker({ format: "MM/dd/yyyy" }); $("#using-date-input").kendoDatePicker({ format: "dd-MM-yyyy", dateInput: true }); $("#using-date-input-with-value").kendoDatePicker({ format: "d.M.yyyy", dateInput: true }); $('#disabled').kendoDatePicker().data('kendoDatePicker').enable(false); $('#readonly').kendoDatePicker().data('kendoDatePicker').readonly(); }); </script>
apache-2.0
C#
4a639128b211f4818cf00cdfccddfb7b8bbb4bb8
Fix hadle -> handle in comment (#1776)
jamespearce2006/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp
CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs
CefSharp.Wpf.Example/Handlers/GeolocationHandler.cs
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows; namespace CefSharp.Wpf.Example.Handlers { internal class GeolocationHandler : IGeolocationHandler { bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback) { //You can execute the callback inline //callback.Continue(true); //return true; //You can execute the callback in an `async` fashion //Open a message box on the `UI` thread and ask for user input. //You can open a form, or do whatever you like, just make sure you either //execute the callback or call `Dispose` as it's an `unmanaged` wrapper. var chromiumWebBrowser = (ChromiumWebBrowser)browserControl; chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() => { //Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times). using (callback) { var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo); //Execute the callback, to allow/deny the request. callback.Continue(result == MessageBoxResult.Yes); } })); //Yes we'd like to handle this request ourselves. return true; } void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId) { } } }
// Copyright © 2010-2016 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.Windows; namespace CefSharp.Wpf.Example.Handlers { internal class GeolocationHandler : IGeolocationHandler { bool IGeolocationHandler.OnRequestGeolocationPermission(IWebBrowser browserControl, IBrowser browser, string requestingUrl, int requestId, IGeolocationCallback callback) { //You can execute the callback inline //callback.Continue(true); //return true; //You can execute the callback in an `async` fashion //Open a message box on the `UI` thread and ask for user input. //You can open a form, or do whatever you like, just make sure you either //execute the callback or call `Dispose` as it's an `unmanaged` wrapper. var chromiumWebBrowser = (ChromiumWebBrowser)browserControl; chromiumWebBrowser.Dispatcher.BeginInvoke((Action)(() => { //Callback wraps an unmanaged resource, so we'll make sure it's Disposed (calling Continue will also Dipose of the callback, it's safe to dispose multiple times). using (callback) { var result = MessageBox.Show(String.Format("{0} wants to use your computer's location. Allow? ** You must set your Google API key in CefExample.Init() for this to work. **", requestingUrl), "Geolocation", MessageBoxButton.YesNo); //Execute the callback, to allow/deny the request. callback.Continue(result == MessageBoxResult.Yes); } })); //Yes we'd like to hadle this request ourselves. return true; } void IGeolocationHandler.OnCancelGeolocationPermission(IWebBrowser browserControl, IBrowser browser, int requestId) { } } }
bsd-3-clause
C#
71ae0a66a104694499f728a502570feff1ee7f45
Fix hardcoded DAP log path
Norbyte/lslib,Norbyte/lslib,Norbyte/lslib
DebuggerFrontend/Program.cs
DebuggerFrontend/Program.cs
using CommandLineParser.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LSTools.DebuggerFrontend { class Program { static void Main(string[] args) { var currentPath = AppDomain.CurrentDomain.BaseDirectory; var logFile = new FileStream(currentPath + "\\DAP.log", FileMode.Create); var dap = new DAPStream(); dap.EnableLogging(logFile); var dapHandler = new DAPMessageHandler(dap); dapHandler.EnableLogging(logFile); try { dap.RunLoop(); } catch (Exception e) { using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true)) { writer.Write(e.ToString()); Console.WriteLine(e.ToString()); } } } } }
using CommandLineParser.Exceptions; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LSTools.DebuggerFrontend { class Program { static void Main(string[] args) { var logFile = new FileStream(@"C:\Dev\DOS\LS\LsLib\DebuggerFrontend\bin\Debug\DAP.log", FileMode.Create); var dap = new DAPStream(); dap.EnableLogging(logFile); var dapHandler = new DAPMessageHandler(dap); dapHandler.EnableLogging(logFile); try { dap.RunLoop(); } catch (Exception e) { using (var writer = new StreamWriter(logFile, Encoding.UTF8, 0x1000, true)) { writer.Write(e.ToString()); Console.WriteLine(e.ToString()); } } } } }
mit
C#
c6bbe89a37ec7fda55d69b5af41ba54162031f2d
Update Form1.cs
Lime-Parallelogram/Socket-Tutorial,Lime-Parallelogram/Socket-Tutorial,Lime-Parallelogram/Socket-Tutorial
ReverseDirection/SocketClient/SocketClient/Form1.cs
ReverseDirection/SocketClient/SocketClient/Form1.cs
//Required Libs using System; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace SocketClient //Sorry about the naming issue (This is a server) { public partial class Form1 : Form { //Vars TcpListener server; TcpClient clientconnection; public Form1() { //Loads form components InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { server = new TcpListener(IPAddress.Any, 8000); //Opens server port server.Start(); //Starts server listBox1.Items.Add("Server Started"); //Adds info to list clientconnection = server.AcceptTcpClient(); //Accepts connection request timer1.Start(); //Starts timer to check stream at regular intervals } private void timer1_Tick(object sender, EventArgs e) { NetworkStream DataStream = clientconnection.GetStream(); //Gets the data stream byte[] buffer = new byte[clientconnection.ReceiveBufferSize]; //Gets required buffer size int Data = DataStream.Read(buffer, 0, clientconnection.ReceiveBufferSize); //Gets message (encoded) string message = Encoding.ASCII.GetString(buffer, 0, Data); //Decoodes message listBox1.Items.Add(message); //Adds message to output window } } }
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 System.Net; using System.Net.Sockets; namespace SocketClient { public partial class Form1 : Form { byte[] bytes = new byte[256]; TcpListener server; TcpClient clientconnection; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { server = new TcpListener(IPAddress.Any, 8000); server.Start(); listBox1.Items.Add("Server Started"); clientconnection = server.AcceptTcpClient(); timer1.Start(); } private void timer1_Tick(object sender, EventArgs e) { NetworkStream streamIn = clientconnection.GetStream(); byte[] buffer = new byte[clientconnection.ReceiveBufferSize]; int Data = streamIn.Read(buffer, 0, clientconnection.ReceiveBufferSize); string ch = Encoding.ASCII.GetString(buffer, 0, Data); listBox1.Items.Add(ch); } } }
mit
C#
b3f1f35ba2a5898fe01bd9418f5e582a545dd8c8
add ExtractTransform
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/MathTransformExtensions.cs
SolidworksAddinFramework/MathTransformExtensions.cs
using System.Linq; using MathNet.Numerics.LinearAlgebra.Double; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class MathTransformExtensions { public static void ExtractTransform(this IMathTransform transform, out DenseMatrix rotation, out DenseVector translation) { double scale; ExtractTransform(transform, out rotation, out translation, out scale); } public static void ExtractTransform(this IMathTransform transform, out DenseMatrix rotation, out DenseVector translation, out double scale) { var transformArray = transform.ArrayData.CastArray<double>(); rotation = new DenseMatrix(3, 3, transformArray.Take(9).ToArray()); translation = new DenseVector(transformArray.Skip(9).Take(3).ToArray()); scale = transformArray[12]; } } }
using System.Linq; using MathNet.Numerics.LinearAlgebra.Double; using SolidWorks.Interop.sldworks; namespace SolidworksAddinFramework { public static class MathTransformExtensions { public static void ExtractTransform(this IMathTransform transform, out DenseMatrix rotation, out DenseVector translation) { var transformArray = transform.ArrayData.CastArray<double>(); rotation = new DenseMatrix(3, 3, transformArray.Take(9).ToArray()); translation = new DenseVector(transformArray.Skip(9).Take(3).ToArray()); } } }
mit
C#
083a0cd14b980e5c79702bfc0cb14e75d96b222b
Fix adding controls to PixelLayout with a different container object
l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto
Source/Eto.Platform.Gtk/Forms/PixelLayoutHandler.cs
Source/Eto.Platform.Gtk/Forms/PixelLayoutHandler.cs
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.Platform.GtkSharp { public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout { public PixelLayoutHandler () { Control = new Gtk.Fixed (); } public void Add (Control child, int x, int y) { var ctl = ((IGtkControl)child.Handler); var gtkcontrol = child.GetContainerWidget (); Control.Put (gtkcontrol, x, y); ctl.Location = new Point (x, y); if (this.Control.Visible) gtkcontrol.ShowAll (); } public void Move (Control child, int x, int y) { var ctl = ((IGtkControl)child.Handler); if (ctl.Location.X != x || ctl.Location.Y != y) { Control.Move (child.GetContainerWidget (), x, y); ctl.Location = new Point (x, y); } } public void Remove (Control child) { Control.Remove (child.GetContainerWidget ()); } } }
using System; using Eto.Forms; using Eto.Drawing; namespace Eto.Platform.GtkSharp { public class PixelLayoutHandler : GtkLayout<Gtk.Fixed, PixelLayout>, IPixelLayout { public PixelLayoutHandler() { Control = new Gtk.Fixed(); } public void Add(Control child, int x, int y) { IGtkControl ctl = ((IGtkControl)child.Handler); var gtkcontrol = (Gtk.Widget)child.ControlObject; Control.Put(gtkcontrol, x, y); ctl.Location = new Point(x, y); gtkcontrol.ShowAll(); } public void Move(Control child, int x, int y) { IGtkControl ctl = ((IGtkControl)child.Handler); if (ctl.Location.X != x || ctl.Location.Y != y) { Control.Move (child.GetContainerWidget (), x, y); ctl.Location = new Point(x, y); } } public void Remove(Control child) { Control.Remove (child.GetContainerWidget ()); } } }
bsd-3-clause
C#
2e71882ff6b6131d76bcc9146dc5a0acf9dec595
Update FilterDef.cs
Sohra/mvc.jquery.datatables,Sohra/mvc.jquery.datatables,mcintyre321/mvc.jquery.datatables,seguemark/mvc.jquery.datatables,mcintyre321/mvc.jquery.datatables,mcintyre321/mvc.jquery.datatables,seguemark/mvc.jquery.datatables
Mvc.JQuery.Datatables/FilterDef.cs
Mvc.JQuery.Datatables/FilterDef.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Mvc.JQuery.Datatables { public class FilterDef : Hashtable { internal object[] values { set { this["values"] = value; } } internal string type { set { this["type"] = value; } } public FilterDef(Type t) { SetDefaultValuesAccordingToColumnType(t); } private static List<Type> DateTypes = new List<Type> { typeof(DateTime), typeof(DateTime?), typeof(DateTimeOffset), typeof(DateTimeOffset?) }; private void SetDefaultValuesAccordingToColumnType(Type t) { if (t==null) { type = "null"; } else if (DateTypes.Contains(t)) { type = "date-range"; } else if (t == typeof (bool)) { type = "select"; values = new object[] {"True", "False"}; } else if (t == typeof (bool?)) { type = "select"; values = new object[] {"True", "False", "null"}; } else if (t.IsEnum) { type = "checkbox"; //values = Enum.GetNames(t).Cast<object>().ToArray(); values = t.EnumValLabPairs(); } else { type = "text"; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace Mvc.JQuery.Datatables { public class FilterDef : Hashtable { internal object[] values { set { this["values"] = value; } } internal string type { set { this["type"] = value; } } public FilterDef(Type t) { SetDefaultValuesAccordingToColumnType(t); } private static List<Type> DateTypes = new List<Type> { typeof(DateTime), typeof(DateTime?), typeof(DateTimeOffset), typeof(DateTimeOffset?) }; private void SetDefaultValuesAccordingToColumnType(Type t) { if (t==null) { type = "null"; } else if (DateTypes.Contains(t)) { type = "date-range"; } else if (t == typeof (bool)) { type = "select"; values = new object[] {"True", "False"}; } else if (t == typeof (bool?)) { type = "select"; values = new object[] {"True", "False", "null"}; } else if (t.IsEnum) { type = "checkbox"; values = Enum.GetNames(t).Cast<object>().ToArray(); } else { type = "text"; } } } }
mit
C#
0418c4c46c02e885e553ce19ee083181013992db
Update CompactBinaryBondDeserializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/Bond/CompactBinaryBondDeserializer.cs
TIKSN.Core/Serialization/Bond/CompactBinaryBondDeserializer.cs
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class CompactBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new CompactBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class CompactBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new CompactBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
mit
C#
27115da951fb02dbc887ad29a959d7782050e2ce
Update StaticTestModel.cs
NMSLanX/Natasha
NatashaUT/Model/StaticTestModel.cs
NatashaUT/Model/StaticTestModel.cs
using System; namespace NatashaUT.Model { public static class StaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public class FakeStaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public static class StaticTestModel1 { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public class FakeStaticTestModel1 { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } }
using System; namespace NatashaUT.Model { public static class StaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public class FakeStaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public static class StaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } public class FakeStaticTestModel { public static int Age; public static string Name { get; set; } public static DateTime Temp; public static float Money; } }
mpl-2.0
C#
753c53bc18dafd5bc29f80b073ba34c7d3845558
Update Spacefolder.cs
KerbaeAdAstra/KerbalFuture
KerbalFuture/Spacefolder.cs
KerbalFuture/Spacefolder.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using KSP; namespace KerbalFuture { class SpacefolderData : MonoBehavior { public static string path() { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } } class FlightDrive : VesselModule { public void FixedUpdate() { if(HighLogic.LoadedSceneIsFlight) { } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using KSP; namespace KerbalFuture { class SpacefolderData : MonoBehavior { public static string path() { return System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); } } class FlightDrive : VesselModule { public st } }
mit
C#
7f27450fe7b5a98462d863e633eb4372779c5e05
Fix tag casing
Sebazzz/IFS,Sebazzz/IFS,Sebazzz/IFS,Sebazzz/IFS
src/IFS.Web/Areas/Administration/Views/Files/Log.cshtml
src/IFS.Web/Areas/Administration/Views/Files/Log.cshtml
@using System.Linq @using Humanizer @model IFS.Web.Core.Upload.UploadedFile @{ ViewBag.Title = $"Access log of {Model.Metadata.OriginalFileName}"; var accessLog = Model.Metadata.Access; } <h2>@ViewBag.Title</h2> @if (accessLog.LogEntries.Count > 0) { <table class="table table-striped"> <thead> <tr> <th>IP address</th> <th>Timestamp</th> </tr> </thead> <tbody> @foreach (var access in accessLog.LogEntries.OrderBy(x => x.Timestamp)) { <tr> <td>@(access.IpAddress ?? "Unknown")</td> <td>@access.Timestamp.ToString("s") (@access.Timestamp.Humanize())</td> </tr> } </tbody> </table> } else { <div class="alert alert-info"> <strong>Sorry...</strong> this file has never been downloaded yet! </div> } <p> <a asp-action="Index" class="btn btn-default">Back to overview</a> </p>
@using System.Linq @using Humanizer @model IFS.Web.Core.Upload.UploadedFile @{ ViewBag.Title = $"Access log of {Model.Metadata.OriginalFileName}"; var accessLog = Model.Metadata.Access; } <h2>@ViewBag.Title</h2> @if (accessLog.LogEntries.Count > 0) { <table class="table table-striped"> <thead> <tr> <th>IP address</th> <th>Timestamp</th> </tr> </thead> <tbody> @foreach (var access in accessLog.LogEntries.OrderBy(x => x.Timestamp)) { <tr> <td>@(access.IpAddress ?? "Unknown")</td> <Td>@access.Timestamp.ToString("s") (@access.Timestamp.Humanize())</Td> </tr> } </tbody> </table> } else { <div class="alert alert-info"> <strong>Sorry...</strong> this file has never been downloaded yet! </div> } <p> <a asp-action="Index" class="btn btn-default">Back to overview</a> </p>
mit
C#
95f0e6d447e2b10458e920046f8d70045a2a3e6a
refactor of tests
lukekavanagh/Text-Parser-Code-Challenge
TextParser_Unit_Tests/UnitTest1.cs
TextParser_Unit_Tests/UnitTest1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TextParser; namespace TextParser_Unit_Tests { [TestFixture] public class UnitTest1 { public TextParserTool textparser = new TextParserTool(); [Test] public void Returns_Correct_Number_Of_Sentences() { string sentences = "This is my sentence. There are many like it but this one is mine"; int numberofSentencesExpected = 2; int sentenceCount = textparser.GetSentenceCount(sentences); Assert.AreEqual(numberofSentencesExpected, sentenceCount); } [Test] public void Returns_Correct_Number_Of_Words() { string words = "Born To Kill"; int numberofWordsExpected = 3; string[] wordCount = textparser.NumberOfWords(words); Assert.AreEqual(numberofWordsExpected, wordCount.Length); } [Test] public void Check_Longest_Sentence_Returned_Is_Correct() { string text = "This is my rifle this is my gun, this is a long sentence. This is a short sentence"; string expectsSentence = "This is my rifle this is my gun, this is a long sentence"; string longSentence = textparser.LongestSentence(text); Assert.AreEqual(expectsSentence, longSentence); } [Test] public void Check_Returns_Most_Frequent_Word() { string[] words = { "Yeah man, love meat, I really enjoyed that meat feast pizza, it was a meat extravaganza" }; string expectedMostFrequentWord = "meat"; string frequencyOfWordSearch = textparser.MostFrequentWord(words); Assert.AreEqual(expectedMostFrequentWord, frequencyOfWordSearch); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; using TextParser; namespace TextParser_Unit_Tests { [TestFixture] public class UnitTest1 { public TextParserTool textparser = new TextParserTool(); [Test] public void Returns_Correct_Number_Of_Sentences() { string sentences = "This is my sentence. There are many like it but this one is mine"; int numberofSentencesExpected = 2; int sentenceCount = textparser.GetSentenceCount(sentences); Assert.AreEqual(numberofSentencesExpected, sentenceCount); } [Test] public void Returns_Correct_Number_Of_Words() { string words = "Born To Kill"; int numberofWordsExpected = 3; string[] wordCount = textparser.NumberOfWords(words); Assert.AreEqual(numberofWordsExpected, wordCount.Length); } [Test] public void Check_Longest_Sentence_Returned_Is_Correct() { string text = "This is my rifle this is my gun, this is a long sentence. This is a short sentence"; string expectsSentence = "This is my rifle this is my gun, this is a long sentence"; string longSentence = textparser.LongestSentence(text); Assert.AreEqual(expectsSentence, longSentence); } [Test] public void Check_Returns_Most_Frequent_Word() { string words = "Yeah man, love meat, I really enjoyed that meat feast pizza, it was a meat extravaganza"; string expectedMostFrequentWord = "meat"; string [] frequencyOfWordSearch = textparser.MostFrequentWord(words); } } }
apache-2.0
C#
0d0485438cd2544c422b05d7de7cd69acabb9bb1
Disable shortcuts and ContextMenu in web browser control.
Jarrey/wizard-framework,Jarrey/wizard-framework,Jarrey/wizard-framework
src/WizardFramework.HTML/HtmlWizardPage{TM}.Designer.cs
src/WizardFramework.HTML/HtmlWizardPage{TM}.Designer.cs
namespace WizardFramework.HTML { partial class HtmlWizardPage<TM> { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form 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.webView = new System.Windows.Forms.WebBrowser(); this.SuspendLayout(); // // webView // this.webView.AllowNavigation = false; this.webView.AllowWebBrowserDrop = false; this.webView.Dock = System.Windows.Forms.DockStyle.Fill; this.webView.IsWebBrowserContextMenuEnabled = false; this.webView.Location = new System.Drawing.Point(0, 0); this.webView.MinimumSize = new System.Drawing.Size(20, 20); this.webView.Name = "webView"; this.webView.Size = new System.Drawing.Size(150, 150); this.webView.TabIndex = 0; this.webView.WebBrowserShortcutsEnabled = false; // // HtmlWizardPage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Controls.Add(this.webView); this.Name = "HtmlWizardPage"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser webView; } }
namespace WizardFramework.HTML { partial class HtmlWizardPage<TM> { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Windows Form 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.webView = new System.Windows.Forms.WebBrowser(); this.SuspendLayout(); // // webView // this.webView.AllowNavigation = false; this.webView.AllowWebBrowserDrop = false; this.webView.Dock = System.Windows.Forms.DockStyle.Fill; this.webView.IsWebBrowserContextMenuEnabled = true; this.webView.Location = new System.Drawing.Point(0, 0); this.webView.MinimumSize = new System.Drawing.Size(20, 20); this.webView.Name = "webView"; this.webView.Size = new System.Drawing.Size(150, 150); this.webView.TabIndex = 0; this.webView.WebBrowserShortcutsEnabled = true; // // HtmlWizardPage // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.Controls.Add(this.webView); this.Name = "HtmlWizardPage"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser webView; } }
mit
C#
296b363a667cbca00a82cc207d5cc942a4d77bbc
set protector and signout url
yanjustino/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,andyshao/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,faithword/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,TomKearney/IdentityServer3.Samples,faithword/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,TomKearney/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,yanjustino/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,EternalXw/IdentityServer3.Samples,IdentityServer/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,codeice/IdentityServer3.Samples,codedecay/IdentityServer3.Samples,codedecay/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,codedecay/IdentityServer3.Samples,kouweizhong/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,vebin/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,andyshao/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples,codeice/IdentityServer3.Samples,yanjustino/IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,MetSystem/IdentityServer3.Samples,jmalca14/IdentityServer3.Samples,TomKearney/IdentityServer3.Samples,MetSystem/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,feanz/Thinktecture.IdentityServer3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,tuyndv/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,tuyndv/IdentityServer3.Samples,vebin/IdentityServer3.Samples,atul221282/IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,nicklv/IdentityServer3.Samples,eric-swann-q2/IdentityServer3.Samples,tuyndv/IdentityServer3.Samples,MetSystem/IdentityServer3.Samples,sumedhmeshram/IdentityServer3.Samples,codeice/IdentityServer3.Samples,daptiv/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,geffzhang/Thinktecture.IdentityServer.v3.Samples,faithword/IdentityServer3.Samples,vebin/IdentityServer3.Samples,ravibisht27/IdentityServer3.Samples,jhoerr/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,andyshao/IdentityServer3.Samples,JaonDong/IdentityServer3.Samples,DosGuru/IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,MartinKip/IdentityServer3.Samples,ryanvgates/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,lvjunlei/IdentityServer3.Samples,stombeur/IdentityServer3.Samples,pirumpi/IdentityServer3.Samples,ccccccmd/IdentityServer3.Samples,nguyentk90/IdentityServer3.Samples,codehedgehog/IdentityServer3.Samples,18098924759/IdentityServer3.Samples,gavinbarron/IdentityServer3.Samples,carlos-sarmiento/IdentityServer3.Samples
source/SelfHost/SelfHost/Startup.cs
source/SelfHost/SelfHost/Startup.cs
using Owin; using SelfHost.Config; using Thinktecture.IdentityServer.Core.Configuration; using Thinktecture.IdentityServer.Host.Config; using Thinktecture.IdentityServer.WsFederation.Configuration; using Thinktecture.IdentityServer.WsFederation.Services; namespace SelfHost { internal class Startup { public void Configuration(IAppBuilder appBuilder) { var factory = Factory.Create( issuerUri: "https://idsrv3.com", siteName: "Thinktecture IdentityServer v3 - preview 1 (SelfHost)"); var options = new IdentityServerOptions { PublicHostName = "http://localhost:3333", Factory = factory, ConfigurePlugins = ConfigurePlugins }; appBuilder.UseIdentityServer(options); } private void ConfigurePlugins(IAppBuilder pluginApp, IdentityServerOptions options) { var wsFedOptions = new WsFederationPluginOptions { Factory = new WsFederationServiceFactory { UserService = options.Factory.UserService, CoreSettings = options.Factory.CoreSettings, RelyingPartyService = Registration.RegisterFactory<IRelyingPartyService>(() => new InMemoryRelyingPartyService(RelyingParties.Get())), WsFederationSettings = Registration.RegisterFactory<WsFederationSettings>(() => new WsFedSettings()) }, DataProtector = options.DataProtector }; options.ProtocolLogoutUrls.Add(wsFedOptions.LogoutUrl); pluginApp.UseWsFederationPlugin(wsFedOptions); } } }
using Owin; using SelfHost.Config; using Thinktecture.IdentityServer.Core.Configuration; using Thinktecture.IdentityServer.Host.Config; using Thinktecture.IdentityServer.WsFederation.Configuration; using Thinktecture.IdentityServer.WsFederation.Services; namespace SelfHost { internal class Startup { public void Configuration(IAppBuilder appBuilder) { var factory = Factory.Create( issuerUri: "https://idsrv3.com", siteName: "Thinktecture IdentityServer v3 - preview 1 (SelfHost)"); var options = new IdentityServerOptions { PublicHostName = "http://localhost:3333", Factory = factory, ConfigurePlugins = ConfigurePlugins }; appBuilder.UseIdentityServer(options); } private void ConfigurePlugins(IAppBuilder pluginApp, IdentityServerOptions options) { var wsFedOptions = new WsFederationPluginOptions { Factory = new WsFederationServiceFactory { UserService = options.Factory.UserService, CoreSettings = options.Factory.CoreSettings, RelyingPartyService = Registration.RegisterFactory<IRelyingPartyService>(() => new InMemoryRelyingPartyService(RelyingParties.Get())), WsFederationSettings = Registration.RegisterFactory<WsFederationSettings>(() => new WsFedSettings()) }, }; pluginApp.UseWsFederationPlugin(wsFedOptions); } } }
apache-2.0
C#
8d6a603553d5449c15cbc417cde909f5d60b10ee
Update unit tests
dfensgmbh/biz.dfch.CS.Activiti.Client
src/biz.dfch.CS.Activiti.Client.Tests/RestClientTest.cs
src/biz.dfch.CS.Activiti.Client.Tests/RestClientTest.cs
/** * Copyright 2015 d-fens GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace biz.dfch.CS.Activiti.Client.Tests { [TestClass] public class RestClientTest { [TestMethod] public void CreatingClientWithParameterlessConstructorSucceeds() { // Arrange // Act var restClient = new RestClient(); // Assert Assert.IsNotNull(restClient); } [TestMethod] public void CreatingClientWithParamterisedConstructorSucceeds() { // Arrange var serveruri = new Uri("http://192.168.112.129:9000/activiti-rest/service/"); var username = "kermit"; var password = "kermit"; // Act var restClient = new RestClient(serveruri, username, password); restClient.Login(); // Assert Assert.IsNotNull(restClient); Assert.AreEqual(serveruri, restClient.UriServer); Assert.AreEqual(username, restClient.Username); //Assert.AreEqual(password, restClient.Password); } [TestMethod] public void CreatingClientAndLoginSucceeds() { // Arrange var serveruri = new Uri("http://192.168.112.129:9000/activiti-rest/service/"); var username = "kermit"; var password = "kermit"; // Act var restClient = new RestClient(serveruri, username, password); var user = restClient.Login(); // Assert Assert.IsNotNull(restClient); Assert.AreEqual(serveruri, restClient.UriServer); Assert.AreEqual(username, restClient.Username); //Assert.AreEqual(password, restClient.Password); } } }
/** * Copyright 2015 d-fens GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace biz.dfch.CS.Activiti.Client.Tests { [TestClass] public class RestClientTest { [TestMethod] public void CreatingClientWithParameterlessConstructorSucceeds() { // Arrange // Act var restClient = new RestClient(); // Assert Assert.IsNotNull(restClient); } [TestMethod] public void CreatingClientWithParamterisedConstructorSucceeds() { // Arrange var server = new Uri("http://localhost"); var username = "arbitrary-user"; var password = "Ym9ndXMtcGFzc3dvcmQ="; // Act var restClient = new RestClient(server, username, password); // Assert Assert.IsNotNull(restClient); Assert.AreEqual(server, restClient.Server); Assert.AreEqual(username, restClient.Username); //Assert.AreEqual(password, restClient.Password); } } }
apache-2.0
C#
e348f8b63acbce16f3234f35c3ab33e4f483638f
Add property to whether mark new Messages as read or not
InfiniteSoul/Azuria
Azuria/Community/MessageEnumerable.cs
Azuria/Community/MessageEnumerable.cs
using System.Collections; using System.Collections.Generic; namespace Azuria.Community { /// <summary> /// </summary> public class MessageEnumerable : IEnumerable<Message> { private readonly int _conferenceId; private readonly Senpai _senpai; internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true) { this._conferenceId = conferenceId; this._senpai = senpai; this.MarkAsRead = markAsRead; } #region Properties /// <summary> /// </summary> public bool MarkAsRead { get; set; } #endregion #region Methods /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator<Message> GetEnumerator() { return new MessageEnumerator(this._conferenceId, this.MarkAsRead, this._senpai); } #endregion } }
using System.Collections; using System.Collections.Generic; namespace Azuria.Community { /// <summary> /// </summary> public class MessageEnumerable : IEnumerable<Message> { private readonly int _conferenceId; private readonly bool _markAsRead; private readonly Senpai _senpai; internal MessageEnumerable(int conferenceId, Senpai senpai, bool markAsRead = true) { this._conferenceId = conferenceId; this._senpai = senpai; this._markAsRead = markAsRead; } #region Methods /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="T:System.Collections.IEnumerator" /> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary>Returns an enumerator that iterates through the collection.</summary> /// <returns>An enumerator that can be used to iterate through the collection.</returns> public IEnumerator<Message> GetEnumerator() { return new MessageEnumerator(this._conferenceId, this._markAsRead, this._senpai); } #endregion } }
mit
C#
332ee4f6b01dbea6bbf55eff1b2d1552e77fdd68
Update NetUtil.cs
win120a/ACClassRoomUtil,win120a/ACClassRoomUtil
ProcessBlockUtil/NetUtil.cs
ProcessBlockUtil/NetUtil.cs
/* Copyright (C) 2011-2014 AC Inc. (Andy Cheung) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; using System.IO; namespace ACProcessBlockUtil { class NetUtil{ } }
apache-2.0
C#
19703360f7286bf8f5faac1cc9be63209c88b5e1
Apply own control theme before templated parent's.
AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia
src/Avalonia.Base/Styling/Styler.cs
src/Avalonia.Base/Styling/Styler.cs
using System; namespace Avalonia.Styling { public class Styler : IStyler { public void ApplyStyles(IStyleable target) { _ = target ?? throw new ArgumentNullException(nameof(target)); // Apply the control theme. target.GetEffectiveTheme()?.TryAttach(target, target); // If the control has a themed templated parent then apply the styles from the // templated parent theme. if (target.TemplatedParent is IStyleable styleableParent) styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent); // Apply styles from the rest of the tree. if (target is IStyleHost styleHost) ApplyStyles(target, styleHost); } private void ApplyStyles(IStyleable target, IStyleHost host) { var parent = host.StylingParent; if (parent != null) ApplyStyles(target, parent); if (host.IsStylesInitialized) host.Styles.TryAttach(target, host); } } }
using System; namespace Avalonia.Styling { public class Styler : IStyler { public void ApplyStyles(IStyleable target) { _ = target ?? throw new ArgumentNullException(nameof(target)); // If the control has a themed templated parent then first apply the styles from // the templated parent theme. if (target.TemplatedParent is IStyleable styleableParent) styleableParent.GetEffectiveTheme()?.TryAttach(target, styleableParent); // Next apply the control theme. target.GetEffectiveTheme()?.TryAttach(target, target); // Apply styles from the rest of the tree. if (target is IStyleHost styleHost) ApplyStyles(target, styleHost); } private void ApplyStyles(IStyleable target, IStyleHost host) { var parent = host.StylingParent; if (parent != null) ApplyStyles(target, parent); if (host.IsStylesInitialized) host.Styles.TryAttach(target, host); } } }
mit
C#
095bee00d4623244c582c713165415e71453e0f0
Undo changes
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Services/IFinancialService.cs
Anlab.Mvc/Services/IFinancialService.cs
using Anlab.Jobs.MoneyMovement; using Microsoft.Extensions.Options; using System; using System.Net.Http; using System.Threading.Tasks; using Anlab.Core.Extensions; using Newtonsoft.Json; namespace AnlabMvc.Services { public interface IFinancialService { Task<string> GetAccountName(string account); } public class FinancialService: IFinancialService { private readonly AppSettings _appSettings; public FinancialService(IOptions<AppSettings> appSettings) { _appSettings = appSettings.Value; } public async Task<string> GetAccountName(string account) { var accountModel = new AccountModel(account); string url; if (!String.IsNullOrWhiteSpace(accountModel.SubAccount)) { url = String.Format("{0}/subaccount/{1}/{2}/{3}/name", _appSettings.FinancialLookupUrl, accountModel.Chart, accountModel.Account, accountModel.SubAccount); //This fails } else { url = String.Format("{0}/account/{1}/{2}/name", _appSettings.FinancialLookupUrl, accountModel.Chart, accountModel.Account); } using (var client = new HttpClient()) { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); var contents = await response.Content.ReadAsStringAsync(); return contents; } } } }
using Anlab.Jobs.MoneyMovement; using Microsoft.Extensions.Options; using System; using System.Net.Http; using System.Threading.Tasks; using Anlab.Core.Extensions; using Newtonsoft.Json; namespace AnlabMvc.Services { public interface IFinancialService { Task<string> GetAccountName(string account); } public class FinancialService: IFinancialService { private readonly AppSettings _appSettings; public FinancialService(IOptions<AppSettings> appSettings) { _appSettings = appSettings.Value; } public async Task<string> GetAccountName(string account) { var accountModel = new AccountModel(account); string url; if (!String.IsNullOrWhiteSpace(accountModel.SubAccount)) { url = String.Format("{0}/subaccount/{1}/{2}/{3}", _appSettings.FinancialLookupUrl, accountModel.Chart, accountModel.Account, accountModel.SubAccount); } else { url = String.Format("{0}/account/{1}/{2}", _appSettings.FinancialLookupUrl, accountModel.Chart, accountModel.Account); } using (var client = new HttpClient()) { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); var contents = await response.Content.ReadAsStringAsync(); var kfsDetails = JsonConvert.DeserializeObject<KfsLookup>(contents); if (kfsDetails.Closed || kfsDetails.AccountExpirationDate != null && kfsDetails.AccountExpirationDate.Value <= DateTime.UtcNow.ToPacificTime()) { throw new Exception("Closed or expired"); } return JsonConvert.SerializeObject(kfsDetails.AccountName); } } } public class KfsLookup { public string AccountName { get; set; } public DateTime? AccountExpirationDate { get; set; } public bool Closed { get; set; } } }
mit
C#
41f9953ceab85275bcede917dc5b1063acbe6614
Fix code analysis
k94ll13nn3/Strinken
src/Strinken/Core/IsExternalInit.cs
src/Strinken/Core/IsExternalInit.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.ComponentModel; namespace System.Runtime.CompilerServices; /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { }
// 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.ComponentModel; namespace System.Runtime.CompilerServices; /// <summary> /// Reserved to be used by the compiler for tracking metadata. /// This class should not be used by developers in source code. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { }
mit
C#
8af19254bab87df5adcdf6c05f887d8950c43383
Add default constructor for product rating
Branimir123/ZobShop,Branimir123/ZobShop,Branimir123/ZobShop
src/ZobShop.Models/ProductRating.cs
src/ZobShop.Models/ProductRating.cs
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ZobShop.Models { public class ProductRating { public ProductRating() { } public ProductRating(int rating, string content, Product product, User author) { this.Rating = rating; this.Content = content; this.Author = author; this.Product = product; } [Key] public int ProductRatingId { get; set; } public int Rating { get; set; } public string Content { get; set; } public int ProductId { get; set; } [ForeignKey("ProductId")] public virtual Product Product { get; set; } [ForeignKey("Author")] public string AuthorId { get; set; } [ForeignKey("Id")] public virtual User Author { get; set; } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ZobShop.Models { public class ProductRating { public ProductRating(int rating, string content, int productId, User author) { this.Rating = rating; this.Content = content; this.ProductId = productId; this.Author = author; } [Key] public int ProductRatingId { get; set; } public int Rating { get; set; } public string Content { get; set; } public int ProductId { get; set; } [ForeignKey("ProductId")] public virtual Product Product { get; set; } [ForeignKey("Author")] public string AuthorId { get; set; } [ForeignKey("Id")] public virtual User Author { get; set; } } }
mit
C#
7982f01c45817ff7be9c21da3914bae811fdfe0b
Update microdata for actual number of students table
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.EduProgramProfiles/Views/Contingent/_ActualRow.cshtml
R7.University.EduProgramProfiles/Views/Contingent/_ActualRow.cshtml
@inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel> @using DotNetNuke.Web.Mvc.Helpers @using R7.University.EduProgramProfiles.ViewModels <td itemprop="eduCode">@Model.EduProfile.EduProgram.Code</td> <td itemprop="eduName">@Model.EduProfileTitle</td> <td itemprop="eduLevel">@Model.EduProfile.EduLevel.Title</td> <td itemprop="eduForm">@Model.EduFormTitle</td> <td itemprop="numberBF">@Model.ActualFB</td> <td itemprop="numberBR">@Model.ActualRB</td> <td itemprop="numberBM">@Model.ActualMB</td> <td itemprop="numberP">@Model.ActualBC</td> <td itemprop="numberF">@Model.ActualForeign</td>
@inherits DotNetNuke.Web.Mvc.Framework.DnnWebViewPage<ContingentViewModel> @using DotNetNuke.Web.Mvc.Helpers @using R7.University.EduProgramProfiles.ViewModels <td itemprop="eduCode">@Model.EduProfile.EduProgram.Code</td> <td itemprop="eduName">@Model.EduProfileTitle</td> <td itemprop="eduLevel">@Model.EduProfile.EduLevel.Title</td> <td itemprop="eduForm">@Model.EduFormTitle</td> <td itemprop="numberBFpriem">@Model.ActualFB</td> <td itemprop="numberBRpriem">@Model.ActualRB</td> <td itemprop="numberBMpriem">@Model.ActualMB</td> <td itemprop="numberPpriem">@Model.ActualBC</td> <td>@Model.ActualForeign</td>
agpl-3.0
C#
ade1feffedfac514f9c39cdcee1a2089ce5f8db0
fix typo
sassembla/Miyamasu,sassembla/Miyamasu
Assets/SampleTests/Editor/SampleTest.cs
Assets/SampleTests/Editor/SampleTest.cs
using System; using System.Net; using System.Net.Sockets; using Miyamasu; /** samples of test. */ public class Tests : MiyamasuTestRunner { [MSetup] public void Setup () { TestLogger.Log("setup"); } [MTeardown] public void Teardown () { TestLogger.Log("teardown"); } /** always a = b. "Assert(bool assertion, string message)" method can raise error when assertion failed. */ [MTest] public void SampleSuccess () { var a = 1; var b = 1; Assert(a == b, "a is not b, a:" + a + " b:" + b); } [MTest] public void SampleFail () { var a = 1; var b = 2; Assert(a == b, "a is not b, a:" + a + " b:" + b); } /** async operation with another thread. "WaitUntil(Func<bool> isCompleted, int waitSeconds)" can wait another thread's done. */ [MTest] public void SampleSuccessAsync () { var done = false; /* the sample case which method own their thread and done with asynchronously. */ { var endPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 80); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var connectArgs = new SocketAsyncEventArgs(); connectArgs.AcceptSocket = socket; connectArgs.RemoteEndPoint = endPoint; connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>( (obj, args) => { // failed or succeded, done will be true. done = true; } ); // next Async operation will be done really soon in async. socket.ConnectAsync(connectArgs); } /* wait while 1st parameter "Func<bool> isCompleted" returns true. in this case, "done" flag become true when async operation is done. 2nd parameter "1" means waiting 1 seconds. */ WaitUntil( () => done, 1 ); } [MTest] public void SampleSuccessAsyncOnMainThread () { var dataPath = string.Empty; /* sometimes we should test the method which can only run in Unity's MainThread. this async operation will be running in Unity's Main Thread. */ Action onMainThread = () => { dataPath = UnityEngine.Application.dataPath;// this code is only available Unity's MainThread. }; RunOnMainThread(onMainThread); /* wait until "dataPath" is not null or empty. */ WaitUntil(() => !string.IsNullOrEmpty(dataPath), 1); } }
using System; using System.Net; using System.Net.Sockets; using Miyamasu; /** samples of test. */ public class Tests : MiyamasuTestRunner { [MSetup] public void Setup () { TestLogger.Log("setup"); } [MTeardown] public void Teardown () { TestLogger.Log("teardown"); } /** always a = b. "Assert(bool assertion, string message)" method can raise error when assertion failed. */ [MTest] public void SampleSuccess () { var a = 1; var b = 1; Assert(a == b, "a is not b, a:" + a + " b:" + b); } [MTest] public void SampleFail () { var a = 1; var b = 2; Assert(a == b, "a is not b, a:" + a + " b:" + b); } /** async operation with another thread. "WaitUntil(Func<bool> completed, )" can wait another thread's done. */ [MTest] public void SampleSuccessAsync () { var done = false; /* the sample case which method own their thread and done with asynchronously. */ { var endPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 80); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); var connectArgs = new SocketAsyncEventArgs(); connectArgs.AcceptSocket = socket; connectArgs.RemoteEndPoint = endPoint; connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>( (obj, args) => { // failed or succeded, done will be true. done = true; } ); // next Async operation will be done really soon in async. socket.ConnectAsync(connectArgs); } /* wait while 1st parameter "Func<bool> isCompleted" returns true. in this case, "done" flag become true when async operation is done. 2nd parameter "1" means waiting 1 seconds. */ WaitUntil( () => done, 1 ); } [MTest] public void SampleSuccessAsyncOnMainThread () { var dataPath = string.Empty; /* sometimes we should test the method which can only run in Unity's MainThread. this async operation will be running in Unity's Main Thread. */ Action onMainThread = () => { dataPath = UnityEngine.Application.dataPath;// this code is only available Unity's MainThread. }; RunOnMainThread(onMainThread); /* wait until "dataPath" is not null or empty. */ WaitUntil(() => !string.IsNullOrEmpty(dataPath), 1); } }
mit
C#
aceb5ddcaadbfaabbc4bb1bd94641d035238e8a7
Add smooth rotation for MetallKefer
emazzotta/unity-tower-defense
Assets/Scripts/MetallKeferController.cs
Assets/Scripts/MetallKeferController.cs
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { private GameController gameController; private GameObject[] baseBuildable; private GameObject nextWaypiont; private float health; private int currentWaypointIndex = 0; private int movementSpeed = 2; void Start () { this.health = 100; this.gameController = GameObject.FindObjectOfType<GameController>(); this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex]; this.setInitialPosition (); } 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 setInitialPosition() { this.transform.position = this.nextWaypiont.transform.position; } private void moveToNextWaypoint() { float step = movementSpeed * Time.deltaTime; var targetRotation = Quaternion.LookRotation(this.nextWaypiont.transform.position - transform.position); transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 5 * Time.deltaTime); //this.transform.LookAt (this.nextWaypiont.transform); this.transform.position = Vector3.MoveTowards(transform.position, this.nextWaypiont.transform.position, step); if (this.transform.position.Equals( this.nextWaypiont.transform.position )) { this.SetNextWaypoint (); } } public void TakeDamage(float damage) { health -= damage; } }
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { private GameController gameController; private GameObject[] baseBuildable; private GameObject nextWaypiont; private float health; private int currentWaypointIndex = 0; private int movementSpeed = 2; void Start () { this.health = 100; this.gameController = GameObject.FindObjectOfType<GameController>(); this.nextWaypiont = this.gameController.getWaypoints () [this.currentWaypointIndex]; this.setInitialPosition (); } 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 setInitialPosition() { this.transform.position = this.nextWaypiont.transform.position; } 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); if (this.transform.position.Equals( this.nextWaypiont.transform.position )) { this.SetNextWaypoint (); } } public void TakeDamage(float damage) { health -= damage; } }
mit
C#
b838b27b75a09308e472b838d18031716e093a18
Save project when addin reference removed
mhutch/MonoDevelop.AddinMaker,mhutch/MonoDevelop.AddinMaker
AddinReferenceNodeBuilder.cs
AddinReferenceNodeBuilder.cs
using System; using MonoDevelop.Components.Commands; using MonoDevelop.Core; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.AddinMaker.AddinBrowser; namespace MonoDevelop.AddinMaker { class AddinReferenceNodeBuilder : TypeNodeBuilder { public override Type NodeDataType { get { return typeof (AddinReference); } } public override string GetNodeName (ITreeNavigator thisNode, object dataObject) { return "AddinReference"; } public override string ContextMenuAddinPath { get { return "/MonoDevelop/AddinMaker/ContextMenu/ProjectPad/AddinReference"; } } public override Type CommandHandlerType { get { return typeof (AddinReferenceCommandHandler); } } public override object GetParentObject (object dataObject) { var addin = (AddinReference)dataObject; return addin.OwnerProject != null ? addin.OwnerProject.AddinReferences : null; } public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { var addin = (AddinReference)dataObject; nodeInfo.Label = GLib.Markup.EscapeText (addin.Id); //TODO: custom icon nodeInfo.Icon = Context.GetIcon ("md-reference-package"); //TODO: get state, mark if unresolved //nodeInfo.StatusSeverity = TaskSeverity.Error; //nodeInfo.StatusMessage = GettextCatalog.GetString ("Could not resolve addin"); } public override bool HasChildNodes (ITreeBuilder builder, object dataObject) { return false; } class AddinReferenceCommandHandler : NodeCommandHandler { public override bool CanDeleteItem () { return true; } [CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.Delete)] public void UpdateDelete (CommandInfo info) { info.Enabled = true; info.Text = GettextCatalog.GetString ("Remove"); } [CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Delete)] public override void DeleteItem () { var addin = (AddinReference) CurrentNode.DataItem; var project = addin.OwnerProject; project.AddinReferences.Remove (addin); IdeApp.ProjectOperations.Save (project); } public override void ActivateItem () { var addin = (AddinReference) CurrentNode.DataItem; var resolved = addin.OwnerProject.AddinRegistry.GetAddin (addin.Id); if (resolved != null) { AddinBrowserViewContent.Open (addin.OwnerProject.AddinRegistry, resolved); } } } } }
using System; using MonoDevelop.Components.Commands; using MonoDevelop.Core; using MonoDevelop.Ide.Gui.Components; using MonoDevelop.AddinMaker.AddinBrowser; namespace MonoDevelop.AddinMaker { class AddinReferenceNodeBuilder : TypeNodeBuilder { public override Type NodeDataType { get { return typeof (AddinReference); } } public override string GetNodeName (ITreeNavigator thisNode, object dataObject) { return "AddinReference"; } public override string ContextMenuAddinPath { get { return "/MonoDevelop/AddinMaker/ContextMenu/ProjectPad/AddinReference"; } } public override Type CommandHandlerType { get { return typeof (AddinReferenceCommandHandler); } } public override object GetParentObject (object dataObject) { var addin = (AddinReference)dataObject; return addin.OwnerProject != null ? addin.OwnerProject.AddinReferences : null; } public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { var addin = (AddinReference)dataObject; nodeInfo.Label = GLib.Markup.EscapeText (addin.Id); //TODO: custom icon nodeInfo.Icon = Context.GetIcon ("md-reference-package"); //TODO: get state, mark if unresolved //nodeInfo.StatusSeverity = TaskSeverity.Error; //nodeInfo.StatusMessage = GettextCatalog.GetString ("Could not resolve addin"); } public override bool HasChildNodes (ITreeBuilder builder, object dataObject) { return false; } class AddinReferenceCommandHandler : NodeCommandHandler { public override bool CanDeleteItem () { return true; } [CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.Delete)] public void UpdateDelete (CommandInfo info) { info.Enabled = true; info.Text = GettextCatalog.GetString ("Remove"); } [CommandHandler (MonoDevelop.Ide.Commands.EditCommands.Delete)] public override void DeleteItem () { var addin = (AddinReference) CurrentNode.DataItem; addin.OwnerProject.AddinReferences.Remove (addin); } public override void ActivateItem () { var addin = (AddinReference) CurrentNode.DataItem; var resolved = addin.OwnerProject.AddinRegistry.GetAddin (addin.Id); if (resolved != null) { AddinBrowserViewContent.Open (addin.OwnerProject.AddinRegistry, resolved); } } } } }
mit
C#
fafb91a62c60750f42983d57cbf2fb7cc99e42fc
Make Shuffle<T> return IEnumerable<T> instead of IList<T>.
AIWolfSharp/AIWolf_NET
AIWolfLib/ShuffleExtensions.cs
AIWolfLib/ShuffleExtensions.cs
// // ShuffleExtensions.cs // // Copyright (c) 2017 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using System; using System.Collections.Generic; using System.Linq; namespace AIWolf.Lib { #if JHELP /// <summary> /// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義 /// </summary> #else /// <summary> /// Defines extension method to shuffle what implements IEnumerable interface. /// </summary> #endif public static class ShuffleExtensions { #if JHELP /// <summary> /// IEnumerableをシャッフルしたものを返す /// </summary> /// <typeparam name="T">IEnumerableの要素の型</typeparam> /// <param name="s">TのIEnumerable</param> /// <returns>シャッフルされたIEnumerable</returns> #else /// <summary> /// Returns shuffled IEnumerable of T. /// </summary> /// <typeparam name="T">Type of element of IEnumerable.</typeparam> /// <param name="s">IEnumerable of T.</param> /// <returns>Shuffled IEnumerable of T.</returns> #endif public static IOrderedEnumerable<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()); } }
// // ShuffleExtensions.cs // // Copyright (c) 2017 Takashi OTSUKI // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // using System; using System.Collections.Generic; using System.Linq; namespace AIWolf.Lib { #if JHELP /// <summary> /// IEnumerableインターフェースを実装したクラスに対するShuffle拡張メソッド定義 /// </summary> #else /// <summary> /// Defines extension method to shuffle what implements IEnumerable interface. /// </summary> #endif public static class ShuffleExtensions { #if JHELP /// <summary> /// IEnumerableをシャッフルしたIListを返す /// </summary> /// <typeparam name="T">IEnumerableの要素の型</typeparam> /// <param name="s">TのIEnumerable</param> /// <returns>シャッフルされたTのIList</returns> #else /// <summary> /// Returns shuffled IList of T. /// </summary> /// <typeparam name="T">Type of element of IEnumerable.</typeparam> /// <param name="s">IEnumerable of T.</param> /// <returns>Shuffled IList of T.</returns> #endif public static IList<T> Shuffle<T>(this IEnumerable<T> s) => s.OrderBy(x => Guid.NewGuid()).ToList(); } }
mit
C#
54ed7d5872c3c1d0bda21da7efe06fb4020d653a
Switch from public properties to serializable private ones
tanuva/planegame
Assets/Scripts/UIController.cs
Assets/Scripts/UIController.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; /// <summary> /// UIController holds references to GUI widgets and acts as data receiver for them. /// </summary> public class UIController : MonoBehaviour, IGUIUpdateTarget { [SerializeField] private Text m_SpeedText; [SerializeField] private Text m_AltitudeText; [SerializeField] private Slider m_ThrottleSlider; [SerializeField] private Slider m_EngineThrottleSlider; public void UpdateSpeed(float speed) { m_SpeedText.text = "IAS: " + (int)(speed * 1.94f) + " kn"; } public void UpdateThrottle(float throttle) { m_ThrottleSlider.value = throttle; } public void UpdateEngineThrottle(float engineThrottle) { m_EngineThrottleSlider.value = engineThrottle; } public void UpdateAltitude(float altitude) { m_AltitudeText.text = "ALT: " + (int)(altitude * 3.28f) + " ft"; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using UnityEngine.UI; using System.Collections; /// <summary> /// UIController holds references to GUI widgets and acts as data receiver for them. /// </summary> public class UIController : MonoBehaviour, IGUIUpdateTarget { public Text SpeedText; public Slider ThrottleSlider; public Slider EngineThrottleSlider; public Text AltitudeText; public void UpdateSpeed(float speed) { SpeedText.text = "IAS: " + (int)(speed * 1.94f) + " kn"; } public void UpdateThrottle(float throttle) { ThrottleSlider.value = throttle; } public void UpdateEngineThrottle(float engineThrottle) { EngineThrottleSlider.value = engineThrottle; } public void UpdateAltitude(float altitude) { AltitudeText.text = "ALT: " + (int)(altitude * 3.28f) + " ft"; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
82105ba81d0cd6b866454402a8b064ecc7ebd514
Change the actual versions allowed to connect, which is different from the interface major version
TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,OpenSimian/opensimulator,TomDataworks/opensim,OpenSimian/opensimulator,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,OpenSimian/opensimulator,OpenSimian/opensimulator,TomDataworks/opensim,RavenB/opensim,OpenSimian/opensimulator,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,OpenSimian/opensimulator,RavenB/opensim,OpenSimian/opensimulator,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC
OpenSim/Server/Base/ProtocolVersions.cs
OpenSim/Server/Base/ProtocolVersions.cs
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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. */ namespace OpenSim.Server.Base { public class ProtocolVersions { /// <value> /// This is the external protocol versions. It is separate from the OpenSimulator project version. /// /// These version numbers should be increased by 1 every time a code /// change in the Service.Connectors and Server.Handlers, espectively, /// makes the previous OpenSimulator revision incompatible /// with the new revision. /// /// Changes which are compatible with an older revision (e.g. older revisions experience degraded functionality /// but not outright failure) do not need a version number increment. /// /// Having this version number allows the grid service to reject connections from regions running a version /// of the code that is too old. /// /// </value> // The range of acceptable servers for client-side connectors public readonly static int ClientProtocolVersionMin = 1; public readonly static int ClientProtocolVersionMax = 1; // The range of acceptable clients in server-side handlers public readonly static int ServerProtocolVersionMin = 1; public readonly static int ServerProtocolVersionMax = 1; } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 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. * * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 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. */ namespace OpenSim.Server.Base { public class ProtocolVersions { /// <value> /// This is the external protocol versions. It is separate from the OpenSimulator project version. /// /// These version numbers should be increased by 1 every time a code /// change in the Service.Connectors and Server.Handlers, espectively, /// makes the previous OpenSimulator revision incompatible /// with the new revision. /// /// Changes which are compatible with an older revision (e.g. older revisions experience degraded functionality /// but not outright failure) do not need a version number increment. /// /// Having this version number allows the grid service to reject connections from regions running a version /// of the code that is too old. /// /// </value> // The range of acceptable servers for client-side connectors public readonly static int ClientProtocolVersionMin = 0; public readonly static int ClientProtocolVersionMax = 0; // The range of acceptable clients in server-side handlers public readonly static int ServerProtocolVersionMin = 0; public readonly static int ServerProtocolVersionMax = 0; } }
bsd-3-clause
C#
4a348d82b2e850c3e4831736ec02053a6668cff2
Fix typo in XML docs
NRules/NRules
src/NRules/NRules/Agenda.cs
src/NRules/NRules/Agenda.cs
namespace NRules { /// <summary> /// Agenda stores matches between rules and facts. These matches are called activations. /// Multiple activations are ordered according to the conflict resolution strategy. /// </summary> public interface IAgenda { /// <summary> /// Indicates whether there are any activations in the agenda. /// </summary> /// <returns>If agenda is empty then <c>true</c> otherwise <c>false</c>.</returns> bool IsEmpty(); /// <summary> /// Retrieves the next match, without removing it from agenda. /// </summary> /// <remarks>Throws <c>InvalidOperationException</c> if agenda is empty.</remarks> /// <returns>Next match.</returns> IActivation Peek(); /// <summary> /// Removes all matches from agenda. /// </summary> void Clear(); } internal interface IAgendaInternal : IAgenda { Activation Pop(); void Add(Activation activation); void Modify(Activation activation); void Remove(Activation activation); } internal class Agenda : IAgendaInternal { private readonly ActivationQueue _activationQueue = new ActivationQueue(); public bool IsEmpty() { return !_activationQueue.HasActive(); } public IActivation Peek() { Activation activation = _activationQueue.Peek(); return activation; } public void Clear() { _activationQueue.Clear(); } public Activation Pop() { Activation activation = _activationQueue.Dequeue(); return activation; } public void Add(Activation activation) { _activationQueue.Enqueue(activation.CompiledRule.Priority, activation); } public void Modify(Activation activation) { _activationQueue.Enqueue(activation.CompiledRule.Priority, activation); } public void Remove(Activation activation) { _activationQueue.Remove(activation); } } }
namespace NRules { /// <summary> /// Agenda stored matches between rules and facts. These matches are called activations. /// Multiple activations are ordered according to the conflict resolution strategy. /// </summary> public interface IAgenda { /// <summary> /// Indicates whether there are any activations in the agenda. /// </summary> /// <returns>If agenda is empty then <c>true</c> otherwise <c>false</c>.</returns> bool IsEmpty(); /// <summary> /// Retrieves the next match, without removing it from agenda. /// </summary> /// <remarks>Throws <c>InvalidOperationException</c> if agenda is empty.</remarks> /// <returns>Next match.</returns> IActivation Peek(); /// <summary> /// Removes all matches from agenda. /// </summary> void Clear(); } internal interface IAgendaInternal : IAgenda { Activation Pop(); void Add(Activation activation); void Modify(Activation activation); void Remove(Activation activation); } internal class Agenda : IAgendaInternal { private readonly ActivationQueue _activationQueue = new ActivationQueue(); public bool IsEmpty() { return !_activationQueue.HasActive(); } public IActivation Peek() { Activation activation = _activationQueue.Peek(); return activation; } public void Clear() { _activationQueue.Clear(); } public Activation Pop() { Activation activation = _activationQueue.Dequeue(); return activation; } public void Add(Activation activation) { _activationQueue.Enqueue(activation.CompiledRule.Priority, activation); } public void Modify(Activation activation) { _activationQueue.Enqueue(activation.CompiledRule.Priority, activation); } public void Remove(Activation activation) { _activationQueue.Remove(activation); } } }
mit
C#
3b855f5e4aec7f818d219060fb84f49d87f4000a
Update StatModifiable
jkpenner/RPGSystemTutorial
Assets/Scripts/RPGSystems/StatTypes/RPGStatModifiable.cs
Assets/Scripts/RPGSystems/StatTypes/RPGStatModifiable.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class RPGStatModifiable : RPGStat, IStatModifiable, IStatValueChange { private List<RPGStatModifier> _statMods; private int _statModValue; public event System.EventHandler OnValueChange; public override int StatValue { get { return base.StatValue + StatModifierValue;} } public int StatModifierValue { get { return _statModValue; } } public RPGStatModifiable() { _statModValue = 0; _statMods = new List<RPGStatModifier>(); } protected void TriggerValueChange() { if (OnValueChange != null) { OnValueChange(this, null); } } public void AddModifier(RPGStatModifier mod) { _statMods.Add(mod); mod.OnValueChange += OnModValueChange; } public void RemoveModifier(RPGStatModifier mod) { _statMods.Add(mod); mod.OnValueChange -= OnModValueChange; } public void ClearModifiers() { foreach (var mod in _statMods) { mod.OnValueChange -= OnModValueChange; } _statMods.Clear(); } public void UpdateModifiers() { _statModValue = 0; var orderGroups = _statMods.GroupBy(mod => mod.Order); foreach(var group in orderGroups) { float sum = 0, max = 0; foreach(var mod in group) { if(mod.Stacks == false) { if(mod.Value > max) { max = mod.Value; } } else { sum += mod.Value; } } _statModValue += group.First().ApplyModifier( StatBaseValue + _statModValue, sum > max ? sum : max); } TriggerValueChange(); } public void OnModValueChange(object modifier, System.EventArgs args) { UpdateModifiers(); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; public class RPGStatModifiable : RPGStat, IStatModifiable, IStatValueChange { private List<RPGStatModifier> _statMods; private int _statModValue; public event System.EventHandler OnValueChange; public override int StatValue { get { return base.StatValue + StatModifierValue;} } public int StatModifierValue { get { return _statModValue; } } public RPGStatModifiable() { _statModValue = 0; _statMods = new List<RPGStatModifier>(); } protected void TriggerValueChange() { if (OnValueChange != null) { OnValueChange(this, null); } } public void AddModifier(RPGStatModifier mod) { _statMods.Add(mod); } public void RemoveModifier(RPGStatModifier mod) { _statMods.Add(mod); } public void ClearModifiers() { _statMods.Clear(); } public void UpdateModifiers() { _statModValue = 0; var orderGroups = _statMods.GroupBy(mod => mod.Order); foreach(var group in orderGroups) { float sum = 0, max = 0; foreach(var mod in group) { if(mod.Stacks == false) { if(mod.Value > max) { max = mod.Value; } } else { sum += mod.Value; } } _statModValue += group.First().ApplyModifier( StatBaseValue + _statModValue, sum > max ? sum : max); } TriggerValueChange(); } }
mit
C#
60d9171c620cfd567d087f019c4ee4af6d62d427
Fix NRE
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
Client/Systems/VesselImmortalSys/VesselImmortalEvents.cs
Client/Systems/VesselImmortalSys/VesselImmortalEvents.cs
using LunaClient.Base; using UniLinq; namespace LunaClient.Systems.VesselImmortalSys { public class VesselImmortalEvents : SubSystem<VesselImmortalSystem> { /// <summary> /// Set vessel immortal state just when the vessel loads /// </summary> public void VesselLoaded(Vessel vessel) { if(vessel == null) return; //Do it this way as vessel can become null later one var vesselId = vessel.id; if (System.OtherPeopleVessels.Any(v => v?.id == vesselId)) { System.SetVesselImmortalState(vessel, true); } } } }
using LunaClient.Base; using UniLinq; namespace LunaClient.Systems.VesselImmortalSys { public class VesselImmortalEvents : SubSystem<VesselImmortalSystem> { /// <summary> /// Set vessel immortal state just when the vessel loads /// </summary> public void VesselLoaded(Vessel vessel) { if(vessel == null) return; //Do it this way as vessel can become null later one var vesselId = vessel.id; if (System.OtherPeopleVessels.Any(v => v.id == vesselId)) { System.SetVesselImmortalState(vessel, true); } } } }
mit
C#
b69605d2659f08a296614189ab17e42393393ab3
Fix GitLock's Default member
github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity
src/GitHub.Api/Git/GitLock.cs
src/GitHub.Api/Git/GitLock.cs
using System; namespace GitHub.Unity { [Serializable] public struct GitLock { public static GitLock Default = new GitLock(); public int ID; public string Path; public string FullPath; public string User; public GitLock(string path, string fullPath, string user, int id) { Path = path; FullPath = fullPath; User = user; ID = id; } public override bool Equals(object other) { if (other is GitLock) { return this.Equals((GitLock)other); } return false; } public bool Equals(GitLock p) { return ID == p.ID; } public override int GetHashCode() { return 17 * 23 + ID.GetHashCode(); } public static bool operator ==(GitLock lhs, GitLock rhs) { return lhs.Equals(rhs); } public static bool operator !=(GitLock lhs, GitLock rhs) { return !(lhs.Equals(rhs)); } public override string ToString() { return $"{{GitLock ({User}) '{Path}'}}"; } } }
using System; namespace GitHub.Unity { [Serializable] public struct GitLock { public static GitLock Default = new GitLock { ID = -1 }; public int ID; public string Path; public string FullPath; public string User; public GitLock(string path, string fullPath, string user, int id) { Path = path; FullPath = fullPath; User = user; ID = id; } public override bool Equals(object other) { if (other is GitLock) { return this.Equals((GitLock)other); } return false; } public bool Equals(GitLock p) { return ID == p.ID; } public override int GetHashCode() { return 17 * 23 + ID.GetHashCode(); } public static bool operator ==(GitLock lhs, GitLock rhs) { return lhs.Equals(rhs); } public static bool operator !=(GitLock lhs, GitLock rhs) { return !(lhs.Equals(rhs)); } public override string ToString() { return $"{{GitLock ({User}) '{Path}'}}"; } } }
mit
C#
38ee43fbd077f2cc4d3408d795d89216509f6146
Use instantiator from injector
DivineInject/DivineInject,DivineInject/DivineInject
DivineInject/DivineInjector.cs
DivineInject/DivineInjector.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DivineInject { public interface IBindingBuilder<TInterface> { DivineInjector To<TImpl>() where TImpl : class; } public class DivineInjector { private Instantiator m_instantiator = new Instantiator(); private IDictionary<Type, object> m_bindings = new Dictionary<Type, object>(); public IBindingBuilder<T> Bind<T>() { return new BindingBuilder<T>(this); } public T Get<T>() { object impl; if (!m_bindings.TryGetValue(typeof(T), out impl)) return default(T); return (T) impl; } private void AddBinding<TInterface, TImpl>() where TImpl : class { var impl = m_instantiator.Create<TImpl>(); m_bindings.Add(typeof(TInterface), impl); } private class BindingBuilder<TInterface> : IBindingBuilder<TInterface> { private DivineInjector m_injector; internal BindingBuilder(DivineInjector injector) { m_injector = injector; } public DivineInjector To<TImpl>() where TImpl : class { m_injector.AddBinding<TInterface, TImpl>(); return m_injector; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DivineInject { public interface IBindingBuilder<TInterface> { DivineInjector To<TImpl>(); } public class DivineInjector { private IDictionary<Type, object> m_bindings = new Dictionary<Type, object>(); public IBindingBuilder<T> Bind<T>() { return new BindingBuilder<T>(this); } public T Get<T>() { object impl; if (!m_bindings.TryGetValue(typeof(T), out impl)) return default(T); return (T) impl; } private void AddBinding<TInterface, TImpl>() { var impl = Activator.CreateInstance<TImpl>(); m_bindings.Add(typeof(TInterface), impl); } private class BindingBuilder<TInterface> : IBindingBuilder<TInterface> { private DivineInjector m_injector; internal BindingBuilder(DivineInjector injector) { m_injector = injector; } public DivineInjector To<TImpl>() { m_injector.AddBinding<TInterface, TImpl>(); return m_injector; } } } }
mit
C#
2187db0dc9675915f72dafa65fad11c1e31725c9
Improve error code throwing
krisbbb/Experiments,krisbbb/Experiments,krisbbb/Experiments,krisbbb/Experiments,krisbbb/Experiments
ProjectEuler/Euler1/Euler1/Program.cs
ProjectEuler/Euler1/Euler1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler1 { class Program { static int Main(string[] args) { int countTo = 0; if(args.Length != 1 || !int.TryParse(args[0], out countTo) || countTo < 1) { Console.WriteLine("Usage: {0} <positive int>", System.Diagnostics.Process.GetCurrentProcess().ProcessName); return -1; } var sum = 0; var count = 0; var mod3 = new ModEnumerable(3); var mod5 = new ModEnumerable(5); var result = mod3.Zip(mod5, (m3, m5) => { count++; if(m3 == 0 || m5 == 0) { sum += count; } return sum; }).Skip(countTo - 1).First(); Console.WriteLine(result); return 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler1 { class Program { static void Main(string[] args) { int countTo = 0; if(args.Length != 1 || !int.TryParse(args[0], out countTo) || countTo < 1) { Console.WriteLine("Usage: {0} <positive int>", System.Diagnostics.Process.GetCurrentProcess().ProcessName); Environment.Exit(-1); } var sum = 0; var count = 0; var mod3 = new ModEnumerable(3); var mod5 = new ModEnumerable(5); var result = mod3.Zip(mod5, (m3, m5) => { count++; if(m3 == 0 || m5 == 0) { sum += count; } return sum; }).Skip(countTo - 1).First(); Console.WriteLine(result); Environment.Exit(0); } } }
mit
C#
fe0af5f2d5e7db144486e4e7232fdf73103f4a86
Allow to clear user defined vars.
lukyad/Eco
Eco/Variables/UserVariables.cs
Eco/Variables/UserVariables.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace Eco { public class UserVariables : IVariableProvider { static readonly Dictionary<string, Func<string>> _variables = new Dictionary<string, Func<string>>(); public static void Add(string name, string value) => Add(name, () => value); public static void Add(string name, Func<string> valueProvider) { if (name == null) throw new ArgumentNullException(nameof(name)); if (valueProvider == null) throw new ArgumentNullException(nameof(valueProvider)); if (_variables.ContainsKey(name)) throw new ArgumentException($"User variable with the same name already exists: `{name}`"); _variables.Add(name, valueProvider); } public static void Clear() => _variables.Clear(); public Dictionary<string, Func<string>> GetVariables() => _variables; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace Eco { public class UserVariables : IVariableProvider { static readonly Dictionary<string, Func<string>> _variables = new Dictionary<string, Func<string>>(); public static void Add(string name, string value) => Add(name, () => value); public static void Add(string name, Func<string> valueProvider) { if (name == null) throw new ArgumentNullException(nameof(name)); if (valueProvider == null) throw new ArgumentNullException(nameof(valueProvider)); if (_variables.ContainsKey(name)) throw new ArgumentException($"User variable with the same name already exists: `{name}`"); _variables.Add(name, valueProvider); } public Dictionary<string, Func<string>> GetVariables() => _variables; } }
apache-2.0
C#
dc8100eb0c84ccee38a390c4fb64639c46c61754
Refactor the QueueInformation partial view to use the new AJAX status widget.
rakutensf-malex/slinqy,rakutensf-malex/slinqy
Source/ExampleApp.Web/Views/Home/QueueInformation.cshtml
Source/ExampleApp.Web/Views/Home/QueueInformation.cshtml
@model ExampleApp.Web.Models.QueueInformationViewModel <div id="QueueInformation"> @Html.LabelFor(m => m.QueueName) <span id="QueueInformation_QueueName">@Model.QueueName</span> @Html.LabelFor(m => m.CurrentQueueSizeMegabytes) <span id="QueueInformation_CurrentQueueSize">@Model.CurrentQueueSizeMegabytes</span> MB @Html.LabelFor(m => m.MaxQueueSizeMegabytes) <span id="QueueInformation_MaxQueueSize">@Model.MaxQueueSizeMegabytes</span> MB <div id="QueueInformationAjaxStatus">?</div> <script type="text/javascript"> function updateQueueInformation() { var ajaxRequest = $.get('@Url.HttpRouteUrl("GetQueue", new {queueName = Model.QueueName})') .done(function (data) { $('#QueueInformation_QueueName').text(data.QueueName); $('#QueueInformation_CurrentQueueSize').text(data.CurrentQueueSizeMegabytes); $('#QueueInformation_MaxQueueSize').text(data.MaxQueueSizeMegabytes); }) .always(function () { setTimeout(updateQueueInformation, 2000); }); ajax.indicate(ajaxRequest, $('#QueueInformationAjaxStatus')); } updateQueueInformation(); </script> </div>
@model ExampleApp.Web.Models.QueueInformationViewModel <div id="QueueInformation"> @Html.LabelFor(m => m.QueueName) <span id="QueueInformation_QueueName">@Model.QueueName</span> @Html.LabelFor(m => m.CurrentQueueSizeMegabytes) <span id="QueueInformation_CurrentQueueSize">@Model.CurrentQueueSizeMegabytes</span> MB @Html.LabelFor(m => m.MaxQueueSizeMegabytes) <span id="QueueInformation_MaxQueueSize">@Model.MaxQueueSizeMegabytes</span> MB <script type="text/javascript"> // TODO: Refactor in to a reusable AJAX UI status widget. function updateQueueInformation() { $('#AjaxResult').text(''); $('#AjaxStatusMessage').text(''); $('#AjaxStatus').text('STARTING'); $.get('@Url.HttpRouteUrl("GetQueue", new {queueName = Model.QueueName})') .done(function (data) { $('#QueueInformation_QueueName').text(data.QueueName); $('#QueueInformation_CurrentQueueSize').text(data.CurrentQueueSizeMegabytes); $('#QueueInformation_MaxQueueSize').text(data.MaxQueueSizeMegabytes); $('#AjaxResult').text('SUCCEEDED'); }) .fail(function (jqxhr, textStatus, error) { $('#AjaxResult').text('FAILED!'); $('#AjaxStatusMessage').text('textStatus: ' + textStatus + 'error: ' + error + ', response: ' + JSON.stringify(jqxhr)); }) .always(function () { $('#AjaxStatus').text('COMPLETED'); setTimeout(updateQueueInformation, 2000); }); $('#AjaxStatus').text('STARTED'); } updateQueueInformation(); </script> </div>
mit
C#
b54820dd748300ffb2ba9ad8843d4581ea6c6786
Move touch screen initialization to property getter
goldbillka/Winium.StoreApps,goldbillka/Winium.StoreApps,krishachetan89/Winium.StoreApps,2gis/Winium.StoreApps,NetlifeBackupSolutions/Winium.StoreApps,NetlifeBackupSolutions/Winium.StoreApps,krishachetan89/Winium.StoreApps,2gis/Winium.StoreApps
Winium/TestApp.Test/Samples/WpDriver.cs
Winium/TestApp.Test/Samples/WpDriver.cs
namespace Samples { #region using System; using OpenQA.Selenium; using OpenQA.Selenium.Remote; #endregion public class WpDriver : RemoteWebDriver, IHasTouchScreen { #region Fields private ITouchScreen touchScreen; #endregion #region Constructors and Destructors public WpDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) : base(commandExecutor, desiredCapabilities) { } public WpDriver(ICapabilities desiredCapabilities) : base(desiredCapabilities) { } public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities) : base(remoteAddress, desiredCapabilities) { } public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout) : base(remoteAddress, desiredCapabilities, commandTimeout) { } #endregion #region Public Properties public ITouchScreen TouchScreen { get { return this.touchScreen ?? (this.touchScreen = new RemoteTouchScreen(this)); } } #endregion } }
namespace Samples { using System; using OpenQA.Selenium; using OpenQA.Selenium.Remote; public class WpDriver : RemoteWebDriver, IHasTouchScreen { public WpDriver(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities) : base(commandExecutor, desiredCapabilities) { TouchScreen = new RemoteTouchScreen(this); } public WpDriver(ICapabilities desiredCapabilities) : base(desiredCapabilities) { TouchScreen = new RemoteTouchScreen(this); } public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities) : base(remoteAddress, desiredCapabilities) { TouchScreen = new RemoteTouchScreen(this); } public WpDriver(Uri remoteAddress, ICapabilities desiredCapabilities, TimeSpan commandTimeout) : base(remoteAddress, desiredCapabilities, commandTimeout) { TouchScreen = new RemoteTouchScreen(this); } public ITouchScreen TouchScreen { get; private set; } } }
mpl-2.0
C#
01be5c15c642df83035363600afbadf180165843
test commit
Krzyrok/FsxWebApi,Krzyrok/FsxWithGoogleMaps
FsxWebApi/FsxWebApi/Program.cs
FsxWebApi/FsxWebApi/Program.cs
namespace FsxWebApi { using System.Web.Http.SelfHost; class Program { static void Main(string[] args) { var configuration = new HttpSelfHostConfiguration("http://localhost:8080"); WebApiConfig.Register(configuration); WebApiStarter.StartServer(configuration); // git tests } } }
namespace FsxWebApi { using System.Web.Http.SelfHost; class Program { static void Main(string[] args) { var configuration = new HttpSelfHostConfiguration("http://localhost:8080"); WebApiConfig.Register(configuration); WebApiStarter.StartServer(configuration); } } }
mit
C#
3296f5e7d0f00067abfa658c5caf8f560a4e30d9
add different directions for teleport destination depending on how the owner is moving
billtowin/mega-epic-super-tankz,billtowin/mega-epic-super-tankz
modules/myModule/scripts/behaviors/combat/powerups/Teleport.cs
modules/myModule/scripts/behaviors/combat/powerups/Teleport.cs
if (!isObject(TeleportBehavior)) { %template = new BehaviorTemplate(TeleportBehavior); %template.friendlyName = "Tank Teleport Ability"; %template.behaviorType = "Combat"; %template.description = "Tank teleport ability"; %template.addBehaviorField(duration, "Duration of Powerup/Ability (negative number for infinite) (in ms)", int, 15000); %template.addBehaviorField(teleportDistance, "Teleport Distance", int, 15); %template.addBehaviorField(reloadTime, "Reload time (in ms)", int, 2000); } function TeleportBehavior::onBehaviorAdd(%this) { %this.isLoaded = true; } function TeleportBehavior::onBehaviorRemove(%this) { %this.stopSounds(); } function TeleportBehavior::stopSounds(%this) { alxStop(%this.reloadSound); alxStop(%this.teleportSound); } function TeleportBehavior::loadTeleport(%this) { %this.reloadSound = alxPlay("MyModule:teleportReloadSound"); %this.isLoaded = true; } function TeleportBehavior::teleport(%this) { if(%this.isLoaded) { if(%this.owner.AngularVelocity > 0) { %this.owner.Position = %this.owner.getWorldPoint((-%this.teleportDistance) SPC 0); } else if (%this.owner.AngularVelocity < 0) { %this.owner.Position = %this.owner.getWorldPoint( %this.teleportDistance SPC 0); } else { %this.owner.Position = %this.owner.getWorldPoint(0 SPC %this.teleportDistance); } %this.teleportSound = alxPlay("MyModule:teleportSound"); %this.isLoaded = false; %this.reloadSchedule = %this.schedule(%this.reloadTime, loadTeleport); } }
if (!isObject(TeleportBehavior)) { %template = new BehaviorTemplate(TeleportBehavior); %template.friendlyName = "Tank Teleport Ability"; %template.behaviorType = "Combat"; %template.description = "Tank teleport ability"; %template.addBehaviorField(duration, "Duration of Powerup/Ability (negative number for infinite) (in ms)", int, 15000); %template.addBehaviorField(teleportDistance, "Teleport Distance", int, 15); %template.addBehaviorField(reloadTime, "Reload time (in ms)", int, 2000); } function TeleportBehavior::onBehaviorAdd(%this) { %this.isLoaded = true; } function TeleportBehavior::onBehaviorRemove(%this) { %this.stopSounds(); } function TeleportBehavior::stopSounds(%this) { alxStop(%this.reloadSound); alxStop(%this.teleportSound); } function TeleportBehavior::loadTeleport(%this) { %this.reloadSound = alxPlay("MyModule:teleportReloadSound"); %this.isLoaded = true; } function TeleportBehavior::teleport(%this) { if(%this.isLoaded) { %adjustedAngle = getPositiveAngle(%this.owner); %teleportOffset = Vector2Direction(%adjustedAngle, %this.teleportDistance); %this.owner.Position = %this.owner.Position.x + %teleportOffset.x SPC %this.owner.Position.y + %teleportOffset.y; %this.teleportSound = alxPlay("MyModule:teleportSound"); %this.isLoaded = false; %this.reloadSchedule = %this.schedule(%this.reloadTime, loadTeleport); } }
mit
C#
6a09b2401229d3dc6ef06cadc6667c3549601838
add WithUniqueIndexMList
AlejandroCano/framework,avifatal/framework,avifatal/framework,AlejandroCano/framework,signumsoftware/framework,signumsoftware/framework
Signum.Engine/Schema/FluentInclude.cs
Signum.Engine/Schema/FluentInclude.cs
using Signum.Engine.Maps; using Signum.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Signum.Engine.Maps { public class FluentInclude<T> where T : Entity { public SchemaBuilder SchemaBuilder { get; private set; } public Table Table { get; private set; } public FluentInclude(Table table, SchemaBuilder schemaBuilder) { Table = table; SchemaBuilder = schemaBuilder; } public FluentInclude<T> WithUniqueIndex(Expression<Func<T, object>> fields, Expression<Func<T, bool>> where = null, Expression<Func<T, object>> includeFields = null) { this.SchemaBuilder.AddUniqueIndex<T>(fields, where, includeFields); return this; } public FluentInclude<T> WithIndex(Expression<Func<T, object>> fields, Expression<Func<T, bool>> where = null, Expression<Func<T, object>> includeFields = null) { this.SchemaBuilder.AddIndex<T>(fields, where, includeFields); return this; } public FluentInclude<T> WithUniqueIndexMList<M>(Expression<Func<T, MList<M>>> mlist, Expression<Func<MListElement<T, M>, object>> fields = null, Expression<Func<MListElement<T, M>, bool>> where = null, Expression<Func<MListElement<T, M>, object>> includeFields = null) { if (fields == null) fields = mle => new { mle.Parent, mle.Element }; this.SchemaBuilder.AddUniqueIndexMList<T, M>(mlist, fields, where, includeFields); return this; } public FluentInclude<T> WithIndexMList<M>(Expression<Func<T, MList<M>>> mlist, Expression<Func<MListElement<T, M>, object>> fields, Expression<Func<MListElement<T, M>, bool>> where = null, Expression<Func<MListElement<T, M>, object>> includeFields = null) { this.SchemaBuilder.AddIndexMList<T, M>(mlist, fields, where, includeFields); return this; } } }
using Signum.Engine.Maps; using Signum.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Signum.Engine.Maps { public class FluentInclude<T> where T : Entity { public SchemaBuilder SchemaBuilder { get; private set; } public Table Table { get; private set; } public FluentInclude(Table table, SchemaBuilder schemaBuilder) { Table = table; SchemaBuilder = schemaBuilder; } public FluentInclude<T> WithUniqueIndex(Expression<Func<T, object>> fields, Expression<Func<T, bool>> where = null, Expression<Func<T, object>> includeFields = null) { this.SchemaBuilder.AddUniqueIndex<T>(fields, where, includeFields); return this; } public FluentInclude<T> WithIndex(Expression<Func<T, object>> fields, Expression<Func<T, bool>> where = null, Expression<Func<T, object>> includeFields = null) { this.SchemaBuilder.AddIndex<T>(fields, where, includeFields); return this; } } }
mit
C#
422ac74cdf77f363e6f997c87e75f7e2bfc7f323
Add compilation message debug log
laedit/vika
NVika/BuildServers/AppVeyor.cs
NVika/BuildServers/AppVeyor.cs
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; private readonly string _appVeyorAPIUrl; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; _appVeyorAPIUrl = Environment.GetEnvironmentVariable("APPVEYOR_API_URL"); } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public async void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(_appVeyorAPIUrl); _logger.Debug("Send compilation message to AppVeyor:"); _logger.Debug("Message: {0}", message); _logger.Debug("Category: {0}", category); _logger.Debug("Details: {0}", details); _logger.Debug("FileName: {0}", filename); _logger.Debug("Line: {0}", line); _logger.Debug("Column: {0}", offset); _logger.Debug("ProjectName: {0}", projectName); await httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }); } } } }
using System; using System.ComponentModel.Composition; using System.Net.Http; namespace NVika { internal sealed class AppVeyorBuildServer : IBuildServer { private readonly Logger _logger; public string Name { get { return "AppVeyor"; } } [ImportingConstructor] public AppVeyorBuildServer(Logger logger) { _logger = logger; } public bool CanApplyToCurrentContext() { return !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("APPVEYOR")); } public void WriteMessage(string message, string category, string details, string filename, string line, string offset, string projectName) { using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(Environment.GetEnvironmentVariable("APPVEYOR_API_URL")); _logger.Debug("AppVeyor API url: {0}", httpClient.BaseAddress); var responseTask = httpClient.PostAsJsonAsync("api/build/compilationmessages", new { Message = message, Category = category, Details = details, FileName = filename, Line = line, Column = offset, ProjectName = projectName }); responseTask.Wait(); _logger.Debug("AppVeyor CompilationMessage Response: {0}", responseTask.Result.StatusCode); _logger.Debug(responseTask.Result.Content.ReadAsStringAsync().Result); } } } }
apache-2.0
C#
9d5e3a6db938ff229f28d6896adaa66a96ec856e
Update Resources.cs
Eversm4nn/Project
GTE/GTE/GTE/GTE/Resources.cs
GTE/GTE/GTE/GTE/Resources.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace GTE { public class Resources { //STATIC FIELDS public static Texture2D texture_player, texture_pointer, texture_bullet, texture_enemy, texture_blood, texture_bloodground; /* map textures */ public static Texture2D texture_window1, texture_window2, texture_wood, texture_wood_down, texture_wood_right, texture_wood_left, texture_wood_up; //RESOURCES public static void LoadContent(ContentManager Content) { texture_pointer = Content.Load<Texture2D>("green_pointer"); texture_player = Content.Load<Texture2D>("Perso"); texture_bullet = Content.Load<Texture2D>("temporarybulletsprite"); texture_enemy = Content.Load<Texture2D>("Enemy_temp"); texture_blood = Content.Load<Texture2D>("blood"); texture_window1 = Content.Load<Texture2D>("MapSprites//window1"); texture_window2 = Content.Load<Texture2D>("MapSprites//window2"); texture_wood = Content.Load<Texture2D>("MapSPrites//wood"); texture_wood_down = Content.Load<Texture2D>("MapSprites//woodWdown"); texture_wood_left = Content.Load<Texture2D>("MapSprites//woodWleft"); texture_wood_right = Content.Load<Texture2D>("MapSprites//woodWright"); texture_wood_up = Content.Load<Texture2D>("MapSprites//woodWup"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace GTE { public class Resources { //STATIC FIELDS public static Texture2D texture_player, texture_pointer, texture_bullet, texture_enemy, texture_blood, texture_bloodground; //RESOURCES public static void LoadContent(ContentManager Content) { texture_pointer = Content.Load<Texture2D>("green_pointer"); texture_player = Content.Load<Texture2D>("Perso"); texture_bullet = Content.Load<Texture2D>("temporarybulletsprite"); texture_enemy = Content.Load<Texture2D>("Enemy_temp"); texture_blood = Content.Load<Texture2D>("blood"); } } }
unlicense
C#
66d6d73384024ca608bebfad0e6e5772bcf8e7c4
Fix event nullability.
GGG-KILLER/GUtils.NET
GUtils.MVVM/ViewModelBase.cs
GUtils.MVVM/ViewModelBase.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace GUtils.MVVM { /// <summary> /// Implements a few utility functions for a ViewModel base /// </summary> public abstract class ViewModelBase : INotifyPropertyChanged { /// <inheritdoc/> public event PropertyChangedEventHandler? PropertyChanged; /// <summary> /// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and /// also sets the value of the field) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="field"></param> /// <param name="newValue"></param> /// <param name="propertyName"></param> [MethodImpl ( MethodImplOptions.NoInlining )] protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null ) { if ( EqualityComparer<T>.Default.Equals ( field, newValue ) ) return; field = newValue; this.OnPropertyChanged ( propertyName ); } /// <summary> /// Invokes <see cref="PropertyChanged"/> /// </summary> /// <param name="propertyName"></param> /// <exception cref="ArgumentNullException"> /// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't /// auto-filled by the compiler) /// </exception> [MethodImpl ( MethodImplOptions.NoInlining )] protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) => this.PropertyChanged?.Invoke ( this, new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) ); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace GUtils.MVVM { /// <summary> /// Implements a few utility functions for a ViewModel base /// </summary> public abstract class ViewModelBase : INotifyPropertyChanged { /// <inheritdoc/> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Does the logic for calling <see cref="PropertyChanged"/> if the value has changed (and /// also sets the value of the field) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="field"></param> /// <param name="newValue"></param> /// <param name="propertyName"></param> [MethodImpl ( MethodImplOptions.NoInlining )] protected virtual void SetField<T> ( ref T field, T newValue, [CallerMemberName] String propertyName = null ) { if ( EqualityComparer<T>.Default.Equals ( field, newValue ) ) return; field = newValue; this.OnPropertyChanged ( propertyName ); } /// <summary> /// Invokes <see cref="PropertyChanged"/> /// </summary> /// <param name="propertyName"></param> /// <exception cref="ArgumentNullException"> /// Invoked if a <paramref name="propertyName"/> is not provided (and the value isn't /// auto-filled by the compiler) /// </exception> [MethodImpl ( MethodImplOptions.NoInlining )] protected virtual void OnPropertyChanged ( [CallerMemberName] String propertyName = null ) => this.PropertyChanged?.Invoke ( this, new PropertyChangedEventArgs ( propertyName ?? throw new ArgumentNullException ( nameof ( propertyName ) ) ) ); } }
mit
C#
1e1c1b3e56af323fb15a552f24f8ce5222038838
Remove unused Linq and Text usings.
joeyespo/google-apps-client
GoogleAppsClient/MainForm.cs
GoogleAppsClient/MainForm.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; namespace GoogleAppsClient { public partial class MainForm : Form { const string BASE_URL = "https://mail.google.com/"; const string DOMAIN_SEPARATOR = "a/"; bool exiting = false; public MainForm() { InitializeComponent(); } #region Event Handlers protected override void OnClosing(CancelEventArgs e) { if (!exiting) { Hide(); e.Cancel = true; } base.OnClosing(e); } protected override bool ProcessDialogKey(Keys keyData) { if (keyData == Keys.Escape) Close(); return base.ProcessDialogKey(keyData); } void closeButton_Click(object sender, EventArgs e) { Close(); } void fileExitToolStripMenuItem_Click(object sender, EventArgs e) { Exit(); } void notifyIcon_DoubleClick(object sender, EventArgs e) { OpenGmail(); } void openGmailToolStripMenuItem_Click(object sender, EventArgs e) { OpenGmail(); } void settingsToolStripMenuItem_Click(object sender, EventArgs e) { ShowSettings(); } void exitToolStripMenuItem_Click(object sender, EventArgs e) { Exit(); } #endregion #region Actions void Exit() { exiting = true; Close(); } void OpenGmail() { var url = BASE_URL; if (!string.IsNullOrWhiteSpace(domainTextBox.Text)) url += DOMAIN_SEPARATOR + domainTextBox.Text; Process.Start(url); } void ShowSettings() { Show(); } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace GoogleAppsClient { public partial class MainForm : Form { const string BASE_URL = "https://mail.google.com/"; const string DOMAIN_SEPARATOR = "a/"; bool exiting = false; public MainForm() { InitializeComponent(); } #region Event Handlers protected override void OnClosing(CancelEventArgs e) { if (!exiting) { Hide(); e.Cancel = true; } base.OnClosing(e); } protected override bool ProcessDialogKey(Keys keyData) { if (keyData == Keys.Escape) Close(); return base.ProcessDialogKey(keyData); } void closeButton_Click(object sender, EventArgs e) { Close(); } void fileExitToolStripMenuItem_Click(object sender, EventArgs e) { Exit(); } void notifyIcon_DoubleClick(object sender, EventArgs e) { OpenGmail(); } void openGmailToolStripMenuItem_Click(object sender, EventArgs e) { OpenGmail(); } void settingsToolStripMenuItem_Click(object sender, EventArgs e) { ShowSettings(); } void exitToolStripMenuItem_Click(object sender, EventArgs e) { Exit(); } #endregion #region Actions void Exit() { exiting = true; Close(); } void OpenGmail() { var url = BASE_URL; if (!string.IsNullOrWhiteSpace(domainTextBox.Text)) url += DOMAIN_SEPARATOR + domainTextBox.Text; Process.Start(url); } void ShowSettings() { Show(); } #endregion } }
mit
C#
dea1b78e7902aebf0c3b6313a91a726d95b4b8e5
Add UWP method for obtaining the default folder (#1314)
realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet
Realm/Realm/InteropConfig.cs
Realm/Realm/InteropConfig.cs
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; namespace Realms { internal static class InteropConfig { private static readonly Lazy<string> _defaultStorageFolder = new Lazy<string>(() => { var specialFolderType = typeof(Environment).GetNestedType("SpecialFolder", BindingFlags.Public); if (specialFolderType != null) { var getFolderPath = typeof(Environment).GetMethod("GetFolderPath", new[] { specialFolderType }); if (getFolderPath != null) { var personalField = specialFolderType.GetField("Personal"); return (string)getFolderPath.Invoke(null, new[] { personalField.GetValue(null) }); } } // On UWP, the sandbox folder is obtained by: // ApplicationData.Current.LocalFolder.Path var applicationData = Type.GetType("Windows.Storage.ApplicationData, Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"); if (applicationData != null) { var currentProperty = applicationData.GetProperty("Current", BindingFlags.Static | BindingFlags.Public); var localFolderProperty = applicationData.GetProperty("LocalFolder", BindingFlags.Public | BindingFlags.Instance); var pathProperty = localFolderProperty.PropertyType.GetProperty("Path", BindingFlags.Public | BindingFlags.Instance); var currentApplicationData = currentProperty.GetValue(null); var localFolder = localFolderProperty.GetValue(currentApplicationData); return (string)pathProperty.GetValue(localFolder); } throw new NotSupportedException(); }); /// <summary> /// Name of the DLL used in native declarations, constant varying per-platform. /// </summary> public const string DLL_NAME = "realm-wrappers"; public static readonly bool Is64BitProcess = IntPtr.Size == 8; public static string DefaultStorageFolder => _defaultStorageFolder.Value; } }
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// using System; using System.Reflection; namespace Realms { internal static class InteropConfig { private static readonly Lazy<string> _defaultStorageFolder = new Lazy<string>(() => { var specialFolderType = typeof(Environment).GetNestedType("SpecialFolder", BindingFlags.Public); if (specialFolderType != null) { var getFolderPath = typeof(Environment).GetMethod("GetFolderPath", new[] { specialFolderType }); if (getFolderPath != null) { var personalField = specialFolderType.GetField("Personal"); return (string)getFolderPath.Invoke(null, new[] { personalField.GetValue(null) }); } } throw new NotSupportedException(); }); /// <summary> /// Name of the DLL used in native declarations, constant varying per-platform. /// </summary> public const string DLL_NAME = "realm-wrappers"; public static readonly bool Is64BitProcess = IntPtr.Size == 8; public static string DefaultStorageFolder => _defaultStorageFolder.Value; } }
apache-2.0
C#
8ba518b4425cc67a739cd847da93633fd43bb110
Update copyright
kendfrey/Tui
Tui/Properties/AssemblyInfo.cs
Tui/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("Tui")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Kendall Frey")] [assembly: AssemblyProduct("Tui")] [assembly: AssemblyCopyright("Copyright © Kendall Frey 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("0d0b8c99-9a6e-4d83-a137-de4332a4bd15")] // 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.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("Tui")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Tui")] [assembly: AssemblyCopyright("Copyright © Microsoft 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("0d0b8c99-9a6e-4d83-a137-de4332a4bd15")] // 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#
2a7675a9472398161b090e92ade289c2b572d9f1
build version: 3.9.71.8
wiesel78/Canwell.OrmLite.MSAccess2003
Source/GlobalAssemblyInfo.cs
Source/GlobalAssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyCompany("canwell - IT Solutions")] [assembly: AssemblyVersion("3.9.71.8")] [assembly: AssemblyFileVersion("3.9.71.8")] [assembly: AssemblyInformationalVersion("3.9.71.8")] [assembly: AssemblyCopyright("Copyright © 2016")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyCompany("canwell - IT Solutions")] [assembly: AssemblyVersion("3.9.71.7")] [assembly: AssemblyFileVersion("3.9.71.7")] [assembly: AssemblyInformationalVersion("3.9.71.7")] [assembly: AssemblyCopyright("Copyright © 2016")]
bsd-3-clause
C#
6068aaa4c9e71e57d47e7d7914591f2c369cf8a9
Improve documentation for BatchType enum
AtwooTM/csharp-driver,mintsoft/csharp-driver,maxwellb/csharp-driver,kishkaru/csharp-driver,oguimbal/csharp-driver,datastax/csharp-driver,trurl123/csharp-driver,jorgebay/csharp-driver,bridgewell/csharp-driver,datastax/csharp-driver,aNutForAJarOfTuna/csharp-driver,maxwellb/csharp-driver,alprema/csharp-driver
src/Cassandra/Requests/BatchType.cs
src/Cassandra/Requests/BatchType.cs
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Cassandra { /// <summary> /// The type of batch to use /// </summary> public enum BatchType { /// <summary> /// A logged batch: Cassandra will first write the batch to its distributed batch log to ensure the atomicity of the batch. /// </summary> Logged = 0, /// <summary> /// An unlogged batch: The batch will not be written to the batch log and atomicity of the batch is NOT guaranteed. /// </summary> Unlogged = 1, /// <summary> /// A counter batch /// </summary> Counter = 2 } }
// // Copyright (C) 2012-2014 DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Cassandra { /// <summary> /// The type of batch to use /// </summary> public enum BatchType { /// <summary> /// A logged batch: Cassandra will first the batch to its distributed batch log to ensure the atomicity of the batch. /// </summary> Logged = 0, /// <summary> /// A logged batch: Cassandra will first the batch to its distributed batch log to ensure the atomicity of the batch. /// </summary> Unlogged = 1, /// <summary> /// A counter batch /// </summary> Counter = 2 } }
apache-2.0
C#
135ceffc55817817594948cac6ce2eec8429f135
Fix crash if GetMatches response is not 200 OK.
dustinsoftware/Challonge-Scheduler
src/Challonge.Data/ChallongeClient.cs
src/Challonge.Data/ChallongeClient.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using Challonge.Data.Properties; using RestSharp; namespace Challonge.Data { public sealed class ChallongeClient { public ChallongeClient() { m_client = new RestClient { BaseUrl = Settings.Default.BaseUri + Settings.Default.TournamentId + "/", }; m_participants = new Dictionary<int, Participant>(); } public IEnumerable<Match> GetMatches(string state) { var result = m_client.Get<List<MatchResult>>(new RestRequest(string.Format("matches.json?state={0}", state) + s_apiKeyString)); return result.ResponseStatus != ResponseStatus.Completed || result.StatusCode != HttpStatusCode.OK ? null : result.Data.Select(x => x.match); } public Participant GetParticipant(int playerId) { lock (m_lock) { Participant participant; if (!m_participants.TryGetValue(playerId, out participant)) { var response = m_client.Get<ParticipantResult>(new RestRequest(string.Format("participants/{0}.json?state=open{1}", playerId, s_apiKeyString))).Data; if (response != null) { participant = response.participant; m_participants.Add(playerId, participant); } } return participant; } } public class Match { public int player1_id { get; set; } public int player2_id { get; set; } public int round { get; set; } public int id { get; set; } public DateTime started_at { get; set; } } public class MatchResult { public Match match { get; set; } } public class Participant { public bool active { get; set; } public bool checked_in { get; set; } public string created_at { get; set; } public object final_rank { get; set; } public object group_id { get; set; } public object icon { get; set; } public int id { get; set; } public object invitation_id { get; set; } public object invite_email { get; set; } public object misc { get; set; } public string name { get; set; } public bool on_waiting_list { get; set; } public int seed { get; set; } public int tournament_id { get; set; } public string updated_at { get; set; } } public class ParticipantResult { public Participant participant { get; set; } } static readonly string s_apiKeyString = "&api_key=" + Settings.Default.ApiKey; readonly RestClient m_client; readonly object m_lock = new object(); readonly Dictionary<int, Participant> m_participants; } }
using System; using System.Collections.Generic; using System.Linq; using Challonge.Data.Properties; using RestSharp; namespace Challonge.Data { public sealed class ChallongeClient { public ChallongeClient() { m_client = new RestClient { BaseUrl = Settings.Default.BaseUri + Settings.Default.TournamentId + "/", }; m_participants = new Dictionary<int, Participant>(); } public IEnumerable<Match> GetMatches(string state) { var result = m_client.Get<List<MatchResult>>(new RestRequest(string.Format("matches.json?state={0}", state) + s_apiKeyString)); return result.ResponseStatus != ResponseStatus.Completed ? null : result.Data.Select(x => x.match); } public Participant GetParticipant(int playerId) { lock (m_lock) { Participant participant; if (!m_participants.TryGetValue(playerId, out participant)) { var response = m_client.Get<ParticipantResult>(new RestRequest(string.Format("participants/{0}.json?state=open{1}", playerId, s_apiKeyString))).Data; if (response != null) { participant = response.participant; m_participants.Add(playerId, participant); } } return participant; } } public class Match { public int player1_id { get; set; } public int player2_id { get; set; } public int round { get; set; } public int id { get; set; } public DateTime started_at { get; set; } } public class MatchResult { public Match match { get; set; } } public class Participant { public bool active { get; set; } public bool checked_in { get; set; } public string created_at { get; set; } public object final_rank { get; set; } public object group_id { get; set; } public object icon { get; set; } public int id { get; set; } public object invitation_id { get; set; } public object invite_email { get; set; } public object misc { get; set; } public string name { get; set; } public bool on_waiting_list { get; set; } public int seed { get; set; } public int tournament_id { get; set; } public string updated_at { get; set; } } public class ParticipantResult { public Participant participant { get; set; } } static readonly string s_apiKeyString = "&api_key=" + Settings.Default.ApiKey; readonly RestClient m_client; readonly object m_lock = new object(); readonly Dictionary<int, Participant> m_participants; } }
apache-2.0
C#
78c9cfb8a93637227ff79f788a12bb87f1ac4ede
Set basic assembly attributes.
LogosBible/Leeroy
src/Leeroy/Properties/AssemblyInfo.cs
src/Leeroy/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Leeroy Build Service")] [assembly: AssemblyDescription("Updates a build git repo when submodules change.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Leeroy")] [assembly: AssemblyCopyright("Copyright 2012 Bradley Grainger")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Leeroy")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Leeroy")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4b3830ce-2525-4874-8d59-22e25f7b7d37")] // 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#
b754ee878e6ad8490c48bae8f66e988a8052075b
Remove Linq usage in TextRenderer
SixLabors/Fonts
src/SixLabors.Fonts/TextRenderer.cs
src/SixLabors.Fonts/TextRenderer.cs
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System.Collections.Generic; using System.Numerics; using SixLabors.Primitives; namespace SixLabors.Fonts { /// <summary> /// Encapulated logic for laying out and then rendering text to a <see cref="IGlyphRenderer"/> surface. /// </summary> public class TextRenderer { private readonly TextLayout layoutEngine; private readonly IGlyphRenderer renderer; internal TextRenderer(IGlyphRenderer renderer, TextLayout layoutEngine) { this.layoutEngine = layoutEngine; this.renderer = renderer; } /// <summary> /// Initializes a new instance of the <see cref="TextRenderer"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public TextRenderer(IGlyphRenderer renderer) : this(renderer, TextLayout.Default) { } /// <summary> /// Renders the text to the <paramref name="renderer"/>. /// </summary> /// <param name="renderer">The target renderer.</param> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public static void RenderTextTo(IGlyphRenderer renderer, string text, RendererOptions options) { new TextRenderer(renderer).RenderText(text, options); } /// <summary> /// Renders the text. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public void RenderText(string text, RendererOptions options) { IReadOnlyList<GlyphLayout> glyphsToRender = this.layoutEngine.GenerateLayout(text, options); Vector2 dpi = new Vector2(options.DpiX, options.DpiY); RectangleF rect = TextMeasurer.GetBounds(glyphsToRender, dpi); this.renderer.BeginText(rect); foreach (GlyphLayout g in glyphsToRender) { if (g.IsWhiteSpace) { continue; } g.Glyph.RenderTo(this.renderer, g.Location, options.DpiX, options.DpiY, g.LineHeight); } this.renderer.EndText(); } } }
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System.Collections.Generic; using System.Linq; using System.Numerics; using SixLabors.Primitives; namespace SixLabors.Fonts { /// <summary> /// Encapulated logic for laying out and then rendering text to a <see cref="IGlyphRenderer"/> surface. /// </summary> public class TextRenderer { private readonly TextLayout layoutEngine; private readonly IGlyphRenderer renderer; internal TextRenderer(IGlyphRenderer renderer, TextLayout layoutEngine) { this.layoutEngine = layoutEngine; this.renderer = renderer; } /// <summary> /// Initializes a new instance of the <see cref="TextRenderer"/> class. /// </summary> /// <param name="renderer">The renderer.</param> public TextRenderer(IGlyphRenderer renderer) : this(renderer, TextLayout.Default) { } /// <summary> /// Renders the text to the <paramref name="renderer"/>. /// </summary> /// <param name="renderer">The target renderer.</param> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public static void RenderTextTo(IGlyphRenderer renderer, string text, RendererOptions options) { new TextRenderer(renderer).RenderText(text, options); } /// <summary> /// Renders the text. /// </summary> /// <param name="text">The text.</param> /// <param name="options">The style.</param> public void RenderText(string text, RendererOptions options) { IReadOnlyList<GlyphLayout> glyphsToRender = this.layoutEngine.GenerateLayout(text, options); Vector2 dpi = new Vector2(options.DpiX, options.DpiY); RectangleF rect = TextMeasurer.GetBounds(glyphsToRender, dpi); this.renderer.BeginText(rect); foreach (GlyphLayout g in glyphsToRender.Where(x => !x.IsWhiteSpace)) { g.Glyph.RenderTo(this.renderer, g.Location, options.DpiX, options.DpiY, g.LineHeight); } this.renderer.EndText(); } } }
apache-2.0
C#
866f98c9794f5317021998ef4a0e960448558db4
Add types
rhynodegreat/CSharpGameLibrary,rhynodegreat/CSharpGameLibrary,vazgriz/CSharpGameLibrary,vazgriz/CSharpGameLibrary
CSGL.Vulkan/types.cs
CSGL.Vulkan/types.cs
using System; using System.Collections.Generic; namespace CSGL.Vulkan { public struct VkOffset2D { public int x; public int y; } public struct VkOffset3D { public int x; public int y; public int z; } public struct VkExtent2D { public int width; public int height; } public struct VkExtent3D { public int width; public int height; public int depth; } public struct VkViewport { public float x; public float y; public float width; public float height; public float minDepth; public float maxDepth; } public struct VkRect2D { public VkOffset2D offset; public VkExtent2D extent; } public struct VkRect3D { public VkOffset3D offset; public VkExtent3D extent; } public struct VkClearRect { public VkRect2D rect; public int baseArrayLayer; public int layerCount; } public struct VkComponentMapping { public VkComponentSwizzle r; public VkComponentSwizzle g; public VkComponentSwizzle b; public VkComponentSwizzle a; } public struct VkMemoryRequirements { public long size; public long alignment; public uint memoryTypeBits; } }
using System; using System.Collections.Generic; namespace CSGL.Vulkan { }
mit
C#
1b264451a4b2a3341521c3a3656a1464aa893fa6
Fix Projectile.Update signature
iridinite/shiftdrive
Client/Projectile.cs
Client/Projectile.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using System.IO; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents a projectile in flight. /// </summary> internal sealed class Projectile : GameObject { public float lifetime; public byte faction; public Projectile(GameState world) : base(world) { type = ObjectType.Projectile; color = Color.White; } public Projectile(GameState world, string spritename, Vector2 position, float facing, float speed, byte faction) : this(world) { this.spritename = spritename; //this.sprite = Assets.GetTexture(spritename); this.position = position; this.facing = facing; this.velocity = speed * new Vector2( (float)Math.Cos(MathHelper.ToRadians(facing - 90f)), (float)Math.Sin(MathHelper.ToRadians(facing - 90f))); this.faction = faction; this.lifetime = 0f; } public override void Update(float deltaTime) { base.Update(deltaTime); // move forward lifetime += deltaTime; // TODO: collision detection // get rid of projectiles that have traveled very far already if (world.IsServer && lifetime >= 10f) Destroy(); // as these move every frame, always re-send them changed = true; } public override void Destroy() { // detonate base.Destroy(); } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using System.IO; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents a projectile in flight. /// </summary> internal sealed class Projectile : GameObject { public float lifetime; public byte faction; public Projectile(GameState world) : base(world) { type = ObjectType.Projectile; color = Color.White; } public Projectile(GameState world, string spritename, Vector2 position, float facing, float speed, byte faction) : this(world) { this.spritename = spritename; //this.sprite = Assets.GetTexture(spritename); this.position = position; this.facing = facing; this.velocity = speed * new Vector2( (float)Math.Cos(MathHelper.ToRadians(facing - 90f)), (float)Math.Sin(MathHelper.ToRadians(facing - 90f))); this.faction = faction; this.lifetime = 0f; } public override void Update(GameState world, float deltaTime) { base.Update(world, deltaTime); // move forward lifetime += deltaTime; // TODO: collision detection // get rid of projectiles that have traveled very far already if (world.IsServer && lifetime >= 10f) Destroy(); // as these move every frame, always re-send them changed = true; } public override void Destroy() { // detonate base.Destroy(); } } }
bsd-3-clause
C#
8ffe0bbd9092adf157c6dba95c270ba0f6e4fa25
refactor complete, ready to pull back to main
Threadnaught/CDS
CDS/RemoteTest/Program.cs
CDS/RemoteTest/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CDS.Common; using CDS.Remote; namespace RemoteTest { class Program { static void Main(string[] args) { System.Threading.Thread.Sleep(1000); Remote.Start(); CDSMessageHandler h = new CDSMessageHandler(System.Net.IPAddress.Parse("127.0.0.1")); CDSRemoteAgent[] agents = new CDSRemoteAgent[500]; for (int i = 0; i < 500; i++) { agents[i] = (CDSRemoteAgent)h.OpenNewChannel(); } while (true) { foreach (CDSRemoteAgent a in agents) { Console.WriteLine(a.Root.ChildByName("TestNode").Read().Data.First()); } } Node n = Remote.FromName("127.0.0.1.TestNode"); //Console.WriteLine(n.GetIfExists()); while(true) foreach (byte b in n.Read().Data) Console.Write(b.ToString() + "\t"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CDS.Common; using CDS.Remote; namespace RemoteTest { class Program { static void Main(string[] args) { System.Threading.Thread.Sleep(1000); Remote.Start(); Node n = Remote.FromName("127.0.0.1.TestNode"); //Console.WriteLine(n.GetIfExists()); while(true) foreach (byte b in n.Read().Data) Console.Write(b.ToString() + "\t"); } } }
apache-2.0
C#
3557c0425fc0c1b95b951fa2324867e112fcabf7
Update AccountAgreementType.cs
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerAccounts.Api.Types/AccountAgreementType.cs
src/SFA.DAS.EmployerAccounts.Api.Types/AccountAgreementType.cs
namespace SFA.DAS.EmployerAccounts.Api.Types { public enum AccountAgreementType { Levy = 0, NonLevyExpressionOfInterest = 1, Combined = 2, Unknown } }
namespace SFA.DAS.EmployerAccounts.Api.Types { public enum AccountAgreementType { Levy = 0, Combined = 2, Unknown } }
mit
C#
57162606a493b6ebea0811c0e88e00dc69f948bf
remove comment
takenet/blip-sdk-csharp
src/Take.Blip.Builder.UnitTests/Actions/RedirectActionTests.cs
src/Take.Blip.Builder.UnitTests/Actions/RedirectActionTests.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NSubstitute; using Serilog; using Take.Blip.Builder.Actions.Redirect; using Take.Blip.Builder.Actions.SetVariable; using Xunit; namespace Take.Blip.Builder.UnitTests.Actions { public class RedirectActionTests : ActionTestsBase { public RedirectActionTests() { RedirectManager = Substitute.For<IRedirectManager>(); Logger = Substitute.For<ILogger>(); } private RedirectAction GetTarget() { return new RedirectAction(RedirectManager, Logger); } public ILogger Logger { get; } public IRedirectManager RedirectManager { get; } [Fact] public async Task ExecuteShouldSuccess() { // Arrange var target = GetTarget(); var redirect = new JObject(); redirect.Add("address", "bot1"); // Act await target.ExecuteAsync(Context, redirect, CancellationToken); // Assert Context.Received(1); } [Fact] public async Task ExecuteWithLogShouldSuccess() { // Arrange var target = GetTarget(); var redirect = new JObject(); redirect.Add("address", "bot1"); Context.Input.Message.Metadata = new Dictionary<string, string> { { "REDIRECT_TEST_LOG", "bot1" } }; // Act await target.ExecuteAsync(Context, redirect, CancellationToken); // Assert Context.Received(1); } [Fact] public async Task ExecuteShouldFailure() { // Arrange var target = GetTarget(); // Act try { await target.ExecuteAsync(Context, null, CancellationToken); } catch (Exception e) { Context.DidNotReceive(); } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using NSubstitute; using Serilog; using Take.Blip.Builder.Actions.Redirect; using Take.Blip.Builder.Actions.SetVariable; using Xunit; namespace Take.Blip.Builder.UnitTests.Actions { public class RedirectActionTests : ActionTestsBase { public RedirectActionTests() { RedirectManager = Substitute.For<IRedirectManager>(); Logger = Substitute.For<ILogger>(); } //public SetVariableSettings Settings { get; } private RedirectAction GetTarget() { return new RedirectAction(RedirectManager, Logger); } public ILogger Logger { get; } public IRedirectManager RedirectManager { get; } [Fact] public async Task ExecuteShouldSuccess() { // Arrange var target = GetTarget(); var redirect = new JObject(); redirect.Add("address", "bot1"); // Act await target.ExecuteAsync(Context, redirect, CancellationToken); // Assert Context.Received(1); } [Fact] public async Task ExecuteWithLogShouldSuccess() { // Arrange var target = GetTarget(); var redirect = new JObject(); redirect.Add("address", "bot1"); Context.Input.Message.Metadata = new Dictionary<string, string> { { "REDIRECT_TEST_LOG", "bot1" } }; // Act await target.ExecuteAsync(Context, redirect, CancellationToken); // Assert Context.Received(1); } [Fact] public async Task ExecuteShouldFailure() { // Arrange var target = GetTarget(); // Act try { await target.ExecuteAsync(Context, null, CancellationToken); } catch (Exception e) { Context.DidNotReceive(); } } } }
apache-2.0
C#
0de5209f9d0663b37a6b44d7817e56738469bd4a
Remove Window.AddFlags() from OnCreate()
EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework
osu.Framework.Android/AndroidGameActivity.cs
osu.Framework.Android/AndroidGameActivity.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; namespace osu.Framework.Android { public abstract class AndroidGameActivity : Activity { protected abstract Game CreateGame(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(new AndroidGameView(this, CreateGame())); } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using Android.App; using Android.OS; using Android.Views; namespace osu.Framework.Android { public abstract class AndroidGameActivity : Activity { protected abstract Game CreateGame(); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window.AddFlags(WindowManagerFlags.Fullscreen); Window.AddFlags(WindowManagerFlags.KeepScreenOn); SetContentView(new AndroidGameView(this, CreateGame())); } } }
mit
C#
5f74dc2c1746dec30ead8270bf58c1635146653d
Simplify osu-ruleset statistics
UselessToucan/osu,2yangk23/osu,peppy/osu-new,UselessToucan/osu,johnneijzen/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,ZLima12/osu,DrabWeb/osu,ppy/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,naoey/osu,naoey/osu,naoey/osu,peppy/osu,peppy/osu,ppy/osu,smoogipooo/osu,ZLima12/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu
osu.Game.Rulesets.Osu/Beatmaps/OsuBeatmap.cs
osu.Game.Rulesets.Osu/Beatmaps/OsuBeatmap.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Beatmaps { public class OsuBeatmap : Beatmap<OsuHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { IEnumerable<HitObject> circles = HitObjects.Where(c => c is HitCircle); IEnumerable<HitObject> sliders = HitObjects.Where(s => s is Slider); IEnumerable<HitObject> spinners = HitObjects.Where(s => s is Spinner); return new[] { new BeatmapStatistic { Name = @"Circle Count", Content = circles.Count().ToString(), Icon = FontAwesome.fa_circle_o }, new BeatmapStatistic { Name = @"Slider Count", Content = sliders.Count().ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Spinner Count", Content = spinners.Count().ToString(), Icon = FontAwesome.fa_circle } }; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Beatmaps { public class OsuBeatmap : Beatmap<OsuHitObject> { public override IEnumerable<BeatmapStatistic> GetStatistics() { IEnumerable<HitObject> circles = HitObjects.Where(c => !(c is IHasEndTime)); IEnumerable<HitObject> sliders = HitObjects.Where(s => s is IHasCurve); IEnumerable<HitObject> spinners = HitObjects.Where(s => s is IHasEndTime && !(s is IHasCurve)); return new[] { new BeatmapStatistic { Name = @"Circle Count", Content = circles.Count().ToString(), Icon = FontAwesome.fa_circle_o }, new BeatmapStatistic { Name = @"Slider Count", Content = sliders.Count().ToString(), Icon = FontAwesome.fa_circle }, new BeatmapStatistic { Name = @"Spinner Count", Content = spinners.Count().ToString(), Icon = FontAwesome.fa_circle } }; } } }
mit
C#
b3babd07aaabcbe1e633cde9eda1a335ddf1bbd5
Rework APIEndpoint.cs
fjch1997/SteamAuth,r2d2rigo/SteamAuth,geel9/SteamAuth,zigagrcar/Steam2faGenerator
SteamAuth/APIEndpoints.cs
SteamAuth/APIEndpoints.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SteamAuth { public static class APIEndpoints { public const string STEAMAPI_BASE = "https://api.steampowered.com"; public const string COMMUNITY_BASE = "https://steamcommunity.com"; public const string TWO_FACTOR_BASE = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001"; public static string TWO_FACTOR_TIME_QUERY = TWO_FACTOR_BASE.Replace("%s", "QueryTime"); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SteamAuth { public static class APIEndpoints { public static string STEAMAPI_BASE = "https://api.steampowered.com"; public static string TWO_FACTOR_BASE = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001"; public static string TWO_FACTOR_TIME_QUERY = TWO_FACTOR_BASE.Replace("%s", "QueryTime"); } }
mit
C#
a1b3b96471113657e580db78aaa2e288d1085f9d
Remove unused member.
PintaProject/Pinta,PintaProject/Pinta,PintaProject/Pinta
Pinta/WindowShell.cs
Pinta/WindowShell.cs
// // WindowShell.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2011 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Gtk; namespace Pinta { public class WindowShell : ApplicationWindow { private VBox shell_layout; private VBox menu_layout; private HBox workspace_layout; private Toolbar main_toolbar; public WindowShell (Application app, string name, string title, int width, int height, bool maximize) : base(app) { Name = name; Title = title; DefaultWidth = width; DefaultHeight = height; WindowPosition = WindowPosition.Center; Resizable = true; if (maximize) Maximize (); shell_layout = new VBox () { Name = "shell_layout" }; menu_layout = new VBox () { Name = "menu_layout" }; shell_layout.PackStart (menu_layout, false, false, 0); Add (shell_layout); shell_layout.ShowAll (); } public Toolbar CreateToolBar (string name) { main_toolbar = new Toolbar (); main_toolbar.Name = name; menu_layout.PackStart (main_toolbar, false, false, 0); main_toolbar.Show (); return main_toolbar; } public HBox CreateWorkspace () { workspace_layout = new HBox (); workspace_layout.Name = "workspace_layout"; shell_layout.PackStart (workspace_layout, true, true, 0); workspace_layout.ShowAll (); return workspace_layout; } public void AddDragDropSupport (params TargetEntry[] entries) { Gtk.Drag.DestSet (this, Gtk.DestDefaults.Motion | Gtk.DestDefaults.Highlight | Gtk.DestDefaults.Drop, entries, Gdk.DragAction.Copy); } } }
// // WindowShell.cs // // Author: // Jonathan Pobst <monkey@jpobst.com> // // Copyright (c) 2011 Jonathan Pobst // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Gtk; namespace Pinta { public class WindowShell : ApplicationWindow { private VBox shell_layout; private VBox menu_layout; private HBox workspace_layout; private MenuBar main_menu; private Toolbar main_toolbar; public WindowShell (Application app, string name, string title, int width, int height, bool maximize) : base(app) { Name = name; Title = title; DefaultWidth = width; DefaultHeight = height; WindowPosition = WindowPosition.Center; Resizable = true; if (maximize) Maximize (); shell_layout = new VBox () { Name = "shell_layout" }; menu_layout = new VBox () { Name = "menu_layout" }; shell_layout.PackStart (menu_layout, false, false, 0); Add (shell_layout); shell_layout.ShowAll (); } public Toolbar CreateToolBar (string name) { main_toolbar = new Toolbar (); main_toolbar.Name = name; menu_layout.PackStart (main_toolbar, false, false, 0); main_toolbar.Show (); return main_toolbar; } public HBox CreateWorkspace () { workspace_layout = new HBox (); workspace_layout.Name = "workspace_layout"; shell_layout.PackStart (workspace_layout, true, true, 0); workspace_layout.ShowAll (); return workspace_layout; } public void AddDragDropSupport (params TargetEntry[] entries) { Gtk.Drag.DestSet (this, Gtk.DestDefaults.Motion | Gtk.DestDefaults.Highlight | Gtk.DestDefaults.Drop, entries, Gdk.DragAction.Copy); } } }
mit
C#
a5bcef4475bf1d52b12ac2b8c029e7e179049863
Fix #2128 Outlining cuts off closing }
jamesqo/roslyn,panopticoncentral/roslyn,genlu/roslyn,cston/roslyn,xasx/roslyn,DustinCampbell/roslyn,VSadov/roslyn,reaction1989/roslyn,tmeschter/roslyn,cston/roslyn,swaroop-sridhar/roslyn,gafter/roslyn,jamesqo/roslyn,mgoertz-msft/roslyn,xasx/roslyn,xasx/roslyn,tmat/roslyn,nguerrera/roslyn,AmadeusW/roslyn,dpoeschl/roslyn,shyamnamboodiripad/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,tmeschter/roslyn,physhi/roslyn,aelij/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,dotnet/roslyn,jamesqo/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,jmarolf/roslyn,KevinRansom/roslyn,DustinCampbell/roslyn,OmarTawfik/roslyn,reaction1989/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,panopticoncentral/roslyn,cston/roslyn,tmeschter/roslyn,tmat/roslyn,tannergooding/roslyn,abock/roslyn,genlu/roslyn,physhi/roslyn,wvdd007/roslyn,dotnet/roslyn,aelij/roslyn,AmadeusW/roslyn,mavasani/roslyn,wvdd007/roslyn,agocke/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,mgoertz-msft/roslyn,jcouv/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,jcouv/roslyn,davkean/roslyn,genlu/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,diryboy/roslyn,abock/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,heejaechang/roslyn,abock/roslyn,agocke/roslyn,brettfo/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,eriawan/roslyn,sharwell/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,OmarTawfik/roslyn,eriawan/roslyn,weltkante/roslyn,sharwell/roslyn,VSadov/roslyn,sharwell/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,reaction1989/roslyn,davkean/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,paulvanbrenk/roslyn,tannergooding/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,OmarTawfik/roslyn,tmat/roslyn,stephentoub/roslyn,AlekseyTs/roslyn,nguerrera/roslyn,weltkante/roslyn,tannergooding/roslyn,panopticoncentral/roslyn,DustinCampbell/roslyn,bkoelman/roslyn,swaroop-sridhar/roslyn,bartdesmet/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mavasani/roslyn,stephentoub/roslyn,brettfo/roslyn,davkean/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,bkoelman/roslyn,ErikSchierboom/roslyn,physhi/roslyn,AlekseyTs/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,bkoelman/roslyn,dotnet/roslyn,nguerrera/roslyn,jcouv/roslyn
src/EditorFeatures/Core.Wpf/IWpfTextViewExtensions.cs
src/EditorFeatures/Core.Wpf/IWpfTextViewExtensions.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IWpfTextViewExtensions { public static void SizeToFit(this IWpfTextView view) { void firstLayout(object sender, TextViewLayoutChangedEventArgs args) { view.VisualElement.Dispatcher.BeginInvoke(new Action(() => { var newHeight = view.LineHeight * view.TextBuffer.CurrentSnapshot.LineCount; if (IsGreater(newHeight, view.VisualElement.Height)) { view.VisualElement.Height = newHeight; } var newWidth = view.MaxTextRightCoordinate; if (IsGreater(newWidth, view.VisualElement.Width)) { view.VisualElement.Width = newWidth; } })); view.LayoutChanged -= firstLayout; } view.LayoutChanged += firstLayout; bool IsGreater(double value, double other) => IsNormal(value) && (!IsNormal(other) || value > other); bool IsNormal(double value) => !double.IsNaN(value) && !double.IsInfinity(value); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IWpfTextViewExtensions { public static void SizeToFit(this IWpfTextView view) { // Computing the height of something is easy. view.VisualElement.Height = view.LineHeight * view.TextBuffer.CurrentSnapshot.LineCount; // Computing the width... less so. We need "MaxTextRightCoordinate", but we won't have // that until a layout occurs. Fortunately, a layout is going to occur because we set // 'Height' above. void firstLayout(object sender, TextViewLayoutChangedEventArgs args) { view.VisualElement.Dispatcher.BeginInvoke(new Action(() => { var newWidth = view.MaxTextRightCoordinate; var currentWidth = view.VisualElement.Width; // If the element already was given a width, then only set the width if we // wouldn't make it any smaller. if (IsNormal(newWidth) && IsNormal(currentWidth) && newWidth <= currentWidth) { return; } view.VisualElement.Width = view.MaxTextRightCoordinate; })); } view.LayoutChanged += firstLayout; } private static bool IsNormal(double value) { return !double.IsNaN(value) && !double.IsInfinity(value); } } }
mit
C#
53f85aaf6a4724818bd4dbf18524759930b83c3d
Use Cached attribute rather than CreateChildDependencies
ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Graphics/Containers/SnapTargetContainer.cs
osu.Framework/Graphics/Containers/SnapTargetContainer.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.Allocation; using osu.Framework.Graphics.Primitives; namespace osu.Framework.Graphics.Containers { public class SnapTargetContainer : SnapTargetContainer<Drawable> { } /// <summary> /// A <see cref="Container{T}"/> that acts a target for <see cref="EdgeSnappingContainer{T}"/>s. /// It is automatically cached as <see cref="ISnapTargetContainer"/> so that it may be resolved by any /// child <see cref="EdgeSnappingContainer{T}"/>s. /// </summary> [Cached(typeof(ISnapTargetContainer))] public class SnapTargetContainer<T> : Container<T>, ISnapTargetContainer where T : Drawable { public virtual RectangleF SnapRectangle => DrawRectangle; public Quad SnapRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(SnapRectangle, other); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics.Primitives; namespace osu.Framework.Graphics.Containers { public class SnapTargetContainer : SnapTargetContainer<Drawable> { } /// <summary> /// A <see cref="Container{T}"/> that acts a target for <see cref="EdgeSnappingContainer{T}"/>s. /// It is automatically cached as <see cref="ISnapTargetContainer"/> so that it may be resolved by any /// child <see cref="EdgeSnappingContainer{T}"/>s. /// </summary> public class SnapTargetContainer<T> : Container<T>, ISnapTargetContainer where T : Drawable { public virtual RectangleF SnapRectangle => DrawRectangle; public Quad SnapRectangleToSpaceOfOtherDrawable(IDrawable other) => ToSpaceOfOtherDrawable(SnapRectangle, other); protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { var dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); dependencies.CacheAs<ISnapTargetContainer>(this); return dependencies; } } }
mit
C#
011b951a29d7a1754ad8e058bc2c092c78c281e3
Update QuoteRepository.cs
powered-by-moe/MikuBot,Taknok/NadekoBot,shikhir-arora/NadekoBot,ScarletKuro/NadekoBot,gfrewqpoiu/NadekoBot,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,miraai/NadekoBot,Youngsie1997/NadekoBot,Midnight-Myth/Mitternacht-NEW,ShadowNoire/NadekoBot,WoodenGlaze/NadekoBot,Nielk1/NadekoBot,PravEF/EFNadekoBot,Midnight-Myth/Mitternacht-NEW,Blacnova/NadekoBot,halitalf/NadekoMods
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
src/NadekoBot/Services/Database/Repositories/Impl/QuoteRepository.cs
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); lowertext = text.toLowerInvariant(); return _set.Where(q => q.Text.Contains(text) || q.Text.Contains(lowertext) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
using NadekoBot.Services.Database.Models; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace NadekoBot.Services.Database.Repositories.Impl { public class QuoteRepository : Repository<Quote>, IQuoteRepository { public QuoteRepository(DbContext context) : base(context) { } public IEnumerable<Quote> GetAllQuotesByKeyword(ulong guildId, string keyword) => _set.Where(q => q.GuildId == guildId && q.Keyword == keyword); public IEnumerable<Quote> GetGroup(ulong guildId, int skip, int take) => _set.Where(q=>q.GuildId == guildId).OrderBy(q => q.Keyword).Skip(skip).Take(take).ToList(); public Task<Quote> GetRandomQuoteByKeywordAsync(ulong guildId, string keyword) { var rng = new NadekoRandom(); return _set.Where(q => q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rng.Next()).FirstOrDefaultAsync(); } public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); return _set.Where(q => q.Text.Contains(text) && q.GuildId == guildId && q.Keyword == keyword).OrderBy(q => rngk.Next()).FirstOrDefaultAsync(); } } }
mit
C#
8d5ec303427f810043109109773168e296d2a959
Fix a typo
domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Ahoy,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore,domaindrivendev/Swashbuckle.AspNetCore
src/Swashbuckle.AspNetCore.SwaggerGen/Generator/IDocumentProvider.cs
src/Swashbuckle.AspNetCore.SwaggerGen/Generator/IDocumentProvider.cs
using System.IO; using System.Threading.Tasks; namespace Microsoft.Extensions.ApiDescription { /// <summary> /// This service will be looked up by name from the service collection when using /// the Microsoft.Extensions.ApiDescription tool. Public only for testing. /// </summary> public interface IDocumentProvider { Task GenerateAsync(string documentName, TextWriter writer); } }
using System.IO; using System.Threading.Tasks; namespace Microsoft.Extensions.ApiDescription { /// <summary> /// his service will be looked up by name from the service collection when using /// the Microsoft.Extensions.ApiDescription tool. Public only for testing. /// </summary> public interface IDocumentProvider { Task GenerateAsync(string documentName, TextWriter writer); } }
mit
C#
5843b3f37e4c1bf8509780deed05abc7e25e16d7
add OpenConnection test and fix other test names
tombogle/libpalaso,gmartin7/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,mccarthyrb/libpalaso,hatton/libpalaso,ddaspit/libpalaso,hatton/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,gmartin7/libpalaso,glasseyes/libpalaso,marksvc/libpalaso,mccarthyrb/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,marksvc/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,hatton/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,ermshiperete/libpalaso,darcywong00/libpalaso,hatton/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso,tombogle/libpalaso,glasseyes/libpalaso,chrisvire/libpalaso,JohnThomson/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,gtryus/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso
PalasoUIWindowsForms.Tests/Keyboarding/IBusAdaptorTestsWithoutIBus.cs
PalasoUIWindowsForms.Tests/Keyboarding/IBusAdaptorTestsWithoutIBus.cs
#if MONO using System; using NUnit.Framework; using Palaso.Reporting; using Palaso.UI.WindowsForms.Keyboarding; using System.Windows.Forms; using System.Collections.Generic; namespace PalasoUIWindowsForms.Tests.Keyboarding { [TestFixture] [Category("SkipOnTeamCity")] public class IBusAdaptorTestsWithoutIBus { [Test] [Category("IBus")] public void EngineAvailable_IBusNotRunning_ReturnsFalse() { using (var e = new IBusEnvironmentForTest(true)) { Assert.IsFalse(IBusAdaptor.EngineAvailable); } } [Test] [Category("IBus")] public void GetActiveKeyboard_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => IBusAdaptor.GetActiveKeyboard() ); } } [Test] [Category("IBus")] public void OpenConnection_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => IBusAdaptor.OpenConnection() ); } } [Test] [Category("IBus")] public void KeyboardDescriptors_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => { var keyboards = IBusAdaptor.KeyboardDescriptors; } ); } } [Test] [Category("IBus")] public void Deactivate_IBusNotRunning_DoesNotThrow() { using (var e = new IBusEnvironmentForTest(true)) { Assert.DoesNotThrow(() => IBusAdaptor.Deactivate()); } } [Test] [Category("IBus")] public void ActivateKeyBoard_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => IBusAdaptor.ActivateKeyboard(IBusEnvironmentForTest.OtherKeyboard) ); } } } } #endif
#if MONO using System; using NUnit.Framework; using Palaso.Reporting; using Palaso.UI.WindowsForms.Keyboarding; using System.Windows.Forms; using System.Collections.Generic; namespace PalasoUIWindowsForms.Tests.Keyboarding { [TestFixture] [Category("SkipOnTeamCity")] public class IBusAdaptorTestsWithoutIBus { [Test] [Category("IBus")] public void EngineAvailable_IBusNotRunning_ReturnsFalse() { using (var e = new IBusEnvironmentForTest(true)) { Assert.IsFalse(IBusAdaptor.EngineAvailable); } } [Test] [Category("IBus")] public void GetActiveKeyboard_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => IBusAdaptor.GetActiveKeyboard() ); } } [Test] [Category("IBus")] public void KeyboardDescriptors_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => { var keyboards = IBusAdaptor.KeyboardDescriptors; } ); } } [Test] [Category("IBus")] public void Deactivate_IBusNotRunning_ThrowsProblemNotificationSentToUser() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( IBusAdaptor.Deactivate ); } } [Test] [Category("IBus")] public void ActivateKeyBoard_IBusNotRunning_DoesNotThrow() { using (var e = new IBusEnvironmentForTest(true)) { Assert.Throws<ErrorReport.ProblemNotificationSentToUserException>( () => IBusAdaptor.ActivateKeyboard(IBusEnvironmentForTest.OtherKeyboard) ); } } } } #endif
mit
C#
0de0684fd6bd45e7d223d8f384e1a1c0e2a82a95
Update DocumentTextBindingBehavior.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Behaviors/DocumentTextBindingBehavior.cs
src/Core2D/Behaviors/DocumentTextBindingBehavior.cs
#nullable enable using System; using Avalonia; using Avalonia.Xaml.Interactivity; using AvaloniaEdit; namespace Core2D.Behaviors; public class DocumentTextBindingBehavior : Behavior<TextEditor> { private TextEditor? _textEditor; public static readonly StyledProperty<string?> TextProperty = AvaloniaProperty.Register<DocumentTextBindingBehavior, string?>(nameof(Text)); public string? Text { get => GetValue(TextProperty); set => SetValue(TextProperty, value); } protected override void OnAttached() { base.OnAttached(); if (AssociatedObject is { } textEditor) { _textEditor = textEditor; _textEditor.TextChanged += TextChanged; this.GetObservable(TextProperty).Subscribe(TextPropertyChanged); } } protected override void OnDetaching() { base.OnDetaching(); if (_textEditor is { }) { _textEditor.TextChanged -= TextChanged; } } private void TextChanged(object? sender, EventArgs eventArgs) { if (_textEditor?.Document is { }) { Text = _textEditor.Document.Text; } } private void TextPropertyChanged(string? text) { if (_textEditor?.Document is { } && text is { }) { var caretOffset = _textEditor.CaretOffset; _textEditor.Document.Text = text; _textEditor.CaretOffset = caretOffset; } } }
#nullable enable using System; using Avalonia; using Avalonia.Xaml.Interactivity; using AvaloniaEdit; namespace Core2D.Behaviors; public class DocumentTextBindingBehavior : Behavior<TextEditor> { private TextEditor _textEditor; public static readonly StyledProperty<string> TextProperty = AvaloniaProperty.Register<DocumentTextBindingBehavior, string>(nameof(Text)); public string Text { get => GetValue(TextProperty); set => SetValue(TextProperty, value); } protected override void OnAttached() { base.OnAttached(); if (AssociatedObject is TextEditor textEditor) { _textEditor = textEditor; _textEditor.TextChanged += TextChanged; this.GetObservable(TextProperty).Subscribe(TextPropertyChanged); } } protected override void OnDetaching() { base.OnDetaching(); if (_textEditor is { }) { _textEditor.TextChanged -= TextChanged; } } private void TextChanged(object? sender, EventArgs eventArgs) { if (_textEditor?.Document is { }) { Text = _textEditor.Document.Text; } } private void TextPropertyChanged(string text) { if (_textEditor?.Document is { } && text is { }) { var caretOffset = _textEditor.CaretOffset; _textEditor.Document.Text = text; _textEditor.CaretOffset = caretOffset; } } }
mit
C#
67d7cbfea638583416aebe2690a6823d8d921741
Fix refl config
DevTeam/patterns
DevTeam.Platform.Reflection/ReflectionContainerConfiguration.cs
DevTeam.Platform.Reflection/ReflectionContainerConfiguration.cs
namespace DevTeam.Platform.Reflection { using System; using System.Collections.Generic; using Patterns.IoC; /// <inheritdoc/> public class ReflectionContainerConfiguration : IConfiguration { /// <inheritdoc/> public IEnumerable<IConfiguration> GetDependencies() { yield break; } /// <inheritdoc/> public IEnumerable<IRegistration> CreateRegistrations(IContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); yield return container.Using<ILifetime>(WellknownLifetime.Singleton).Register<IReflection>(() => new Reflection(container.Resolver<System.Reflection.Assembly, IAssembly>())); yield return container.Register<System.Reflection.Assembly, IAssembly>(assembly => new Assembly(assembly, container.Resolver<System.Type, IType>())); yield return container.Register<System.Type, IType>(type => new Type(type, container.Resolver<System.Reflection.MethodInfo, IMethodInfo>())); yield return container.Register<System.Reflection.MethodInfo, IMethodInfo>(methodInfo => new MethodInfo(methodInfo)); } } }
namespace DevTeam.Platform.Reflection { using System; using System.Collections.Generic; using Patterns.IoC; /// <inheritdoc/> public class ReflectionContainerConfiguration : IConfiguration { /// <inheritdoc/> public IEnumerable<IConfiguration> GetDependencies() { yield break; } /// <inheritdoc/> public IEnumerable<IRegistration> CreateRegistrations(IContainer container) { if (container == null) throw new ArgumentNullException(nameof(container)); yield return container.Using<ILifetime>(WellknownLifetime.Singleton).Register<IReflection>(() => new Reflection(container.Resolver<System.Reflection.Assembly, IAssembly>())); yield return container.Using<ILifetime>(WellknownLifetime.Singleton).Register<System.Reflection.Assembly, IAssembly>(assembly => new Assembly(assembly, container.Resolver<System.Type, IType>())); yield return container.Using<ILifetime>(WellknownLifetime.Singleton).Register<System.Type, IType>(type => new Type(type, container.Resolver<System.Reflection.MethodInfo, IMethodInfo>())); yield return container.Using<ILifetime>(WellknownLifetime.Singleton).Register<System.Reflection.MethodInfo, IMethodInfo>(methodInfo => new MethodInfo(methodInfo)); } } }
mit
C#