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
4792e3b12e3beaf0ed99585793c92c5d1178a1b4
Add tests for Tgstation.Server.Host.Program
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
tests/Tgstation.Server.Host.Tests/TestProgram.cs
tests/Tgstation.Server.Host.Tests/TestProgram.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using System; using System.IO; using System.Threading; using System.Threading.Tasks; using Tgstation.Server.Host.IO; namespace Tgstation.Server.Host.Tests { /// <summary> /// Tests for <see cref="Program"/>. /// </summary> [TestClass] public sealed class TestProgram { [TestMethod] public async Task TestIncompatibleWatchdog() { await Assert.ThrowsExceptionAsync<InvalidOperationException>(() => Program.Main(new string[] { "garbage", "0.0.1" })).ConfigureAwait(false); } [TestMethod] public async Task TestStandardRun() { var mockServer = new Mock<IServer>(); mockServer.Setup(x => x.RunAsync(It.IsAny<CancellationToken>())).Returns(Task.CompletedTask); mockServer.SetupGet(x => x.RestartRequested).Returns(false); var mockServerFactory = new Mock<IServerFactory>(); mockServerFactory.Setup(x => x.CreateServer(It.IsNotNull<string[]>(), It.IsAny<string>())).Returns(mockServer.Object); Program.ServerFactory = mockServerFactory.Object; var result = await Program.Main(Array.Empty<string>()).ConfigureAwait(false); Assert.AreEqual(0, result); } [TestMethod] public async Task TestStandardRunWithRestart() { var mockServer = new Mock<IServer>(); mockServer.Setup(x => x.RunAsync(It.IsAny<CancellationToken>())).Returns(Task.CompletedTask); mockServer.SetupGet(x => x.RestartRequested).Returns(true); var mockServerFactory = new Mock<IServerFactory>(); mockServerFactory.Setup(x => x.CreateServer(It.IsNotNull<string[]>(), It.IsAny<string>())).Returns(mockServer.Object); Program.ServerFactory = mockServerFactory.Object; var result = await Program.Main(Array.Empty<string>()).ConfigureAwait(false); Assert.AreEqual(1, result); } [TestMethod] public async Task TestStandardRunWithException() { var mockServer = new Mock<IServer>(); mockServer.Setup(x => x.RunAsync(It.IsAny<CancellationToken>())).Throws(new DivideByZeroException()); mockServer.SetupGet(x => x.RestartRequested).Returns(true); var mockServerFactory = new Mock<IServerFactory>(); mockServerFactory.Setup(x => x.CreateServer(It.IsNotNull<string[]>(), It.IsAny<string>())).Returns(mockServer.Object); Program.ServerFactory = mockServerFactory.Object; await Assert.ThrowsExceptionAsync<DivideByZeroException>(() => Program.Main(Array.Empty<string>())).ConfigureAwait(false); } [TestMethod] public async Task TestStandardRunWithExceptionAndWatchdog() { var mockServer = new Mock<IServer>(); var exception = new DivideByZeroException(); mockServer.Setup(x => x.RunAsync(It.IsAny<CancellationToken>())).Throws(exception); mockServer.SetupGet(x => x.RestartRequested).Returns(true); var mockServerFactory = new Mock<IServerFactory>(); mockServerFactory.SetupGet(x => x.IOManager).Returns(new DefaultIOManager()); mockServerFactory.Setup(x => x.CreateServer(It.IsNotNull<string[]>(), It.IsAny<string>())).Returns(mockServer.Object); Program.ServerFactory = mockServerFactory.Object; var tempFileName = Path.GetTempFileName(); File.Delete(tempFileName); try { var result = await Program.Main(new string[] { tempFileName }).ConfigureAwait(false); Assert.AreEqual(2, result); Assert.AreEqual(exception.ToString(), File.ReadAllText(tempFileName)); } finally { File.Delete(tempFileName); } } } }
agpl-3.0
C#
1895e154d99d3125d15506bf49fac255bd8834f1
Add missing file
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer.Client/Models/CreateApiKeyRequest.cs
BTCPayServer.Client/Models/CreateApiKeyRequest.cs
using System; using System.Collections.Generic; using System.Text; using BTCPayServer.Client.JsonConverters; using Newtonsoft.Json; namespace BTCPayServer.Client.Models { public class CreateApiKeyRequest { public string Label { get; set; } [JsonProperty(ItemConverterType = typeof(PermissionJsonConverter))] public Permission[] Permissions { get; set; } } }
mit
C#
6a03d993f08f182f9203cff73246716c08aa135e
Fix a potential overflow issue in Environment.TickCount tests.
ellismg/corefx,SGuyGe/corefx,ellismg/corefx,krk/corefx,twsouthwick/corefx,DnlHarvey/corefx,jlin177/corefx,Ermiar/corefx,Petermarcu/corefx,iamjasonp/corefx,dotnet-bot/corefx,Chrisboh/corefx,JosephTremoulet/corefx,ellismg/corefx,ptoonen/corefx,stone-li/corefx,shahid-pk/corefx,ericstj/corefx,MaggieTsang/corefx,the-dwyer/corefx,tstringer/corefx,elijah6/corefx,marksmeltzer/corefx,manu-silicon/corefx,SGuyGe/corefx,billwert/corefx,zhenlan/corefx,marksmeltzer/corefx,ViktorHofer/corefx,krytarowski/corefx,nchikanov/corefx,ptoonen/corefx,wtgodbe/corefx,jlin177/corefx,Jiayili1/corefx,JosephTremoulet/corefx,ericstj/corefx,weltkante/corefx,Jiayili1/corefx,rubo/corefx,stone-li/corefx,elijah6/corefx,weltkante/corefx,lggomez/corefx,stone-li/corefx,rjxby/corefx,gkhanna79/corefx,Priya91/corefx-1,YoupHulsebos/corefx,gkhanna79/corefx,tijoytom/corefx,JosephTremoulet/corefx,wtgodbe/corefx,rjxby/corefx,JosephTremoulet/corefx,Chrisboh/corefx,Petermarcu/corefx,cydhaselton/corefx,ViktorHofer/corefx,krk/corefx,richlander/corefx,cartermp/corefx,mazong1123/corefx,manu-silicon/corefx,Petermarcu/corefx,ptoonen/corefx,dsplaisted/corefx,parjong/corefx,Ermiar/corefx,shmao/corefx,jhendrixMSFT/corefx,twsouthwick/corefx,wtgodbe/corefx,YoupHulsebos/corefx,parjong/corefx,alexperovich/corefx,parjong/corefx,Jiayili1/corefx,krytarowski/corefx,shmao/corefx,krk/corefx,iamjasonp/corefx,mmitche/corefx,YoupHulsebos/corefx,dhoehna/corefx,rahku/corefx,cartermp/corefx,DnlHarvey/corefx,rahku/corefx,alphonsekurian/corefx,nchikanov/corefx,gkhanna79/corefx,Ermiar/corefx,jlin177/corefx,twsouthwick/corefx,ericstj/corefx,mmitche/corefx,cydhaselton/corefx,lggomez/corefx,parjong/corefx,marksmeltzer/corefx,krk/corefx,shimingsg/corefx,the-dwyer/corefx,cartermp/corefx,Priya91/corefx-1,rahku/corefx,billwert/corefx,ravimeda/corefx,the-dwyer/corefx,DnlHarvey/corefx,wtgodbe/corefx,iamjasonp/corefx,rahku/corefx,zhenlan/corefx,BrennanConroy/corefx,rubo/corefx,nbarbettini/corefx,dhoehna/corefx,ericstj/corefx,shahid-pk/corefx,cartermp/corefx,tijoytom/corefx,Jiayili1/corefx,dhoehna/corefx,stephenmichaelf/corefx,mazong1123/corefx,JosephTremoulet/corefx,rjxby/corefx,mmitche/corefx,mazong1123/corefx,nchikanov/corefx,yizhang82/corefx,Priya91/corefx-1,shimingsg/corefx,shimingsg/corefx,Ermiar/corefx,nbarbettini/corefx,yizhang82/corefx,marksmeltzer/corefx,MaggieTsang/corefx,jlin177/corefx,tijoytom/corefx,rjxby/corefx,twsouthwick/corefx,shmao/corefx,Chrisboh/corefx,elijah6/corefx,jhendrixMSFT/corefx,billwert/corefx,seanshpark/corefx,shmao/corefx,dhoehna/corefx,shmao/corefx,rjxby/corefx,SGuyGe/corefx,elijah6/corefx,shahid-pk/corefx,nchikanov/corefx,stephenmichaelf/corefx,Chrisboh/corefx,rahku/corefx,dhoehna/corefx,ViktorHofer/corefx,yizhang82/corefx,tstringer/corefx,Jiayili1/corefx,parjong/corefx,dhoehna/corefx,yizhang82/corefx,manu-silicon/corefx,Ermiar/corefx,YoupHulsebos/corefx,stephenmichaelf/corefx,adamralph/corefx,manu-silicon/corefx,Priya91/corefx-1,krytarowski/corefx,alexperovich/corefx,YoupHulsebos/corefx,jhendrixMSFT/corefx,richlander/corefx,Chrisboh/corefx,stephenmichaelf/corefx,Petermarcu/corefx,seanshpark/corefx,BrennanConroy/corefx,Petermarcu/corefx,rahku/corefx,Ermiar/corefx,axelheer/corefx,iamjasonp/corefx,MaggieTsang/corefx,wtgodbe/corefx,Chrisboh/corefx,twsouthwick/corefx,ravimeda/corefx,ellismg/corefx,Petermarcu/corefx,zhenlan/corefx,dotnet-bot/corefx,SGuyGe/corefx,khdang/corefx,ViktorHofer/corefx,MaggieTsang/corefx,Petermarcu/corefx,the-dwyer/corefx,rubo/corefx,lggomez/corefx,stone-li/corefx,fgreinacher/corefx,jhendrixMSFT/corefx,weltkante/corefx,ellismg/corefx,ViktorHofer/corefx,iamjasonp/corefx,manu-silicon/corefx,manu-silicon/corefx,lggomez/corefx,DnlHarvey/corefx,DnlHarvey/corefx,krytarowski/corefx,parjong/corefx,nchikanov/corefx,richlander/corefx,tijoytom/corefx,Jiayili1/corefx,gkhanna79/corefx,alexperovich/corefx,Ermiar/corefx,jlin177/corefx,MaggieTsang/corefx,lggomez/corefx,stephenmichaelf/corefx,adamralph/corefx,Jiayili1/corefx,mazong1123/corefx,stephenmichaelf/corefx,the-dwyer/corefx,alphonsekurian/corefx,yizhang82/corefx,stephenmichaelf/corefx,axelheer/corefx,rjxby/corefx,nchikanov/corefx,elijah6/corefx,seanshpark/corefx,dotnet-bot/corefx,ViktorHofer/corefx,weltkante/corefx,ptoonen/corefx,alphonsekurian/corefx,axelheer/corefx,billwert/corefx,dotnet-bot/corefx,billwert/corefx,alphonsekurian/corefx,stone-li/corefx,cartermp/corefx,cydhaselton/corefx,dhoehna/corefx,axelheer/corefx,richlander/corefx,alphonsekurian/corefx,nbarbettini/corefx,alphonsekurian/corefx,Priya91/corefx-1,nbarbettini/corefx,weltkante/corefx,mazong1123/corefx,krytarowski/corefx,JosephTremoulet/corefx,tstringer/corefx,gkhanna79/corefx,marksmeltzer/corefx,jhendrixMSFT/corefx,the-dwyer/corefx,parjong/corefx,dotnet-bot/corefx,ptoonen/corefx,shmao/corefx,Priya91/corefx-1,dsplaisted/corefx,ravimeda/corefx,alexperovich/corefx,stone-li/corefx,lggomez/corefx,jlin177/corefx,shahid-pk/corefx,shimingsg/corefx,weltkante/corefx,dotnet-bot/corefx,mmitche/corefx,ptoonen/corefx,MaggieTsang/corefx,khdang/corefx,seanshpark/corefx,krytarowski/corefx,JosephTremoulet/corefx,elijah6/corefx,nchikanov/corefx,ericstj/corefx,rjxby/corefx,fgreinacher/corefx,ravimeda/corefx,nbarbettini/corefx,zhenlan/corefx,rubo/corefx,shimingsg/corefx,rahku/corefx,dotnet-bot/corefx,seanshpark/corefx,billwert/corefx,tstringer/corefx,ericstj/corefx,jlin177/corefx,seanshpark/corefx,YoupHulsebos/corefx,iamjasonp/corefx,alphonsekurian/corefx,khdang/corefx,DnlHarvey/corefx,axelheer/corefx,cydhaselton/corefx,marksmeltzer/corefx,yizhang82/corefx,seanshpark/corefx,shahid-pk/corefx,tstringer/corefx,jhendrixMSFT/corefx,twsouthwick/corefx,cydhaselton/corefx,khdang/corefx,marksmeltzer/corefx,BrennanConroy/corefx,tijoytom/corefx,cydhaselton/corefx,richlander/corefx,zhenlan/corefx,ravimeda/corefx,fgreinacher/corefx,MaggieTsang/corefx,richlander/corefx,shmao/corefx,dsplaisted/corefx,mmitche/corefx,krk/corefx,yizhang82/corefx,krk/corefx,ViktorHofer/corefx,cydhaselton/corefx,rubo/corefx,richlander/corefx,shimingsg/corefx,adamralph/corefx,cartermp/corefx,krk/corefx,shimingsg/corefx,ericstj/corefx,alexperovich/corefx,mazong1123/corefx,gkhanna79/corefx,ellismg/corefx,billwert/corefx,twsouthwick/corefx,tijoytom/corefx,gkhanna79/corefx,shahid-pk/corefx,mmitche/corefx,SGuyGe/corefx,tstringer/corefx,manu-silicon/corefx,axelheer/corefx,iamjasonp/corefx,nbarbettini/corefx,fgreinacher/corefx,krytarowski/corefx,elijah6/corefx,nbarbettini/corefx,ravimeda/corefx,ravimeda/corefx,zhenlan/corefx,lggomez/corefx,ptoonen/corefx,wtgodbe/corefx,mmitche/corefx,alexperovich/corefx,mazong1123/corefx,zhenlan/corefx,SGuyGe/corefx,weltkante/corefx,tijoytom/corefx,alexperovich/corefx,khdang/corefx,DnlHarvey/corefx,khdang/corefx,the-dwyer/corefx,wtgodbe/corefx,YoupHulsebos/corefx,stone-li/corefx,jhendrixMSFT/corefx
src/System.Runtime.Extensions/tests/System/Environment.TickCount.cs
src/System.Runtime.Extensions/tests/System/Environment.TickCount.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.Threading; using Xunit; namespace System.Tests { public class EnvironmentTickCount { [Fact] public void TickCountTest() { int start = Environment.TickCount; Assert.True(SpinWait.SpinUntil(() => Environment.TickCount - start > 0, TimeSpan.FromSeconds(1))); } } }
// 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.Threading; using Xunit; namespace System.Tests { public class EnvironmentTickCount { [Fact] public void TickCountTest() { int start = Environment.TickCount; Assert.True(SpinWait.SpinUntil(() => Environment.TickCount > start, TimeSpan.FromSeconds(1))); } } }
mit
C#
29033dc370287fe435174c5c8325af1771513fcd
add the new Models
iordan93/TeamPompeii,iordan93/TeamPompeii,iordan93/TeamPompeii
PompeiiSquare/PompeiiSquare.Server/Areas/Administrator/Models/UserShowModel.cs
PompeiiSquare/PompeiiSquare.Server/Areas/Administrator/Models/UserShowModel.cs
using PompeiiSquare.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace PompeiiSquare.Server.Areas.Administrator.Models { public class UserShowModel { public string FirstName { get; set; } public string LastName { get; set; } public string HomeCity { get; set; } public Gender Gender { get; set; } public virtual string Email { get; set; } } }
mit
C#
10f1ddd7687d5be6cb9ab67f0220ca1eef5f6bab
Add sync rendering for the consent field
kjac/FormEditor,kjac/FormEditor,kjac/FormEditor
Source/Umbraco/Views/Partials/FormEditor/FieldsSync/core.consent.cshtml
Source/Umbraco/Views/Partials/FormEditor/FieldsSync/core.consent.cshtml
@inherits Umbraco.Web.Mvc.UmbracoViewPage<FormEditor.Fields.ConsentField> <div class="form-group required @(Model.Invalid ? "has-error" : null) consent"> <div class="text"> @Html.Raw(Umbraco.ReplaceLineBreaksForHtml(Model.ConsentText)) </div> @if (string.IsNullOrWhiteSpace(Model.LinkText) == false && Model.Page != null) { <div class="link"> <a href="@Model.Page.Url" target="_blank">@Model.LinkText</a> </div> } <div class="checkbox"> <label> <input type="checkbox" name="@Model.FormSafeName" value="true" required/> @Model.Label </label> @Html.Partial("FormEditor/FieldsSync/core.utils.helptext") @Html.Partial("FormEditor/FieldsSync/core.utils.validationerror") </div> </div>
mit
C#
514bea5c12ff013a529c0dc0b6e7cdd258fc7589
Add TestSceneIgnore
smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework.Tests/Visual/Testing/TestSceneIgnore.cs
osu.Framework.Tests/Visual/Testing/TestSceneIgnore.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 NUnit.Framework; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneIgnore : FrameworkTestScene { [Test] [Ignore("test")] public void IgnoredTest() { AddStep($"Throw {typeof(InvalidOperationException)}", () => throw new InvalidOperationException()); } } }
mit
C#
7a2955f91f887f3eafeaebae8425d83858495925
Add remote message client publisher hub that clients can tap
mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype
src/Glimpse.Server.Web/Resources/RemoteStreamMessageClientPublisherResource.cs
src/Glimpse.Server.Web/Resources/RemoteStreamMessageClientPublisherResource.cs
using Microsoft.AspNet.SignalR; using System; namespace Glimpse.Server.Resources { public class RemoteStreamMessageClientPublisherResource : Hub { } }
mit
C#
389f7cdaa72feb0eb58acf0413a6151314d85897
Add ValueChangedTriggerBehavior
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/ValueChangedTriggerBehavior.cs
src/Avalonia.Xaml.Interactions/Custom/ValueChangedTriggerBehavior.cs
using System; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom { /// <summary> /// A behavior that performs actions when the bound data produces new value. /// </summary> public sealed class ValueChangedTriggerBehavior : Trigger { static ValueChangedTriggerBehavior() { BindingProperty.Changed.Subscribe(e => OnValueChanged(e.Sender, e)); } /// <summary> /// Identifies the <seealso cref="Binding"/> avalonia property. /// </summary> public static readonly StyledProperty<object?> BindingProperty = AvaloniaProperty.Register<ValueChangedTriggerBehavior, object?>(nameof(Binding)); /// <summary> /// Gets or sets the bound object that the <see cref="ValueChangedTriggerBehavior"/> will listen to. This is a avalonia property. /// </summary> public object? Binding { get => GetValue(BindingProperty); set => SetValue(BindingProperty, value); } private static void OnValueChanged(IAvaloniaObject avaloniaObject, AvaloniaPropertyChangedEventArgs args) { if (!(avaloniaObject is ValueChangedTriggerBehavior behavior) || behavior.AssociatedObject is null) { return; } var binding = behavior.Binding; if (binding is { }) { Interaction.ExecuteActions(behavior.AssociatedObject, behavior.Actions, args); } } } }
mit
C#
3024efd9478413394debcf83f9874edcbc702f03
Create main.cs
serega-cpp/mpTIFF
main.cs
main.cs
using System; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; public class MyMPTiffApp { [STAThread] public static int Main() { MyMPTiffApp app = new MyMPTiffApp(); app.DoGdiPlus(); return 0; } protected void DoGdiPlus() { //// Get source files names OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = "Specify source files for multi-pages TIFF (at least 2 files)"; openFileDialog.Filter = "TIFF files (*.tif)|*.tif|All files (*.*)|*.*"; openFileDialog.Multiselect = true; if (openFileDialog.ShowDialog() != DialogResult.OK) return; string[] srcFileNames = openFileDialog.FileNames; if (srcFileNames.Length < 2) { MessageBox.Show("At least 2 files required for conversion", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //// Get destanation file name SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Title = "Specify destination file name"; saveFileDialog.Filter = "TIFF files (*.tif)|*.tif|All files (*.*)|*.*"; if (saveFileDialog.ShowDialog() != DialogResult.OK) return; string destFileName = saveFileDialog.FileName; //// Create multipage TIFF file EncoderParameters tiffEncoderParams = new EncoderParameters(1); tiffEncoderParams.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame); ImageCodecInfo tiffCodecInfo = GetEncoderInfo("image/tiff"); Image gim = Image.FromFile(srcFileNames[0]); for (int i = 0; i < srcFileNames.Length; i++) { if (i == 0) { // Save first page gim.Save(destFileName, tiffCodecInfo, tiffEncoderParams); tiffEncoderParams.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); } else { // Add and Save other pages Image img = Image.FromFile(srcFileNames[i]); gim.SaveAdd(img, tiffEncoderParams); } } // Finalize file tiffEncoderParams.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush); gim.SaveAdd(tiffEncoderParams); MessageBox.Show("File " + destFileName + " was successfully created!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information); } private static ImageCodecInfo GetEncoderInfo(String mimeType) { ImageCodecInfo[] encoders; encoders = ImageCodecInfo.GetImageEncoders(); for (int j = 0; j < encoders.Length; ++j) { if (encoders[j].MimeType == mimeType) return encoders[j]; } return null; } };
unlicense
C#
3dbef1400c4de97fcf8ebb4b3952b4eff4a19b35
Refactor setting storage related
qianlifeng/Wox,mika76/Wox,sanbinabu/Wox,gnowxilef/Wox,shangvven/Wox,qianlifeng/Wox,dstiert/Wox,vebin/Wox,derekforeman/Wox,Wox-launcher/Wox,jondaniels/Wox,zlphoenix/Wox,vebin/Wox,lances101/Wox,JohnTheGr8/Wox,apprentice3d/Wox,renzhn/Wox,18098924759/Wox,kdar/Wox,shangvven/Wox,EmuxEvans/Wox,Wox-launcher/Wox,apprentice3d/Wox,AlexCaranha/Wox,dstiert/Wox,vebin/Wox,JohnTheGr8/Wox,apprentice3d/Wox,mika76/Wox,gnowxilef/Wox,18098924759/Wox,gnowxilef/Wox,Launchify/Launchify,yozora-hitagi/Saber,derekforeman/Wox,AlexCaranha/Wox,18098924759/Wox,kdar/Wox,medoni/Wox,kayone/Wox,EmuxEvans/Wox,yozora-hitagi/Saber,medoni/Wox,danisein/Wox,kayone/Wox,danisein/Wox,derekforeman/Wox,kayone/Wox,EmuxEvans/Wox,Megasware128/Wox,sanbinabu/Wox,zlphoenix/Wox,dstiert/Wox,lances101/Wox,sanbinabu/Wox,qianlifeng/Wox,Megasware128/Wox,kdar/Wox,mika76/Wox,Launchify/Launchify,jondaniels/Wox,renzhn/Wox,AlexCaranha/Wox,shangvven/Wox
Wox.Infrastructure/Storage/UserSettings/PluginHotkey.cs
Wox.Infrastructure/Storage/UserSettings/PluginHotkey.cs
namespace Wox.Infrastructure.Storage.UserSettings { public class CustomPluginHotkey { public string Hotkey { get; set; } public string ActionKeyword { get; set; } } }
mit
C#
6d4bf11b0d52b3c1e08279c18b138422c22c3168
Update VlcManager.GetMediaMeta.cs
RickyGAkl/Vlc.DotNet,marcomeyer/Vlc.DotNet,raydtang/Vlc.DotNet,RickyGAkl/Vlc.DotNet,thephez/Vlc.DotNet,agherardi/Vlc.DotNet,raydtang/Vlc.DotNet,marcomeyer/Vlc.DotNet,ZeBobo5/Vlc.DotNet,thephez/Vlc.DotNet,agherardi/Vlc.DotNet,jeremyVignelles/Vlc.DotNet,xue-blood/wpfVlc,xue-blood/wpfVlc
src/Vlc.DotNet.Core.Interops/VlcManager.GetMediaMeta.cs
src/Vlc.DotNet.Core.Interops/VlcManager.GetMediaMeta.cs
using System; using System.Runtime.InteropServices; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core.Interops { public sealed partial class VlcManager { public string GetMediaMeta(VlcMediaInstance mediaInstance, MediaMetadatas metadata) { if (mediaInstance == IntPtr.Zero) throw new ArgumentException("Media instance is not initialized."); var ptr = GetInteropDelegate<GetMediaMetadata>().Invoke(mediaInstance, metadata); if (ptr == IntPtr.Zero) return null; return Marshal.PtrToStringAnsi(ptr); } } }
using System; using System.Runtime.InteropServices; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core.Interops { public sealed partial class VlcManager { public string GetMediaMeta(VlcMediaInstance mediaInstance, MediaMetadatas metadata) { if (mediaInstance == IntPtr.Zero) throw new ArgumentException("Media instance is not initialized."); var ptr = GetInteropDelegate<GetMediaMetadata>().Invoke(mediaInstance, metadata); if (ptr == IntPtr.Zero) return null; return Marshal.PtrToStringUni(ptr); } } }
mit
C#
4992bcfd191e8d3ec287a328e85749ba5bb60d04
Add files via upload
leocabrallce/HackerRank,leocabrallce/HackerRank
Algorithms/A_Very_Big_Sum/A_Very_Big_Sum_CSharp.cs
Algorithms/A_Very_Big_Sum/A_Very_Big_Sum_CSharp.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; class Solution { static void Main(String[] args) { int n = Convert.ToInt32(Console.ReadLine()); string[] arr_temp = Console.ReadLine().Split(' '); long[] arr = Array.ConvertAll(arr_temp, Int64.Parse); long sum = arr.Sum(); Console.WriteLine(sum); } }
mit
C#
ab522e1569e23000df98840a2f286f233a973284
Add test coverage of team display on leaderboard
peppy/osu-new,UselessToucan/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu
osu.Game.Tests/Visual/Multiplayer/TestSceneMultiplayerGameplayLeaderboardTeams.cs
osu.Game.Tests/Visual/Multiplayer/TestSceneMultiplayerGameplayLeaderboardTeams.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Configuration; using osu.Game.Online.API; using osu.Game.Online.Multiplayer.MatchTypes.TeamVersus; using osu.Game.Online.Rooms; using osu.Game.Rulesets.Osu.Scoring; using osu.Game.Screens.Play.HUD; using osu.Game.Tests.Visual.OnlinePlay; using osu.Game.Tests.Visual.Spectator; using osu.Game.Users; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMultiplayerGameplayLeaderboardTeams : MultiplayerTestScene { private static IEnumerable<int> users => Enumerable.Range(0, 16); public new TestSceneMultiplayerGameplayLeaderboard.TestMultiplayerSpectatorClient SpectatorClient => (TestSceneMultiplayerGameplayLeaderboard.TestMultiplayerSpectatorClient)OnlinePlayDependencies?.SpectatorClient; protected override OnlinePlayTestSceneDependencies CreateOnlinePlayDependencies() => new TestDependencies(); protected class TestDependencies : MultiplayerTestSceneDependencies { protected override TestSpectatorClient CreateSpectatorClient() => new TestSceneMultiplayerGameplayLeaderboard.TestMultiplayerSpectatorClient(); } private MultiplayerGameplayLeaderboard leaderboard; protected override Room CreateRoom() { var room = base.CreateRoom(); room.Type.Value = MatchType.TeamVersus; return room; } [SetUpSteps] public override void SetUpSteps() { AddStep("set local user", () => ((DummyAPIAccess)API).LocalUser.Value = LookupCache.GetUserAsync(1).Result); AddStep("create leaderboard", () => { leaderboard?.Expire(); OsuScoreProcessor scoreProcessor; Beatmap.Value = CreateWorkingBeatmap(Ruleset.Value); var playable = Beatmap.Value.GetPlayableBeatmap(Ruleset.Value); foreach (var user in users) { SpectatorClient.StartPlay(user, Beatmap.Value.BeatmapInfo.OnlineBeatmapID ?? 0); var roomUser = OnlinePlayDependencies.Client.AddUser(new User { Id = user }); roomUser.MatchState = new TeamVersusUserState { TeamID = RNG.Next(0, 2) }; } // Todo: This is REALLY bad. Client.CurrentMatchPlayingUserIds.AddRange(users); Children = new Drawable[] { scoreProcessor = new OsuScoreProcessor(), }; scoreProcessor.ApplyBeatmap(playable); LoadComponentAsync(leaderboard = new MultiplayerGameplayLeaderboard(scoreProcessor, users.ToArray()) { Anchor = Anchor.Centre, Origin = Anchor.Centre, }, Add); }); AddUntilStep("wait for load", () => leaderboard.IsLoaded); AddUntilStep("wait for user population", () => Client.CurrentMatchPlayingUserIds.Count > 0); } [Test] public void TestScoreUpdates() { AddRepeatStep("update state", () => SpectatorClient.RandomlyUpdateState(), 100); AddToggleStep("switch compact mode", expanded => leaderboard.Expanded.Value = expanded); } } }
mit
C#
3a4adfa410756d72c1aa4a41bc3697b4fe40b6a7
Fix audio occlusion
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/Audio/ContentAudioSystem.cs
Content.Client/Audio/ContentAudioSystem.cs
using Content.Shared.Physics; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; namespace Content.Client.Audio { public sealed class ContentAudioSystem : EntitySystem { public override void Initialize() { base.Initialize(); Get<AudioSystem>().OcclusionCollisionMask = (int) CollisionGroup.Impassable; } } }
mit
C#
20d09322ba79f0088984dd39bb0c2fa94d69636f
Add `Vector3Int.ToVector3` extension method
mminer/unity-extensions
Extensions/Vector3IntExtensions.cs
Extensions/Vector3IntExtensions.cs
using System; using UnityEngine; namespace Extensions { /// <summary> /// Extension methods for UnityEngine.Vector3Int. /// </summary> public static class Vector3IntExtensions { /// <summary> /// Converts a Vector3Int struct to a Vector3. /// </summary> /// <param name="vector">Vector.</param> /// <returns>Vector3 struct.</returns> public static Vector3 ToVector3 (this Vector3Int vector) { return new Vector3( Convert.ToSingle(vector.x), Convert.ToSingle(vector.y), Convert.ToSingle(vector.z) ); } } }
mit
C#
d9febe3a2c41847b1d3f3cb50d0ab2bca43d04c9
add MapDefaultHealthChecks extension
Abhith/Code.Library,Abhith/Code.Library
src/Code.Library.AspNetCore/Extensions/HealthCheckEndpointRouteBuilderExtensions.cs
src/Code.Library.AspNetCore/Extensions/HealthCheckEndpointRouteBuilderExtensions.cs
using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; using HealthChecks.UI.Client; namespace Code.Library.AspNetCore.Extensions { public static class HealthCheckEndpointRouteBuilderExtensions { public static IEndpointRouteBuilder MapDefaultHealthChecks(this IEndpointRouteBuilder endpoints) { endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") }); return endpoints; } } }
apache-2.0
C#
d881fdaf1c6df653d5142ba2f379c4cbab5fc75b
add VS-generated AssemblyInfo.cs
isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,maul-esel/ssharp,isse-augsburg/ssharp,isse-augsburg/ssharp,maul-esel/ssharp
models/SelfOrganizingPillProduction/Properties/AssemblyInfo.cs
models/SelfOrganizingPillProduction/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SelfOrganizingPillProduction")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SelfOrganizingPillProduction")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ab94e0eb-c085-421f-9a29-441409bcd30f")] // 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#
656efc674be9d7331ac48f1b9eed472dc1be0b7b
Add integration test for sitemap.xml
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
tests/LondonTravel.Site.Tests/Integration/SiteMapTests.cs
tests/LondonTravel.Site.Tests/Integration/SiteMapTests.cs
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.LondonTravel.Site.Integration { using System; using System.Globalization; using System.Net; using System.Threading.Tasks; using System.Xml; using Shouldly; using Xunit; /// <summary> /// A class containing tests for the site map. /// </summary> public class SiteMapTests : IntegrationTest { /// <summary> /// Initializes a new instance of the <see cref="SiteMapTests"/> class. /// </summary> /// <param name="fixture">The fixture to use.</param> public SiteMapTests(HttpServerFixture fixture) : base(fixture) { } [Fact] public async Task Site_Map_Locations_Are_Valid() { XmlNodeList locations; // Act using (var response = await Fixture.Client.GetAsync("sitemap.xml")) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string xml = await response.Content.ReadAsStringAsync(); locations = GetSitemapLocations(xml); } // Assert locations.ShouldNotBeNull(); locations.Count.ShouldBeGreaterThan(0); foreach (XmlNode location in locations) { string url = location.InnerText; Assert.True(Uri.TryCreate(url, UriKind.Absolute, out Uri uri)); uri.Scheme.ShouldBe("https"); uri.Port.ShouldBe(443); uri.Host.ShouldBe("londontravel.martincostello.com"); uri.AbsolutePath.ShouldEndWith("/"); using (var response = await Fixture.Client.GetAsync(uri.PathAndQuery)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } } private static XmlNodeList GetSitemapLocations(string xml) { string prefix = "ns"; string uri = "http://www.sitemaps.org/schemas/sitemap/0.9"; var sitemap = new XmlDocument(); sitemap.LoadXml(xml); var nsmgr = new XmlNamespaceManager(sitemap.NameTable); nsmgr.AddNamespace(prefix, uri); string xpath = string.Format(CultureInfo.InvariantCulture, "/{0}:urlset/{0}:url/{0}:loc", prefix); return sitemap.SelectNodes(xpath, nsmgr); } } }
apache-2.0
C#
59371c4af9d31a76aa34470fa67b110eb5cbd060
Test code
OlegJakushkin/AzureWebAppTest
site/index.cshtml
site/index.cshtml
@{ var txt = DateTime.Now; // C# } <html> <body> <p>The dateTime is @txt</p> </body> </html>
mit
C#
9162a7bea9554671cb903646ceae218dc064fc96
Create mediaPicker.cshtml
go4web/Umbraco-Snippets
mediaPicker.cshtml
mediaPicker.cshtml
@if (Model.Content.GetPropertyValue("topImage") != string.Empty) { var mediaItem = Umbraco.Media(@Model.Content.GetPropertyValue("topImage")); <img src="@mediaItem.Url" alt="@mediaItem.Name" /> }
mit
C#
c66252b22d5e11b4d415edb959eb2d8eeed03fb4
switch config
LeeCampbell/ReactiveTrader,singhdev/ReactiveTrader,mrClapham/ReactiveTrader,mrClapham/ReactiveTrader,rikoe/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,HalidCisse/ReactiveTrader,rikoe/ReactiveTrader,singhdev/ReactiveTrader,jorik041/ReactiveTrader,abbasmhd/ReactiveTrader,LeeCampbell/ReactiveTrader,mrClapham/ReactiveTrader,jorik041/ReactiveTrader,akrisiun/ReactiveTrader,akrisiun/ReactiveTrader,AdaptiveConsulting/ReactiveTrader,abbasmhd/ReactiveTrader,rikoe/ReactiveTrader,rikoe/ReactiveTrader,abbasmhd/ReactiveTrader,akrisiun/ReactiveTrader,LeeCampbell/ReactiveTrader,LeeCampbell/ReactiveTrader,HalidCisse/ReactiveTrader,jorik041/ReactiveTrader,singhdev/ReactiveTrader,akrisiun/ReactiveTrader,abbasmhd/ReactiveTrader,singhdev/ReactiveTrader,mrClapham/ReactiveTrader,HalidCisse/ReactiveTrader,HalidCisse/ReactiveTrader,jorik041/ReactiveTrader
src/Adaptive.ReactiveTrader.Client.WindowsStoreApp/Configuration/ConfigurationProvider.cs
src/Adaptive.ReactiveTrader.Client.WindowsStoreApp/Configuration/ConfigurationProvider.cs
namespace Adaptive.ReactiveTrader.Client.Configuration { class ConfigurationProvider : IConfigurationProvider { public string[] Servers { //get { return new[] { "http://localhost:8080" }; } get { return new[] { "http://reactivetrader.azurewebsites.net/signalr" }; } } } }
namespace Adaptive.ReactiveTrader.Client.Configuration { class ConfigurationProvider : IConfigurationProvider { public string[] Servers { get { return new[] { "http://localhost:8080" }; } //get { return new[] { "http://reactivetrader.azurewebsites.net/signalr" }; } } } }
apache-2.0
C#
399c98ff1156cab6c16e81c0f746e5464f884465
Add Enumerable.IsEmpty and IsNullOrEmpty
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Utilities/Collections/Enumerable.Emptiness.cs
source/Nuke.Common/Utilities/Collections/Enumerable.Emptiness.cs
// Copyright 2021 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System.Collections.Generic; using System.Linq; namespace Nuke.Common.Utilities.Collections { public static partial class EnumerableExtensions { public static bool IsEmpty<T>(this IEnumerable<T> enumerable) { return !enumerable.Any(); } public static bool IsNullOrEmpty<T>(this IEnumerable<T> enumerable) { return enumerable == null || enumerable.IsEmpty(); } } }
mit
C#
850ee6a25bef9631c2a82c3695d1e282a3aa7699
change LetterboxPosition from integer to double
ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,ppy/osu-framework,paparony03/osu-framework,RedNesto/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,smoogipooo/osu-framework,default0/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,ZLima12/osu-framework,peppy/osu-framework,default0/osu-framework,EVAST9919/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,RedNesto/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,ppy/osu-framework
osu.Framework/Configuration/FrameworkConfigManager.cs
osu.Framework/Configuration/FrameworkConfigManager.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform; namespace osu.Framework.Configuration { public class FrameworkConfigManager : ConfigManager<FrameworkConfig> { protected override string Filename => @"framework.ini"; protected override void InitialiseDefaults() { #pragma warning disable CS0612 // Type or member is obsolete Set(FrameworkConfig.ShowLogOverlay, true); Set(FrameworkConfig.Width, 1366, 640); Set(FrameworkConfig.Height, 768, 480); Set(FrameworkConfig.WindowedPositionX, 0.5, -0.1, 1.1); Set(FrameworkConfig.WindowedPositionY, 0.5, -0.1, 1.1); Set(FrameworkConfig.AudioDevice, string.Empty); Set(FrameworkConfig.VolumeUniversal, 1.0, 0, 1); Set(FrameworkConfig.VolumeMusic, 1.0, 0, 1); Set(FrameworkConfig.VolumeEffect, 1.0, 0, 1); Set(FrameworkConfig.WidthFullscreen, 9999, 320, 9999); Set(FrameworkConfig.HeightFullscreen, 9999, 240, 9999); Set(FrameworkConfig.Letterboxing, true); Set(FrameworkConfig.LetterboxPositionX, 0.0, -1, 1); Set(FrameworkConfig.LetterboxPositionY, 0.0, -1, 1); Set(FrameworkConfig.FrameSync, FrameSync.Limit120); Set(FrameworkConfig.WindowMode, WindowMode.Windowed); #pragma warning restore CS0612 // Type or member is obsolete } public FrameworkConfigManager(Storage storage) : base(storage) { } } public enum FrameworkConfig { ShowLogOverlay, AudioDevice, VolumeUniversal, VolumeEffect, VolumeMusic, Width, Height, WindowedPositionX, WindowedPositionY, HeightFullscreen, WidthFullscreen, WindowMode, Letterboxing, LetterboxPositionX, LetterboxPositionY, FrameSync, } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Platform; namespace osu.Framework.Configuration { public class FrameworkConfigManager : ConfigManager<FrameworkConfig> { protected override string Filename => @"framework.ini"; protected override void InitialiseDefaults() { #pragma warning disable CS0612 // Type or member is obsolete Set(FrameworkConfig.ShowLogOverlay, true); Set(FrameworkConfig.Width, 1366, 640); Set(FrameworkConfig.Height, 768, 480); Set(FrameworkConfig.WindowedPositionX, 0.5, -0.1, 1.1); Set(FrameworkConfig.WindowedPositionY, 0.5, -0.1, 1.1); Set(FrameworkConfig.AudioDevice, string.Empty); Set(FrameworkConfig.VolumeUniversal, 1.0, 0, 1); Set(FrameworkConfig.VolumeMusic, 1.0, 0, 1); Set(FrameworkConfig.VolumeEffect, 1.0, 0, 1); Set(FrameworkConfig.WidthFullscreen, 9999, 320, 9999); Set(FrameworkConfig.HeightFullscreen, 9999, 240, 9999); Set(FrameworkConfig.Letterboxing, true); Set(FrameworkConfig.LetterboxPositionX, 0, -100, 100); Set(FrameworkConfig.LetterboxPositionY, 0, -100, 100); Set(FrameworkConfig.FrameSync, FrameSync.Limit120); Set(FrameworkConfig.WindowMode, WindowMode.Windowed); #pragma warning restore CS0612 // Type or member is obsolete } public FrameworkConfigManager(Storage storage) : base(storage) { } } public enum FrameworkConfig { ShowLogOverlay, AudioDevice, VolumeUniversal, VolumeEffect, VolumeMusic, Width, Height, WindowedPositionX, WindowedPositionY, HeightFullscreen, WidthFullscreen, WindowMode, Letterboxing, LetterboxPositionX, LetterboxPositionY, FrameSync, } }
mit
C#
fced262c41859aa3fc01f3ffcb3eeded6610245e
Add labelled dropdown component
EVAST9919/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipooo/osu,peppy/osu,EVAST9919/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,johnneijzen/osu,ppy/osu,peppy/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu
osu.Game/Graphics/UserInterfaceV2/LabelledDropdown.cs
osu.Game/Graphics/UserInterfaceV2/LabelledDropdown.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Graphics.UserInterfaceV2 { public class LabelledDropdown<T> : LabelledComponent<OsuDropdown<T>, T> { public LabelledDropdown() : base(true) { } public IEnumerable<T> Items { get => Component.Items; set => Component.Items = value; } protected override OsuDropdown<T> CreateComponent() => new OsuDropdown<T> { RelativeSizeAxes = Axes.X, Width = 0.5f, }; } }
mit
C#
911d7f4018a3dbecf13ab64c8044945658c0a6ea
Add Twitch filter for blockings
Nanabell/NoAdsHere
NoAdsHere/Services/AntiAds/Twitch.cs
NoAdsHere/Services/AntiAds/Twitch.cs
using System; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Discord; using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using MongoDB.Driver; using NLog; using NoAdsHere.Common; using NoAdsHere.Services.Penalties; namespace NoAdsHere.Services.AntiAds { public class Twitch { private readonly Regex _stream = new Regex(@"(?i)twitch\.(?i)tv\/(#)?([a-zA-Z0-9][\w]{2,24})", RegexOptions.Compiled); private readonly Regex _video = new Regex(@"(?i)twitch\.(?i)tv\/(?i)videos\/(#)?([0-9]{2,24})", RegexOptions.Compiled); private readonly Regex _clip = new Regex(@"(?i)clips\.(?i)twitch\.(?i)tv\/(#)?([a-zA-Z0-9][\w]{4,50})", RegexOptions.Compiled); private readonly DiscordSocketClient _client; private readonly MongoClient _mongo; private readonly Logger _logger = LogManager.GetLogger("AntiAds"); public Twitch(IServiceProvider provider) { _client = provider.GetService<DiscordSocketClient>(); _mongo = provider.GetService<MongoClient>(); } public Task StartService() { _client.MessageReceived += TwitchChecker; _logger.Info("Anti Twitch Service Started"); return Task.CompletedTask; } private async Task TwitchChecker(SocketMessage socketMessage) { var message = socketMessage as SocketUserMessage; if (message == null) return; var context = GetConxtext(message); if (context.Guild == null) return; if (context.User.IsBot) return; if (_stream.IsMatch(context.Message.Content) || _clip.IsMatch(context.Message.Content) || _video.IsMatch(context.Message.Content)) { _logger.Info($"Detected Youtube Link in Message {context.Message.Id}"); var setting = await _mongo.GetCollection<GuildSetting>(_client).GetGuildAsync(context.Guild.Id); await TryDelete(setting, context); } } private ICommandContext GetConxtext(SocketUserMessage message) => new SocketCommandContext(_client, message); private async Task TryDelete(GuildSetting settings, ICommandContext context) { var guildUser = context.User as IGuildUser; if (settings.Ignorings.Users.Contains(context.User.Id)) return; if (settings.Ignorings.Channels.Contains(context.Channel.Id)) return; if (guildUser != null && guildUser.RoleIds.Any(userRole => settings.Ignorings.Roles.Contains(userRole))) return; if (settings.Blockings.Twitch) { if (context.Channel.CheckChannelPermission(ChannelPermission.ManageMessages, await context.Guild.GetCurrentUserAsync())) { _logger.Info($"Deleting Message {context.Message.Id} from {context.User}. Message contained a Twitch Link"); try { await context.Message.DeleteAsync(); } catch (Exception e) { _logger.Warn(e, $"Deleting of Message {context.Message.Id} Failed"); } } else _logger.Warn($"Unable to Delete Message {context.Message.Id}. Missing ManageMessages Permission"); await Violations.AddPoint(context); } } } }
mit
C#
bc99bed0388d2d5691915943e5307144e2ba953c
Read file from osz archive.
Meowtrix/osu-Auto-Mapping-Toolkit
Training/DataGenerator/OszArchive.cs
Training/DataGenerator/OszArchive.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace Meowtrix.osuAMT.Training.DataGenerator { class OszArchive : Archive, IDisposable { public ZipArchive archive; public OszArchive(Stream stream) { archive = new ZipArchive(stream, ZipArchiveMode.Read, false); } public void Dispose() => archive.Dispose(); public override Stream OpenFile(string filename) => archive.GetEntry(filename).Open(); public override IEnumerable<Stream> OpenOsuFiles() => archive.Entries.Where(x => x.Name.EndsWith(".osz")).Select(e => e.Open()); } }
mit
C#
1f1f2f41b83225992c3e3071706a6a69499682f0
add LiteQueryable IncludeAll extension
zmira/abremir.AllMyBricks
abremir.AllMyBricks.Data/Extensions/LiteQueryableExtension.cs
abremir.AllMyBricks.Data/Extensions/LiteQueryableExtension.cs
using LiteDB; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace abremir.AllMyBricks.Data.Extensions { public static class LiteQueryableExtension { public static ILiteQueryable<T> IncludeAll<T>(this ILiteQueryable<T> liteQueryable) where T : class { return liteQueryable.Include(GetRecursivePaths(typeof(T))); } private static List<BsonExpression> GetRecursivePaths(Type pathType, string basePath = null) { var fields = pathType.GetProperties() .Where(property => !property.PropertyType.IsValueType && (property.GetCustomAttribute<BsonRefAttribute>() != null || typeof(IEnumerable).IsAssignableFrom(property.PropertyType) && property.PropertyType != typeof(string))); var paths = new List<BsonExpression>(); basePath = string.IsNullOrEmpty(basePath) ? "$" : basePath; foreach (var field in fields) { var path = typeof(IEnumerable).IsAssignableFrom(field.PropertyType) ? $"{basePath}.{field.Name}[*]" : $"{basePath}.{field.Name}"; if (field.GetCustomAttribute<BsonRefAttribute>() != null) { paths.Add(path); } paths.AddRange(GetRecursivePaths(field.PropertyType.GetInnerGenericType(), path)); } return paths; } public static Type GetInnerGenericType(this Type type) { // Attempt to get the inner generic type Type innerType = type.GetGenericArguments().FirstOrDefault(); // Recursively call this function until no inner type is found return innerType is null ? type : innerType.GetInnerGenericType(); } } }
mit
C#
d2a088ab25d2648bef9c109117f4558cf27b3616
Create JamesPetty.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/JamesPetty.cs
src/Firehose.Web/Authors/JamesPetty.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class MarkKraus : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "James"; public string LastName => "Petty"; public string ShortBioOrTagLine => "Windows Server Administrator, PowerShell enthusiast, PowerShell.org CFO"; public string StateOrRegion => "Chattanooga, Tennessee, USA"; public string EmailAddress => ""; public string TwitterHandle => "psjamesp"; public string GitHubHandle => "psjamesp"; public string GravatarHash => "a7f8b94204f4ca1e53c84aedc1242f8e"; public GeoPosition Position => new GeoPosition(35.045631, ‎-85.309677); public Uri WebSite => new Uri("https://www.scriptautomaterepeat.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://scriptautomaterepeat.com/feed/"); } } public bool Filter(SyndicationItem item) { return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
mit
C#
55148de344c2bde8507229d4d136f763dd9b7432
Add DataQueue.cs
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
QueueDataGraphic/QueueDataGraphic/CSharpFiles/DataQueue.cs
QueueDataGraphic/QueueDataGraphic/CSharpFiles/DataQueue.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { class DataQueue { } }
apache-2.0
C#
83a73e6e8d7525e21559d1b5c2e2eb53a3e74ab5
Create Edit.cshtml
CarmelSoftware/Generic-Data-Repository-for-ASP.NET-MVC
Views/Blogs/Edit.cshtml
Views/Blogs/Edit.cshtml
@model GenericRepository.Models.Blog @{ ViewBag.Title = "Edit"; } <div class="jumbotron"> <h2>Generic Data Repository - Edit</h2><br /><h4>By Carmel Schvartzman</h4> </div> <div class="jumbotron"> @using (Html.BeginForm()) { @Html.AntiForgeryToken() @Html.ValidationSummary(true) <fieldset> <legend>Blog</legend> @Html.HiddenFor(model => model.BlogID) <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Title, new { @class="form-control"}) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.Text) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Text, new { @class="form-control" }) @Html.ValidationMessageFor(model => model.Text) </div> <div class="editor-label"> @Html.LabelFor(model => model.DatePosted) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.DatePosted, new { @class="form-control"}) @Html.ValidationMessageFor(model => model.DatePosted) </div> <div class="editor-label"> @Html.LabelFor(model => model.MainPicture) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.MainPicture, new { @class="form-control"}) @Html.ValidationMessageFor(model => model.MainPicture) </div> <div class="editor-label"> @Html.LabelFor(model => model.BloggerID, "Blogger") </div> <div class="editor-field"> @Html.DropDownList("BloggerID",null, new { @class="form-control"}) @Html.ValidationMessageFor(model => model.BloggerID) </div> <p> <input type="submit" value="Save" class="btn btn-success" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index", null, new { @class="btn btn-success" }) </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") } </div>
mit
C#
5924cd05d99c68efb11763d58017a3b65ffd2cae
Create PuppetVrRig.cs
efruchter/UnityUtilities
PuppetVrRig.cs
PuppetVrRig.cs
using System; using UnityEngine; /// <summary> /// Copies transform position/orientation from one reference frame to another. /// </summary> public class PuppetVrRig : MonoBehaviour { [ SerializeField, Tooltip( "The Rig that you want the puppet to imitate." ) ] private RigProfile driver; [ SerializeField, Tooltip( "The puppet's rig." ) ] private RigProfile driven; [ Serializable ] public struct RigProfile { public Transform Area, Head, LeftHand, RightHand; } #region Unity void LateUpdate() { TransferPose(); } #endregion private void TransferPose() { if ( driver.Area && driven.Area ) { // Create the mappings from coordinate space of DRIVER to coordinate space of DRIVEN var tMat = driver.Area.localToWorldMatrix * driven.Area.localToWorldMatrix; var rQuat = Quaternion.Inverse( driver.Area.rotation ) * driven.Area.rotation; if ( driver.Head && driven.Head ) { driven.Head.localPosition = tMat * driver.Head.localPosition; driven.Head.localRotation = rQuat * driver.Head.localRotation; } if ( driver.LeftHand && driven.LeftHand ) { driven.LeftHand.localPosition = tMat * driver.LeftHand.localPosition; driven.LeftHand.localRotation = rQuat * driver.LeftHand.localRotation; } if ( driver.RightHand && driven.RightHand ) { driven.RightHand.localPosition = tMat * driver.RightHand.localPosition; driven.RightHand.localRotation = rQuat * driver.RightHand.localRotation; } } } }
mit
C#
d9dc9621046493747d23c26c657b09907b5025d4
Add foundation of integration test runner
SoundMetrics/aris-integration-sdk,SoundMetrics/aris-integration-sdk,SoundMetrics/aris-integration-sdk,SoundMetrics/aris-integration-sdk,SoundMetrics/aris-integration-sdk
common/platform-dotnet/test/SimplifiedProtocolTest/SimplifiedProtocolTestWpfCore/IntegrationTest.cs
common/platform-dotnet/test/SimplifiedProtocolTest/SimplifiedProtocolTestWpfCore/IntegrationTest.cs
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SimplifiedProtocolTestWpfCore { internal static class IntegrationTest { public static Task<IntegrationTestResult[]> RunAsync(CancellationToken ct) { return Task<IntegrationTestResult[]>.Run(() => RunTestCases(testCases, ct)); } private static IntegrationTestResult[] RunTestCases( IEnumerable<IntegrationTestCase> localTestCases, CancellationToken ct) { return RunTestCases().ToArray(); IEnumerable<IntegrationTestResult> RunTestCases() { foreach (var testCase in localTestCases) { if (ct.IsCancellationRequested) { // Return a failed "cancelled" result only if // there were more test cases to work on. yield return new IntegrationTestResult { Success = false, Messages = new List<string> { "Test run cancelled" }, }; break; } yield return RunTestSafe(testCase); } } } private static IntegrationTestResult RunTestSafe(IntegrationTestCase testCase) { return new IntegrationTestResult { Success = false, TestName = testCase.Name, Messages = new List<string> { "No code to run tests yet" }, }; } private delegate IntegrationTestResult IntegrationTestRunner(string name); private struct IntegrationTestCase { public string Name; public IntegrationTestRunner IntegrationTestRunner; } private static readonly IntegrationTestCase[] testCases = { new IntegrationTestCase { Name = "Dummy test", IntegrationTestRunner = name => { return new IntegrationTestResult(); }, }, }; } }
mit
C#
e50c749126caae0030f88c63e63f6834bb2499b4
Disable parallelization on the AspNet Integration tests (#1762)
jskeet/gcloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,googleapis/google-cloud-dotnet,benwulfe/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,benwulfe/google-cloud-dotnet,iantalarico/google-cloud-dotnet,jskeet/google-cloud-dotnet,iantalarico/google-cloud-dotnet,evildour/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,evildour/google-cloud-dotnet,googleapis/google-cloud-dotnet
apis/Google.Cloud.Diagnostics.AspNet/Google.Cloud.Diagnostics.AspNet.IntegrationTests/AssemblyInfo.cs
apis/Google.Cloud.Diagnostics.AspNet/Google.Cloud.Diagnostics.AspNet.IntegrationTests/AssemblyInfo.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 Xunit; [assembly: CollectionBehavior(DisableTestParallelization = true)]
apache-2.0
C#
ae042c243425be4ac6472be69995482db9488a71
Create MapColumn.cs
lancyan/SQLServerSync
MapColumn.cs
MapColumn.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZD.SyncDB { public class MapColumn { public string Name { get; set; } public bool IsPrimaryKey { get; set; } public Type ColumnType { get; set; } } }
apache-2.0
C#
0a173be4579887823ff0ad1731bd77ab8a2a380c
Create c5p6.cs
jtibau/EjerciciosSebesta,jtibau/EjerciciosSebesta,jtibau/EjerciciosSebesta
c5p6.cs
c5p6.cs
using System; class c5p6 { static void Main() { for(int i = 0 ; i < 10 ; i++) { Console.WriteLine(i); } Console.WriteLine(i); //Intentando acceder a variable i } } //c5p6.cs(11,23): error CS0103: The name `i' does //not exist in the current context
unlicense
C#
c877e2929d7388bebdbb1fcfe65b8f4b15ad195f
enable migration of database
DatabaseApp-Team-Linnaeus/DatabasesApp,DatabaseApp-Team-Linnaeus/DatabasesApp
SupermarketsChain/SupermarketsChain.Data/Migrations/Configuration.cs
SupermarketsChain/SupermarketsChain.Data/Migrations/Configuration.cs
namespace SupermarketsChain.Data.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using SupermarketsChain.Models; internal sealed class Configuration : DbMigrationsConfiguration<SupermarketsChain.Data.SupermarketsChainDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(SupermarketsChain.Data.SupermarketsChainDbContext context) { context.Measures.Add(new Measure() { Name = "kilogram" }); } } }
mit
C#
db326038f073de9fa9ce4a9bcc87644d98087ecf
Add snippet getting messages prices for twilio-csharp 4.x
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets
pricing/get-messaging-country/get-messaging-country.4.x.cs
pricing/get-messaging-country/get-messaging-country.4.x.cs
// The C# helper library 5.x will support Pricing Messaging, for now we'll use a simple RestSharp HTTP client using RestSharp; using RestSharp.Authenticators; using System; using System.Collections.Generic; public class Example { public static void Main(string[] args) { // Find your Account SID and Auth Token at twilio.com/console const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; const string authToken = "your_auth_token"; var client = new RestClient(); client.Authenticator = new HttpBasicAuthenticator(accountSid, authToken); client.BaseUrl = new Uri("https://pricing.twilio.com/"); var request = new RestRequest(Method.GET); request.Resource = $"v1/Messaging/Countries/EE"; var country = client.Execute<PricingMessagingCountry>(request).Data; foreach (var price in country.InboundSmsPrices) { Console.WriteLine(price.NumberType); Console.WriteLine($"Current price {price.CurrentPrice} {country.PriceUnit}"); } } } class PricingMessagingCountry { public string PriceUnit { get; set; } public List<SmsPrice> InboundSmsPrices { get; set; } } class SmsPrice { public string NumberType { get; set; } public string BasePrice { get; set; } public string CurrentPrice { get; set; } }
mit
C#
5f96e34b1a183dfcf0f791d77c6a8add30e599dd
Add math extension
theezak/BloomFilters
TBag.BloomFilter.Test/MathExtensions.cs
TBag.BloomFilter.Test/MathExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TBag.BloomFilter.Test { internal static class MathExtensions { public static double Variance(this IEnumerable<int> source) { if (source == null) throw new ArgumentNullException("source"); int n = 0; double mean = 0; double M2 = 0; foreach (var x in source) { n++; double delta = (double)x - mean; mean += delta / n; M2 += delta * ((double)x - mean); } if (n < 2) throw new InvalidOperationException("Source must have at least 2 elements"); return (double)(M2 / (n - 1)); } } }
mit
C#
40571bbae89a9e53bbda7e0584bfecb8d03561b9
Fix test to use serializable classes now that ERLB clones objects on save.
ronnymgm/csla-light,jonnybee/csla,JasonBock/csla,jonnybee/csla,MarimerLLC/csla,jonnybee/csla,ronnymgm/csla-light,JasonBock/csla,BrettJaner/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,rockfordlhotka/csla,BrettJaner/csla,BrettJaner/csla,rockfordlhotka/csla
cslatest/Csla.Test/EditableRootList/ERitem.cs
cslatest/Csla.Test/EditableRootList/ERitem.cs
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.EditableRootList { [Serializable] public class ERitem : BusinessBase<ERitem> { string _data = string.Empty; public string Data { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _data; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (!_data.Equals(value)) { _data = value; PropertyHasChanged(); } } } protected override object GetIdValue() { return _data; } private ERitem() { /* require use of factory methods */ } private ERitem(string data) { _data = data; MarkOld(); } public static ERitem NewItem() { return new ERitem(); } public static ERitem GetItem(string data) { return new ERitem(data); } protected override void DataPortal_Insert() { ApplicationContext.GlobalContext["DP"] = "Insert"; } protected override void DataPortal_Update() { ApplicationContext.GlobalContext["DP"] = "Update"; } protected override void DataPortal_DeleteSelf() { ApplicationContext.GlobalContext["DP"] = "DeleteSelf"; } protected override void DataPortal_Delete(object criteria) { ApplicationContext.GlobalContext["DP"] = "Delete"; } } }
using System; using System.Collections.Generic; using System.Text; namespace Csla.Test.EditableRootList { public class ERitem : BusinessBase<ERitem> { string _data = string.Empty; public string Data { [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] get { CanReadProperty(true); return _data; } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] set { CanWriteProperty(true); if (!_data.Equals(value)) { _data = value; PropertyHasChanged(); } } } protected override object GetIdValue() { return _data; } private ERitem() { /* require use of factory methods */ } private ERitem(string data) { _data = data; MarkOld(); } public static ERitem NewItem() { return new ERitem(); } public static ERitem GetItem(string data) { return new ERitem(data); } protected override void DataPortal_Insert() { ApplicationContext.GlobalContext["DP"] = "Insert"; } protected override void DataPortal_Update() { ApplicationContext.GlobalContext["DP"] = "Update"; } protected override void DataPortal_DeleteSelf() { ApplicationContext.GlobalContext["DP"] = "DeleteSelf"; } protected override void DataPortal_Delete(object criteria) { ApplicationContext.GlobalContext["DP"] = "Delete"; } } }
mit
C#
dd38f0cb26e428b6ec6a77256a325a466cfd412c
Add RemoveClassAction
wieslawsoltes/AvaloniaBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Custom/RemoveClassAction.cs
src/Avalonia.Xaml.Interactions/Custom/RemoveClassAction.cs
using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Custom { /// <summary> /// Removes a specified <see cref="RemoveClassAction.ClassName"/> from <see cref="IStyledElement.Classes"/> collection when invoked. /// </summary> public class RemoveClassAction : AvaloniaObject, IAction { /// <summary> /// Identifies the <seealso cref="ClassName"/> avalonia property. /// </summary> public static readonly StyledProperty<string> ClassNameProperty = AvaloniaProperty.Register<RemoveClassAction, string>(nameof(ClassName)); /// <summary> /// Identifies the <seealso cref="StyledElement"/> avalonia property. /// </summary> public static readonly StyledProperty<IStyledElement?> StyledElementProperty = AvaloniaProperty.Register<RemoveClassAction, IStyledElement?>(nameof(StyledElement)); /// <summary> /// Gets or sets the class name that should be removed. This is a avalonia property. /// </summary> public string ClassName { get => GetValue(ClassNameProperty); set => SetValue(ClassNameProperty, value); } /// <summary> /// Gets or sets the target styled element that class name that should be removed from. This is a avalonia property. /// </summary> public IStyledElement? StyledElement { get => GetValue(StyledElementProperty); set => SetValue(StyledElementProperty, value); } /// <summary> /// Executes the action. /// </summary> /// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param> /// <param name="parameter">The value of this parameter is determined by the caller.</param> /// <returns>True if the class is successfully added; else false.</returns> public object Execute(object? sender, object? parameter) { var target = GetValue(StyledElementProperty) is { } ? StyledElement : sender as IStyledElement; if (target is null || string.IsNullOrEmpty(ClassName)) { return false; } if (target.Classes.Contains(ClassName)) { target.Classes.Remove(ClassName); } return true; } } }
mit
C#
48d4c797b34f69e9ee1be450eea3e7056cacbc01
Create CommandLineConfigurationExtensions.cs
tiksn/TIKSN-Framework
TIKSN.Core/Configuration/CommandLineConfigurationExtensions.cs
TIKSN.Core/Configuration/CommandLineConfigurationExtensions.cs
using System.Collections.Generic; using Microsoft.Extensions.Configuration; using TIKSN.Analytics.Logging.NLog; namespace TIKSN.Configuration { public static class CommandLineConfigurationExtensions { public static IConfigurationBuilder AddFrameworkCommandLine( this IConfigurationBuilder configurationBuilder, string[] args, IDictionary<string, string> switchMappings) { var frameworkSwitchMappings = MergeFrameworkSwitchMappings(switchMappings); return configurationBuilder.AddCommandLine(args, frameworkSwitchMappings); } private static IDictionary<string, string> GetFrameworkSwitchMappings() => new Dictionary<string, string> { { "--nlog-viewer-address", ConfigurationPath.Combine(RemoteNLogViewerOptions.RemoteNLogViewerConfigurationSection, nameof(RemoteNLogViewerOptions.Address)) }, { "--nlog-viewer-include-call-site", ConfigurationPath.Combine(RemoteNLogViewerOptions.RemoteNLogViewerConfigurationSection, nameof(RemoteNLogViewerOptions.IncludeCallSite)) }, { "--nlog-viewer-include-source-info", ConfigurationPath.Combine(RemoteNLogViewerOptions.RemoteNLogViewerConfigurationSection, nameof(RemoteNLogViewerOptions.IncludeSourceInfo)) } }; private static IDictionary<string, string> MergeFrameworkSwitchMappings(IDictionary<string, string> switchMappings) { var mappings = GetFrameworkSwitchMappings(); if (switchMappings is not null) { foreach (var item in switchMappings) { mappings[item.Key] = item.Value; } } return mappings; } public static IConfigurationBuilder AddFrameworkCommandLine( this IConfigurationBuilder configurationBuilder, string[] args) => configurationBuilder.AddFrameworkCommandLine(args, switchMappings: null); } }
mit
C#
46f4bd70b73aace82fc3133f97a98ed576089aef
Create UserDetail.cs
ryanmcdonough/CrowdSSO
UserDetail.cs
UserDetail.cs
public class UserDetail { public int ID { get; set; } public string Username { get; set; } public string Email { get; set; } public string FirstName { get; set; } public string LastName { get; set; } // Serialize public override string ToString() { JavaScriptSerializer serializer = new JavaScriptSerializer(); string result = serializer.Serialize(this); return result; } // Deserialize public static UserDetail FromString(string text) { JavaScriptSerializer serializer = new JavaScriptSerializer(); return serializer.Deserialize<UserDetail>(text); } }
mit
C#
e3218bc51da464a8c3033c2d75e78ae69e56de48
Fix EventSource test to be aware of ArrayPoolEventSource
rubo/corefx,mazong1123/corefx,richlander/corefx,DnlHarvey/corefx,rahku/corefx,dhoehna/corefx,billwert/corefx,stephenmichaelf/corefx,mmitche/corefx,yizhang82/corefx,richlander/corefx,wtgodbe/corefx,DnlHarvey/corefx,mmitche/corefx,zhenlan/corefx,shimingsg/corefx,MaggieTsang/corefx,gkhanna79/corefx,rahku/corefx,ViktorHofer/corefx,jlin177/corefx,rjxby/corefx,Jiayili1/corefx,axelheer/corefx,mazong1123/corefx,seanshpark/corefx,lggomez/corefx,BrennanConroy/corefx,stone-li/corefx,yizhang82/corefx,wtgodbe/corefx,dotnet-bot/corefx,zhenlan/corefx,ericstj/corefx,rjxby/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,dotnet-bot/corefx,Petermarcu/corefx,YoupHulsebos/corefx,the-dwyer/corefx,billwert/corefx,zhenlan/corefx,richlander/corefx,cydhaselton/corefx,gkhanna79/corefx,Petermarcu/corefx,dhoehna/corefx,mazong1123/corefx,parjong/corefx,rjxby/corefx,lggomez/corefx,mazong1123/corefx,krytarowski/corefx,twsouthwick/corefx,ViktorHofer/corefx,axelheer/corefx,JosephTremoulet/corefx,DnlHarvey/corefx,rubo/corefx,the-dwyer/corefx,seanshpark/corefx,Ermiar/corefx,alexperovich/corefx,nchikanov/corefx,yizhang82/corefx,parjong/corefx,marksmeltzer/corefx,weltkante/corefx,MaggieTsang/corefx,fgreinacher/corefx,DnlHarvey/corefx,ericstj/corefx,weltkante/corefx,nchikanov/corefx,ravimeda/corefx,jlin177/corefx,krk/corefx,marksmeltzer/corefx,parjong/corefx,nbarbettini/corefx,stephenmichaelf/corefx,parjong/corefx,Jiayili1/corefx,MaggieTsang/corefx,billwert/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,mmitche/corefx,ericstj/corefx,yizhang82/corefx,MaggieTsang/corefx,DnlHarvey/corefx,alexperovich/corefx,gkhanna79/corefx,krytarowski/corefx,ptoonen/corefx,tijoytom/corefx,dhoehna/corefx,mmitche/corefx,krytarowski/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,shimingsg/corefx,jlin177/corefx,Ermiar/corefx,Ermiar/corefx,nchikanov/corefx,Petermarcu/corefx,YoupHulsebos/corefx,seanshpark/corefx,tijoytom/corefx,alexperovich/corefx,mazong1123/corefx,dhoehna/corefx,rahku/corefx,Ermiar/corefx,krytarowski/corefx,richlander/corefx,Jiayili1/corefx,dhoehna/corefx,shimingsg/corefx,gkhanna79/corefx,mazong1123/corefx,seanshpark/corefx,twsouthwick/corefx,axelheer/corefx,rubo/corefx,ptoonen/corefx,stone-li/corefx,nchikanov/corefx,nbarbettini/corefx,Ermiar/corefx,the-dwyer/corefx,alexperovich/corefx,the-dwyer/corefx,axelheer/corefx,zhenlan/corefx,wtgodbe/corefx,ViktorHofer/corefx,nchikanov/corefx,Jiayili1/corefx,shimingsg/corefx,wtgodbe/corefx,alexperovich/corefx,seanshpark/corefx,billwert/corefx,Jiayili1/corefx,ViktorHofer/corefx,seanshpark/corefx,krk/corefx,nbarbettini/corefx,twsouthwick/corefx,jlin177/corefx,jlin177/corefx,stephenmichaelf/corefx,billwert/corefx,tijoytom/corefx,ravimeda/corefx,elijah6/corefx,parjong/corefx,zhenlan/corefx,krytarowski/corefx,MaggieTsang/corefx,elijah6/corefx,cydhaselton/corefx,rjxby/corefx,stone-li/corefx,weltkante/corefx,krk/corefx,tijoytom/corefx,dotnet-bot/corefx,marksmeltzer/corefx,axelheer/corefx,stone-li/corefx,rjxby/corefx,rahku/corefx,dhoehna/corefx,JosephTremoulet/corefx,elijah6/corefx,nbarbettini/corefx,twsouthwick/corefx,Petermarcu/corefx,Petermarcu/corefx,dotnet-bot/corefx,nchikanov/corefx,rjxby/corefx,krytarowski/corefx,ViktorHofer/corefx,wtgodbe/corefx,ravimeda/corefx,ptoonen/corefx,Ermiar/corefx,weltkante/corefx,twsouthwick/corefx,JosephTremoulet/corefx,nchikanov/corefx,Petermarcu/corefx,MaggieTsang/corefx,richlander/corefx,ptoonen/corefx,parjong/corefx,yizhang82/corefx,JosephTremoulet/corefx,tijoytom/corefx,billwert/corefx,gkhanna79/corefx,marksmeltzer/corefx,ericstj/corefx,krk/corefx,wtgodbe/corefx,krk/corefx,fgreinacher/corefx,cydhaselton/corefx,parjong/corefx,ravimeda/corefx,richlander/corefx,lggomez/corefx,Jiayili1/corefx,DnlHarvey/corefx,YoupHulsebos/corefx,elijah6/corefx,dotnet-bot/corefx,lggomez/corefx,gkhanna79/corefx,rubo/corefx,mmitche/corefx,jlin177/corefx,axelheer/corefx,weltkante/corefx,nbarbettini/corefx,fgreinacher/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,jlin177/corefx,twsouthwick/corefx,YoupHulsebos/corefx,cydhaselton/corefx,rahku/corefx,krk/corefx,ptoonen/corefx,the-dwyer/corefx,elijah6/corefx,zhenlan/corefx,JosephTremoulet/corefx,ptoonen/corefx,JosephTremoulet/corefx,mmitche/corefx,BrennanConroy/corefx,marksmeltzer/corefx,krk/corefx,ravimeda/corefx,yizhang82/corefx,Petermarcu/corefx,rahku/corefx,krytarowski/corefx,mazong1123/corefx,gkhanna79/corefx,tijoytom/corefx,stone-li/corefx,MaggieTsang/corefx,cydhaselton/corefx,BrennanConroy/corefx,weltkante/corefx,nbarbettini/corefx,richlander/corefx,stone-li/corefx,shimingsg/corefx,stone-li/corefx,alexperovich/corefx,shimingsg/corefx,seanshpark/corefx,rjxby/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,wtgodbe/corefx,cydhaselton/corefx,tijoytom/corefx,shimingsg/corefx,yizhang82/corefx,Jiayili1/corefx,ericstj/corefx,ravimeda/corefx,billwert/corefx,ravimeda/corefx,cydhaselton/corefx,ptoonen/corefx,elijah6/corefx,DnlHarvey/corefx,ericstj/corefx,zhenlan/corefx,marksmeltzer/corefx,the-dwyer/corefx,the-dwyer/corefx,stephenmichaelf/corefx,twsouthwick/corefx,lggomez/corefx,fgreinacher/corefx,nbarbettini/corefx,weltkante/corefx,elijah6/corefx,rahku/corefx,mmitche/corefx,stephenmichaelf/corefx,alexperovich/corefx,Ermiar/corefx,rubo/corefx,dhoehna/corefx,lggomez/corefx,lggomez/corefx,ViktorHofer/corefx,ericstj/corefx
src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestUtilities.cs
src/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestUtilities.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.Diagnostics.Tracing; using System.Diagnostics; using Xunit; using System; namespace BasicEventSourceTests { internal class TestUtilities { /// <summary> /// Confirms that there are no EventSources running. /// </summary> /// <param name="message">Will be printed as part of the Assert</param> public static void CheckNoEventSourcesRunning(string message = "") { var eventSources = EventSource.GetSources(); string eventSourceNames = ""; foreach (var eventSource in EventSource.GetSources()) { if (eventSource.Name != "System.Threading.Tasks.TplEventSource" && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource" && eventSource.Name != "System.Buffers.ArrayPoolEventSource") { eventSourceNames += eventSource.Name + " "; } } Debug.WriteLine(message); Assert.Equal("", eventSourceNames); } } }
// 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.Diagnostics.Tracing; using System.Diagnostics; using Xunit; using System; namespace BasicEventSourceTests { internal class TestUtilities { /// <summary> /// Confirms that there are no EventSources running. /// </summary> /// <param name="message">Will be printed as part of the Assert</param> public static void CheckNoEventSourcesRunning(string message = "") { var eventSources = EventSource.GetSources(); string eventSourceNames = ""; foreach (var eventSource in EventSource.GetSources()) { if (eventSource.Name != "System.Threading.Tasks.TplEventSource" && eventSource.Name != "System.Diagnostics.Eventing.FrameworkEventSource") { eventSourceNames += eventSource.Name + " "; } } Debug.WriteLine(message); Assert.Equal("", eventSourceNames); } } }
mit
C#
405b6c301e704b19bdad6f702ecef206d15e5551
Add AccountAvailableCash enum
jzebedee/lcapi
LCAPI/LCAPI/Models/AccountAvailableCash.cs
LCAPI/LCAPI/Models/AccountAvailableCash.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LendingClub.Models { /// <summary> /// Provides the most up to date value of the cash available in the investor's account. /// </summary> public class AccountAvailableCash { /// <summary> /// Investor ID /// </summary> public int InvestorId { get; set; } /// <summary> /// Available cash amount /// </summary> public decimal AvailableCash { get; set; } } }
agpl-3.0
C#
dab1197e4879367cf9949e336423e9a2a638c580
Rename the ___<P,F> overloads to __Convert<P,F> to allow for better type inference by the compiler.
rockfordlhotka/csla,rockfordlhotka/csla,jonnybee/csla,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,JasonBock/csla,BrettJaner/csla,jonnybee/csla,BrettJaner/csla,MarimerLLC/csla,ronnymgm/csla-light,BrettJaner/csla
cslalighttest/CslaLight.Testing/Server/EditableRootTests/MockEditableRoot.cs
cslalighttest/CslaLight.Testing/Server/EditableRootTests/MockEditableRoot.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Csla.Serialization; namespace Csla.Testing.Business.EditableRootTests { [Serializable] public partial class MockEditableRoot : BusinessBase<MockEditableRoot> { public static readonly Guid MockEditableRootId = new Guid("{7E7127CF-F22C-4903-BDCE-1714C81A9E89}"); #region Business Methods private static PropertyInfo<Guid> IdProperty = RegisterProperty( typeof(MockEditableRoot), new PropertyInfo<Guid>("Id")); private static PropertyInfo<string> NameProperty = RegisterProperty( typeof(MockEditableRoot), new PropertyInfo<string>("Name")); private static PropertyInfo<string> DataPortalMethodProperty = RegisterProperty( typeof(MockEditableRoot), new PropertyInfo<string>("DataPortalMethod")); public Guid Id { get { return GetProperty(IdProperty); } } private string _name = NameProperty.DefaultValue; public string Name { get { return GetProperty(NameProperty, _name); } set { SetProperty(NameProperty, ref _name, value); } } public string DataPortalMethod { get { return GetProperty(DataPortalMethodProperty); } set { SetProperty(DataPortalMethodProperty, value); } } public override string ToString() { return Id.ToString(); } #endregion #region Validation Rules //protected override void AddBusinessRules() //{ // // TODO: add business rules //} #endregion #region Authorization Rules //protected override void AddAuthorizationRules() //{ // // add AuthorizationRules here //} //protected static void AddObjectAuthorizationRules() //{ // // add object-level authorization rules here //} #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using Csla.Serialization; namespace Csla.Testing.Business.EditableRootTests { [Serializable] public partial class MockEditableRoot : BusinessBase<MockEditableRoot> { public static readonly Guid MockEditableRootId = new Guid("{7E7127CF-F22C-4903-BDCE-1714C81A9E89}"); #region Business Methods private static PropertyInfo<Guid> IdProperty = RegisterProperty<Guid>( typeof(MockEditableRoot), new PropertyInfo<Guid>("Id")); private static PropertyInfo<string> NameProperty = RegisterProperty<string>( typeof(MockEditableRoot), new PropertyInfo<string>("Name")); private static PropertyInfo<string> DataPortalMethodProperty = RegisterProperty<string>( typeof(MockEditableRoot), new PropertyInfo<string>("DataPortalMethod")); public Guid Id { get { return GetProperty<Guid>(IdProperty); } } public string Name { get { return GetProperty<string>(NameProperty); } set { SetProperty<string>(NameProperty, value); } } public string DataPortalMethod { get { return GetProperty<string>(DataPortalMethodProperty); } set { SetProperty<string>(DataPortalMethodProperty, value); } } public override string ToString() { return Id.ToString(); } #endregion #region Validation Rules //protected override void AddBusinessRules() //{ // // TODO: add business rules //} #endregion #region Authorization Rules //protected override void AddAuthorizationRules() //{ // // add AuthorizationRules here //} //protected static void AddObjectAuthorizationRules() //{ // // add object-level authorization rules here //} #endregion } }
mit
C#
bf7532998075a94094c6b5d63de3b2d1b0a4896a
Update XML comment of `ClearsValueUsingCtrlADeleteKeysAttribute`
atata-framework/atata,atata-framework/atata
src/Atata/Attributes/Behaviors/ValueClear/ClearsValueUsingCtrlADeleteKeysAttribute.cs
src/Atata/Attributes/Behaviors/ValueClear/ClearsValueUsingCtrlADeleteKeysAttribute.cs
using System.Runtime.InteropServices; using OpenQA.Selenium; namespace Atata { /// <summary> /// Represents the behavior for control value clearing by performing "Ctrl+A, Delete" ("Cmd+A, Delete" on macOS) keyboard shortcut. /// </summary> public class ClearsValueUsingCtrlADeleteKeysAttribute : ValueClearBehaviorAttribute { /// <inheritdoc/> public override void Execute<TOwner>(IUIComponent<TOwner> component) { var scopeElement = component.Scope; var platformSpecificKey = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? Keys.Command : Keys.Control; component.Owner.Driver.Perform(x => x .KeyDown(scopeElement, platformSpecificKey) .SendKeys("a") .KeyUp(platformSpecificKey) .SendKeys(Keys.Delete)); } } }
using System.Runtime.InteropServices; using OpenQA.Selenium; namespace Atata { /// <summary> /// Represents the behavior for control value clearing by performing "Ctrl+A, Delete" keyboard shortcut. /// </summary> public class ClearsValueUsingCtrlADeleteKeysAttribute : ValueClearBehaviorAttribute { /// <inheritdoc/> public override void Execute<TOwner>(IUIComponent<TOwner> component) { var scopeElement = component.Scope; var platformSpecificKey = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? Keys.Command : Keys.Control; component.Owner.Driver.Perform(x => x .KeyDown(scopeElement, platformSpecificKey) .SendKeys("a") .KeyUp(platformSpecificKey) .SendKeys(Keys.Delete)); } } }
apache-2.0
C#
16bf2d1498b5e652bb52b000579530953c2319ac
Remove unused LogCallback
treziac/confluent-kafka-dotnet,treziac/confluent-kafka-dotnet,MrGlenThomas/confluent-kafka-dotnet,ah-/rdkafka-dotnet,MaximGurschi/rdkafka-dotnet,MrGlenThomas/confluent-kafka-dotnet,bjornicus/confluent-kafka-dotnet,bjornicus/confluent-kafka-dotnet
src/RdKafka/Library.cs
src/RdKafka/Library.cs
using System; using System.Runtime.InteropServices; using RdKafka.Internal; namespace RdKafka { public static class Library { /// <summary> /// Returns the librdkafka version as integer. /// /// Interpreted as hex MM.mm.rr.xx: /// - MM = Major /// - mm = minor /// - rr = revision /// - xx = pre-release id (0xff is the final release) /// /// E.g.: \c 0x000901ff = 0.9.1 /// </summary> public static int Version => (int) LibRdKafka.version(); /// <summary> /// The librdkafka version as string. /// </summary> public static string VersionString => Marshal.PtrToStringAnsi(LibRdKafka.version_str()); /// <summary> /// List of the supported debug contexts. /// </summary> public static string[] DebugContexts => Marshal.PtrToStringAnsi(LibRdKafka.get_debug_contexts()).Split(','); public static void SetLogLevel(int logLevel) { LibRdKafka.set_log_level(IntPtr.Zero, (IntPtr) logLevel); } /// <summary> /// Wait for all rdkafka objects to be destroyed. /// /// Returns if all kafka objects are now destroyed, /// or throw TimeoutException if the timeout was reached. /// /// Since RdKafka handle deletion is an async operation the /// WaitDestroyed() function can be used for applications where /// a clean shutdown is required. /// </summary> public static void WaitDestroyed(long timeoutMs) { if ((long) LibRdKafka.wait_destroyed((IntPtr) timeoutMs) != 0) { throw new TimeoutException(); } } } }
using System; using System.Runtime.InteropServices; using RdKafka.Internal; namespace RdKafka { public static class Library { public delegate void LogCallback(string handle, int level, string fac, string buf); /// <summary> /// Returns the librdkafka version as integer. /// /// Interpreted as hex MM.mm.rr.xx: /// - MM = Major /// - mm = minor /// - rr = revision /// - xx = pre-release id (0xff is the final release) /// /// E.g.: \c 0x000901ff = 0.9.1 /// </summary> public static int Version => (int) LibRdKafka.version(); /// <summary> /// The librdkafka version as string. /// </summary> public static string VersionString => Marshal.PtrToStringAnsi(LibRdKafka.version_str()); /// <summary> /// List of the supported debug contexts. /// </summary> public static string[] DebugContexts => Marshal.PtrToStringAnsi(LibRdKafka.get_debug_contexts()).Split(','); public static void SetLogLevel(int logLevel) { LibRdKafka.set_log_level(IntPtr.Zero, (IntPtr) logLevel); } /// <summary> /// Wait for all rdkafka objects to be destroyed. /// /// Returns if all kafka objects are now destroyed, /// or throw TimeoutException if the timeout was reached. /// /// Since RdKafka handle deletion is an async operation the /// WaitDestroyed() function can be used for applications where /// a clean shutdown is required. /// </summary> public static void WaitDestroyed(long timeoutMs) { if ((long) LibRdKafka.wait_destroyed((IntPtr) timeoutMs) != 0) { throw new TimeoutException(); } } } }
apache-2.0
C#
ea46f26e9540ca2683bfdacbeadc22c3115c023d
Add Support for Contentment Content blocks.
KevinJump/uSync,KevinJump/uSync,KevinJump/uSync
uSync.Community.Contrib/Mappers/ContentmentContentBlocks.cs
uSync.Community.Contrib/Mappers/ContentmentContentBlocks.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using Umbraco.Cms.Core.Services; using Umbraco.Extensions; using uSync.Core.Dependency; using uSync.Core.Mapping; namespace uSync.Community.Contrib.Mappers { /// <summary> /// value mapper for Contentment content blocks. /// </summary> public class ContentmentContentBlocks : SyncNestedValueMapperBase, ISyncMapper { public ContentmentContentBlocks(IEntityService entityService, Lazy<SyncValueMapperCollection> mapperCollection, IContentTypeService contentTypeService, IDataTypeService dataTypeService) : base(entityService, mapperCollection, contentTypeService, dataTypeService) { } public override string Name => "Contentment content block mapper"; public override string[] Editors => new string[] { "Umbraco.Community.Contentment.ContentBlocks" }; /// <summary> /// get the formatted export value, /// </summary> /// <remarks> /// for 99% of the time you don't need to do this, but there can be formatting /// issues with internal values (notably Umbraco.Datattime) so we recurse in to /// ensure the format of other nested values comes out at we expect it to. /// </remarks> /// <param name="value"></param> /// <param name="editorAlias"></param> /// <returns></returns> public override string GetExportValue(object value, string editorAlias) { var stringValue = GetValueAs<string>(value); if (string.IsNullOrWhiteSpace(stringValue) || !stringValue.DetectIsJson()) return value.ToString(); var elements = JsonConvert.DeserializeObject<JArray>(stringValue); if (elements == null || !elements.Any()) return value.ToString(); foreach(var item in elements.Cast<JObject>()) { var itemValue = item.Value<JObject>("value"); if (itemValue == null) continue; var doctype = GetDocTypeByKey(item, "elementType"); if (doctype == null) continue; item["value"] = GetExportProperties(itemValue, doctype); } return JsonConvert.SerializeObject(elements, Formatting.Indented); } public override IEnumerable<uSyncDependency> GetDependencies(object value, string editorAlias, DependencyFlags flags) { var stringValue = GetValueAs<string>(value); if (string.IsNullOrWhiteSpace(stringValue) || !stringValue.DetectIsJson()) return Enumerable.Empty<uSyncDependency>(); var elements = JsonConvert.DeserializeObject<JArray>(stringValue); if (elements == null || !elements.Any()) return Enumerable.Empty<uSyncDependency>(); var dependencies = new List<uSyncDependency>(); foreach(var item in elements.Cast<JObject>()) { var itemValue = item.Value<JObject>("value"); if (itemValue == null) continue; var doctype = GetDocTypeByKey(item, "elementType"); if (doctype == null) continue; if (flags.HasFlag(DependencyFlags.IncludeDependencies)) { var doctypeDependency = CreateDocTypeDependency(doctype.Alias, flags); if (doctypeDependency != null) dependencies.Add(doctypeDependency); } dependencies.AddRange(GetPropertyDependencies(itemValue, doctype, flags)); } return dependencies; } } }
mpl-2.0
C#
0c7ef7f899ba3021705074af9f37f82f54abcd64
Add Database methods
sjrawlins/JobSearchScorecard
JobSearchScorecard.PCL/Data/ScorecardDatabase.cs
JobSearchScorecard.PCL/Data/ScorecardDatabase.cs
using System; using System.Diagnostics; using SQLite; using System.Collections.Generic; using System.Linq; using Xamarin.Forms; namespace JobSearchScorecard { public class ScorecardDatabase { static object locker = new object (); SQLiteConnection database; public ScorecardDatabase() { database = DependencyService.Get<ISQLite> ().GetConnection (); // create the tables database.CreateTable<Task>(); database.CreateTable<Period> (); if (database.Table<Period> ().Count() == 0) { // only insert the data if it doesn't already exist var newPeriod = new Period (); database.Insert (newPeriod); } } public Period GetActivePeriod() { IEnumerable<Period> periodRows; lock (locker) { periodRows = database.Query<Period> ("select * from [Period] where [EndDt] > ?", DateTime.Now); if (periodRows == null) { throw new Exception ("Current period not found in database"); } return periodRows.First (); // For some reason the following did not work for me (never got to the bottom of it & decided to // re-write the query as Query<Period> instead of Table //var query = database.Table<Period> ().Where (p => p.EndDT > DateTime.Now); //return query; } } public IEnumerable<Task> GetTasks () { lock (locker) { return (from i in database.Table<Task>() select i).ToList(); } } public IEnumerable<Task> GetTasksWithinPeriod () { lock (locker) { return database.Query<Task> ("SELECT * FROM [Task]"); // WHERE [DT]"); // need sub-query for active period to know WHERE [DT] BETWEEN start_date and max_date } } public Task GetTask (int id) { lock (locker) { return database.Table<Task>().FirstOrDefault(x => x.ID == id); } } public int SaveTask (Task item) { lock (locker) { if (item.ID != 0) { database.Update(item); return item.ID; } else { return database.Insert(item); } } } public int DeleteTask(int id) { lock (locker) { return database.Delete<Task>(id); } } public int DeleteCurrentPeriodTasks() { // delete all rows in Task table EXCEPT for once-in-a-lifetime lock (locker) { return database.Execute ("DELETE FROM [Task] WHERE [OneTimeOnly] = 0"); } } public void DeleteAll() { lock (locker) { database.DeleteAll<Task> (); database.DeleteAll<Period> (); } } public int SavePeriod() { int sqlReturn = 0; lock (locker) { // For Debug purposes, show how many rows in [Period] now var countPeriod = database.Table<Period> ().Count(); Debug.WriteLine ("Before adding new cycle, [Period] has " + countPeriod + " rows"); var setNow = DateTime.Now; sqlReturn = database.Execute ( "update [Period] set [EndDt] = ? where [EndDt] > ? ", setNow, setNow); if (sqlReturn > 1) { throw new Exception("Failed to properly UPDATE row to end current [Period]. RC=" + sqlReturn); } var newPeriod = new Period (); sqlReturn = database.Insert (newPeriod); if (sqlReturn != 1) { throw new Exception("Failed to properly INSERT new row in [Period]. RC=" + sqlReturn); } countPeriod = database.Table<Period> ().Count(); Debug.WriteLine ("[Period] now has " + countPeriod + " rows"); return sqlReturn; } } } }
bsd-3-clause
C#
0ace5e5843af895841267acab0a63917aeb4fb06
Add new tables
olebg/Movie-Theater-Project
MovieTheater/MovieTheater.Models/HallShedules.cs
MovieTheater/MovieTheater.Models/HallShedules.cs
namespace MovieTheater.Models { public class HallShedules { } }
mit
C#
76fcb92fe72a4ccdfe70261e0c69628ea4e80430
Add snippet to list voice countries for Twilio-csharp 4.x
TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,teoreteetik/api-snippets,TwilioDevEd/api-snippets
pricing/list-messaging-countries/list-messaging-countries.4.x.cs
pricing/list-messaging-countries/list-messaging-countries.4.x.cs
// The C# helper library 5.x will support Pricing Messaging, for now we'll use a simple RestSharp HTTP client using RestSharp; using RestSharp.Authenticators; using System; using System.Collections.Generic; class VoiceCountry { public string Country { get; set; } public string IsoCountry { get; set; } public Uri Url { get; set; } } class VoiceCountriesResponse { public List<VoiceCountry> Countries { get; set; } public Meta Meta { get; set; } } class Meta { public int Page { get; set; } public int PageSize { get; set; } public Uri FirstPageUrl { get; set; } public Uri PreviousPageUrl { get; set; } public Uri Url { get; set; } public Uri NextPageUrl { get; set; } public string Key { get; set; } } class Example { public static void Main(string[] args) { // Find your Account SID and Auth Token at twilio.com/console const string accountSid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; const string authToken = "your_auth_token"; var client = new RestClient(); client.Authenticator = new HttpBasicAuthenticator(accountSid, authToken); client.BaseUrl = new Uri("https://pricing.twilio.com/"); var request = new RestRequest(Method.GET); request.Resource = "v1/Voice/Countries"; var response = client.Execute<VoiceCountriesResponse>(request); while (response.Data.Meta.NextPageUrl != null) { foreach (var country in response.Data.Countries) { Console.WriteLine(country.IsoCountry); } request.Resource = response.Data.Meta.NextPageUrl.PathAndQuery; response = client.Execute<VoiceCountriesResponse>(request); } } }
mit
C#
6d394e0fbb8c69a39eb1ae16808e77f21e07be85
Create SumOfSelfPowers.cs
DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges
Sum_Of_Self_Powers/SumOfSelfPowers.cs
Sum_Of_Self_Powers/SumOfSelfPowers.cs
using System; namespace SumOfSelfPowers { class MainClass { public static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("This program requires 1 integer input"); Environment.Exit(0); } long totalSum = 0; int inputtedNum = Convert.ToInt32(args[0]); for (int i = 1; i <= inputtedNum; i++) { long val = (long)Math.Pow(i, i); totalSum += val; Console.WriteLine(val); } Console.WriteLine("Total Sum - " + totalSum); Console.WriteLine(); Console.ReadKey(); } } }
unlicense
C#
515b0bf3db095273818ee9a98d66c6d114707c06
Add Debug.cs file
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
UartOscilloscope/CSharpFiles/Debug.cs
UartOscilloscope/CSharpFiles/Debug.cs
/******************************************************************** * Develop by Jimmy Hu * * This program is licensed under the Apache License 2.0. * * Debug.cs * * 本檔案用於宣告偵錯相關工具物件 * ******************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace QueueDataGraphic.CSharpFiles { // namespace start, 進入命名空間 class Debug // Debug class, Debug類別 { // Debug class start, 進入Debug類別 public readonly static Debug Instance = new Debug(); // Debug class instance, 設計Debug存取介面 /// <summary> /// DebugMode would be setted "true" during debugging. /// 在偵錯模式中將DebugMode設為true /// </summary> public readonly static bool DebugMode = true; // DebugMode variable /// <summary> /// ShowQueueData method could print the data in InputQueue. /// ShowQueueData用於顯示輸入Queue的資料 /// </summary> /// <param name="InputQueue">欲顯示內容之Queue</param> public void ShowQueueData(Queue<object> InputQueue) // ShowQueueData method, ShowQueueData方法 { // ShowQueueData method start, 進入ShowQueueData方法 foreach (var item in InputQueue) // get each element in InputQueue, 取得InputQueue各項元素 { // foreach statement start, 進入foreach敘述 Console.WriteLine(item.ToString()); // show element data, 顯示元素資料 } // foreach statement end, 結束foreach敘述 } // ShowQueueData method end, 結束ShowQueueData方法 } // Debug class eud, 結束Debug類別 } // namespace end, 結束命名空間
apache-2.0
C#
d7b5934636a97342e270ddc3586a6d1b0c602216
Create CameraSetup.cs
BorisMilkman/PathFinding3D
Unity3d/Scripts/Camera/CameraSetup.cs
Unity3d/Scripts/Camera/CameraSetup.cs
using UnityEngine; using System.Collections; public class CameraSetup : MonoBehaviour { void Start () { gameObject.transform.position = new Vector3(30, 30, 30); gameObject.transform.Rotate(new Vector3(35, 225, 0)); } }
mit
C#
1989baf76ee5ad72082a937049ee843c20909ec0
添加 Xlsx 类型字段;
hjj2017/xgame-code_server,hjj2017/xgame-code_server,hjj2017/xgame-code_server,hjj2017/xgame-code_server
client_wpf/Xgame.GamePart/Tmpl/XlsxTmplServ.cs
client_wpf/Xgame.GamePart/Tmpl/XlsxTmplServ.cs
using System; namespace Xgame.GamePart.Tmpl { /// <summary> /// Xlsx 模板服务 /// </summary> public sealed class XlsxTmplServ { /** 单例对象 */ public static readonly XlsxTmplServ OBJ = new XlsxTmplServ(); #region 类构造器 /// <summary> /// 类默认构造器 /// </summary> private XlsxTmplServ() { this.Lang = "zh_CN"; } #endregion /// <summary> /// 获取或设置 Excel 文件所在目录 /// </summary> public string XlsxFileDir { get; set; } /// <summary> /// 获取或设置多语言环境, 默认 = zh_CN 简体中文 /// </summary> public string Lang { get; set; } /// <summary> /// 获取或设置输出类文件到目标目录, 主要用于调试 /// </summary> public string DebugClazzToDir { get; set; } } }
apache-2.0
C#
0e941adaf80554f0c78aaa2322fc3b564310cfab
Create CommandDataModel
DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho,DimitarDKirov/Forum-Paulo-Coelho
Forum-Paulo-Coelho/ForumSystem.Api/Models/CommentDataModel.cs
Forum-Paulo-Coelho/ForumSystem.Api/Models/CommentDataModel.cs
namespace ForumSystem.Api.Models { using ForumSystem.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Web; public class CommentDataModel { public static Expression<Func<Comment, CommentDataModel>> FromComment { get { return c => new CommentDataModel { UserName = c.User.UserName, Content = c.Content, CommentDate = c.CommentDate, Id = c.Id }; } } public int Id { get; set; } public string UserName { get; set; } public DateTime CommentDate { get; set; } public string Content { get; set; } [Required] public int PostId { get; set; } } }
mit
C#
bbce843fe0793278bc5b0f428f303fc6de42a8dc
Create Graphics_Blit.cs
UnityCommunity/UnityLibrary
Docs/Graphics/Graphics_Blit.cs
Docs/Graphics/Graphics_Blit.cs
using UnityEngine; using System.Collections; // Example: Using Graphics.Blit to draw a full screen texture, with particle shader // Usage: Attach to Main Camera // Optional: Assign some texture into the displayTexture field in inspector public class Graphics_Blit : MonoBehaviour { public Texture displayTexture; // assign texture you want to blit fullscreen Material mat; // material(shader) to use for blitting void Awake() { if (displayTexture == null) displayTexture = Texture2D.whiteTexture; // use white texture, if nothing is set // use particle shader for the Blit material var shader = Shader.Find("Particles/Multiply (Double)"); mat = new Material(shader); } // This function is called only if the script is attached to the camera and is enabled void OnPostRender() { // Copies source texture into destination render texture with a shader // Destination RenderTexture is null to blit directly to screen Graphics.Blit(displayTexture, null, mat); } }
mit
C#
63e9cef1754bd961e2a1c0e1a4c5fe18d88ba8c7
Create Timeseries.cs
danesparza/MailChimp.NET,marmind/MailChimp.NET-APIv2
MailChimp/Reports/Timeseries.cs
MailChimp/Reports/Timeseries.cs
using System.Runtime.Serialization; namespace MailChimp.Reports { /// <summary> /// optional - various extra options based on the campaign type /// </summary> [DataContract] public class Industry { /// <summary> ///the selected industry /// </summary> [DataMember(Name = "type")] public string Type { get; set; } /// <summary> ///industry open rate /// </summary> [DataMember(Name = "open_rate")] public float OpenRate { get; set; } /// <summary> ///industry click rate /// </summary> [DataMember(Name = "click_rate")] public float ClickRate { get; set; } /// <summary> ///industry bounce rate /// </summary> [DataMember(Name = "bounce_rate")] public float BounceRate { get; set; } /// <summary> ///industry unopen rate /// </summary> [DataMember(Name = "unopen_rate")] public float UnopenRate { get; set; } /// <summary> ///industry unsub rate /// </summary> [DataMember(Name = "unsub_rate")] public float UnsubRate { get; set; } /// <summary> ///industry abuse rate /// </summary> [DataMember(Name = "abuse_rate")] public float AbuseRate { get; set; } } }
mit
C#
520635d40565f39d410f1e72cc9a163e2687401c
Add ContextAccessor
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
src/WeihanLi.Common/Helpers/ContextAccessor.cs
src/WeihanLi.Common/Helpers/ContextAccessor.cs
// Copyright (c) Weihan Li. All rights reserved. // Licensed under the Apache license. namespace WeihanLi.Common.Helpers; public sealed class ContextAccessor<TContext> where TContext: class { private static readonly AsyncLocal<ContextHolder<TContext>> ContextCurrent = new(); public static TContext? Context { get { return ContextCurrent.Value?.Value; } set { var holder = ContextCurrent.Value; if (holder != null) { // Clear current Value trapped in the AsyncLocals, as its done. holder.Value = null; } if (value != null) { // Use an object indirection to hold the Value in the AsyncLocal, // so it can be cleared in all ExecutionContexts when its cleared. ContextCurrent.Value = new ContextHolder<TContext> { Value = value }; } } } } file sealed class ContextHolder<TContext> where TContext: class { public TContext? Value; }
mit
C#
c42caaa1017d8727a6f71d74fd24d0e4237e47e2
Fix a small, old typo
halforbit/data-stores
Halforbit.DataStores/FileStores/LocalStorage/Attributes/RootPathAttribute.cs
Halforbit.DataStores/FileStores/LocalStorage/Attributes/RootPathAttribute.cs
using Halforbit.DataStores.FileStores.Implementation; using Halforbit.DataStores.FileStores.LocalStorage.Implementation; using Halforbit.Facets.Attributes; using System; namespace Halforbit.DataStores.FileStores.LocalStorage.Attributes { public class RootPathAttribute : FacetParameterAttribute { public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { } public override Type TargetType => typeof(LocalFileStore); public override string ParameterName => "rootPath"; public override Type[] ImpliedTypes => new Type[] { typeof(FileStoreDataStore<,>) }; } }
using Halforbit.DataStores.FileStores.Implementation; using Halforbit.DataStores.FileStores.LocalStorage.Implementation; using Halforbit.Facets.Attributes; using System; namespace HalfOrbit.DataStores.FileStores.LocalStorage.Attributes { public class RootPathAttribute : FacetParameterAttribute { public RootPathAttribute(string value = null, string configKey = null) : base(value, configKey) { } public override Type TargetType => typeof(LocalFileStore); public override string ParameterName => "rootPath"; public override Type[] ImpliedTypes => new Type[] { typeof(FileStoreDataStore<,>) }; } }
mit
C#
42f3f30a2538abf324e00e92df60b523d4d3ea3e
Fix default value.
nuitsjp/KAMISHIBAI
Sample/SampleBrowser/SampleBrowser.ViewModel/Page/NavigationMenuViewModel.cs
Sample/SampleBrowser/SampleBrowser.ViewModel/Page/NavigationMenuViewModel.cs
using System.Windows.Input; using Kamishibai; using Microsoft.Toolkit.Mvvm.Input; using PropertyChanged; namespace SampleBrowser.ViewModel.Page; [AddINotifyPropertyChangedInterface] public class NavigationMenuViewModel : IPausingAware { private readonly IPresentationService _presentationService; public NavigationMenuViewModel(IPresentationService presentationService) { _presentationService = presentationService; } public bool BlockNavigation { get; set; } public string Message { get; set; } = string.Empty; public ICommand NavigateByTypeCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync(typeof(ContentViewModel))); public ICommand NavigateByGenericTypeCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync<ContentViewModel>()); public string Message1 { get; set; } = "Hello, Instance!"; public ICommand NavigateByInstanceCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync(new MessageViewModel(Message1, _presentationService))); public string Message2 { get; set; } = "Hello, Callback!"; public ICommand NavigateWithCallbackCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync<ContentViewModel>(viewModel => viewModel.Message = Message2)); public string Message3 { get; set; } = "Hello, Parameter!"; public ICommand NavigateWithSafeParameterCommand => new AsyncRelayCommand(() => _presentationService.NavigateToMessageAsync(Message3)); public bool OnPausing() { if (BlockNavigation) { Message = "Navigation blocked."; return false; } Message = string.Empty; return true; } }
using System.Windows.Input; using Kamishibai; using Microsoft.Toolkit.Mvvm.Input; using PropertyChanged; namespace SampleBrowser.ViewModel.Page; [AddINotifyPropertyChangedInterface] public class NavigationMenuViewModel : IPausingAware { private readonly IPresentationService _presentationService; public NavigationMenuViewModel(IPresentationService presentationService) { _presentationService = presentationService; } public bool BlockNavigation { get; set; } public string Message { get; set; } public ICommand NavigateByTypeCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync(typeof(ContentViewModel))); public ICommand NavigateByGenericTypeCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync<ContentViewModel>()); public string Message1 { get; set; } = "Hello, Instance!"; public ICommand NavigateByInstanceCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync(new MessageViewModel(Message1, _presentationService))); public string Message2 { get; set; } = "Hello, Callback!"; public ICommand NavigateWithCallbackCommand => new AsyncRelayCommand(() => _presentationService.NavigateAsync<ContentViewModel>(viewModel => viewModel.Message = Message2)); public string Message3 { get; set; } = "Hello, Parameter!"; public ICommand NavigateWithSafeParameterCommand => new AsyncRelayCommand(() => _presentationService.NavigateToMessageAsync(Message3)); public bool OnPausing() { if (BlockNavigation) { Message = "Navigation blocked."; return false; } Message = string.Empty; return true; } }
mit
C#
cd3b5e23282f089e59b737407e270bf035372b66
Add 'number of pages' config for DeleteItemPage
dustinleavins/LeavinsSoftware.CIB
LeavinsSoftware.Collection.Program/DeleteItemPage.xaml.cs
LeavinsSoftware.Collection.Program/DeleteItemPage.xaml.cs
// Copyright (c) 2013, 2014 Dustin Leavins // See the file 'LICENSE.txt' for copying permission. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using KSMVVM.WPF; using KSMVVM.WPF.Messaging; using LeavinsSoftware.Collection.Models; using LeavinsSoftware.Collection.Program.ViewModels; namespace LeavinsSoftware.Collection.Program { /// <summary> /// Interaction logic for DeleteItemPage.xaml /// </summary> public partial class DeleteItemPage : Page { public class DeleteItemPageConfig { /// <summary> /// Number of pages to go back after successful deletion. /// </summary> /// <remarks> /// Default - 2 /// </remarks> public int PagesToGoBack { get; set; } } private DeleteItemPage(DeleteItemPageConfig config = null) { InitializeComponent(); Configuration = config; } public static DeleteItemPage Page<T>(T item, DeleteItemPageConfig config = null) where T : Item { var page = new DeleteItemPage(config); page.DataContext = DeleteItemViewModel.New(item, new PageNavigationService(page)); return page; } void Page_Loaded(object sender, RoutedEventArgs e) { BasicMessenger.Default.Register(MessageIds.App_ItemDeleted, OnItemDeleted); } void Page_Unloaded(object sender, RoutedEventArgs e) { BasicMessenger.Default.Unregister(MessageIds.App_ItemDeleted); } void OnItemDeleted() { var configInstance = Configuration ?? DefaultConfig; for(int x = 0; x < configInstance.PagesToGoBack; ++x) { NavigationService.GoBack(); } } private static DeleteItemPageConfig DefaultConfig { get { return new DeleteItemPageConfig() { PagesToGoBack = 2 }; } } private readonly DeleteItemPageConfig Configuration; } }
// Copyright (c) 2013, 2014 Dustin Leavins // See the file 'LICENSE.txt' for copying permission. using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using KSMVVM.WPF; using KSMVVM.WPF.Messaging; using LeavinsSoftware.Collection.Models; using LeavinsSoftware.Collection.Program.ViewModels; namespace LeavinsSoftware.Collection.Program { /// <summary> /// Interaction logic for DeleteItemPage.xaml /// </summary> public partial class DeleteItemPage : Page { private DeleteItemPage() { InitializeComponent(); } public static DeleteItemPage Page<T>(T item) where T : Item { var page = new DeleteItemPage(); page.DataContext = DeleteItemViewModel.New(item, new PageNavigationService(page)); return page; } void Page_Loaded(object sender, RoutedEventArgs e) { BasicMessenger.Default.Register(MessageIds.App_ItemDeleted, OnItemDeleted); } void Page_Unloaded(object sender, RoutedEventArgs e) { BasicMessenger.Default.Unregister(MessageIds.App_ItemDeleted); } void OnItemDeleted() { NavigationService.GoBack(); NavigationService.GoBack(); } } }
mit
C#
68912c257276199a48cab8eaf77dad4f771c2030
Create Sequence Marker only if it is used.
linksplatform/Crawler,linksplatform/Crawler,linksplatform/Crawler
Platform/Platform.Data.Core/Sequences/SequencesOptions.cs
Platform/Platform.Data.Core/Sequences/SequencesOptions.cs
using System; using Platform.Data.Core.Pairs; namespace Platform.Data.Core.Sequences { public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function. { public ulong SequenceMarkerLink; public bool UseCascadeUpdate; public bool UseCascadeDelete; public bool UseSequenceMarker; public bool UseCompression; public bool UseGarbageCollection; public bool EnforceSingleSequenceVersionOnWrite; // TODO: Реализовать компактификацию при чтении //public bool EnforceSingleSequenceVersionOnRead; //public bool UseRequestMarker; //public bool StoreRequestResults; public void InitOptions(ILinks<ulong> links) { if (UseSequenceMarker && SequenceMarkerLink == LinksConstants.Null) SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself); } public void ValidateOptions() { if (UseGarbageCollection && !UseSequenceMarker) throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on."); } } }
using System; using Platform.Data.Core.Pairs; namespace Platform.Data.Core.Sequences { public struct SequencesOptions // TODO: To use type parameter <TLink> the ILinks<TLink> must contain GetConstants function. { public ulong SequenceMarkerLink; public bool UseCascadeUpdate; public bool UseCascadeDelete; public bool UseSequenceMarker; public bool UseCompression; public bool UseGarbageCollection; public bool EnforceSingleSequenceVersionOnWrite; public bool EnforceSingleSequenceVersionOnRead; // TODO: Реализовать компактификацию при чтении public bool UseRequestMarker; public bool StoreRequestResults; public void InitOptions(ILinks<ulong> links) { if (SequenceMarkerLink == LinksConstants.Null) SequenceMarkerLink = links.Create(LinksConstants.Itself, LinksConstants.Itself); } public void ValidateOptions() { if (UseGarbageCollection && !UseSequenceMarker) throw new NotSupportedException("To use garbage collection UseSequenceMarker option must be on."); } } }
unlicense
C#
c17774e23c6b770d07cd2d9ea059ca1bcc4dff1a
Add xmldoc
smoogipooo/osu,peppy/osu-new,peppy/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,smoogipoo/osu
osu.Game/Utils/TaskChain.cs
osu.Game/Utils/TaskChain.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Threading.Tasks; namespace osu.Game.Utils { /// <summary> /// A chain of <see cref="Task"/>s that run sequentially. /// </summary> public class TaskChain { private readonly object currentTaskLock = new object(); private Task? currentTask; /// <summary> /// Adds a new task to the end of this <see cref="TaskChain"/>. /// </summary> /// <param name="taskFunc">The task creation function.</param> /// <returns>The awaitable <see cref="Task"/>.</returns> public Task Add(Func<Task> taskFunc) { lock (currentTaskLock) { currentTask = currentTask == null ? taskFunc() : currentTask.ContinueWith(_ => taskFunc()).Unwrap(); return currentTask; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Threading.Tasks; namespace osu.Game.Utils { /// <summary> /// A chain of <see cref="Task"/>s that run sequentially. /// </summary> public class TaskChain { private readonly object currentTaskLock = new object(); private Task? currentTask; public Task Add(Func<Task> taskFunc) { lock (currentTaskLock) { currentTask = currentTask == null ? taskFunc() : currentTask.ContinueWith(_ => taskFunc()).Unwrap(); return currentTask; } } } }
mit
C#
d509debd0c7fe059e1c5d0fb721cf20a7610cf20
Disable walk-behind drawable by default
tzachshabtay/MonoAGS
Source/Engine/AGS.Engine/Rooms/Areas/AGSWalkBehindsMap.cs
Source/Engine/AGS.Engine/Rooms/Areas/AGSWalkBehindsMap.cs
using AGS.API; using System.Collections.Generic; using AreaKey = System.ValueTuple<AGS.API.IArea, AGS.API.IBitmap>; using System; namespace AGS.Engine { public class AGSWalkBehindsMap { private readonly Dictionary<AreaKey, IImage> _images; private readonly Dictionary<AreaKey, IObject> _objects; private readonly IGameFactory _factory; private readonly Func<AreaKey, IImage> _createImageFunc; private readonly Func<AreaKey, IObject> _createObjectFunc; public AGSWalkBehindsMap(IGameFactory factory) { _factory = factory; _images = new Dictionary<AreaKey, IImage> (100); _objects = new Dictionary<AreaKey, IObject> (100); //Creating delegates in advance to avoid memory allocations on critical path _createImageFunc = key => createImage(key.Item1, key.Item2); _createObjectFunc = key => createObject(key.Item1.ID); } public IObject GetDrawable(IArea area, IBitmap bg) { IWalkBehindArea walkBehind = area.GetComponent<IWalkBehindArea>(); if (walkBehind == null) return null; AreaKey key = new AreaKey (area, bg); IObject obj = _objects.GetOrAdd(key, _createObjectFunc); obj.Z = walkBehind.Baseline == null ? area.Mask.MinY : walkBehind.Baseline.Value; obj.Image = _images.GetOrAdd(key, _createImageFunc); obj.Enabled = false; return obj; } private IImage createImage(IArea area, IBitmap bg) { var bitmap = bg.ApplyArea(area); return _factory.Graphics.LoadImage(bitmap); } private IObject createObject(string id) { var obj = _factory.Object.GetObject("Walk-Behind Drawable: " + id); obj.Pivot = new PointF (); return obj; } } }
using AGS.API; using System.Collections.Generic; using AreaKey = System.ValueTuple<AGS.API.IArea, AGS.API.IBitmap>; using System; namespace AGS.Engine { public class AGSWalkBehindsMap { private readonly Dictionary<AreaKey, IImage> _images; private readonly Dictionary<AreaKey, IObject> _objects; private readonly IGameFactory _factory; private readonly Func<AreaKey, IImage> _createImageFunc; private readonly Func<AreaKey, IObject> _createObjectFunc; public AGSWalkBehindsMap(IGameFactory factory) { _factory = factory; _images = new Dictionary<AreaKey, IImage> (100); _objects = new Dictionary<AreaKey, IObject> (100); //Creating delegates in advance to avoid memory allocations on critical path _createImageFunc = key => createImage(key.Item1, key.Item2); _createObjectFunc = key => createObject(key.Item1.ID); } public IObject GetDrawable(IArea area, IBitmap bg) { IWalkBehindArea walkBehind = area.GetComponent<IWalkBehindArea>(); if (walkBehind == null) return null; AreaKey key = new AreaKey (area, bg); IObject obj = _objects.GetOrAdd(key, _createObjectFunc); obj.Z = walkBehind.Baseline == null ? area.Mask.MinY : walkBehind.Baseline.Value; obj.Image = _images.GetOrAdd(key, _createImageFunc); return obj; } private IImage createImage(IArea area, IBitmap bg) { var bitmap = bg.ApplyArea(area); return _factory.Graphics.LoadImage(bitmap); } private IObject createObject(string id) { var obj = _factory.Object.GetObject("Walk-Behind Drawable: " + id); obj.Pivot = new PointF (); return obj; } } }
artistic-2.0
C#
13aafc96b177038568ad353f51f514cf43024af9
Add property for response content, mapped to Data collection.
mios-fi/mios.payment
core/VerificationProviderException.cs
core/VerificationProviderException.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Payment { [Serializable] public class VerificationProviderException : Exception { public string ResponseContent { get { return Data["Response"] as string; } set { Data["Response"] = value; } } public VerificationProviderException() { } public VerificationProviderException(string message) : base(message) { } public VerificationProviderException(string message, Exception inner) : base(message, inner) { } protected VerificationProviderException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mios.Payment { [Serializable] public class VerificationProviderException : Exception { public VerificationProviderException() { } public VerificationProviderException(string message) : base(message) { } public VerificationProviderException(string message, Exception inner) : base(message, inner) { } protected VerificationProviderException( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } } }
bsd-2-clause
C#
40773d6ad8f33db483f474606fb5177ddef9556e
Add basic crosshair
Warhead-Entertainment/OpenWorld
Assets/Scripts/HUD.cs
Assets/Scripts/HUD.cs
using UnityEngine; using System.Collections; public class HUD : MonoBehaviour { private int frameCount = 0; private float dt = 0.0F; private float fps = 0.0F; private float updateRate = 4.0F; void Start () { } void Update () { frameCount++; dt += Time.deltaTime; if (dt > 1.0F / updateRate) { fps = frameCount / dt ; frameCount = 0; dt -= 1.0F / updateRate; } } void OnGUI () { GUI.Label(new Rect (10,10,150,100), "Current FPS: "+ ((int)fps).ToString()); GUI.Box(new Rect(Screen.width / 2, Screen.height / 2, 0, 0), "This is a crosshair"); } }
using UnityEngine; using System.Collections; public class HUD : MonoBehaviour { private int frameCount = 0; private float dt = 0.0F; private float fps = 0.0F; private float updateRate = 4.0F; void Start () { } void Update () { frameCount++; dt += Time.deltaTime; if (dt > 1.0F / updateRate) { fps = frameCount / dt ; frameCount = 0; dt -= 1.0F / updateRate; } } void OnGUI () { GUI.Label(new Rect (10,10,150,100), "Current FPS: "+ ((int)fps).ToString()); } }
mit
C#
eec3c4ecec2febf14726748c48cf509b6986358b
Fix Linux build (BL-3665)
BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,gmartin7/myBloomFork,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop
src/BloomExe/RobustIO.cs
src/BloomExe/RobustIO.cs
using System; using System.Collections.Generic; #if !__MonoCS__ using NAudio.Wave; #endif using SIL.Code; using SIL.Windows.Forms.ClearShare; using SIL.Windows.Forms.ImageToolbox; using TidyManaged; namespace Bloom { /// <summary> /// Provides a more robust version of various IO methods. /// The original intent of this class is to attempt to mitigate issues /// where we attempt IO but the file is locked by another application. /// Our theory is that some anti-virus software locks files while it scans them. /// /// There is a similar class in SIL.IO, but that handles more generic calls /// which would not require additional dependencies. /// </summary> public class RobustIO { #if !__MonoCS__ public static WaveFileReader CreateWaveFileReader(string wavFile) { return RetryUtility.Retry(() => new WaveFileReader(wavFile)); } #endif public static Document DocumentFromFile(string filePath) { return RetryUtility.Retry(() => Document.FromFile(filePath)); } public static Metadata MetadataFromFile(string path) { return RetryUtility.Retry(() => Metadata.FromFile(path)); } public static PalasoImage PalasoImageFromFile(string path) { return RetryUtility.Retry(() => PalasoImage.FromFile(path), RetryUtility.kDefaultMaxRetryAttempts, RetryUtility.kDefaultRetryDelay, new HashSet<Type> { Type.GetType("System.IO.IOException"), // Odd type to catch... but it seems that Image.FromFile (which is called in the bowels of PalasoImage.FromFile) // throws OutOfMemoryException when the file is inaccessible. // See http://stackoverflow.com/questions/2610416/is-there-a-reason-image-fromfile-throws-an-outofmemoryexception-for-an-invalid-i Type.GetType("System.OutOfMemoryException") }); } public static void SavePalasoImage(PalasoImage image, string path) { RetryUtility.Retry(() => image.Save(path)); } } }
using System; using System.Collections.Generic; using NAudio.Wave; using SIL.Code; using SIL.Windows.Forms.ClearShare; using SIL.Windows.Forms.ImageToolbox; using TidyManaged; namespace Bloom { /// <summary> /// Provides a more robust version of various IO methods. /// The original intent of this class is to attempt to mitigate issues /// where we attempt IO but the file is locked by another application. /// Our theory is that some anti-virus software locks files while it scans them. /// /// There is a similar class in SIL.IO, but that handles more generic calls /// which would not require additional dependencies. /// </summary> public class RobustIO { public static WaveFileReader CreateWaveFileReader(string wavFile) { return RetryUtility.Retry(() => new WaveFileReader(wavFile)); } public static Document DocumentFromFile(string filePath) { return RetryUtility.Retry(() => Document.FromFile(filePath)); } public static Metadata MetadataFromFile(string path) { return RetryUtility.Retry(() => Metadata.FromFile(path)); } public static PalasoImage PalasoImageFromFile(string path) { return RetryUtility.Retry(() => PalasoImage.FromFile(path), RetryUtility.kDefaultMaxRetryAttempts, RetryUtility.kDefaultRetryDelay, new HashSet<Type> { Type.GetType("System.IO.IOException"), // Odd type to catch... but it seems that Image.FromFile (which is called in the bowels of PalasoImage.FromFile) // throws OutOfMemoryException when the file is inaccessible. // See http://stackoverflow.com/questions/2610416/is-there-a-reason-image-fromfile-throws-an-outofmemoryexception-for-an-invalid-i Type.GetType("System.OutOfMemoryException") }); } public static void SavePalasoImage(PalasoImage image, string path) { RetryUtility.Retry(() => image.Save(path)); } } }
mit
C#
6fd839223e5569367916c5176e65476abbcb442b
Fix Blockbusters not accepting uppercase input
samfun123/KtaneTwitchPlays,CaitSith2/KtaneTwitchPlays
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/BlockbustersComponentSolver.cs
TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/BlockbustersComponentSolver.cs
using System.Collections; using System.Linq; using System.Text.RegularExpressions; public class BlockbustersComponentSolver : ComponentSolver { public BlockbustersComponentSolver(TwitchModule module) : base(module) { selectables = Module.BombComponent.GetComponent<KMSelectable>().Children; ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row."); } int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1'; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = Regex.Replace(inputCommand.ToLowerInvariant(), @"(\W|_|^(press|submit|click|answer))", ""); if (inputCommand.Length != 2) yield break; int column = CharacterToIndex(inputCommand[0]); int row = CharacterToIndex(inputCommand[1]); if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1)) { yield return null; yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]); } } private readonly KMSelectable[] selectables; }
using System.Collections; using System.Linq; using System.Text.RegularExpressions; public class BlockbustersComponentSolver : ComponentSolver { public BlockbustersComponentSolver(TwitchModule module) : base(module) { selectables = Module.BombComponent.GetComponent<KMSelectable>().Children; ModInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press a tile using !{0} 2E. Tiles are specified by column then row."); } int CharacterToIndex(char character) => character >= 'a' ? character - 'a' : character - '1'; protected internal override IEnumerator RespondToCommandInternal(string inputCommand) { inputCommand = Regex.Replace(inputCommand, @"(\W|_|^(press|submit|click|answer))", ""); if (inputCommand.Length != 2) yield break; int column = CharacterToIndex(inputCommand[0]); int row = CharacterToIndex(inputCommand[1]); if (column.InRange(0, 4) && row.InRange(0, 4) && (row < 4 || column % 2 == 1)) { yield return null; yield return DoInteractionClick(selectables[Enumerable.Range(0, column).Select(n => (n % 2 == 0) ? 4 : 5).Sum() + row]); } } private readonly KMSelectable[] selectables; }
mit
C#
2378d926e8e265ffecc3320869849c7554eda4dd
Set DOTNET_HOST_PATH so Roslyn tasks will use the right host
Microsoft/msbuild,mono/msbuild,mono/msbuild,AndyGerlicher/msbuild,cdmihai/msbuild,rainersigwald/msbuild,mono/msbuild,AndyGerlicher/msbuild,jeffkl/msbuild,chipitsine/msbuild,sean-gilliam/msbuild,cdmihai/msbuild,sean-gilliam/msbuild,chipitsine/msbuild,jeffkl/msbuild,cdmihai/msbuild,Microsoft/msbuild,chipitsine/msbuild,chipitsine/msbuild,jeffkl/msbuild,AndyGerlicher/msbuild,AndyGerlicher/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,jeffkl/msbuild,Microsoft/msbuild,rainersigwald/msbuild,mono/msbuild,Microsoft/msbuild,rainersigwald/msbuild,cdmihai/msbuild,sean-gilliam/msbuild
build/TestAssemblyInfo.cs
build/TestAssemblyInfo.cs
 using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Xml.Linq; using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)] // Register test framework for assembly fixture [assembly: TestFramework("Xunit.NetCore.Extensions.XunitTestFrameworkWithAssemblyFixture", "Xunit.NetCore.Extensions")] [assembly: AssemblyFixture(typeof(MSBuildTestAssemblyFixture))] public class MSBuildTestAssemblyFixture { public MSBuildTestAssemblyFixture() { // Find correct version of "dotnet", and set DOTNET_HOST_PATH so that the Roslyn tasks will use the right host var currentFolder = System.AppContext.BaseDirectory; while (currentFolder != null) { string potentialVersionsPropsPath = Path.Combine(currentFolder, "build", "Versions.props"); if (File.Exists(potentialVersionsPropsPath)) { var doc = XDocument.Load(potentialVersionsPropsPath); var ns = doc.Root.Name.Namespace; var cliVersionElement = doc.Root.Elements(ns + "PropertyGroup").Elements(ns + "DotNetCliVersion").FirstOrDefault(); if (cliVersionElement != null) { string cliVersion = cliVersionElement.Value; string dotnetPath = Path.Combine(currentFolder, "artifacts", ".dotnet", cliVersion, "dotnet"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { dotnetPath += ".exe"; } Environment.SetEnvironmentVariable("DOTNET_HOST_PATH", dotnetPath); } break; } currentFolder = Directory.GetParent(currentFolder)?.FullName; } } }
 using Xunit; [assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly)]
mit
C#
f36b8d09d83c71f8ffadaf894fda8a06abad3c1a
Update UserStore.cs
aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
aspnet-core/src/AbpCompanyName.AbpProjectName.Core/Authorization/Users/UserStore.cs
aspnet-core/src/AbpCompanyName.AbpProjectName.Core/Authorization/Users/UserStore.cs
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using Abp.Organizations; using AbpCompanyName.AbpProjectName.Authorization.Roles; namespace AbpCompanyName.AbpProjectName.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository) : base(unitOfWorkManager, userRepository, roleRepository, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository, userOrganizationUnitRepository, organizationUnitRoleRepository ) { } } }
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using Abp.Organizations; using AbpCompanyName.AbpProjectName.Authorization.Roles; namespace AbpCompanyName.AbpProjectName.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository, IRepository<UserOrganizationUnit, long> userOrganizationUnitRepository, IRepository<OrganizationUnitRole, long> organizationUnitRoleRepository) : base( unitOfWorkManager, userRepository, roleRepository, asyncQueryableExecuter, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository, userOrganizationUnitRepository, organizationUnitRoleRepository) { } } }
mit
C#
830ee023812c1016712e66d7608d4e3a3d260889
switch synapse to have axon ptr instead of value
jobeland/NeuralNetwork
NeuralNetwork/NeuralNetwork/Synapse.cs
NeuralNetwork/NeuralNetwork/Synapse.cs
namespace ArtificialNeuralNetwork { public class Synapse { public IAxon Axon { get; set; } public double Weight { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork { public class Synapse { public double Value { get; set; } public double Weight { get; set; } } }
mit
C#
ed1afa1cf0d9beba87d154495946bb1df85eda7b
Update BigtableClientBuilder to populate LastCreatedChannel
googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/gcloud-dotnet
apis/Google.Cloud.Bigtable.V2/Google.Cloud.Bigtable.V2/BigtableClientBuilder.cs
apis/Google.Cloud.Bigtable.V2/Google.Cloud.Bigtable.V2/BigtableClientBuilder.cs
// Copyright 2019 Google LLC // // 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 // // https://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 Google.Api.Gax.Grpc; using System; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Bigtable.V2 { // TODO: Add emulator support in the same way as FirestoreClient etc. /// <summary> /// Builder class for <see cref="BigtableClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class BigtableClientBuilder : ClientBuilderBase<BigtableClient> { /// <summary> /// The settings to use for RPCs, or null for the default settings. /// </summary> public BigtableServiceApiSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BigtableClientBuilder() : base(BigtableServiceApiClient.ServiceMetadata) { } /// <inheritdoc/> public override BigtableClient Build() { var builder = new BigtableServiceApiClientBuilder(this); var client = BigtableClient.Create(builder.Build()); LastCreatedChannel = builder.LastCreatedChannel; return client; } /// <inheritdoc /> public override async Task<BigtableClient> BuildAsync(CancellationToken cancellationToken = default) { var builder = new BigtableServiceApiClientBuilder(this); var client = BigtableClient.Create(await builder.BuildAsync(cancellationToken).ConfigureAwait(false)); LastCreatedChannel = builder.LastCreatedChannel; return client; } // Overrides for abstract methods that will never actually be called. /// <inheritdoc /> protected override ChannelPool GetChannelPool() => throw new NotImplementedException(); } }
// Copyright 2019 Google LLC // // 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 // // https://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 Google.Api.Gax.Grpc; using System; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.Bigtable.V2 { // TODO: Add emulator support in the same way as FirestoreClient etc. /// <summary> /// Builder class for <see cref="BigtableClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class BigtableClientBuilder : ClientBuilderBase<BigtableClient> { /// <summary> /// The settings to use for RPCs, or null for the default settings. /// </summary> public BigtableServiceApiSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public BigtableClientBuilder() : base(BigtableServiceApiClient.ServiceMetadata) { } /// <inheritdoc/> public override BigtableClient Build() { var builder = new BigtableServiceApiClientBuilder(this); return BigtableClient.Create(builder.Build()); } /// <inheritdoc /> public override async Task<BigtableClient> BuildAsync(CancellationToken cancellationToken = default) { var builder = new BigtableServiceApiClientBuilder(this); return BigtableClient.Create(await builder.BuildAsync(cancellationToken).ConfigureAwait(false)); } // Overrides for abstract methods that will never actually be called. /// <inheritdoc /> protected override ChannelPool GetChannelPool() => throw new NotImplementedException(); } }
apache-2.0
C#
3ff7fe147f690fcfa11f6164f63f123bec560fa9
Update DefaultTableService.cs
tamasflamich/nmemory
Main/Source/NMemory.Shared/Services/DefaultTableService.cs
Main/Source/NMemory.Shared/Services/DefaultTableService.cs
// ---------------------------------------------------------------------------------- // <copyright file="DefaultTableService.cs" company="NMemory Team"> // Copyright (C) NMemory Team // // 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. // </copyright> // ---------------------------------------------------------------------------------- namespace NMemory.Services { using NMemory.Indexes; using NMemory.Modularity; using NMemory.Services.Contracts; using NMemory.Tables; internal class DefaultTableService : ITableService { public Table<TEntity, TPrimaryKey> CreateTable<TEntity, TPrimaryKey>( IKeyInfo<TEntity, TPrimaryKey> primaryKey, IdentitySpecification<TEntity> identitySpecification, IDatabase database, object tableInfo) where TEntity : class { Table<TEntity, TPrimaryKey> table = new DefaultTable<TEntity, TPrimaryKey>( database, primaryKey, identitySpecification, tableInfo); return table; } public Table<TEntity, TPrimaryKey> CreateTable<TEntity, TPrimaryKey>( IKeyInfo<TEntity, TPrimaryKey> primaryKey, IdentitySpecification<TEntity> identitySpecification, IDatabase database ) where TEntity : class { return CreateTable(primaryKey, identitySpecification, database, null); } } }
// ---------------------------------------------------------------------------------- // <copyright file="DefaultTableService.cs" company="NMemory Team"> // Copyright (C) NMemory Team // // 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. // </copyright> // ---------------------------------------------------------------------------------- namespace NMemory.Services { using NMemory.Indexes; using NMemory.Modularity; using NMemory.Services.Contracts; using NMemory.Tables; internal class DefaultTableService : ITableService { public Table<TEntity, TPrimaryKey> CreateTable<TEntity, TPrimaryKey>( IKeyInfo<TEntity, TPrimaryKey> primaryKey, IdentitySpecification<TEntity> identitySpecification, IDatabase database, object tableInfo = null) where TEntity : class { Table<TEntity, TPrimaryKey> table = new DefaultTable<TEntity, TPrimaryKey>( database, primaryKey, identitySpecification, tableInfo); return table; } } }
mit
C#
0f418d50a7d5e1d82df4d7baeb70ee9ac83635c3
Update HttpPoller.cs
keith-hall/Extensions,keith-hall/Extensions
src/HttpPoller.cs
src/HttpPoller.cs
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { public static class HttpPoller { public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; } /// <summary> /// Poll a <paramref name="url"/> at the specified <paramref name="frequency"/> and create an observable that will update every time the content recieved changes. /// </summary> /// <param name="url">The url to poll.</param> /// <param name="frequency">The frequency to poll at.</param> /// <param name="createWebClient">An optional function to create a WebClient instance, for overriding timeouts, request headers etc.</param> /// <returns>An observable containing the response headers and content of the specified url.</returns> /// <exception cref="ArgumentNullException"><paramref name="url" /> or <paramref name="frequency" /> are <c>null</c>.</exception> /// <exception cref="WebException">A problem occurs polling the specified <paramref name="url"/>.</exception> public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
using System; using System.Net; using System.Reactive.Linq; namespace HallLibrary.Extensions { public static class HttpPoller { public struct ResponseDetails { public WebHeaderCollection Headers; public string Text; } /// <summary> /// Poll a <paramref name="url"/> at the specified <paramref name="frequency"/> and create an observable that will update every time the content recieved changes. /// </summary> /// <param name="url">The url to poll.</param> /// <param name="frequency">The frequency to poll at.</param> /// <param name="createWebClient">An optional function to create a WebClient instance, for overriding timeouts, request headers etc.</param> /// <returns>An observable containing the response headers and content of the specified url.</returns> public static IObservable<ResponseDetails> PollURL(string url, TimeSpan frequency, Func<WebClient> createWebClient = null) { createWebClient = createWebClient ?? (() => new WebClient()); Func<ResponseDetails> download = () => { var wc = createWebClient(); return new ResponseDetails { Text = wc.DownloadString(url), Headers = wc.ResponseHeaders }; }; return Observable.Interval(frequency) .Select(l => download()) .StartWith(download()) .DistinctUntilChanged(wc => wc.Text).Publish().RefCount(); } } }
apache-2.0
C#
be775954e058c7e95d4ce9bdbaf43ea2a636deed
bump version
Fody/Freezable
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Freezable")] [assembly: AssemblyProduct("Freezable")] [assembly: AssemblyVersion("1.6.11")] [assembly: AssemblyFileVersion("1.6.11")]
using System.Reflection; [assembly: AssemblyTitle("Freezable")] [assembly: AssemblyProduct("Freezable")] [assembly: AssemblyVersion("1.6.10")] [assembly: AssemblyFileVersion("1.6.10")]
mit
C#
ac8a83177fd177d8dfe6cb22882b8d68e89a4812
Make AutoInterningStringKeyCaseInsensitiveDictionaryConverter case insensitive
JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS
src/Umbraco.Core/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs
src/Umbraco.Core/Serialization/AutoInterningStringKeyCaseInsensitiveDictionaryConverter.cs
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Umbraco.Core.Serialization { /// <summary> /// When applied to a dictionary with a string key, will ensure the deserialized string keys are interned /// </summary> /// <typeparam name="TValue"></typeparam> /// <remarks> /// borrowed from https://stackoverflow.com/a/36116462/694494 /// </remarks> internal class AutoInterningStringKeyCaseInsensitiveDictionaryConverter<TValue> : CaseInsensitiveDictionaryConverter<TValue> { public AutoInterningStringKeyCaseInsensitiveDictionaryConverter() { } public AutoInterningStringKeyCaseInsensitiveDictionaryConverter(StringComparer comparer) : base(comparer) { } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject) { var dictionary = Create(objectType); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var key = string.Intern(reader.Value.ToString()); if (!reader.Read()) throw new Exception("Unexpected end when reading object."); var v = serializer.Deserialize<TValue>(reader); dictionary[key] = v; break; case JsonToken.Comment: break; case JsonToken.EndObject: return dictionary; } } } return null; } } }
using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Umbraco.Core.Serialization { /// <summary> /// When applied to a dictionary with a string key, will ensure the deserialized string keys are interned /// </summary> /// <typeparam name="TValue"></typeparam> /// <remarks> /// borrowed from https://stackoverflow.com/a/36116462/694494 /// </remarks> internal class AutoInterningStringKeyCaseInsensitiveDictionaryConverter<TValue> : CaseInsensitiveDictionaryConverter<TValue> { public AutoInterningStringKeyCaseInsensitiveDictionaryConverter() { } public AutoInterningStringKeyCaseInsensitiveDictionaryConverter(StringComparer comparer) : base(comparer) { } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.StartObject) { var dictionary = new Dictionary<string, TValue>(); while (reader.Read()) { switch (reader.TokenType) { case JsonToken.PropertyName: var key = string.Intern(reader.Value.ToString()); if (!reader.Read()) throw new Exception("Unexpected end when reading object."); var v = serializer.Deserialize<TValue>(reader); dictionary[key] = v; break; case JsonToken.Comment: break; case JsonToken.EndObject: return dictionary; } } } return null; } } }
mit
C#
a5e5eeafa05bb65d531c05435953a01385ebb96e
Remove obsolete line
imanushin/NullCheck
NullCheck/NullCheckAnalyzer/NullCheckAnalyzer/NullCheckAnalyzer.cs
NullCheck/NullCheckAnalyzer/NullCheckAnalyzer/NullCheckAnalyzer.cs
using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace NullCheckAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NullCheckAnalyzer : DiagnosticAnalyzer { public const string ParameterIsNullId = "NullCheckAnalyzer_MethodContainNulls"; // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat. internal static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources)); internal static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); internal static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources)); internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(ParameterIsNullId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { var methodSymbol = context.Symbol as IMethodSymbol; if (ReferenceEquals(null, methodSymbol) || methodSymbol.DeclaredAccessibility == Accessibility.Private) { return; } foreach (var parameter in ParametersGetter.GetParametersToFix(methodSymbol)) { var type = methodSymbol.ContainingType; // For all such symbols, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, parameter.Locations[0], methodSymbol.Name, type.Name, parameter.Name); context.ReportDiagnostic(diagnostic); } } } }
using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace NullCheckAnalyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public class NullCheckAnalyzer : DiagnosticAnalyzer { public const string ParameterIsNullId = "NullCheckAnalyzer_MethodContainNulls"; public const string ParameterIsNullIdWithoutCodeFix = "NullCheckAnalyzer_MethodContainNullsAssemblyIsNotReferenced"; // You can change these strings in the Resources.resx file. If you do not want your analyzer to be localize-able, you can use regular strings for Title and MessageFormat. internal static readonly LocalizableString Title = new LocalizableResourceString(nameof(Resources.AnalyzerTitle), Resources.ResourceManager, typeof(Resources)); internal static readonly LocalizableString MessageFormat = new LocalizableResourceString(nameof(Resources.AnalyzerMessageFormat), Resources.ResourceManager, typeof(Resources)); internal static readonly LocalizableString Description = new LocalizableResourceString(nameof(Resources.AnalyzerDescription), Resources.ResourceManager, typeof(Resources)); internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(ParameterIsNullId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.Method); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { var methodSymbol = context.Symbol as IMethodSymbol; if (ReferenceEquals(null, methodSymbol) || methodSymbol.DeclaredAccessibility == Accessibility.Private) { return; } foreach (var parameter in ParametersGetter.GetParametersToFix(methodSymbol)) { var type = methodSymbol.ContainingType; // For all such symbols, produce a diagnostic. var diagnostic = Diagnostic.Create(Rule, parameter.Locations[0], methodSymbol.Name, type.Name, parameter.Name); context.ReportDiagnostic(diagnostic); } } } }
mit
C#
6a3ab12cb2659db1a953dd2cd185a7948cbad884
Add AddElement and RemoveElement to IPostData
dga711/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,Livit/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,wangzheng888520/CefSharp,rlmcneary2/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,dga711/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp
CefSharp/IPostData.cs
CefSharp/IPostData.cs
// Copyright © 2010-2015 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.Collections.Generic; namespace CefSharp { public interface IPostData : IDisposable { /// <summary> /// Add the specified <see cref="IPostDataElement"/>. /// </summary> /// <param name="element">element to be added.</param> /// <returns> Returns true if the add succeeds.</returns> bool AddElement(IPostDataElement element); /// <summary> /// Remove the specified <see cref="IPostDataElement"/>. /// </summary> /// <param name="element">element to be removed.</param> /// <returns> Returns true if the add succeeds.</returns> bool RemoveElement(IPostDataElement element); /// <summary> /// Retrieve the post data elements. /// </summary> IList<IPostDataElement> Elements { get; } /// <summary> /// Returns true if this object is read-only. /// </summary> bool IsReadOnly { get; } /// <summary> /// Remove all existing post data elements. /// </summary> void RemoveElements(); /// <summary> /// Gets a value indicating whether the object has been disposed of. /// </summary> bool IsDisposed { get; } /// <summary> /// Create a new <see cref="IPostDataElement"/> instance /// </summary> /// <returns></returns> IPostDataElement CreatePostDataElement(); } }
// Copyright © 2010-2015 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.Collections.Generic; namespace CefSharp { public interface IPostData : IDisposable { //bool AddElement(IPostDataElement element); /// <summary> /// Retrieve the post data elements. /// </summary> IList<IPostDataElement> Elements { get; } /// <summary> /// Returns true if this object is read-only. /// </summary> bool IsReadOnly { get; } //bool RemoveElement(IPostDataElement element); /// <summary> /// Remove all existing post data elements. /// </summary> void RemoveElements(); /// <summary> /// Gets a value indicating whether the object has been disposed of. /// </summary> bool IsDisposed { get; } /// <summary> /// Create a new <see cref="IPostDataElement"/> instance /// </summary> /// <returns></returns> IPostDataElement CreatePostDataElement(); } }
bsd-3-clause
C#
4c8dab76f48d533351ccac250241b9c01fa03cad
Test dasdas das das
WS-and-Cloud/Task-Managment,WS-and-Cloud/Task-Managment
TaskManagment/TaskManagment.Services/Controllers/HomeController.cs
TaskManagment/TaskManagment.Services/Controllers/HomeController.cs
using System.Web.Mvc; namespace TaskManagment.Services.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } public ActionResult Test() { return View(); } } }
using System.Web.Mvc; namespace TaskManagment.Services.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } } }
mit
C#
ad684ec651cf819802cfa3f30d89a95bd87751cf
Remove async helper methods for json serialization.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Utils/Json.cs
Source/Lib/TraktApiSharp/Utils/Json.cs
namespace TraktApiSharp.Utils { using Newtonsoft.Json; internal static class Json { internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS = new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }; internal static string Serialize(object value) { return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS); } internal static TResult Deserialize<TResult>(string value) { return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS); } } }
namespace TraktApiSharp.Utils { using Newtonsoft.Json; using System.Threading.Tasks; internal static class Json { internal static readonly JsonSerializerSettings DEFAULT_JSON_SETTINGS = new JsonSerializerSettings { Formatting = Formatting.None, NullValueHandling = NullValueHandling.Ignore }; internal static string Serialize(object value) { return JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS); } internal static TResult Deserialize<TResult>(string value) { return JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS); } internal static async Task<string> SerializeAsync(object value) { return await Task.Run(() => JsonConvert.SerializeObject(value, DEFAULT_JSON_SETTINGS)); } internal static async Task<TResult> DeserializeAsync<TResult>(string value) { return await Task.Run(() => JsonConvert.DeserializeObject<TResult>(value, DEFAULT_JSON_SETTINGS)); } } }
mit
C#
47e35b570b1a7325e5e68d249d1bf3c3cf2c6921
bump version
Fody/Validar
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Validar")] [assembly: AssemblyProduct("Validar")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; [assembly: AssemblyTitle("Validar")] [assembly: AssemblyProduct("Validar")] [assembly: AssemblyVersion("0.10.0.0")] [assembly: AssemblyFileVersion("0.10.0.0")]
mit
C#
746244df5da515243866d03167c8986ecb72cac7
Use private accessor for property
Utdanningsdirektoratet/PAS2-Public,Utdanningsdirektoratet/PAS2-Public,Utdanningsdirektoratet/PAS2-Public,Utdanningsdirektoratet/PAS2-Public
ExampleClients/dotnet/UDIR.PAS2.Example.Client/UDIR.PAS2.OAuth.Client/AuthorizationServer.cs
ExampleClients/dotnet/UDIR.PAS2.Example.Client/UDIR.PAS2.OAuth.Client/AuthorizationServer.cs
using System; namespace UDIR.PAS2.OAuth.Client { internal class AuthorizationServer { public AuthorizationServer(Uri baseAddress) { BaseAddress = baseAddress; TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString(); } public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress)) { } public string TokenEndpoint { get; private set; } public Uri BaseAddress { get; private set; } } }
using System; namespace UDIR.PAS2.OAuth.Client { internal class AuthorizationServer { public AuthorizationServer(Uri baseAddress) { BaseAddress = baseAddress; TokenEndpoint = new Uri(baseAddress, "/connect/token").ToString(); } public AuthorizationServer(string baseAddress) : this(new Uri(baseAddress)) { } public string TokenEndpoint { get; } public Uri BaseAddress { get; } } }
apache-2.0
C#
ef4c073b838a96a986e0cc3c29c52a551b90607a
refactor the test set up into separate method
milleniumbug/Taxonomy
Tests/Program.cs
Tests/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using TaxonomyLib; namespace Tests { [TestFixture] class ATest { private string projectDirectory; private Taxonomy taxonomy; [OneTimeSetUp] public void OneTimeSetUp() { string executablePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; projectDirectory = new FileInfo(executablePath).Directory.Parent.Parent.FullName; Directory.SetCurrentDirectory(projectDirectory); } [SetUp] public void SetUp() { taxonomy = Taxonomy.CreateNew(@"testdata\test.sql"); } [TearDown] public void TearDown() { taxonomy.Dispose(); } [Test] public void T() { var firstFile = taxonomy.GetFile(@"testdata\emptyfile.txt"); var sameFile = taxonomy.GetFile(@"testdata\emptyfile.txt"); Assert.AreSame(firstFile, sameFile); var secondFile = taxonomy.GetFile(@"testdata\😂non😂bmp😂name😂\Audio.png"); var thirdFile = taxonomy.GetFile(@"testdata\zażółć gęślą jaźń\samecontent2.txt"); var rodzaj = new Namespace("rodzaj"); var firstTag = taxonomy.AddTag(rodzaj, new TagName("film")); var secondTag = taxonomy.AddTag(rodzaj, new TagName("ŚmieszneObrazki")); firstFile.Tags.Add(firstTag); thirdFile.Tags.Add(firstTag); secondFile.Tags.Add(secondTag); CollectionAssert.AreEquivalent(new[] {firstFile, thirdFile}, taxonomy.LookupFilesByTags(new[] {firstTag}).ToList()); CollectionAssert.AreEqual(new[] { rodzaj }, taxonomy.AllNamespaces().ToList()); CollectionAssert.AreEquivalent(new[] { firstTag, secondTag }, taxonomy.TagsInNamespace(rodzaj).ToList()); } static void Main() { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using NUnit.Framework; using TaxonomyLib; namespace Tests { [TestFixture] class ATest { private string projectDirectory; [SetUp] public void SetUp() { string executablePath = new Uri(Assembly.GetExecutingAssembly().CodeBase).AbsolutePath; projectDirectory = new FileInfo(executablePath).Directory.Parent.Parent.FullName; } [Test] public void T() { using (var taxonomy = Taxonomy.CreateNew(Path.Combine(projectDirectory, @"testdata\test.sql"))) { var firstFile = taxonomy.GetFile(Path.Combine(projectDirectory, @"testdata\emptyfile.txt")); var sameFile = taxonomy.GetFile(Path.Combine(projectDirectory, @"testdata\emptyfile.txt")); Assert.AreSame(firstFile, sameFile); var secondFile = taxonomy.GetFile(Path.Combine(projectDirectory, @"testdata\😂non😂bmp😂name😂\Audio.png")); var thirdFile = taxonomy.GetFile(Path.Combine(projectDirectory, @"testdata\zażółć gęślą jaźń\samecontent2.txt")); var rodzaj = new Namespace("rodzaj"); var firstTag = taxonomy.AddTag(rodzaj, new TagName("film")); var secondTag = taxonomy.AddTag(rodzaj, new TagName("ŚmieszneObrazki")); firstFile.Tags.Add(firstTag); thirdFile.Tags.Add(firstTag); secondFile.Tags.Add(secondTag); CollectionAssert.AreEquivalent(new[] {firstFile, thirdFile}, taxonomy.LookupFilesByTags(new[] {firstTag}).ToList()); CollectionAssert.AreEqual(new[] { rodzaj }, taxonomy.AllNamespaces().ToList()); CollectionAssert.AreEquivalent(new[] { firstTag, secondTag }, taxonomy.TagsInNamespace(rodzaj).ToList()); } } static void Main() { } } }
mit
C#
a0263c444ec6e90871b4ba4c8b9d56f14cef198c
Add check for success
maxthecatstudios/UnityTC
UnityTC/Unity.cs
UnityTC/Unity.cs
// // © 2016 Max the Cat Studios Ltd. // // https://maxthecatstudios.com // @maxthecatstudio // // Created By Desmond Fernando 2016 06 30 12:08 PM // // // using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; namespace UnityTC { public class Unity { /// <summary> /// /// </summary> /// <param name="unityPath"></param> /// <param name="args"></param> /// <returns></returns> public static int StartUnity( string unityPath, string args ) { var sb = new StringBuilder(); var watcher = new Watcher( Path.GetTempFileName() ); var watcherThread = new Thread( watcher.Run ); watcherThread.Start(); var unity = new Process { StartInfo = new ProcessStartInfo( unityPath ) }; sb.Append( $"-logFile \"{watcher.LogPath}\"" ); sb.Append( $" {args}" ); //for ( var i = 1; i < args.Length; i++ ) // sb.Append( $" \"{args[ i ]}\"" ); unity.StartInfo.Arguments = sb.ToString(); Console.WriteLine( $"##teamcity[progressMessage 'Starting Unity {unity.StartInfo.Arguments}']" ); unity.Start(); Console.WriteLine( $"##teamcity[setParameter name='unityPID' value='{unity.Id}']" ); unity.WaitForExit(); watcher.Stop(); watcherThread.Join(); if ( watcher.FullLog.Contains( "Successful build ~0xDEADBEEF" ) ) { Console.WriteLine( "##teamcity[progressMessage 'Success']" ); Environment.Exit( 0 ); } else { Console.WriteLine( "##teamcity[progressMessage 'Failed']" ); Environment.Exit( 1 ); } return unity.ExitCode; } } }
// // © 2016 Max the Cat Studios Ltd. // // https://maxthecatstudios.com // @maxthecatstudio // // Created By Desmond Fernando 2016 06 30 12:08 PM // // // using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; namespace UnityTC { public class Unity { /// <summary> /// /// </summary> /// <param name="unityPath"></param> /// <param name="args"></param> /// <returns></returns> public static int StartUnity( string unityPath, string args ) { var sb = new StringBuilder(); var watcher = new Watcher( Path.GetTempFileName() ); var watcherThread = new Thread( watcher.Run ); watcherThread.Start(); var unity = new Process { StartInfo = new ProcessStartInfo( unityPath ) }; sb.Append( $"-logFile \"{watcher.LogPath}\"" ); sb.Append( $" {args}" ); //for ( var i = 1; i < args.Length; i++ ) // sb.Append( $" \"{args[ i ]}\"" ); unity.StartInfo.Arguments = sb.ToString(); Console.WriteLine( $"##teamcity[progressMessage 'Starting Unity {unity.StartInfo.Arguments}'" ); unity.Start(); Console.WriteLine( $"##teamcity[setParameter name='unityPID' value='{unity.Id}']" ); unity.WaitForExit(); watcher.Stop(); watcherThread.Join(); return unity.ExitCode; } } }
mit
C#
67deeafccca23ffda14784c97ea2868c172f085d
Split cell text into many lines
12joan/hangman
cell.cs
cell.cs
using System; namespace Hangman { public class Cell { public const int RightAlign = 0; public const int CentreAlign = 1; public const int LeftAlign = 2; public string Text; public int Align; public Cell(string text) { Text = text; Align = LeftAlign; } public Cell(string text, int align) { Text = text; Align = align; } public string[] Lines() { return Text.Split('\n'); } } }
using System; namespace Hangman { public class Cell { public const int RightAlign = 0; public const int CentreAlign = 1; public const int LeftAlign = 2; public string Text; public int Align; public Cell(string text) { Text = text; Align = LeftAlign; } public Cell(string text, int align) { Text = text; Align = align; } } }
unlicense
C#
88d98a47fdedb091e14c9f63c0c25bf4b52975f8
Use builtin MongoDB Bson serialization
peterblazejewicz/m101DotNet-vNext,peterblazejewicz/m101DotNet-vNext
M101DotNet/Program.cs
M101DotNet/Program.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Bson.IO; namespace M101DotNet { public class Program { public static void Main(string[] args) { MainAsync(args).Wait(); Console.WriteLine(); Console.WriteLine("Press Enter"); Console.ReadLine(); } static async Task MainAsync(string[] args) { var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var db = client.GetDatabase("test"); var person = new Person { Name = "Jones", Age = 30, Colors = new List<string> {"red", "blue"}, Pets = new List<Pet> { new Pet { Name = "Puffy", Type = "Pig" } } }; Console.WriteLine(person); using (var writer = new JsonWriter(Console.Out)) { BsonSerializer.Serialize(writer, person); }; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Bson.Serialization; using Newtonsoft.Json; namespace M101DotNet { public class Program { public static void Main(string[] args) { MainAsync(args).Wait(); Console.WriteLine(); Console.WriteLine("Press Enter"); Console.ReadLine(); } static async Task MainAsync(string[] args) { var connectionString = "mongodb://localhost:27017"; var client = new MongoClient(connectionString); var db = client.GetDatabase("test"); var person = new Person { Name = "Jones", Age = 30, Colors = new List<string> {"red", "blue"}, Pets = new List<Pet> { new Pet { Name = "Puffy", Type = "Pig" } } }; Console.WriteLine(person); // using (var writer = new JsonWriter(Console.Out)) // { // BsonSerializer.Serialize(writer, person); // }; } } }
mit
C#
b1e599706d7b379872c72ee23f5137e9b047a33f
Improve performance on Robot_names_are_unique
robkeim/xcsharp,robkeim/xcsharp,exercism/xcsharp,exercism/xcsharp
exercises/robot-name/RobotNameTest.cs
exercises/robot-name/RobotNameTest.cs
using System.Collections.Generic; using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } [Fact(Skip = "Remove to run test")] public void After_reset_the_name_is_valid() { robot.Reset(); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Robot_names_are_unique() { var names = new HashSet<string>(); for (int i = 0; i < 10_000; i++) { var robot = new Robot(); Assert.True(names.Add(robot.Name)); } } }
using System.Collections.Generic; using Xunit; public class RobotNameTest { private readonly Robot robot = new Robot(); [Fact] public void Robot_has_a_name() { Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Name_is_the_same_each_time() { Assert.Equal(robot.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Different_robots_have_different_names() { var robot2 = new Robot(); Assert.NotEqual(robot2.Name, robot.Name); } [Fact(Skip = "Remove to run test")] public void Can_reset_the_name() { var originalName = robot.Name; robot.Reset(); Assert.NotEqual(originalName, robot.Name); } [Fact(Skip = "Remove to run test")] public void After_reset_the_name_is_valid() { robot.Reset(); Assert.Matches(@"^[A-Z]{2}\d{3}$", robot.Name); } [Fact(Skip = "Remove to run test")] public void Robot_names_are_unique() { var names = new HashSet<string>(); for (int i = 0; i < 10_000; i++) { var robot = new Robot(); Assert.DoesNotContain(robot.Name, names); names.Add(robot.Name); } } }
mit
C#
92db75d442d769dc45ef33e1b0d53009a839e084
Fix webkit enums that are ushort (not the default int32)
dlech/monomac,PlayScriptRedux/monomac
src/WebKit/Enums.cs
src/WebKit/Enums.cs
using System; namespace MonoMac.WebKit { public enum DomCssRuleType : ushort { Unknown = 0, Style = 1, Charset = 2, Import = 3, Media = 4, FontFace = 5, Page = 6, Variables = 7, WebKitKeyFrames = 8, WebKitKeyFrame = 9 } public enum DomCssValueType : ushort { Inherit = 0, PrimitiveValue = 1, ValueList = 2, Custom = 3 } [Flags] public enum DomDocumentPosition { Disconnected = 0x01, Preceeding = 0x02, Following = 0x04, Contains = 0x08, ContainedBy = 0x10, ImplementationSpecific = 0x20 } public enum DomNodeType : ushort { Element = 1, Attribute = 2, Text = 3, CData = 4, EntityReference = 5, Entity = 6, ProcessingInstruction = 7, Comment = 8, Document = 9, DocumentType = 10, DocumentFragment = 11, Notation = 12 } public enum DomRangeCompareHow : ushort { StartToStart = 0, StartToEnd = 1, EndToEnd = 2, EndToStart = 3 } public enum WebCacheModel { DocumentViewer, DocumentBrowser, PrimaryWebBrowser } public enum DomEventPhase : ushort { Capturing = 1, AtTarget, Bubbling } [Flags] public enum WebDragSourceAction : uint { None = 0, DHTML = 1, Image = 2, Link = 4, Selection = 8, Any = UInt32.MaxValue } [Flags] public enum WebDragDestinationAction : uint { None = 0, DHTML = 1, Image = 2, Link = 4, Selection = 8, Any = UInt32.MaxValue } public enum WebNavigationType { LinkClicked, FormSubmitted, BackForward, Reload, FormResubmitted, Other } }
using System; namespace MonoMac.WebKit { public enum DomCssRuleType { Unknown = 0, Style = 1, Charset = 2, Import = 3, Media = 4, FontFace = 5, Page = 6, Variables = 7, WebKitKeyFrames = 8, WebKitKeyFrame = 9 } public enum DomCssValueType { Inherit = 0, PrimitiveValue = 1, ValueList = 2, Custom = 3 } [Flags] public enum DomDocumentPosition { Disconnected = 0x01, Preceeding = 0x02, Following = 0x04, Contains = 0x08, ContainedBy = 0x10, ImplementationSpecific = 0x20 } public enum DomNodeType { Element = 1, Attribute = 2, Text = 3, CData = 4, EntityReference = 5, Entity = 6, ProcessingInstruction = 7, Comment = 8, Document = 9, DocumentType = 10, DocumentFragment = 11, Notation = 12 } public enum DomRangeCompareHow { StartToStart = 0, StartToEnd = 1, EndToEnd = 2, EndToStart = 3 } public enum WebCacheModel { DocumentViewer, DocumentBrowser, PrimaryWebBrowser } public enum DomEventPhase { Capturing = 1, AtTarget, Bubbling } [Flags] public enum WebDragSourceAction : uint { None = 0, DHTML = 1, Image = 2, Link = 4, Selection = 8, Any = UInt32.MaxValue } [Flags] public enum WebDragDestinationAction : uint { None = 0, DHTML = 1, Image = 2, Link = 4, Selection = 8, Any = UInt32.MaxValue } public enum WebNavigationType { LinkClicked, FormSubmitted, BackForward, Reload, FormResubmitted, Other } }
apache-2.0
C#
178b991b3b43326c7c5b3a0e4610e7bee76326ad
Comment fix
AtaS/lowercase-dashed-route
LowercaseDashedRouting/DashedRouteHandler.cs
LowercaseDashedRouting/DashedRouteHandler.cs
using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LowercaseDashedRouting { public class DashedRouteHandler : MvcRouteHandler { /// <summary> /// The route handler which ignores dashes. /// </summary> /// <param name="requestContext"></param> /// <returns></returns> protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var values = requestContext.RouteData.Values; values["action"] = values["action"].ToString().Replace("-", ""); values["controller"] = values["controller"].ToString().Replace("-", ""); return base.GetHttpHandler(requestContext); } } }
// by Ata Sasmaz http://www.ata.io using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace LowercaseDashedRouting { public class DashedRouteHandler : MvcRouteHandler { /// <summary> /// The route handler which ignores dashes. /// </summary> /// <param name="requestContext"></param> /// <returns></returns> protected override IHttpHandler GetHttpHandler(RequestContext requestContext) { var values = requestContext.RouteData.Values; values["action"] = values["action"].ToString().Replace("-", ""); values["controller"] = values["controller"].ToString().Replace("-", ""); return base.GetHttpHandler(requestContext); } } }
mit
C#
42b071bb9d18bcf13ccd41ac6dd3a768720b08a6
Add a little more info to the thread listing.
GunioRobot/sdb-cli,GunioRobot/sdb-cli
Mono.Debugger.Cli/Commands/ThreadsCommand.cs
Mono.Debugger.Cli/Commands/ThreadsCommand.cs
using System.Collections.Generic; using Mono.Debugger.Cli.Debugging; using Mono.Debugger.Cli.Logging; namespace Mono.Debugger.Cli.Commands { public sealed class ThreadsCommand : ICommand { public string Name { get { return "Threads"; } } public string Description { get { return "Lists all active threads."; } } public IEnumerable<string> Arguments { get { return Argument.None(); } } public void Execute(CommandArguments args) { var session = SoftDebugger.Session; if (SoftDebugger.State == DebuggerState.Null) { Logger.WriteErrorLine("No session active."); return; } if (SoftDebugger.State == DebuggerState.Initialized) { Logger.WriteErrorLine("No process active."); return; } var threads = session.VirtualMachine.GetThreads(); foreach (var thread in threads) { var id = thread.Id.ToString(); if (thread.IsThreadPoolThread) id += " (TP)"; Logger.WriteInfoLine("[{0}: {1}] {2}: {3}", thread.Domain.FriendlyName, id, thread.Name, thread.ThreadState); } } } }
using System.Collections.Generic; using Mono.Debugger.Cli.Debugging; using Mono.Debugger.Cli.Logging; namespace Mono.Debugger.Cli.Commands { public sealed class ThreadsCommand : ICommand { public string Name { get { return "Threads"; } } public string Description { get { return "Lists all active threads."; } } public IEnumerable<string> Arguments { get { return Argument.None(); } } public void Execute(CommandArguments args) { var session = SoftDebugger.Session; if (SoftDebugger.State == DebuggerState.Null) { Logger.WriteErrorLine("No session active."); return; } if (SoftDebugger.State == DebuggerState.Initialized) { Logger.WriteErrorLine("No process active."); return; } var threads = session.VirtualMachine.GetThreads(); foreach (var thread in threads) Logger.WriteInfoLine("[{0}] {1}: {2}", thread.Id, thread.Name, thread.ThreadState); } } }
mit
C#
0ff8e03f31534ebbda31b22926c7eded89b3e42a
Remove ToTab().
GetTabster/Tabster.Core
Plugins/IRemoteTab.cs
Plugins/IRemoteTab.cs
#region using System; #endregion namespace Tabster.Core.Plugins { public interface IRemoteTab { Uri Url { get; set; } string Artist { get; set; } string Title { get; set; } TabType Type { get; set; } string Contents { get; set; } } }
#region using System; #endregion namespace Tabster.Core.Plugins { public interface IRemoteTab { Uri Url { get; set; } string Artist { get; set; } string Title { get; set; } TabType Type { get; set; } string Contents { get; set; } Tab ToTab(); } }
apache-2.0
C#
74f1dee7078a13b32ffeed7eb2114592910b73cc
bump version
Dalet/140-speedrun-timer,Dalet/140-speedrun-timer,Dalet/140-speedrun-timer
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyVersion("0.7.3.2")] [assembly: AssemblyFileVersion("0.7.3.2")]
using System.Reflection; [assembly: AssemblyVersion("0.7.3.1")] [assembly: AssemblyFileVersion("0.7.3.1")]
unlicense
C#
df3b821153bc3b9cac70afde4537eec1d5b078a3
Support of option /logPath
Seddryck/RsPackage
SsrsDeploy/Options.cs
SsrsDeploy/Options.cs
using CommandLine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SsrsDeploy { public class Options { [Option('u', "url", Required = true, HelpText = "Url of the webservice where to deploy the reports.")] public string Url { get; set; } // Omitting long name, default --verbose [Option('s', "solution", Required = true, HelpText = "File containing the definition of artefacts to deploy.")] public string SourceFile { get; set; } [Option('f', "folder", Required = true, HelpText = "Parent folder on SSRS where the reports and data sources are deployed.")] public string ParentFolder { get; set; } [Option('r', "resources", Required = false, HelpText = "Path of the local folder containing all the resources (reports, data sources, shared datasets). If missing the path of the solution will be assumed.")] public string ResourcePath { get; set; } [Option('l', "log", Required = false, HelpText = "Path of the local folder to redirect all the logs. If missing the logs will be displayed on the console.")] public string LogPath { get; set; } } }
using CommandLine; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SsrsDeploy { public class Options { [Option('u', "url", Required = true, HelpText = "Url of the webservice where to deploy the reports.")] public string Url { get; set; } // Omitting long name, default --verbose [Option('s', "solution", Required = true, HelpText = "File containing the definition of artefacts to deploy.")] public string SourceFile { get; set; } [Option('f', "folder", Required = true, HelpText = "Parent folder on SSRS where the reports and data sources are deployed.")] public string ParentFolder { get; set; } [Option('r', "resources", Required = false, HelpText = "Path of the local folder containing all the resources (reports, data sources, shared datasets). If missing the path of the solution will be assumed.")] public string ResourcePath { get; set; } } }
apache-2.0
C#
83840b2debf8c20890a00b6da1e5feaae5d720dd
Update App.xaml.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D/App.xaml.cs
src/Draw2D/App.xaml.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 System; using Avalonia; using Avalonia.Logging.Serilog; using Avalonia.Markup.Xaml; using Draw2D.Editor; using Draw2D.Views; namespace Draw2D { public class App : Application { [STAThread] static void Main(string[] args) { BuildAvaloniaApp().Start(AppMain, args); } static void AppMain(Application app, string[] args) { var window = new MainWindow { DataContext = new ContainerEditor(), }; app.Run(window); } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .With(new Win32PlatformOptions { AllowEglInitialization = false }) .With(new X11PlatformOptions { UseGpu = true, UseEGL = false }) .With(new AvaloniaNativePlatformOptions { UseGpu = true }) .UseSkia() .LogToDebug(); public override void Initialize() { AvaloniaXamlLoader.Load(this); } } }
// 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 System; using Avalonia; using Avalonia.Logging.Serilog; using Avalonia.Markup.Xaml; using Draw2D.Editor; using Draw2D.Views; namespace Draw2D { public class App : Application { [STAThread] static void Main(string[] args) { BuildAvaloniaApp().Start(AppMain, args); } static void AppMain(Application app, string[] args) { var window = new MainWindow { DataContext = new ContainerEditor(), }; app.Run(window); } public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure<App>() .UsePlatformDetect() .With(new Win32PlatformOptions { AllowEglInitialization = true }) .With(new X11PlatformOptions { UseGpu = true, UseEGL = true }) .With(new AvaloniaNativePlatformOptions { UseGpu = true }) .UseSkia() .LogToDebug(); public override void Initialize() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
86f480f3a99046003622e714b1970597c5a1c63a
Bump patch version
pragmatrix/NEventSocket,danbarua/NEventSocket,danbarua/NEventSocket,pragmatrix/NEventSocket
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NEventSocket")] [assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")] [assembly: AssemblyCompany("Dan Barua")] [assembly: AssemblyProduct("NEventSocket")] [assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")] [assembly: AssemblyVersion("0.5.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NEventSocket")] [assembly: AssemblyDescription("An async reactive EventSocket driver for FreeSwitch")] [assembly: AssemblyCompany("Dan Barua")] [assembly: AssemblyProduct("NEventSocket")] [assembly: AssemblyCopyright("Copyright (C) 2014 Dan Barua and contributers. All rights reserved.")] [assembly: AssemblyVersion("0.4.0.0")]
mpl-2.0
C#
89881654829506eb43054b983d39f0b8d16fe48d
Add more visualisation
ruarai/Trigrad,ruarai/Trigrad
Trigrad/Extensions.cs
Trigrad/Extensions.cs
using TriangleNet.Data; using System.Drawing; using TriangleNet; namespace Trigrad { internal static class Extensions { public static Point Point(this Vertex t) { return new Point((int)t.X, (int)t.Y); } public static Bitmap ToBitmap(this Mesh mesh,int width,int height) { Bitmap b = new Bitmap(width, height); Graphics g = Graphics.FromImage(b); foreach (var tri in mesh.Triangles) { var pU = tri.GetVertex(0).Point(); var pV = tri.GetVertex(1).Point(); var pW = tri.GetVertex(2).Point(); g.DrawLine(new Pen(Color.DarkSlateGray), pU, pV); g.DrawLine(new Pen(Color.DarkSlateGray), pV, pW); g.DrawLine(new Pen(Color.DarkSlateGray), pU, pW); } b.Save("mesh.png"); return b; } } }
using TriangleNet.Data; using System.Drawing; namespace Trigrad { internal static class Extensions { public static Point Point(this Vertex t) { return new Point((int)t.X, (int)t.Y); } } }
mit
C#
daf90e6bcf30df4fa1caee7500650d7b4944a77e
Add OSX default install location for BeyondCompare.
droyad/Assent
src/Assent/Reporters/DiffPrograms/BeyondCompareDiffProgram.cs
src/Assent/Reporters/DiffPrograms/BeyondCompareDiffProgram.cs
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class BeyondCompareDiffProgram : DiffProgramBase { static BeyondCompareDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .SelectMany(p => new[] { $@"{p}\Beyond Compare 4\BCompare.exe", $@"{p}\Beyond Compare 3\BCompare.exe" }) .ToArray()); } else { paths.Add("/usr/bin/bcompare"); paths.Add("/usr/local/bin/bcompare"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public BeyondCompareDiffProgram() : base(DefaultSearchPaths) { } public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile); var argChar = DiffReporter.IsWindows ? "/" : "-"; return $"{defaultArgs} {argChar}solo" ; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Assent.Reporters.DiffPrograms { public class BeyondCompareDiffProgram : DiffProgramBase { static BeyondCompareDiffProgram() { var paths = new List<string>(); if (DiffReporter.IsWindows) { paths.AddRange(WindowsProgramFilePaths .SelectMany(p => new[] { $@"{p}\Beyond Compare 4\BCompare.exe", $@"{p}\Beyond Compare 3\BCompare.exe" }) .ToArray()); } else { paths.Add("/usr/bin/bcompare"); } DefaultSearchPaths = paths; } public static readonly IReadOnlyList<string> DefaultSearchPaths; public BeyondCompareDiffProgram() : base(DefaultSearchPaths) { } public BeyondCompareDiffProgram(IReadOnlyList<string> searchPaths) : base(searchPaths) { } protected override string CreateProcessStartArgs(string receivedFile, string approvedFile) { var defaultArgs = base.CreateProcessStartArgs(receivedFile, approvedFile); var argChar = DiffReporter.IsWindows ? "/" : "-"; return $"{defaultArgs} {argChar}solo" ; } } }
mit
C#
54d0880efb9db929d89ba15b601d5be41e333029
Add some simple runtime stats while implementing the Z80 core
eightlittlebits/elbsms
elbsms_console/Program.cs
elbsms_console/Program.cs
using System; using System.Diagnostics; using elbsms_core; namespace elbsms_console { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: elbsms_console <path to rom>"); return; } string romPath = args[0]; Cartridge cartridge = Cartridge.LoadFromFile(romPath); MasterSystem masterSystem = new MasterSystem(cartridge); Console.WriteLine($"Starting: {DateTime.Now}"); Console.WriteLine(); ulong instructionCount = 0; var sw = Stopwatch.StartNew(); try { while (true) { instructionCount++; masterSystem.SingleStep(); } } catch (NotImplementedException ex) { Console.WriteLine(ex.Message); } sw.Stop(); Console.WriteLine(); Console.WriteLine($"Finished: {DateTime.Now}"); Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds}ms Instructions: {instructionCount}, Instructions/ms: {instructionCount/(double)sw.ElapsedMilliseconds}"); } } }
using System; using elbsms_core; namespace elbsms_console { class Program { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("Usage: elbsms_console <path to rom>"); return; } string romPath = args[0]; Cartridge cartridge = Cartridge.LoadFromFile(romPath); MasterSystem masterSystem = new MasterSystem(cartridge); try { while (true) { masterSystem.SingleStep(); } } catch (NotImplementedException ex) { Console.WriteLine(ex.Message); } } } }
mit
C#
5e85f238c0716d8102aa69c7dcb874656f370eb8
Work emumerable record reader
arkivverket/arkade5,arkivverket/arkade5,arkivverket/arkade5
src/Arkivverket.Arkade/Core/Addml/DelimiterDileRecordEnumerator.cs
src/Arkivverket.Arkade/Core/Addml/DelimiterDileRecordEnumerator.cs
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arkivverket.Arkade.Core.Addml { class DelimiterDileRecordEnumerator : IEnumerator { private StreamReader _stream; private string _delimiter; private string _foundRecord = null; private bool _isMoveNext = false; public DelimiterDileRecordEnumerator(StreamReader stream, string delimiter) { _stream = stream; _delimiter = delimiter; } public object Current { get { if (!string.IsNullOrEmpty(_foundRecord)) { return _foundRecord; } else { throw new Exception("Current element null error"); } } } public bool MoveNext() { StringBuilder strBld = new StringBuilder(); int readChar; bool search = true; while (search) { readChar = _stream.Read(); if (readChar == -1) { if (strBld.Length > 0) { _foundRecord = strBld.ToString(); return true; } else { _foundRecord = null; return false; } } strBld.Append(Convert.ToChar(readChar)); if (_CheckIfEndOfStringContainsDelimiter(strBld, _delimiter)) { _foundRecord = _ReturnStringWithoutDelimAtEndOfStringbuilder(strBld, _delimiter); return true; } } } public void Reset() { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } private bool _CheckIfEndOfStringContainsDelimiter(StringBuilder sb, string delim) { if (sb.Length < delim.Length) { return false; } else { return(_ReturnStringWithoutDelimAtEndOfStringbuilder(sb, delim).Equals(delim)); } } private string _ReturnStringWithoutDelimAtEndOfStringbuilder(StringBuilder sb, string delim) { if (sb.Length < delim.Length) { return String.Empty; } else { return (sb.ToString(sb.Length - delim.Length, sb.Length)); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Arkivverket.Arkade.Core.Addml { class DelimiterDileRecordEnumerator : IEnumerator { private StreamReader _stream; private string _delimiter; public DelimiterDileRecordEnumerator(StreamReader stream, string delimiter) { _stream = stream; _delimiter = delimiter; } public object Current { get { throw new NotImplementedException(); } } public bool MoveNext() { throw new NotImplementedException(); } public void Reset() { throw new NotImplementedException(); } } }
agpl-3.0
C#